[teiid-commits] teiid SVN: r3221 - in tags: teiid-parent-7.5.0.Alpha1 and 133 other directories.
teiid-commits at lists.jboss.org
teiid-commits at lists.jboss.org
Sun Jun 5 14:45:22 EDT 2011
Author: shawkins
Date: 2011-06-05 14:45:10 -0400 (Sun, 05 Jun 2011)
New Revision: 3221
Added:
tags/teiid-parent-7.5.0.Alpha1/
tags/teiid-parent-7.5.0.Alpha1/adminshell/pom.xml
tags/teiid-parent-7.5.0.Alpha1/api/pom.xml
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/CommandContext.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/AuditMessage.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogManager.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogMessage.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/metadata/Table.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/BaseDelegatingExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionContext.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/api/src/test/java/org/teiid/logging/TestLogManager.java
tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml
tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/teiid-releasenotes.html
tags/teiid-parent-7.5.0.Alpha1/build/pom.xml
tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/pom.xml
tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java
tags/teiid-parent-7.5.0.Alpha1/client-jdk15/pom.xml
tags/teiid-parent-7.5.0.Alpha1/client-jdk15/src/main/java/net/sf/retrotranslator/runtime/java/net/
tags/teiid-parent-7.5.0.Alpha1/client/pom.xml
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/Session.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadata.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadataMapper.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/JDBCURL.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/StatementImpl.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/TeiidURL.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java
tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestStatement.java
tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java
tags/teiid-parent-7.5.0.Alpha1/common-core/pom.xml
tags/teiid-parent-7.5.0.Alpha1/common-core/src/main/java/org/teiid/core/util/PropertiesUtils.java
tags/teiid-parent-7.5.0.Alpha1/connectors/connector-file/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ldap/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/connector-salesforce/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ws/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/salesforce-api/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/translator-yahoo/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-file/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ingres/IngresExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/intersyscache/InterSystemsCacheExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/ModeShapeExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/teradata/TestTeradataTranslator.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/src/test/java/org/teiid/translator/ldap/TestIQueryToLdapSearchParser.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-loopback/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-olap/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/SalesForceExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ws/pom.xml
tags/teiid-parent-7.5.0.Alpha1/console/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/admin-guide/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/caching-guide/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-connection.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-extensions.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/odbc.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/ssl.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/logging.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/udf.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/quick-start-example/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/reference/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/federated_planning.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/sql_support.xml
tags/teiid-parent-7.5.0.Alpha1/engine/pom.xml
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/BlockedException.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ExecutionContextImpl.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/LanguageBridgeFactory.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/RuntimeMetadataImpl.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataRoleAuthorizationValidator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingAttribute.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingBaseNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingCriteriaNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingDocument.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingElement.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNodeConstants.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingOutputter.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingRecursiveElement.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/ResultSetInfo.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/CompositeMetadataStore.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataAdapter.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataID.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TransformationMetadata.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/BasicSourceCapabilities.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/SourceCapabilities.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/plantree/NodeConstants.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CapabilitiesUtil.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseDependent.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleCollapseSource.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleImplementJoinStrategy.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeCriteria.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlaceAccess.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanJoins.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushAggregates.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ContextReplacerVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/CriteriaPlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/MarkExcludeVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/NameInSourceResolverVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/SourceNodePlannerVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ValidateMappedCriteriaVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLNodeMappingVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanToProcessVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLProjectionMinimizer.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLQueryPlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLStagaingQueryPlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/AccessNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentCriteriaProcessor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentValueSource.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/EnhancedSortMergeJoinStrategy.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/JoinNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/ProjectIntoNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/SortNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/UnionAllNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/xml/XMLContext.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/InsertResolver.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/SimpleQueryResolver.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/XMLQueryResolver.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/LanguageObject.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ArrayTable.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ExistsCriteria.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/FromClause.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/JoinPredicate.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Select.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/SubqueryFromClause.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TableFunctionReference.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TextTable.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/UnaryFromClause.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/XMLTable.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/util/ValueIteratorSource.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/PredicateCollectorVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/security/Credentials.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/resources/org/teiid/query/i18n.properties
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorWorkItem.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestElementImpl.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestGroupImpl.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestInsertImpl.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestMetadataFactory.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TstLanguageBridgeFactory.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCachedResults.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatementBatchedUpdate.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceElementReplacementVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceMetadataWrapper.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/mapping/xml/TestMappingElement.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/metadata/TestTransformationMetadata.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/proc/TestProcedurePlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCapabilitiesUtil.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCriteriaCapabilityValidatorVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAccessPatternValidation.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAssignOutputElements.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleChooseDependent.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePlaceAccess.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePushSelectCriteria.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleValidateWhereAll.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestMarkExcludeVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestNameInSourceResolverVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLNodeMappingVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLPlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestOptionsAndHints.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestParser.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcessor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTextTable.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/eval/TestExpressionEvaluator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/proc/TestProcedureProcessor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestAccessNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestBatchedUpdateNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestJoinNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestProjectNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestSelectNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestInstructions.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestSourceNodeGenaratorVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLPlanningEnhancements.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestFunctionResolving.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestProcedureResolving.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestResolver.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestXMLResolver.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestOrderByRewrite.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/util/TestElementSymbolOptimizer.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestEvaluatableVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestSQLStringVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestUpdateValidator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/resources/text/cdm_dos_win.txt
tags/teiid-parent-7.5.0.Alpha1/hibernate-dialect/pom.xml
tags/teiid-parent-7.5.0.Alpha1/jboss-integration/pom.xml
tags/teiid-parent-7.5.0.Alpha1/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
tags/teiid-parent-7.5.0.Alpha1/metadata/pom.xml
tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/api/TranslationUtility.java
tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/unittest/FakeTranslationFactory.java
tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/metadata/index/TestStagingTable.java
tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/resources/test.vdb
tags/teiid-parent-7.5.0.Alpha1/pom.xml
tags/teiid-parent-7.5.0.Alpha1/runtime/pom.xml
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCClientRemote.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCServerRemoteImpl.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/LogonImpl.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/PgBackendProtocol.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/resources/org/teiid/runtime/i18n.properties
tags/teiid-parent-7.5.0.Alpha1/runtime/src/test/java/org/teiid/deployers/TestCompositeVDB.java
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/pom.xml
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestCrossSourceStarJoin.java
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestRelate.java
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/TestLocalConnections.java
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/resources/relate/
tags/teiid-parent-7.5.0.Alpha1/test-integration/db/pom.xml
tags/teiid-parent-7.5.0.Alpha1/test-integration/pom.xml
Removed:
tags/teiid-parent-7.5.0.Alpha1/adminshell/pom.xml
tags/teiid-parent-7.5.0.Alpha1/api/pom.xml
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/CommandContext.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/AuditMessage.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogManager.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogMessage.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/metadata/Table.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/BaseDelegatingExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionContext.java
tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/api/src/test/java/org/teiid/logging/TestLogManager.java
tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml
tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/teiid-releasenotes.html
tags/teiid-parent-7.5.0.Alpha1/build/pom.xml
tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/pom.xml
tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java
tags/teiid-parent-7.5.0.Alpha1/client-jdk15/pom.xml
tags/teiid-parent-7.5.0.Alpha1/client/pom.xml
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/Session.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadata.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadataMapper.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/JDBCURL.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/StatementImpl.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/TeiidURL.java
tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java
tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestStatement.java
tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java
tags/teiid-parent-7.5.0.Alpha1/common-core/pom.xml
tags/teiid-parent-7.5.0.Alpha1/common-core/src/main/java/org/teiid/core/util/PropertiesUtils.java
tags/teiid-parent-7.5.0.Alpha1/connectors/connector-file/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ldap/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/connector-salesforce/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ws/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/salesforce-api/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/translator-yahoo/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-file/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ingres/IngresExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/intersyscache/InterSystemsCacheExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/ModeShapeExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSpatialFunctions.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/teradata/TestTeradataTranslator.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/src/test/java/org/teiid/translator/ldap/TestIQueryToLdapSearchParser.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-loopback/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-olap/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/pom.xml
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/SalesForceExecutionFactory.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java
tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ws/pom.xml
tags/teiid-parent-7.5.0.Alpha1/console/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/admin-guide/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/caching-guide/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-connection.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-extensions.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/odbc.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/ssl.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/logging.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/udf.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/quick-start-example/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/reference/pom.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/federated_planning.xml
tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/sql_support.xml
tags/teiid-parent-7.5.0.Alpha1/engine/pom.xml
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/BlockedException.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ExecutionContextImpl.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/LanguageBridgeFactory.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/RuntimeMetadataImpl.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataRoleAuthorizationValidator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingAttribute.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingBaseNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingCriteriaNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingDocument.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingElement.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNodeConstants.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingOutputter.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingRecursiveElement.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/ResultSetInfo.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/CompositeMetadataStore.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataAdapter.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataID.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TransformationMetadata.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/BasicSourceCapabilities.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/SourceCapabilities.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/plantree/NodeConstants.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CapabilitiesUtil.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseDependent.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleCollapseSource.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleImplementJoinStrategy.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeCriteria.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlaceAccess.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanJoins.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushAggregates.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ContextReplacerVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/CriteriaPlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/MarkExcludeVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/NameInSourceResolverVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/SourceNodePlannerVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ValidateMappedCriteriaVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLNodeMappingVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanToProcessVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLQueryPlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLStagaingQueryPlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/AccessNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentCriteriaProcessor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentValueSource.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/EnhancedSortMergeJoinStrategy.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/JoinNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/ProjectIntoNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/SortNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/UnionAllNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/xml/JoinedWhileInstruction.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/xml/XMLContext.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/InsertResolver.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/SimpleQueryResolver.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/XMLQueryResolver.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/LanguageObject.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ArrayTable.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ExistsCriteria.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/FromClause.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/JoinPredicate.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Select.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/SubqueryFromClause.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TableFunctionReference.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TextTable.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/UnaryFromClause.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/XMLTable.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/util/ValueIteratorSource.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/PredicateCollectorVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/security/Credentials.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/main/resources/org/teiid/query/i18n.properties
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorWorkItem.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestElementImpl.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestGroupImpl.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestInsertImpl.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestMetadataFactory.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TstLanguageBridgeFactory.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCachedResults.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatementBatchedUpdate.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceElementReplacementVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceMetadataWrapper.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/mapping/xml/TestMappingElement.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/metadata/TestTransformationMetadata.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/proc/TestProcedurePlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCapabilitiesUtil.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCriteriaCapabilityValidatorVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAccessPatternValidation.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAssignOutputElements.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleChooseDependent.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePlaceAccess.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePushSelectCriteria.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleValidateWhereAll.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestMarkExcludeVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestNameInSourceResolverVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLNodeMappingVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLPlanner.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestOptionsAndHints.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestParser.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcessor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTextTable.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/eval/TestExpressionEvaluator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/proc/TestProcedureProcessor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestAccessNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestBatchedUpdateNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestJoinNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestProjectNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestSelectNode.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestInstructions.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestSourceNodeGenaratorVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLPlanningEnhancements.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestFunctionResolving.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestProcedureResolving.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestResolver.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestXMLResolver.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestOrderByRewrite.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/util/TestElementSymbolOptimizer.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestEvaluatableVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestSQLStringVisitor.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFacade.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFactory.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/FakeMetadataObject.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/FakeMetadataStore.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestUpdateValidator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java
tags/teiid-parent-7.5.0.Alpha1/engine/src/test/resources/text/cdm_dos_win.txt
tags/teiid-parent-7.5.0.Alpha1/hibernate-dialect/pom.xml
tags/teiid-parent-7.5.0.Alpha1/jboss-integration/pom.xml
tags/teiid-parent-7.5.0.Alpha1/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
tags/teiid-parent-7.5.0.Alpha1/metadata/pom.xml
tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/api/TranslationUtility.java
tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/unittest/FakeTranslationFactory.java
tags/teiid-parent-7.5.0.Alpha1/pom.xml
tags/teiid-parent-7.5.0.Alpha1/runtime/pom.xml
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCClientRemote.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCServerRemoteImpl.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/LogonImpl.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/PgBackendProtocol.java
tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/resources/org/teiid/runtime/i18n.properties
tags/teiid-parent-7.5.0.Alpha1/runtime/src/test/java/org/teiid/deployers/TestCompositeVDB.java
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/pom.xml
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestCrossSourceStarJoin.java
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/TestLocalConnections.java
tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java
tags/teiid-parent-7.5.0.Alpha1/test-integration/db/pom.xml
tags/teiid-parent-7.5.0.Alpha1/test-integration/pom.xml
Modified:
tags/teiid-parent-7.5.0.Alpha1/metadata/
Log:
[maven-release-plugin] copy for tag teiid-parent-7.5.0.Alpha1
Deleted: tags/teiid-parent-7.5.0.Alpha1/adminshell/pom.xml
===================================================================
--- trunk/adminshell/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/adminshell/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,69 +0,0 @@
-<?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-adminshell</artifactId>
- <name>Adminshell</name>
- <description>Adminshell for Teiid</description>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <type>test-jar</type>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.codehaus.groovy</groupId>
- <artifactId>groovy-all</artifactId>
- <version>1.7.2</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.1</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.4</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>jline</groupId>
- <artifactId>jline</artifactId>
- <version>0.9.94</version>
- <scope>compile</scope>
- <exclusions>
- <exclusion>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.fusesource.jansi</groupId>
- <artifactId>jansi</artifactId>
- <version>1.2.1</version>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>commons-cli</groupId>
- <artifactId>commons-cli</artifactId>
- <version>1.2</version>
- <scope>compile</scope>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/adminshell/pom.xml (from rev 3220, trunk/adminshell/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/adminshell/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/adminshell/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,69 @@
+<?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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>teiid-adminshell</artifactId>
+ <name>Adminshell</name>
+ <description>Adminshell for Teiid</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.codehaus.groovy</groupId>
+ <artifactId>groovy-all</artifactId>
+ <version>1.7.2</version>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>3.8.1</version>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.4</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>jline</groupId>
+ <artifactId>jline</artifactId>
+ <version>0.9.94</version>
+ <scope>compile</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.fusesource.jansi</groupId>
+ <artifactId>jansi</artifactId>
+ <version>1.2.1</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-cli</groupId>
+ <artifactId>commons-cli</artifactId>
+ <version>1.2</version>
+ <scope>compile</scope>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/api/pom.xml
===================================================================
--- trunk/api/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/api/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,34 +0,0 @@
-<?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-api</artifactId>
- <name>Teiid Translator API</name>
- <description>API for creating Translators and other common extenders in Teiid</description>
-
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
-
- </dependencies>
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/api/pom.xml (from rev 3220, trunk/api/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/api/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/api/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,40 @@
+<?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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>teiid-api</artifactId>
+ <name>Teiid API</name>
+ <description>API for creating Translators and other extensions to Teiid</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <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>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ </dependencies>
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/CommandContext.java
===================================================================
--- trunk/api/src/main/java/org/teiid/CommandContext.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/CommandContext.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,56 +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;
-
-import java.util.Properties;
-import java.util.TimeZone;
-
-import javax.security.auth.Subject;
-
-/**
- * Context information for the currently executing command.
- * Can be used as an argument to UDFs.
- */
-public interface CommandContext {
-
- String getUserName();
-
- String getVdbName();
-
- int getVdbVersion();
-
- String getConnectionID();
-
- Properties getEnvironmentProperties();
-
- double getNextRand();
-
- double getNextRand(long seed);
-
- int getProcessorBatchSize();
-
- TimeZone getServerTimeZone();
-
- Subject getSubject();
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/CommandContext.java (from rev 3218, trunk/api/src/main/java/org/teiid/CommandContext.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/CommandContext.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/CommandContext.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,121 @@
+/*
+ * 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.io.Serializable;
+import java.util.Properties;
+import java.util.TimeZone;
+
+import javax.security.auth.Subject;
+
+import org.teiid.adminapi.Session;
+
+/**
+ * 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();
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/AuditMessage.java
===================================================================
--- trunk/api/src/main/java/org/teiid/logging/AuditMessage.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/AuditMessage.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.logging;
-
-import java.util.Arrays;
-
-/**
- * Log format for auditing.
- */
-public class AuditMessage {
- private String context;
- private String activity;
- private String principal;
- private Object[] resources;
-
- public AuditMessage(String context, String activity, String principal, String[] resources ) {
- this.context = context;
- this.activity = activity;
- this.principal = principal;
- this.resources = resources;
- }
-
- public String getContext() {
- return this.context;
- }
-
- public String getActivity() {
- return this.activity;
- }
-
- public String getPrincipal() {
- return this.principal;
- }
-
- public Object[] getResources() {
- return this.resources;
- }
-
- public String toString() {
- StringBuffer msg = new StringBuffer();
- msg.append(" ["); //$NON-NLS-1$
- msg.append( getPrincipal() );
- msg.append("] <"); //$NON-NLS-1$
- msg.append( getContext() );
- msg.append('.');
- msg.append( getActivity() );
- msg.append("> "); //$NON-NLS-1$
- msg.append( Arrays.toString(resources) );
- return msg.toString();
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/AuditMessage.java (from rev 3218, trunk/api/src/main/java/org/teiid/logging/AuditMessage.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/AuditMessage.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/AuditMessage.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.logging;
+
+import java.util.Arrays;
+
+import org.teiid.CommandContext;
+
+/**
+ * Log format for auditing.
+ */
+public class AuditMessage {
+ private String context;
+ private String activity;
+ private String[] resources;
+ private CommandContext commandContext;
+
+ public AuditMessage(String context, String activity, String[] resources, CommandContext commandContext) {
+ this.context = context;
+ this.activity = activity;
+ this.resources = resources;
+ this.commandContext = commandContext;
+ }
+
+ public String getContext() {
+ return this.context;
+ }
+
+ public String getActivity() {
+ return this.activity;
+ }
+
+ public String getPrincipal() {
+ return this.commandContext.getUserName();
+ }
+
+ 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$
+ msg.append( getContext() );
+ msg.append('.');
+ msg.append( getActivity() );
+ msg.append("> "); //$NON-NLS-1$
+ msg.append( Arrays.toString(resources) );
+ return msg.toString();
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogManager.java
===================================================================
--- trunk/api/src/main/java/org/teiid/logging/LogManager.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogManager.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,399 +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.logging;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-
-
-
-/**
- * This class represents the interface to a single logging framework
- * that is easily accessible by any component. Using the LogManager, a component
- * can quickly submit a log message, and can rely upon the LogManager to determine
- * (a) whether that message is to be recorded or discarded; and (b) where
- * to send any recorded messages. Thus, the component's code that submits
- * messages does not have to be modified to alter the logging behavior of the
- * application.
- * <p>
- * By default, all context(s) are logged by the LogManager. The messages that
- * the LogManager actually records and sends to the destinations
- * can be controlled using two different and orthogonal parameters.
- * The first is a message <i>level</i> that filters messages based upon detail,
- * and the second is a message <i>context</i> that filters messages based upon
- * origin. The LogManager tracks only those context(s) that should NOT be
- * logged. Only if a message (which also is defined with these two parameters)
- * passes both filters will it be sent to the destinations.
- * <p>
- * Each message is submitted with one of the following levels (determined
- * by the particular method used to submit the message), sorted from the
- * least detailed to the greatest:
- * <li><b>Critical</b>: This level of message is generally
- * used to record an event or error that must be recorded (if any logging
- * is used). If it is used to record an error, it generally means that the
- * system encountered a critical error which affects the integrity, accuracy,
- * reliability and/or capability of the system.</li>
- * <li><b>Error</b>: Error messages are generally used
- * to record unexpected problems, or errors that are not critical in nature
- * and from which the system can automatically recover.</li>
- * <li><b>Warning</b>: Warning messages generally described
- * expected errors from which the system should recover. However, this level
- * is used to record the fact that such an error or event did occur.</li>
- * <li><b>Information</b>: This level of logging is the usually
- * the normal level. All interesting periodic events should be logged at this
- * level so someone looking through the log can see the amount and kind of
- * processing happening in the system.</li>
- * <li><b>Detail</b>: Such messages are moderately detailed,
- * and help to debug typical problems in the system. Generally, these
- * messages are not so detailed that the big picture gets lost.</li>
- * <li><b>Trace</b>: A trace message is the most detailed
- * logging level, used to trace system execution for really nasty problems.
- * At this level, logging will be so verbose that the system performance
- * may be affected.</li>
- * <p>
- * The context for a message is any application-specified String. Again, only
- * those message contexts that match those in the LogManager's configuration will
- * be sent to the destinations.
- *
- */
-public final class LogManager {
-
- public static class LoggingProxy implements InvocationHandler {
- private final Object instance;
- private final String loggingContext;
- private final int level;
-
- public LoggingProxy(Object instance, String loggingContext, int level) {
- this.instance = instance;
- this.loggingContext = loggingContext;
- this.level = level;
- }
-
- public Object invoke(Object proxy,
- Method method,
- Object[] args) throws Throwable {
- boolean log = LogManager.isMessageToBeRecorded(loggingContext, level);
- if (log) {
- StringBuffer message = new StringBuffer();
- message.append("before "); //$NON-NLS-1$
- message.append(method.getName());
- message.append(":"); //$NON-NLS-1$
- message.append(instance);
- message.append("("); //$NON-NLS-1$
- if (args != null) {
- for (int i = 0; i < args.length; i++) {
- if (args[i] != null) {
- message.append(args[i]);
- } else {
- message.append("null"); //$NON-NLS-1$
- }
- if (i != args.length - 1) {
- message.append(","); //$NON-NLS-1$
- }
- }
- }
- message.append(")"); //$NON-NLS-1$
- LogManager.log(level, loggingContext, message.toString());
- }
- try {
- Object result = method.invoke(instance, args);
- if (log) {
- LogManager.log(level, loggingContext,
- "after " + method.getName()+ " : "+result); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return result;
- } catch (InvocationTargetException e) {
- throw e.getTargetException();
- }
- }
- }
-
- static Logger logListener = new JavaLogger(); // either injected or manually set using the set methods
-
- /**
- * Send a critical message to the log. This level of message is generally
- * used to record an event or error that must be recorded (if any logging
- * is used). If it is used to record an error, it generally means that the
- * system encountered a critical error which affects the integrity, accuracy,
- * reliability and/or capability of the system.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param message the log message; the message is
- * not logged if this parameter is null
- */
- public static void logCritical(String context, String message) {
- logMessage(MessageLevel.CRITICAL, context, message);
- }
-
- /**
- * Send a critical message to the log. This level of message is generally
- * used to record an event or error that must be recorded (if any logging
- * is used). If it is used to record an error, it generally means that the
- * system encountered a critical error which affects the integrity, accuracy,
- * reliability and/or capability of the system.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param e the exception that is to be logged; the message is
- * not logged if this parameter is null
- * @param message the log message (may be null)
- */
- public static void logCritical(String context, Throwable e, String message) {
- log(MessageLevel.CRITICAL,context,e,message);
- }
-
- /**
- * Send an error message to the log. Error messages are generally used
- * to record unexpected problems, or errors that are not critical in nature
- * and from which the system can automatically recover.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param message the log message; the message is
- * not logged if this parameter is null
- */
- public static void logError(String context, String message) {
- logMessage(MessageLevel.ERROR, context,message);
- }
-
- /**
- * Send an error message to the log. Error messages are generally used
- * to record unexpected problems, or errors that are not critical in nature
- * and from which the system can automatically recover.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param e the exception that is to be logged; the message is
- * not logged if this parameter is null
- * @param message the log message (may be null)
- */
- public static void logError(String context, Throwable e, String message) {
- log(MessageLevel.ERROR,context,e,message);
- }
-
- /**
- * Send a warning message to the log. Warning messages generally described
- * expected errors from which the system should recover. However, this level
- * is used to record the fact that such an error or event did occur.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param message the log message; the message is
- * not logged if this parameter is null
- */
- public static void logWarning(String context, String message) {
- logMessage(MessageLevel.WARNING, context,message);
- }
-
- /**
- * Send a warning message to the log. Warning messages generally described
- * expected errors from which the system should recover. However, this level
- * is used to record the fact that such an error or event did occur.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param e the exception that is to be logged; the message is
- * not logged if this parameter is null
- * @param message the log message (may be null)
- */
- public static void logWarning(String context, Throwable e, String message) {
- log(MessageLevel.WARNING,context,e,message);
- }
-
- /**
- * Send a information message to the log. This level of logging is the usually
- * the normal level. All interesting periodic events should be logged at this
- * level so someone looking through the log can see the amount and kind of
- * processing happening in the system.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param message the log message; the message is
- * not logged if this parameter is null
- */
- public static void logInfo(String context, String message) {
- logMessage(MessageLevel.INFO, context,message);
- }
-
- /**
- * Send a detail message to the log. Such messages are moderately detailed,
- * and help to debug typical problems in the system. Generally, these
- * messages are not so detailed that the big picture gets lost.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param msgParts the individual parts of the log message; the message is
- * not logged if this parameter is null
- */
- public static void logDetail(String context, Object ... msgParts) {
- logMessage(MessageLevel.DETAIL, context, msgParts);
- }
-
- /**
- * Send a detail message to the log. Such messages are moderately detailed,
- * and help to debug typical problems in the system. Generally, these
- * messages are not so detailed that the big picture gets lost.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param e the exception that is to be logged; the message is
- * not logged if this parameter is null
- * @param message the log message (may be null)
- */
- public static void logDetail(String context, Throwable e, Object ... message) {
- log(MessageLevel.DETAIL,context,e,message);
- }
-
- /**
- * Send a trace message to the log. A trace message is the most detailed
- * logging level, used to trace system execution for really nasty problems.
- * At this level, logging will be so verbose that the system performance
- * may be affected.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param msgParts the individual parts of the log message; the message is
- * not logged if this parameter is null
- */
- public static void logTrace(String context, Object ... msgParts) {
- logMessage(MessageLevel.TRACE, context, msgParts);
- }
-
- /**
- * Send a trace message to the log. A trace message is the most detailed
- * logging level, used to trace system execution for really nasty problems.
- * At this level, logging will be so verbose that the system performance
- * may be affected.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param e the exception that is to be logged; the message is
- * not logged if this parameter is null
- * @param msgParts the individual parts of the log message (may be null)
- */
- public static void logTrace(String context, Throwable e, Object ... msgParts) {
- logMessage(MessageLevel.TRACE,context,e,msgParts);
- }
-
- /**
- * Send a message of the specified level to the log.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param msgLevel
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param message the individual parts of the log message; the message is
- * not logged if this parameter is null
- */
- public static void log(int msgLevel, String context, Object message) {
- logMessage(msgLevel, context, message);
- }
-
- /**
- * Send a message of the specified level to the log.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param e the exception that is to be logged; the message is
- * not logged if this parameter is null
- * @param message the individual parts of the log message; the message is
- * not logged if this parameter is null
- */
- public static void log(int msgLevel, String context, Throwable e, Object message) {
- if (!isMessageToBeRecorded(context, msgLevel)) {
- return;
- }
- logListener.log(msgLevel, context, e, message);
- }
-
- public static void setLogListener(Logger listener) {
- logListener.shutdown();
- if (listener != null) {
- logListener = listener;
- }
- else {
- logListener = new JavaLogger();
- }
- }
-
- /**
- * Utility method to identify whether a log message with the specified
- * context and level will be recorded in the LogManager's destinations.
- * @param context
- * @param msgLevel
- * @return true if the message would be recorded if sent to the LogManager,
- * or false if it would be discarded by the LogManager.
- */
- public static boolean isMessageToBeRecorded(String context, int msgLevel) {
- if (logListener != null) {
- return logListener.isEnabled(context, msgLevel);
- }
- return true;
- }
-
- private static void logMessage(int level, String context, Object ... msgParts) {
- if (msgParts == null || msgParts.length == 0 || !isMessageToBeRecorded(context, level)) {
- return;
- }
- logListener.log(level, context, new LogMessage(msgParts));
- }
-
-
- /**
- * Create a logging proxy, that logs at entry and exit points of the method calls on the provided interfaces.
- */
- public static Object createLoggingProxy(final String loggingContext,
- final Object instance,
- final Class<?>[] interfaces,
- final int level) {
- return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new LoggingProxy(instance, loggingContext, level));
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogManager.java (from rev 3218, trunk/api/src/main/java/org/teiid/logging/LogManager.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogManager.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogManager.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,402 @@
+/*
+ * 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.logging;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+
+
+
+/**
+ * This class represents the interface to a single logging framework
+ * that is easily accessible by any component. Using the LogManager, a component
+ * can quickly submit a log message, and can rely upon the LogManager to determine
+ * (a) whether that message is to be recorded or discarded; and (b) where
+ * to send any recorded messages. Thus, the component's code that submits
+ * messages does not have to be modified to alter the logging behavior of the
+ * application.
+ * <p>
+ * By default, all context(s) are logged by the LogManager. The messages that
+ * the LogManager actually records and sends to the destinations
+ * can be controlled using two different and orthogonal parameters.
+ * The first is a message <i>level</i> that filters messages based upon detail,
+ * and the second is a message <i>context</i> that filters messages based upon
+ * origin. The LogManager tracks only those context(s) that should NOT be
+ * logged. Only if a message (which also is defined with these two parameters)
+ * passes both filters will it be sent to the destinations.
+ * <p>
+ * Each message is submitted with one of the following levels (determined
+ * by the particular method used to submit the message), sorted from the
+ * least detailed to the greatest:
+ * <li><b>Critical</b>: This level of message is generally
+ * used to record an event or error that must be recorded (if any logging
+ * is used). If it is used to record an error, it generally means that the
+ * system encountered a critical error which affects the integrity, accuracy,
+ * reliability and/or capability of the system.</li>
+ * <li><b>Error</b>: Error messages are generally used
+ * to record unexpected problems, or errors that are not critical in nature
+ * and from which the system can automatically recover.</li>
+ * <li><b>Warning</b>: Warning messages generally described
+ * expected errors from which the system should recover. However, this level
+ * is used to record the fact that such an error or event did occur.</li>
+ * <li><b>Information</b>: This level of logging is the usually
+ * the normal level. All interesting periodic events should be logged at this
+ * level so someone looking through the log can see the amount and kind of
+ * processing happening in the system.</li>
+ * <li><b>Detail</b>: Such messages are moderately detailed,
+ * and help to debug typical problems in the system. Generally, these
+ * messages are not so detailed that the big picture gets lost.</li>
+ * <li><b>Trace</b>: A trace message is the most detailed
+ * logging level, used to trace system execution for really nasty problems.
+ * At this level, logging will be so verbose that the system performance
+ * may be affected.</li>
+ * <p>
+ * The context for a message is any application-specified String. Again, only
+ * those message contexts that match those in the LogManager's configuration will
+ * be sent to the destinations.
+ *
+ */
+public final class LogManager {
+
+ public static class LoggingProxy implements InvocationHandler {
+ private final Object instance;
+ private final String loggingContext;
+ private final int level;
+
+ public LoggingProxy(Object instance, String loggingContext, int level) {
+ this.instance = instance;
+ this.loggingContext = loggingContext;
+ this.level = level;
+ }
+
+ public Object invoke(Object proxy,
+ Method method,
+ Object[] args) throws Throwable {
+ boolean log = LogManager.isMessageToBeRecorded(loggingContext, level);
+ if (log) {
+ StringBuffer message = new StringBuffer();
+ message.append("before "); //$NON-NLS-1$
+ message.append(method.getName());
+ message.append(":"); //$NON-NLS-1$
+ message.append(instance);
+ message.append("("); //$NON-NLS-1$
+ if (args != null) {
+ for (int i = 0; i < args.length; i++) {
+ if (args[i] != null) {
+ message.append(args[i]);
+ } else {
+ message.append("null"); //$NON-NLS-1$
+ }
+ if (i != args.length - 1) {
+ message.append(","); //$NON-NLS-1$
+ }
+ }
+ }
+ message.append(")"); //$NON-NLS-1$
+ LogManager.log(level, loggingContext, message.toString());
+ }
+ try {
+ Object result = method.invoke(instance, args);
+ if (log) {
+ LogManager.log(level, loggingContext,
+ "after " + method.getName()+ " : "+result); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return result;
+ } catch (InvocationTargetException e) {
+ throw e.getTargetException();
+ }
+ }
+ }
+
+ static Logger logListener = new JavaLogger(); // either injected or manually set using the set methods
+
+ /**
+ * Send a critical message to the log. This level of message is generally
+ * used to record an event or error that must be recorded (if any logging
+ * is used). If it is used to record an error, it generally means that the
+ * system encountered a critical error which affects the integrity, accuracy,
+ * reliability and/or capability of the system.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param message the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void logCritical(String context, String message) {
+ logMessage(MessageLevel.CRITICAL, context, message);
+ }
+
+ /**
+ * Send a critical message to the log. This level of message is generally
+ * used to record an event or error that must be recorded (if any logging
+ * is used). If it is used to record an error, it generally means that the
+ * system encountered a critical error which affects the integrity, accuracy,
+ * reliability and/or capability of the system.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param e the exception that is to be logged; the message is
+ * not logged if this parameter is null
+ * @param message the log message (may be null)
+ */
+ public static void logCritical(String context, Throwable e, String message) {
+ log(MessageLevel.CRITICAL,context,e,message);
+ }
+
+ /**
+ * Send an error message to the log. Error messages are generally used
+ * to record unexpected problems, or errors that are not critical in nature
+ * and from which the system can automatically recover.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param message the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void logError(String context, String message) {
+ logMessage(MessageLevel.ERROR, context,message);
+ }
+
+ /**
+ * Send an error message to the log. Error messages are generally used
+ * to record unexpected problems, or errors that are not critical in nature
+ * and from which the system can automatically recover.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param e the exception that is to be logged; the message is
+ * not logged if this parameter is null
+ * @param message the log message (may be null)
+ */
+ public static void logError(String context, Throwable e, String message) {
+ log(MessageLevel.ERROR,context,e,message);
+ }
+
+ /**
+ * Send a warning message to the log. Warning messages generally described
+ * expected errors from which the system should recover. However, this level
+ * is used to record the fact that such an error or event did occur.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param message the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void logWarning(String context, String message) {
+ logMessage(MessageLevel.WARNING, context,message);
+ }
+
+ /**
+ * Send a warning message to the log. Warning messages generally described
+ * expected errors from which the system should recover. However, this level
+ * is used to record the fact that such an error or event did occur.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param e the exception that is to be logged; the message is
+ * not logged if this parameter is null
+ * @param message the log message (may be null)
+ */
+ public static void logWarning(String context, Throwable e, String message) {
+ log(MessageLevel.WARNING,context,e,message);
+ }
+
+ /**
+ * Send a information message to the log. This level of logging is the usually
+ * the normal level. All interesting periodic events should be logged at this
+ * level so someone looking through the log can see the amount and kind of
+ * processing happening in the system.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param message the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void logInfo(String context, String message) {
+ logMessage(MessageLevel.INFO, context,message);
+ }
+
+ /**
+ * Send a detail message to the log. Such messages are moderately detailed,
+ * and help to debug typical problems in the system. Generally, these
+ * messages are not so detailed that the big picture gets lost.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param msgParts the individual parts of the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void logDetail(String context, Object ... msgParts) {
+ logMessage(MessageLevel.DETAIL, context, msgParts);
+ }
+
+ /**
+ * Send a detail message to the log. Such messages are moderately detailed,
+ * and help to debug typical problems in the system. Generally, these
+ * messages are not so detailed that the big picture gets lost.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param e the exception that is to be logged; the message is
+ * not logged if this parameter is null
+ * @param message the log message (may be null)
+ */
+ public static void logDetail(String context, Throwable e, Object ... message) {
+ log(MessageLevel.DETAIL,context,e,message);
+ }
+
+ /**
+ * Send a trace message to the log. A trace message is the most detailed
+ * logging level, used to trace system execution for really nasty problems.
+ * At this level, logging will be so verbose that the system performance
+ * may be affected.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param msgParts the individual parts of the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void logTrace(String context, Object ... msgParts) {
+ logMessage(MessageLevel.TRACE, context, msgParts);
+ }
+
+ /**
+ * Send a trace message to the log. A trace message is the most detailed
+ * logging level, used to trace system execution for really nasty problems.
+ * At this level, logging will be so verbose that the system performance
+ * may be affected.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param e the exception that is to be logged; the message is
+ * not logged if this parameter is null
+ * @param msgParts the individual parts of the log message (may be null)
+ */
+ public static void logTrace(String context, Throwable e, Object ... msgParts) {
+ logMessage(MessageLevel.TRACE,context,e,msgParts);
+ }
+
+ /**
+ * Send a message of the specified level to the log.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param msgLevel
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param message the individual parts of the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void log(int msgLevel, String context, Object message) {
+ logMessage(msgLevel, context, message);
+ }
+
+ /**
+ * Send a message of the specified level to the log.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param e the exception that is to be logged; the message is
+ * not logged if this parameter is null
+ * @param message the individual parts of the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void log(int msgLevel, String context, Throwable e, Object message) {
+ if (!isMessageToBeRecorded(context, msgLevel)) {
+ return;
+ }
+ if (message != null && message.getClass().isArray()) {
+ message = new LogMessage((Object[]) message);
+ }
+ logListener.log(msgLevel, context, e, message);
+ }
+
+ public static void setLogListener(Logger listener) {
+ logListener.shutdown();
+ if (listener != null) {
+ logListener = listener;
+ }
+ else {
+ logListener = new JavaLogger();
+ }
+ }
+
+ /**
+ * Utility method to identify whether a log message with the specified
+ * context and level will be recorded in the LogManager's destinations.
+ * @param context
+ * @param msgLevel
+ * @return true if the message would be recorded if sent to the LogManager,
+ * or false if it would be discarded by the LogManager.
+ */
+ public static boolean isMessageToBeRecorded(String context, int msgLevel) {
+ if (logListener != null) {
+ return logListener.isEnabled(context, msgLevel);
+ }
+ return true;
+ }
+
+ private static void logMessage(int level, String context, Object ... msgParts) {
+ if (msgParts == null || msgParts.length == 0 || !isMessageToBeRecorded(context, level)) {
+ return;
+ }
+ logListener.log(level, context, msgParts.length == 1? msgParts[0] : new LogMessage(msgParts));
+ }
+
+
+ /**
+ * Create a logging proxy, that logs at entry and exit points of the method calls on the provided interfaces.
+ */
+ public static Object createLoggingProxy(final String loggingContext,
+ final Object instance,
+ final Class<?>[] interfaces,
+ final int level) {
+ return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new LoggingProxy(instance, loggingContext, level));
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogMessage.java
===================================================================
--- trunk/api/src/main/java/org/teiid/logging/LogMessage.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogMessage.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,62 +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.logging;
-
-import java.io.Serializable;
-
-
-public class LogMessage implements Serializable{
-
- private Object[] msgParts;
-
- public LogMessage(Object[] msgParts) {
- this.msgParts = msgParts;
- }
-
- public Object[] getMessageParts() {
- return this.msgParts;
- }
-
- public String getText() {
- StringBuffer text = null;
- if(msgParts != null) {
- text = new StringBuffer();
- for(int i=0; i<msgParts.length; i++) {
- if (i>0) text.append(" "); //$NON-NLS-1$
- Object omsg = msgParts[i];
- if ( omsg != null ) {
- text.append(omsg.toString());
- }
- }
- }
-
- if (text == null) {
- return "NULL"; //$NON-NLS-1$
- }
- return text.toString();
- }
-
- public String toString() {
- return getText();
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogMessage.java (from rev 3218, trunk/api/src/main/java/org/teiid/logging/LogMessage.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogMessage.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/logging/LogMessage.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,64 @@
+/*
+ * 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.logging;
+
+import java.io.Serializable;
+
+
+public class LogMessage implements Serializable{
+
+ private static final long serialVersionUID = -134503344442009940L;
+
+ private Object[] msgParts;
+
+ public LogMessage(Object[] msgParts) {
+ this.msgParts = msgParts;
+ }
+
+ public Object[] getMessageParts() {
+ return this.msgParts;
+ }
+
+ public String getText() {
+ StringBuffer text = null;
+ if(msgParts != null) {
+ text = new StringBuffer();
+ for(int i=0; i<msgParts.length; i++) {
+ if (i>0) text.append(" "); //$NON-NLS-1$
+ Object omsg = msgParts[i];
+ if ( omsg != null ) {
+ text.append(omsg.toString());
+ }
+ }
+ }
+
+ if (text == null) {
+ return "NULL"; //$NON-NLS-1$
+ }
+ return text.toString();
+ }
+
+ public String toString() {
+ return getText();
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/metadata/Table.java
===================================================================
--- trunk/api/src/main/java/org/teiid/metadata/Table.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/metadata/Table.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,336 +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.metadata;
-
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.metadata.AbstractMetadataRecord.DataModifiable;
-import org.teiid.metadata.AbstractMetadataRecord.Modifiable;
-
-public class Table extends ColumnSet<Schema> implements Modifiable, DataModifiable {
-
- private static final long serialVersionUID = 4891356771125218672L;
-
- public enum Type {
- Table,
- View,
- Document,
- XmlMappingClass,
- XmlStagingTable,
- MaterializedTable
- }
-
- public static enum TriggerEvent {
- INSERT,
- UPDATE,
- DELETE
- }
-
- private int cardinality;
- private Type tableType;
- private boolean isVirtual;
- private boolean isSystem;
- private boolean isMaterialized;
- private boolean supportsUpdate;
- private List<ForeignKey> foriegnKeys = new LinkedList<ForeignKey>();
- private List<KeyRecord> indexes = new LinkedList<KeyRecord>();
- private List<KeyRecord> uniqueKeys = new LinkedList<KeyRecord>();
- private List<KeyRecord> accessPatterns = new LinkedList<KeyRecord>();
- private KeyRecord primaryKey;
-
- //view information
- private String selectTransformation;
- private String insertPlan;
- private String updatePlan;
- private String deletePlan;
- private boolean insertPlanEnabled;
- private boolean updatePlanEnabled;
- private boolean deletePlanEnabled;
- private Table materializedStageTable;
- private Table materializedTable;
-
- //XML specific
- private List<String> bindings;
- private List<String> schemaPaths;
- private String resourcePath;
-
- private transient long lastModified;
- private transient long lastDataModification;
-
- public List<String> getBindings() {
- return bindings;
- }
-
- public void setBindings(List<String> bindings) {
- this.bindings = bindings;
- }
-
- public List<String> getSchemaPaths() {
- return schemaPaths;
- }
-
- public void setSchemaPaths(List<String> schemaPaths) {
- this.schemaPaths = schemaPaths;
- }
-
- public int getCardinality() {
- return cardinality;
- }
-
- public boolean isVirtual() {
- return isVirtual;
- }
-
- public boolean isMaterialized() {
- return isMaterialized;
- }
-
- public boolean isPhysical() {
- return !isVirtual();
- }
-
- public boolean isSystem() {
- return isSystem;
- }
-
- public Type getTableType() {
- if (tableType == null) {
- return Type.Table;
- }
- return tableType;
- }
-
- public boolean supportsUpdate() {
- return supportsUpdate;
- }
-
- /**
- * @param i
- */
- public void setCardinality(int i) {
- cardinality = i;
- }
-
- /**
- * @param i
- */
- public void setTableType(Type i) {
- tableType = i;
- }
-
- /**
- * @param b
- */
- public void setSupportsUpdate(boolean b) {
- supportsUpdate = b;
- }
-
- /**
- * @param b
- */
- public void setVirtual(boolean b) {
- isVirtual = b;
- }
-
- /**
- * @param isMaterialized The isMaterialized to set.
- * @since 4.2
- */
- public void setMaterialized(boolean isMaterialized) {
- this.isMaterialized = isMaterialized;
- }
-
- /**
- * @param b
- */
- public void setSystem(boolean b) {
- isSystem = b;
- }
-
- public String getInsertPlan() {
- return insertPlan;
- }
-
- public String getUpdatePlan() {
- return updatePlan;
- }
-
- public String getDeletePlan() {
- return deletePlan;
- }
-
- public void setInsertPlan(String insertPlan) {
- this.insertPlan = DataTypeManager.getCanonicalString(insertPlan);
- this.insertPlanEnabled = true;
- }
-
- public void setUpdatePlan(String updatePlan) {
- this.updatePlan = DataTypeManager.getCanonicalString(updatePlan);
- this.updatePlanEnabled = true;
- }
-
- public void setDeletePlan(String deletePlan) {
- this.deletePlan = DataTypeManager.getCanonicalString(deletePlan);
- this.deletePlanEnabled = true;
- }
-
- public List<ForeignKey> getForeignKeys() {
- return this.foriegnKeys;
- }
-
- public void setForiegnKeys(List<ForeignKey> foriegnKeys) {
- this.foriegnKeys = foriegnKeys;
- }
-
- public List<KeyRecord> getIndexes() {
- return this.indexes;
- }
-
- public void setIndexes(List<KeyRecord> indexes) {
- this.indexes = indexes;
- }
-
- public List<KeyRecord> getUniqueKeys() {
- return this.uniqueKeys;
- }
-
- public void setUniqueKeys(List<KeyRecord> uniqueKeys) {
- this.uniqueKeys = uniqueKeys;
- }
-
- public List<KeyRecord> getAccessPatterns() {
- return this.accessPatterns;
- }
-
- public void setAccessPatterns(List<KeyRecord> accessPatterns) {
- this.accessPatterns = accessPatterns;
- }
-
- public KeyRecord getPrimaryKey() {
- return this.primaryKey;
- }
-
- public void setPrimaryKey(KeyRecord primaryKey) {
- this.primaryKey = primaryKey;
- }
-
- public String getSelectTransformation() {
- return selectTransformation;
- }
-
- public void setSelectTransformation(String selectTransformation) {
- this.selectTransformation = DataTypeManager.getCanonicalString(selectTransformation);
- }
-
- public Table getMaterializedStageTable() {
- return materializedStageTable;
- }
-
- public Table getMaterializedTable() {
- return materializedTable;
- }
-
- public void setMaterializedStageTable(Table materializedStageTable) {
- this.materializedStageTable = materializedStageTable;
- }
-
- public void setMaterializedTable(Table materializedTable) {
- this.materializedTable = materializedTable;
- }
-
- public void setResourcePath(String resourcePath) {
- this.resourcePath = DataTypeManager.getCanonicalString(resourcePath);
- }
-
- public String getResourcePath() {
- return resourcePath;
- }
-
- public Collection<KeyRecord> getAllKeys() {
- Collection<KeyRecord> keys = new LinkedList<KeyRecord>();
- if (getPrimaryKey() != null) {
- keys.add(getPrimaryKey());
- }
- keys.addAll(getForeignKeys());
- keys.addAll(getAccessPatterns());
- keys.addAll(getIndexes());
- keys.addAll(getUniqueKeys());
- return keys;
- }
-
- @Override
- public void addColumn(Column column) {
- super.addColumn(column);
- column.setParent(this);
- }
-
- public long getLastDataModification() {
- return lastDataModification;
- }
-
- public long getLastModified() {
- return lastModified;
- }
-
- public void setLastDataModification(long lastDataModification) {
- this.lastDataModification = lastDataModification;
- }
-
- public void setLastModified(long lastModified) {
- this.lastModified = lastModified;
- }
-
- public void setTableStats(TableStats stats) {
- if (stats.getCardinality() != null) {
- setCardinality(stats.getCardinality());
- }
- }
-
- public boolean isDeletePlanEnabled() {
- return deletePlanEnabled;
- }
-
- public boolean isInsertPlanEnabled() {
- return insertPlanEnabled;
- }
-
- public boolean isUpdatePlanEnabled() {
- return updatePlanEnabled;
- }
-
- public void setInsertPlanEnabled(boolean insertPlanEnabled) {
- this.insertPlanEnabled = insertPlanEnabled;
- }
-
- public void setDeletePlanEnabled(boolean deletePlanEnabled) {
- this.deletePlanEnabled = deletePlanEnabled;
- }
-
- public void setUpdatePlanEnabled(boolean updatePlanEnabled) {
- this.updatePlanEnabled = updatePlanEnabled;
- }
-
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/metadata/Table.java (from rev 3218, trunk/api/src/main/java/org/teiid/metadata/Table.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/metadata/Table.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/metadata/Table.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.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;
+import org.teiid.metadata.AbstractMetadataRecord.Modifiable;
+
+public class Table extends ColumnSet<Schema> implements Modifiable, DataModifiable {
+
+ private static final long serialVersionUID = 4891356771125218672L;
+
+ public enum Type {
+ Table,
+ View,
+ Document,
+ XmlMappingClass,
+ XmlStagingTable,
+ MaterializedTable
+ }
+
+ public static enum TriggerEvent {
+ INSERT,
+ UPDATE,
+ DELETE
+ }
+
+ private int cardinality;
+ private Type tableType;
+ private boolean isVirtual;
+ private boolean isSystem;
+ private boolean isMaterialized;
+ private boolean supportsUpdate;
+ private List<ForeignKey> foriegnKeys = new LinkedList<ForeignKey>();
+ private List<KeyRecord> indexes = new LinkedList<KeyRecord>();
+ private List<KeyRecord> uniqueKeys = new LinkedList<KeyRecord>();
+ private List<KeyRecord> accessPatterns = new LinkedList<KeyRecord>();
+ private KeyRecord primaryKey;
+
+ //view information
+ private String selectTransformation;
+ private String insertPlan;
+ private String updatePlan;
+ private String deletePlan;
+ private boolean insertPlanEnabled;
+ private boolean updatePlanEnabled;
+ private boolean deletePlanEnabled;
+ private Table materializedStageTable;
+ private Table materializedTable;
+
+ //XML specific
+ private List<String> bindings;
+ private List<String> schemaPaths;
+ private String resourcePath;
+
+ private transient long lastModified;
+ private transient long lastDataModification;
+
+ private transient Map<Class<?>, Object> attachments;
+
+ public List<String> getBindings() {
+ return bindings;
+ }
+
+ public void setBindings(List<String> bindings) {
+ this.bindings = bindings;
+ }
+
+ public List<String> getSchemaPaths() {
+ return schemaPaths;
+ }
+
+ public void setSchemaPaths(List<String> schemaPaths) {
+ this.schemaPaths = schemaPaths;
+ }
+
+ public int getCardinality() {
+ return cardinality;
+ }
+
+ public boolean isVirtual() {
+ return isVirtual;
+ }
+
+ public boolean isMaterialized() {
+ return isMaterialized;
+ }
+
+ public boolean isPhysical() {
+ return !isVirtual();
+ }
+
+ public boolean isSystem() {
+ return isSystem;
+ }
+
+ public Type getTableType() {
+ if (tableType == null) {
+ return Type.Table;
+ }
+ return tableType;
+ }
+
+ public boolean supportsUpdate() {
+ return supportsUpdate;
+ }
+
+ /**
+ * @param i
+ */
+ public void setCardinality(int i) {
+ cardinality = i;
+ }
+
+ /**
+ * @param i
+ */
+ public void setTableType(Type i) {
+ tableType = i;
+ }
+
+ /**
+ * @param b
+ */
+ public void setSupportsUpdate(boolean b) {
+ supportsUpdate = b;
+ }
+
+ /**
+ * @param b
+ */
+ public void setVirtual(boolean b) {
+ isVirtual = b;
+ }
+
+ /**
+ * @param isMaterialized The isMaterialized to set.
+ * @since 4.2
+ */
+ public void setMaterialized(boolean isMaterialized) {
+ this.isMaterialized = isMaterialized;
+ }
+
+ /**
+ * @param b
+ */
+ public void setSystem(boolean b) {
+ isSystem = b;
+ }
+
+ public String getInsertPlan() {
+ return insertPlan;
+ }
+
+ public String getUpdatePlan() {
+ return updatePlan;
+ }
+
+ public String getDeletePlan() {
+ return deletePlan;
+ }
+
+ public void setInsertPlan(String insertPlan) {
+ this.insertPlan = DataTypeManager.getCanonicalString(insertPlan);
+ this.insertPlanEnabled = true;
+ }
+
+ public void setUpdatePlan(String updatePlan) {
+ this.updatePlan = DataTypeManager.getCanonicalString(updatePlan);
+ this.updatePlanEnabled = true;
+ }
+
+ public void setDeletePlan(String deletePlan) {
+ this.deletePlan = DataTypeManager.getCanonicalString(deletePlan);
+ this.deletePlanEnabled = true;
+ }
+
+ public List<ForeignKey> getForeignKeys() {
+ return this.foriegnKeys;
+ }
+
+ public void setForiegnKeys(List<ForeignKey> foriegnKeys) {
+ this.foriegnKeys = foriegnKeys;
+ }
+
+ public List<KeyRecord> getIndexes() {
+ return this.indexes;
+ }
+
+ public void setIndexes(List<KeyRecord> indexes) {
+ this.indexes = indexes;
+ }
+
+ public List<KeyRecord> getUniqueKeys() {
+ return this.uniqueKeys;
+ }
+
+ public void setUniqueKeys(List<KeyRecord> uniqueKeys) {
+ this.uniqueKeys = uniqueKeys;
+ }
+
+ public List<KeyRecord> getAccessPatterns() {
+ return this.accessPatterns;
+ }
+
+ public void setAccessPatterns(List<KeyRecord> accessPatterns) {
+ this.accessPatterns = accessPatterns;
+ }
+
+ public KeyRecord getPrimaryKey() {
+ return this.primaryKey;
+ }
+
+ public void setPrimaryKey(KeyRecord primaryKey) {
+ this.primaryKey = primaryKey;
+ }
+
+ public String getSelectTransformation() {
+ return selectTransformation;
+ }
+
+ public void setSelectTransformation(String selectTransformation) {
+ this.selectTransformation = DataTypeManager.getCanonicalString(selectTransformation);
+ }
+
+ public Table getMaterializedStageTable() {
+ return materializedStageTable;
+ }
+
+ public Table getMaterializedTable() {
+ return materializedTable;
+ }
+
+ public void setMaterializedStageTable(Table materializedStageTable) {
+ this.materializedStageTable = materializedStageTable;
+ }
+
+ public void setMaterializedTable(Table materializedTable) {
+ this.materializedTable = materializedTable;
+ }
+
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = DataTypeManager.getCanonicalString(resourcePath);
+ }
+
+ public String getResourcePath() {
+ return resourcePath;
+ }
+
+ public Collection<KeyRecord> getAllKeys() {
+ Collection<KeyRecord> keys = new LinkedList<KeyRecord>();
+ if (getPrimaryKey() != null) {
+ keys.add(getPrimaryKey());
+ }
+ keys.addAll(getForeignKeys());
+ keys.addAll(getAccessPatterns());
+ keys.addAll(getIndexes());
+ keys.addAll(getUniqueKeys());
+ return keys;
+ }
+
+ @Override
+ public void addColumn(Column column) {
+ super.addColumn(column);
+ column.setParent(this);
+ }
+
+ public long getLastDataModification() {
+ return lastDataModification;
+ }
+
+ public long getLastModified() {
+ return lastModified;
+ }
+
+ public void setLastDataModification(long lastDataModification) {
+ this.lastDataModification = lastDataModification;
+ }
+
+ public void setLastModified(long lastModified) {
+ this.lastModified = lastModified;
+ }
+
+ public void setTableStats(TableStats stats) {
+ if (stats.getCardinality() != null) {
+ setCardinality(stats.getCardinality());
+ }
+ }
+
+ public boolean isDeletePlanEnabled() {
+ return deletePlanEnabled;
+ }
+
+ public boolean isInsertPlanEnabled() {
+ return insertPlanEnabled;
+ }
+
+ public boolean isUpdatePlanEnabled() {
+ return updatePlanEnabled;
+ }
+
+ public void setInsertPlanEnabled(boolean insertPlanEnabled) {
+ this.insertPlanEnabled = insertPlanEnabled;
+ }
+
+ public void setDeletePlanEnabled(boolean deletePlanEnabled) {
+ this.deletePlanEnabled = deletePlanEnabled;
+ }
+
+ public void setUpdatePlanEnabled(boolean updatePlanEnabled) {
+ 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
Deleted: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/BaseDelegatingExecutionFactory.java
===================================================================
--- trunk/api/src/main/java/org/teiid/translator/BaseDelegatingExecutionFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/BaseDelegatingExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,351 +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;
-
-import java.util.List;
-
-import org.teiid.language.Call;
-import org.teiid.language.Command;
-import org.teiid.language.LanguageFactory;
-import org.teiid.language.QueryExpression;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.MetadataFactory;
-import org.teiid.metadata.RuntimeMetadata;
-
-/**
- * Delegate translator. User can define a {@link ExecutionFactory} of their own and have this translator
- * delegate all the calls to that class. Please note that your 'vdb.xml' file will contain
- * an xml fragment like the following to configure a delegating translator.
- * <pre>
- * {@code
- <translator type="delegate" name="my-translator" description="custom translator">
- <property value="delegateName" name="name of the delegate instance"/>
- </translator>
- }
- * </pre>
- *
- */
-public class BaseDelegatingExecutionFactory<F, C> extends ExecutionFactory<F, C> implements DelegatingExecutionFactory<F, C> {
-
- private String delegateName;
- private ExecutionFactory<F, C> delegate;
-
- /**
- * For testing only
- */
- ExecutionFactory<F, C> getDelegate() {
- return this.delegate;
- }
-
- public void setDelegate(ExecutionFactory<F, C> delegate) {
- this.delegate = delegate;
- }
-
- @TranslatorProperty(display="Delegate name", required = true)
- public String getDelegateName() {
- return this.delegateName;
- }
-
- public void setDelegateName(String delegateName) {
- this.delegateName = delegateName;
- }
-
- @Override
- public void start() throws TranslatorException {
- this.delegate.start();
- }
-
- @Override
- public boolean areLobsUsableAfterClose() {
- return delegate.areLobsUsableAfterClose();
- }
- @Override
- public void closeConnection(C connection, F factory) {
- delegate.closeConnection(connection, factory);
- }
- @Override
- public Execution createExecution(Command command,
- ExecutionContext executionContext, RuntimeMetadata metadata,
- C connection) throws TranslatorException {
- return delegate.createExecution(command, executionContext, metadata,
- connection);
- }
- @Override
- public ProcedureExecution createProcedureExecution(Call command,
- ExecutionContext executionContext, RuntimeMetadata metadata,
- C connection) throws TranslatorException {
- return delegate.createProcedureExecution(command, executionContext,
- metadata, connection);
- }
- @Override
- public ResultSetExecution createResultSetExecution(QueryExpression command,
- ExecutionContext executionContext, RuntimeMetadata metadata,
- C connection) throws TranslatorException {
- return delegate.createResultSetExecution(command, executionContext,
- metadata, connection);
- }
- @Override
- public UpdateExecution createUpdateExecution(Command command,
- ExecutionContext executionContext, RuntimeMetadata metadata,
- C connection) throws TranslatorException {
- return delegate.createUpdateExecution(command, executionContext,
- metadata, connection);
- }
- @Override
- public C getConnection(F factory) throws TranslatorException {
- return delegate.getConnection(factory);
- }
- @Override
- public NullOrder getDefaultNullOrder() {
- return delegate.getDefaultNullOrder();
- }
- @Override
- public LanguageFactory getLanguageFactory() {
- return delegate.getLanguageFactory();
- }
- @Override
- public int getMaxFromGroups() {
- return delegate.getMaxFromGroups();
- }
- @Override
- public void getMetadata(MetadataFactory metadataFactory, C conn)
- throws TranslatorException {
- delegate.getMetadata(metadataFactory, conn);
- }
- @Override
- public List<FunctionMethod> getPushDownFunctions() {
- return delegate.getPushDownFunctions();
- }
- @Override
- public List<String> getSupportedFunctions() {
- return delegate.getSupportedFunctions();
- }
- @Override
- public TypeFacility getTypeFacility() {
- return delegate.getTypeFacility();
- }
- @Override
- public boolean isImmutable() {
- return delegate.isImmutable();
- }
- @Override
- public boolean isSourceRequired() {
- return delegate.isSourceRequired();
- }
- @Override
- public boolean supportsAggregatesAvg() {
- return delegate.supportsAggregatesAvg();
- }
- @Override
- public boolean supportsAggregatesCount() {
- return delegate.supportsAggregatesCount();
- }
- @Override
- public boolean supportsAggregatesCountStar() {
- return delegate.supportsAggregatesCountStar();
- }
- @Override
- public boolean supportsAggregatesDistinct() {
- return delegate.supportsAggregatesDistinct();
- }
- @Override
- public boolean supportsAggregatesEnhancedNumeric() {
- return delegate.supportsAggregatesEnhancedNumeric();
- }
- @Override
- public boolean supportsAggregatesMax() {
- return delegate.supportsAggregatesMax();
- }
- @Override
- public boolean supportsAggregatesMin() {
- return delegate.supportsAggregatesMin();
- }
- @Override
- public boolean supportsAggregatesSum() {
- return delegate.supportsAggregatesSum();
- }
- @Override
- public boolean supportsAliasedTable() {
- return delegate.supportsAliasedTable();
- }
- @Override
- public boolean supportsBatchedUpdates() {
- return delegate.supportsBatchedUpdates();
- }
- @Override
- public boolean supportsBetweenCriteria() {
- return delegate.supportsBetweenCriteria();
- }
- @Override
- public boolean supportsBulkUpdate() {
- return delegate.supportsBulkUpdate();
- }
- @Override
- public boolean supportsCaseExpressions() {
- return delegate.supportsCaseExpressions();
- }
- @Override
- public boolean supportsCommonTableExpressions() {
- return delegate.supportsCommonTableExpressions();
- }
- @Override
- public boolean supportsCompareCriteriaEquals() {
- return delegate.supportsCompareCriteriaEquals();
- }
- @Override
- public boolean supportsCompareCriteriaOrdered() {
- return delegate.supportsCompareCriteriaOrdered();
- }
- @Override
- public boolean supportsCorrelatedSubqueries() {
- return delegate.supportsCorrelatedSubqueries();
- }
- @Override
- public boolean supportsExcept() {
- return delegate.supportsExcept();
- }
- @Override
- public boolean supportsExistsCriteria() {
- return delegate.supportsExistsCriteria();
- }
- @Override
- public boolean supportsFunctionsInGroupBy() {
- return delegate.supportsFunctionsInGroupBy();
- }
- @Override
- public boolean supportsGroupBy() {
- return delegate.supportsGroupBy();
- }
- @Override
- public boolean supportsHaving() {
- return delegate.supportsHaving();
- }
- @Override
- public boolean supportsInCriteria() {
- return delegate.supportsInCriteria();
- }
- @Override
- public boolean supportsInCriteriaSubquery() {
- return delegate.supportsInCriteriaSubquery();
- }
- @Override
- public boolean supportsInlineViews() {
- return delegate.supportsInlineViews();
- }
- @Override
- public boolean supportsInsertWithIterator() {
- return delegate.supportsInsertWithIterator();
- }
- @Override
- public boolean supportsInsertWithQueryExpression() {
- return delegate.supportsInsertWithQueryExpression();
- }
- @Override
- public boolean supportsIntersect() {
- return delegate.supportsIntersect();
- }
- @Override
- public boolean supportsIsNullCriteria() {
- return delegate.supportsIsNullCriteria();
- }
- @Override
- public boolean supportsLikeCriteria() {
- return delegate.supportsLikeCriteria();
- }
- @Override
- public boolean supportsLikeCriteriaEscapeCharacter() {
- return delegate.supportsLikeCriteriaEscapeCharacter();
- }
- @Override
- public boolean supportsNotCriteria() {
- return delegate.supportsNotCriteria();
- }
- @Override
- public boolean supportsOrCriteria() {
- return delegate.supportsOrCriteria();
- }
- @Override
- public boolean supportsOrderByNullOrdering() {
- return delegate.supportsOrderByNullOrdering();
- }
- @Override
- public boolean supportsOrderByUnrelated() {
- return delegate.supportsOrderByUnrelated();
- }
- @Override
- public boolean supportsQuantifiedCompareCriteriaAll() {
- return delegate.supportsQuantifiedCompareCriteriaAll();
- }
- @Override
- public boolean supportsQuantifiedCompareCriteriaSome() {
- return delegate.supportsQuantifiedCompareCriteriaSome();
- }
- @Override
- public boolean supportsRowLimit() {
- return delegate.supportsRowLimit();
- }
- @Override
- public boolean supportsRowOffset() {
- return delegate.supportsRowOffset();
- }
- @Override
- public boolean supportsScalarSubqueries() {
- return delegate.supportsScalarSubqueries();
- }
- @Override
- public boolean supportsSearchedCaseExpressions() {
- return delegate.supportsSearchedCaseExpressions();
- }
- @Override
- public boolean supportsSelectExpression() {
- return delegate.supportsSelectExpression();
- }
- @Override
- public boolean supportsSelfJoins() {
- return delegate.supportsSelfJoins();
- }
- @Override
- public boolean supportsSetQueryOrderBy() {
- return delegate.supportsSetQueryOrderBy();
- }
- @Override
- public boolean supportsUnions() {
- return delegate.supportsUnions();
- }
- @Override
- public String toString() {
- return delegate.toString();
- }
- @Override
- public boolean useAnsiJoin() {
- return delegate.useAnsiJoin();
- }
- @Override
- public boolean equals(Object obj) {
- return delegate.equals(obj);
- }
- @Override
- public int hashCode() {
- return delegate.hashCode();
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/BaseDelegatingExecutionFactory.java (from rev 3218, trunk/api/src/main/java/org/teiid/translator/BaseDelegatingExecutionFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/BaseDelegatingExecutionFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/BaseDelegatingExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,350 @@
+/*
+ * 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;
+
+import java.util.List;
+
+import org.teiid.language.Call;
+import org.teiid.language.Command;
+import org.teiid.language.LanguageFactory;
+import org.teiid.language.QueryExpression;
+import org.teiid.metadata.FunctionMethod;
+import org.teiid.metadata.MetadataFactory;
+import org.teiid.metadata.RuntimeMetadata;
+
+/**
+ * Delegate translator. User can define a {@link ExecutionFactory} of their own and have this translator
+ * delegate all the calls to that class. Please note that your 'vdb.xml' file will contain
+ * an xml fragment like the following to configure a delegating translator.
+ * <pre>
+ * {@code
+ <translator type="delegate" name="my-translator" description="custom translator">
+ <property value="delegateName" name="name of the delegate instance"/>
+ </translator>
+ }
+ * </pre>
+ *
+ */
+public class BaseDelegatingExecutionFactory<F, C> extends ExecutionFactory<F, C> implements DelegatingExecutionFactory<F, C> {
+
+ private String delegateName;
+ private ExecutionFactory<F, C> delegate;
+
+ /**
+ * For testing only
+ */
+ ExecutionFactory<F, C> getDelegate() {
+ return this.delegate;
+ }
+
+ public void setDelegate(ExecutionFactory<F, C> delegate) {
+ this.delegate = delegate;
+ }
+
+ @TranslatorProperty(display="Delegate name", required = true)
+ public String getDelegateName() {
+ return this.delegateName;
+ }
+
+ public void setDelegateName(String delegateName) {
+ this.delegateName = delegateName;
+ }
+
+ @Override
+ public void start() throws TranslatorException {
+ this.delegate.start();
+ }
+
+ @Override
+ public boolean areLobsUsableAfterClose() {
+ return delegate.areLobsUsableAfterClose();
+ }
+ @Override
+ public void closeConnection(C connection, F factory) {
+ delegate.closeConnection(connection, factory);
+ }
+ @Override
+ public Execution createExecution(Command command,
+ ExecutionContext executionContext, RuntimeMetadata metadata,
+ C connection) throws TranslatorException {
+ return delegate.createExecution(command, executionContext, metadata,
+ connection);
+ }
+ @Override
+ public ProcedureExecution createProcedureExecution(Call command,
+ ExecutionContext executionContext, RuntimeMetadata metadata,
+ C connection) throws TranslatorException {
+ return delegate.createProcedureExecution(command, executionContext,
+ metadata, connection);
+ }
+ @Override
+ public ResultSetExecution createResultSetExecution(QueryExpression command,
+ ExecutionContext executionContext, RuntimeMetadata metadata,
+ C connection) throws TranslatorException {
+ return delegate.createResultSetExecution(command, executionContext,
+ metadata, connection);
+ }
+ @Override
+ public UpdateExecution createUpdateExecution(Command command,
+ ExecutionContext executionContext, RuntimeMetadata metadata,
+ C connection) throws TranslatorException {
+ return delegate.createUpdateExecution(command, executionContext,
+ metadata, connection);
+ }
+ public C getConnection(F factory, ExecutionContext executionContext) throws TranslatorException {
+ return delegate.getConnection(factory, executionContext);
+ }
+ @Override
+ public NullOrder getDefaultNullOrder() {
+ return delegate.getDefaultNullOrder();
+ }
+ @Override
+ public LanguageFactory getLanguageFactory() {
+ return delegate.getLanguageFactory();
+ }
+ @Override
+ public int getMaxFromGroups() {
+ return delegate.getMaxFromGroups();
+ }
+ @Override
+ public void getMetadata(MetadataFactory metadataFactory, C conn)
+ throws TranslatorException {
+ delegate.getMetadata(metadataFactory, conn);
+ }
+ @Override
+ public List<FunctionMethod> getPushDownFunctions() {
+ return delegate.getPushDownFunctions();
+ }
+ @Override
+ public List<String> getSupportedFunctions() {
+ return delegate.getSupportedFunctions();
+ }
+ @Override
+ public TypeFacility getTypeFacility() {
+ return delegate.getTypeFacility();
+ }
+ @Override
+ public boolean isImmutable() {
+ return delegate.isImmutable();
+ }
+ @Override
+ public boolean isSourceRequired() {
+ return delegate.isSourceRequired();
+ }
+ @Override
+ public boolean supportsAggregatesAvg() {
+ return delegate.supportsAggregatesAvg();
+ }
+ @Override
+ public boolean supportsAggregatesCount() {
+ return delegate.supportsAggregatesCount();
+ }
+ @Override
+ public boolean supportsAggregatesCountStar() {
+ return delegate.supportsAggregatesCountStar();
+ }
+ @Override
+ public boolean supportsAggregatesDistinct() {
+ return delegate.supportsAggregatesDistinct();
+ }
+ @Override
+ public boolean supportsAggregatesEnhancedNumeric() {
+ return delegate.supportsAggregatesEnhancedNumeric();
+ }
+ @Override
+ public boolean supportsAggregatesMax() {
+ return delegate.supportsAggregatesMax();
+ }
+ @Override
+ public boolean supportsAggregatesMin() {
+ return delegate.supportsAggregatesMin();
+ }
+ @Override
+ public boolean supportsAggregatesSum() {
+ return delegate.supportsAggregatesSum();
+ }
+ @Override
+ public boolean supportsAliasedTable() {
+ return delegate.supportsAliasedTable();
+ }
+ @Override
+ public boolean supportsBatchedUpdates() {
+ return delegate.supportsBatchedUpdates();
+ }
+ @Override
+ public boolean supportsBetweenCriteria() {
+ return delegate.supportsBetweenCriteria();
+ }
+ @Override
+ public boolean supportsBulkUpdate() {
+ return delegate.supportsBulkUpdate();
+ }
+ @Override
+ public boolean supportsCaseExpressions() {
+ return delegate.supportsCaseExpressions();
+ }
+ @Override
+ public boolean supportsCommonTableExpressions() {
+ return delegate.supportsCommonTableExpressions();
+ }
+ @Override
+ public boolean supportsCompareCriteriaEquals() {
+ return delegate.supportsCompareCriteriaEquals();
+ }
+ @Override
+ public boolean supportsCompareCriteriaOrdered() {
+ return delegate.supportsCompareCriteriaOrdered();
+ }
+ @Override
+ public boolean supportsCorrelatedSubqueries() {
+ return delegate.supportsCorrelatedSubqueries();
+ }
+ @Override
+ public boolean supportsExcept() {
+ return delegate.supportsExcept();
+ }
+ @Override
+ public boolean supportsExistsCriteria() {
+ return delegate.supportsExistsCriteria();
+ }
+ @Override
+ public boolean supportsFunctionsInGroupBy() {
+ return delegate.supportsFunctionsInGroupBy();
+ }
+ @Override
+ public boolean supportsGroupBy() {
+ return delegate.supportsGroupBy();
+ }
+ @Override
+ public boolean supportsHaving() {
+ return delegate.supportsHaving();
+ }
+ @Override
+ public boolean supportsInCriteria() {
+ return delegate.supportsInCriteria();
+ }
+ @Override
+ public boolean supportsInCriteriaSubquery() {
+ return delegate.supportsInCriteriaSubquery();
+ }
+ @Override
+ public boolean supportsInlineViews() {
+ return delegate.supportsInlineViews();
+ }
+ @Override
+ public boolean supportsInsertWithIterator() {
+ return delegate.supportsInsertWithIterator();
+ }
+ @Override
+ public boolean supportsInsertWithQueryExpression() {
+ return delegate.supportsInsertWithQueryExpression();
+ }
+ @Override
+ public boolean supportsIntersect() {
+ return delegate.supportsIntersect();
+ }
+ @Override
+ public boolean supportsIsNullCriteria() {
+ return delegate.supportsIsNullCriteria();
+ }
+ @Override
+ public boolean supportsLikeCriteria() {
+ return delegate.supportsLikeCriteria();
+ }
+ @Override
+ public boolean supportsLikeCriteriaEscapeCharacter() {
+ return delegate.supportsLikeCriteriaEscapeCharacter();
+ }
+ @Override
+ public boolean supportsNotCriteria() {
+ return delegate.supportsNotCriteria();
+ }
+ @Override
+ public boolean supportsOrCriteria() {
+ return delegate.supportsOrCriteria();
+ }
+ @Override
+ public boolean supportsOrderByNullOrdering() {
+ return delegate.supportsOrderByNullOrdering();
+ }
+ @Override
+ public boolean supportsOrderByUnrelated() {
+ return delegate.supportsOrderByUnrelated();
+ }
+ @Override
+ public boolean supportsQuantifiedCompareCriteriaAll() {
+ return delegate.supportsQuantifiedCompareCriteriaAll();
+ }
+ @Override
+ public boolean supportsQuantifiedCompareCriteriaSome() {
+ return delegate.supportsQuantifiedCompareCriteriaSome();
+ }
+ @Override
+ public boolean supportsRowLimit() {
+ return delegate.supportsRowLimit();
+ }
+ @Override
+ public boolean supportsRowOffset() {
+ return delegate.supportsRowOffset();
+ }
+ @Override
+ public boolean supportsScalarSubqueries() {
+ return delegate.supportsScalarSubqueries();
+ }
+ @Override
+ public boolean supportsSearchedCaseExpressions() {
+ return delegate.supportsSearchedCaseExpressions();
+ }
+ @Override
+ public boolean supportsSelectExpression() {
+ return delegate.supportsSelectExpression();
+ }
+ @Override
+ public boolean supportsSelfJoins() {
+ return delegate.supportsSelfJoins();
+ }
+ @Override
+ public boolean supportsSetQueryOrderBy() {
+ return delegate.supportsSetQueryOrderBy();
+ }
+ @Override
+ public boolean supportsUnions() {
+ return delegate.supportsUnions();
+ }
+ @Override
+ public String toString() {
+ return delegate.toString();
+ }
+ @Override
+ public boolean useAnsiJoin() {
+ return delegate.useAnsiJoin();
+ }
+ @Override
+ public boolean equals(Object obj) {
+ return delegate.equals(obj);
+ }
+ @Override
+ public int hashCode() {
+ return delegate.hashCode();
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionContext.java
===================================================================
--- trunk/api/src/main/java/org/teiid/translator/ExecutionContext.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionContext.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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;
-
-import java.io.Serializable;
-
-import javax.security.auth.Subject;
-
-
-
-/**
- * The security context provides information about the user context in which
- * this query is being run.
- *
- * As of 4.2, the SecurityContext is a sub-interface of ExecutionContext such
- * that both interfaces contain all of the methods from the prior independent
- * interfaces. Thus, these interfaces can now be used interchangeably.
- *
- */
-public interface ExecutionContext {
-
- /**
- * Get the identifier for the current connector running the command
- * @return Connector identifier; never null
- */
- String getConnectorIdentifier();
-
- /**
- * Get the identifier for the command being executed. This can be
- * correlated back to identifiers exposed in other parts of the system.
- * @return command identifier
- */
- String getRequestIdentifier();
-
- /**
- * This specifies the node id for the atomic request in the relational plan of query.
- * when combined with the request identifier, uniquely identifies a command sent to a connector.
- */
- String getPartIdentifier();
-
- /**
- * Execution count defines an id; where every access to the connector from
- * the server in a given command execution boundary is uniquely defined;
- * Like for example in the case of "batched execution" of commands, each execution of
- * command gets new identifier.
- */
- String getExecutionCountIdentifier();
-
- /**
- * Get the name of the VDB this query is being run against.
- * @return VDB name, never null
- */
- String getVirtualDatabaseName();
-
- /**
- * Get the version of the VDB this query is being run against.
- * @return VDB version, never null
- */
- int getVirtualDatabaseVersion();
-
- /**
- * Get the user for the user running this query.
- * @return User, never null
- */
- Subject getSubject();
-
- /**
- * Get the trusted payload passed when the user statement was executed.
- * Teiid has no knowledge about what the payload contains - it is merely
- * passed through the system. It is most often used to pass security
- * information such as credentials.
- *
- * <p>Given that the Execution Payload is not authenticated by the Teiid
- * system, connector writers are responsible for ensuring its validity. </p>
- *
- * @return Trusted execution payload if one exists, otherwise null
- * @since 4.2
- */
- Serializable getExecutionPayload();
-
- /**
- * Get the identifier for the connection through which
- * the command is being executed. This represents the original JDBC user
- * connection to the Teiid system
- * @return Connection identifier
- */
- String getConnectionIdentifier();
-
- /**
- * When the execution is turned on with "alive=true", the execution object will not
- * be implicitly closed at the end of the last batch. It will only be closed at end
- * of the user query.
- * <p>
- * The engine will already detect situations when the connection should stay open for
- * LOB (clob/blob/xml) streaming.
- * <p>
- * Keeping the execution alive unnecessarily may cause issues with connection usage
- * as the connection instance may not be usable by other queries.
- *
- * @param alive
- */
- void keepExecutionAlive(boolean alive);
-
- /**
- * Return the current connector batch size. This may be used as a hint to the underlying source query.
- * @return the Connector batch size.
- */
- int getBatchSize();
-
- /**
- * Add an exception as a warning to this Execution.
- * @param ex
- */
- void addWarning(Exception ex);
-
- /**
- * Flag indicates that the operation needs to be executed in a XA transaction.
- * @return
- */
- boolean isTransactional();
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionContext.java (from rev 3218, trunk/api/src/main/java/org/teiid/translator/ExecutionContext.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionContext.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionContext.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,149 @@
+/*
+ * 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;
+
+import java.io.Serializable;
+
+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.
+ *
+ * As of 4.2, the SecurityContext is a sub-interface of ExecutionContext such
+ * that both interfaces contain all of the methods from the prior independent
+ * interfaces. Thus, these interfaces can now be used interchangeably.
+ *
+ */
+public interface ExecutionContext {
+
+ /**
+ * Get the identifier for the current connector running the command
+ * @return Connector identifier; never null
+ */
+ String getConnectorIdentifier();
+
+ /**
+ * Get the identifier for the command being executed. This can be
+ * correlated back to identifiers exposed in other parts of the system.
+ * @return command identifier
+ */
+ String getRequestIdentifier();
+
+ /**
+ * This specifies the node id for the atomic request in the relational plan of query.
+ * when combined with the request identifier, uniquely identifies a command sent to a connector.
+ */
+ String getPartIdentifier();
+
+ /**
+ * Execution count defines an id; where every access to the connector from
+ * the server in a given command execution boundary is uniquely defined;
+ * Like for example in the case of "batched execution" of commands, each execution of
+ * command gets new identifier.
+ */
+ String getExecutionCountIdentifier();
+
+ /**
+ * Get the name of the VDB this query is being run against.
+ * @return VDB name, never null
+ */
+ String getVirtualDatabaseName();
+
+ /**
+ * Get the version of the VDB this query is being run against.
+ * @return VDB version, never null
+ */
+ int getVirtualDatabaseVersion();
+
+ /**
+ * Get the user for the user running this query.
+ * @return User, never null
+ */
+ Subject getSubject();
+
+ /**
+ * Get the trusted payload passed when the user statement was executed.
+ * Teiid has no knowledge about what the payload contains - it is merely
+ * passed through the system. It is most often used to pass security
+ * information such as credentials.
+ *
+ * <p>Given that the Execution Payload is not authenticated by the Teiid
+ * system, connector writers are responsible for ensuring its validity. </p>
+ *
+ * @return Trusted execution payload if one exists, otherwise null
+ * @since 4.2
+ */
+ Serializable getExecutionPayload();
+
+ /**
+ * Get the identifier for the connection through which
+ * the command is being executed. This represents the original JDBC user
+ * connection to the Teiid system
+ * @return Connection identifier
+ */
+ String getConnectionIdentifier();
+
+ /**
+ * When the execution is turned on with "alive=true", the execution object will not
+ * be implicitly closed at the end of the last batch. It will only be closed at end
+ * of the user query.
+ * <p>
+ * The engine will already detect situations when the connection should stay open for
+ * LOB (clob/blob/xml) streaming.
+ * <p>
+ * Keeping the execution alive unnecessarily may cause issues with connection usage
+ * as the connection instance may not be usable by other queries.
+ *
+ * @param alive
+ */
+ void keepExecutionAlive(boolean alive);
+
+ /**
+ * Return the current connector batch size. This may be used as a hint to the underlying source query.
+ * @return the Connector batch size.
+ */
+ int getBatchSize();
+
+ /**
+ * Add an exception as a warning to this Execution.
+ * @param ex
+ */
+ void addWarning(Exception ex);
+
+ /**
+ * Flag indicates that the operation needs to be executed in a XA transaction.
+ * @return
+ */
+ boolean isTransactional();
+
+ /**
+ * Get the current session.
+ * @return
+ */
+ Session getSession();
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionFactory.java
===================================================================
--- trunk/api/src/main/java/org/teiid/translator/ExecutionFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,824 +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;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.resource.ResourceException;
-import javax.resource.cci.Connection;
-import javax.resource.cci.ConnectionFactory;
-
-import org.teiid.core.TeiidException;
-import org.teiid.core.util.ReflectionHelper;
-import org.teiid.language.BatchedUpdates;
-import org.teiid.language.Call;
-import org.teiid.language.Command;
-import org.teiid.language.LanguageFactory;
-import org.teiid.language.QueryExpression;
-import org.teiid.language.Select;
-import org.teiid.language.SetQuery;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.MetadataFactory;
-import org.teiid.metadata.RuntimeMetadata;
-
-
-
-/**
- * <p>The primary entry point for a Translator. This class should be extended by the custom translator writer.</p>
- *
- * The deployer instantiates this class through reflection. So it is important to have no-arg constructor. Once constructed
- * the "start" method is called. This class represents the basic capabilities of the translator.
- */
-public class ExecutionFactory<F, C> {
-
- public enum SupportedJoinCriteria {
- /**
- * Indicates that any supported criteria is allowed.
- */
- ANY,
- /**
- * Indicates that any simple comparison of elements is allowed.
- */
- THETA,
- /**
- * Indicates that only equality predicates of elements are allowed.
- */
- EQUI,
- /**
- * Indicates that only equality predicates between
- * exactly one primary and foreign key is allowed per join.
- */
- KEY
- }
-
- public enum NullOrder {
- HIGH,
- LOW,
- FIRST,
- LAST,
- UNKNOWN
- }
-
- public static final int DEFAULT_MAX_FROM_GROUPS = -1;
- public static final int DEFAULT_MAX_IN_CRITERIA_SIZE = -1;
-
- private static final TypeFacility TYPE_FACILITY = new TypeFacility();
-
- /*
- * Managed execution properties
- */
- private boolean immutable;
- private boolean sourceRequired = true;
-
- /*
- * Support properties
- */
- private boolean supportsSelectDistinct;
- private boolean supportsOuterJoins;
- private SupportedJoinCriteria supportedJoinCriteria = SupportedJoinCriteria.ANY;
- private boolean supportsOrderBy;
- private boolean supportsInnerJoins;
- private boolean supportsFullOuterJoins;
- private boolean requiresCriteria;
- private int maxInSize = DEFAULT_MAX_IN_CRITERIA_SIZE;
- private int maxDependentInPredicates = DEFAULT_MAX_IN_CRITERIA_SIZE;
-
- /**
- * Initialize the connector with supplied configuration
- */
- @SuppressWarnings("unused")
- public void start() throws TranslatorException {
- }
-
- /**
- * Defines if the Connector is read-only connector
- * @return
- */
- @TranslatorProperty(display="Is Immutable",description="Is Immutable, True if the source never changes.",advanced=true)
- public boolean isImmutable() {
- return immutable;
- }
-
- public void setImmutable(boolean arg0) {
- this.immutable = arg0;
- }
-
- /**
- * 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.
- *
- * @param factory
- * @return
- * @throws TranslatorException
- */
- @SuppressWarnings("unchecked")
- public C getConnection(F factory) throws TranslatorException {
- if (factory == null) {
- return null;
- }
- if (factory instanceof ConnectionFactory) {
- try {
- return (C) ((ConnectionFactory)factory).getConnection();
- } catch (ResourceException e) {
- throw new TranslatorException(e);
- }
- }
- throw new AssertionError("A connection factory was supplied, but no implementation was provided getConnection"); //$NON-NLS-1$
- }
-
- /**
- * Closes a connection object from the given connection factory.
- *
- * The default implementation assumes a JCA {@link Connection}. Subclasses should override, if they use
- * another type of connection.
- *
- * @param connection
- * @param factory
- */
- public void closeConnection(C connection, F factory) {
- if (connection == null) {
- return;
- }
- if (connection instanceof Connection) {
- try {
- ((Connection)connection).close();
- } catch (ResourceException e) {
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, e, "Error closing"); //$NON-NLS-1$
- }
- return;
- }
- throw new AssertionError("A connection was created, but no implementation provided for closeConnection"); //$NON-NLS-1$
- }
-
- /**
- * Flag that indicates if a underlying source connection required for this execution factory to work
- * @return
- */
- public boolean isSourceRequired() {
- return sourceRequired;
- }
-
- public void setSourceRequired(boolean value) {
- this.sourceRequired = value;
- }
-
- /**
- * Obtain a reference to the default LanguageFactory that can be used to construct
- * new language interface objects. This is typically needed when modifying the language
- * objects passed to the connector or for testing when objects need to be created.
- */
- public LanguageFactory getLanguageFactory() {
- return LanguageFactory.INSTANCE;
- }
-
- /**
- * Obtain a reference to the type facility, which can be used to perform many type
- * conversions supplied by the Connector API.
- */
- public TypeFacility getTypeFacility() {
- return TYPE_FACILITY;
- }
-
- /**
- * Create an execution object for the specified command
- * @param command the command
- * @param executionContext Provides information about the context that this command is
- * executing within, such as the identifiers for the command being executed
- * @param metadata Access to runtime metadata if needed to translate the command
- * @param connection connection factory object to the data source
- * @return An execution object that can use to execute the command
- */
- public Execution createExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, C connection) throws TranslatorException {
- if (command instanceof QueryExpression) {
- return createResultSetExecution((QueryExpression)command, executionContext, metadata, connection);
- }
- if (command instanceof Call) {
- return createProcedureExecution((Call)command, executionContext, metadata, connection);
- }
- return createUpdateExecution(command, executionContext, metadata, connection);
- }
-
- @SuppressWarnings("unused")
- public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, C connection) throws TranslatorException {
- throw new TranslatorException("Unsupported Execution"); //$NON-NLS-1$
- }
-
- @SuppressWarnings("unused")
- public ProcedureExecution createProcedureExecution(Call command, ExecutionContext executionContext, RuntimeMetadata metadata, C connection) throws TranslatorException {
- throw new TranslatorException("Unsupported Execution");//$NON-NLS-1$
- }
-
- @SuppressWarnings("unused")
- public UpdateExecution createUpdateExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, C connection) throws TranslatorException {
- throw new TranslatorException("Unsupported Execution");//$NON-NLS-1$
- }
-
- /**
- * Support indicates connector can accept queries with SELECT DISTINCT
- * @since 3.1 SP2
- */
- @TranslatorProperty(display="Supports Select Distinct", description="True, if this connector supports SELECT DISTINCT", advanced=true)
- public final boolean supportsSelectDistinct() {
- return supportsSelectDistinct;
- }
-
- public void setSupportsSelectDistinct(boolean supportsSelectDistinct) {
- this.supportsSelectDistinct = supportsSelectDistinct;
- }
-
- /**
- * Support indicates connector can accept expressions other than element
- * symbols in the SELECT clause. Specific supports for the expression
- * type are still checked.
- * @since 6.1.0
- */
- public boolean supportsSelectExpression() {
- return false;
- }
-
- /**
- * Support indicates connector can accept groups with aliases
- * @since 3.1 SP2
- */
- public boolean supportsAliasedTable() {
- return false;
- }
-
- /**
- * Get the supported join criteria. A null return value will be treated
- * as {@link SupportedJoinCriteria#ANY}
- * @since 6.1.0
- */
- @TranslatorProperty(display="Supported Join Criteria", description="Returns one of any, theta, equi, or key", advanced=true)
- public final SupportedJoinCriteria getSupportedJoinCriteria() {
- return supportedJoinCriteria;
- }
-
- public void setSupportedJoinCriteria(
- SupportedJoinCriteria supportedJoinCriteria) {
- this.supportedJoinCriteria = supportedJoinCriteria;
- }
-
- /**
- * Support indicates connector can accept inner or cross joins
- * @since 6.1.0
- */
- @TranslatorProperty(display="Supports Inner Joins", description="True, if this connector supports inner joins", advanced=true)
- public final boolean supportsInnerJoins() {
- return supportsInnerJoins;
- }
-
- public void setSupportsInnerJoins(boolean supportsInnerJoins) {
- this.supportsInnerJoins = supportsInnerJoins;
- }
-
- /**
- * Support indicates connector can accept self-joins where a
- * group is joined to itself with aliases. Connector must also support
- * {@link #supportsAliasedTable()}.
- * @since 3.1 SP2
- */
- public boolean supportsSelfJoins() {
- return false;
- }
-
- /**
- * Support indicates connector can accept left outer joins
- * @since 3.1 SP2
- */
- @TranslatorProperty(display="Supports Outer Joins", description="True, if this connector supports outer joins", advanced=true)
- public final boolean supportsOuterJoins() {
- return supportsOuterJoins;
- }
-
- public void setSupportsOuterJoins(boolean supportsOuterJoins) {
- this.supportsOuterJoins = supportsOuterJoins;
- }
-
- /**
- * Support indicates connector can accept full outer joins
- * @since 3.1 SP2
- */
- @TranslatorProperty(display="Supports Full Outer Joins", description="True, if this connector supports full outer joins", advanced=true)
- public final boolean supportsFullOuterJoins() {
- return supportsFullOuterJoins;
- }
-
- public void setSupportsFullOuterJoins(boolean supportsFullOuterJoins) {
- this.supportsFullOuterJoins = supportsFullOuterJoins;
- }
-
- /**
- * Support indicates connector can accept inline views (subqueries
- * in the FROM clause).
- * @since 4.1
- */
- public boolean supportsInlineViews() {
- return false;
- }
-
- /**
- * Support indicates connector accepts criteria of form (element BETWEEN constant AND constant)
- * <br>NOT CURRENTLY USED - between is rewritten as compound compare criteria
- * @since 4.0
- */
- public boolean supportsBetweenCriteria() {
- return false;
- }
-
- /**
- * Support indicates connector accepts criteria of form (element = constant)
- * @since 3.1 SP2
- */
- public boolean supportsCompareCriteriaEquals() {
- return false;
- }
-
- /**
- * Support indicates connector accepts criteria of form (element <=|>= constant)
- * <br>The query engine will may pushdown queries containing < or > if NOT is also
- * supported.
- * @since 3.1 SP2
- */
- public boolean supportsCompareCriteriaOrdered() {
- return false;
- }
-
- /**
- * Support indicates connector accepts criteria of form (element LIKE constant)
- * @since 3.1 SP2
- */
- public boolean supportsLikeCriteria() {
- return false;
- }
-
- /**
- * Support indicates connector accepts criteria of form (element LIKE constant ESCAPE char)
- * @since 3.1 SP2
- */
- public boolean supportsLikeCriteriaEscapeCharacter() {
- return false;
- }
-
- /**
- * Support indicates connector accepts criteria of form (element IN set)
- * @since 3.1 SP2
- */
- public boolean supportsInCriteria() {
- return false;
- }
-
- /**
- * Support indicates connector accepts IN criteria with a subquery on the right side
- * @since 4.0
- */
- public boolean supportsInCriteriaSubquery() {
- return false;
- }
-
- /**
- * Support indicates connector accepts criteria of form (element IS NULL)
- * @since 3.1 SP2
- */
- public boolean supportsIsNullCriteria() {
- return false;
- }
-
- /**
- * Support indicates connector accepts logical criteria connected by OR
- * @since 3.1 SP2
- */
- public boolean supportsOrCriteria() {
- return false;
- }
-
- /**
- * Support indicates connector accepts logical criteria NOT
- * @since 3.1 SP2
- */
- public boolean supportsNotCriteria() {
- return false;
- }
-
- /**
- * Support indicates connector accepts the EXISTS criteria
- * @since 4.0
- */
- public boolean supportsExistsCriteria() {
- return false;
- }
-
- /**
- * Support indicates connector accepts the quantified comparison criteria that
- * use SOME
- * @since 4.0
- */
- public boolean supportsQuantifiedCompareCriteriaSome() {
- return false;
- }
-
- /**
- * Support indicates connector accepts the quantified comparison criteria that
- * use ALL
- * @since 4.0
- */
- public boolean supportsQuantifiedCompareCriteriaAll() {
- return false;
- }
-
- /**
- * Support indicates connector accepts ORDER BY clause, including multiple elements
- * and ascending and descending sorts.
- * @since 3.1 SP2
- */
- @TranslatorProperty(display="Supports ORDER BY", description="True, if this connector supports ORDER BY", advanced=true)
- public final boolean supportsOrderBy() {
- return supportsOrderBy;
- }
-
- public void setSupportsOrderBy(boolean supportsOrderBy) {
- this.supportsOrderBy = supportsOrderBy;
- }
-
- /**
- * Support indicates connector accepts ORDER BY clause with columns not from the select
- * @since 6.2
- * @return
- */
- public boolean supportsOrderByUnrelated() {
- return false;
- }
-
- /**
- * Returns the default null ordering
- * @since 7.1
- * @return the {@link NullOrder}
- */
- public NullOrder getDefaultNullOrder() {
- return NullOrder.UNKNOWN;
- }
-
- /**
- * Returns whether the database supports explicit join ordering.
- * @since 7.1
- * @return true if nulls first/last can be specified
- */
- public boolean supportsOrderByNullOrdering() {
- return false;
- }
-
- /**
- * Whether the source supports an explicit GROUP BY clause
- * @since 6.1
- */
- public boolean supportsGroupBy() {
- return false;
- }
-
- /**
- * Whether the source supports the HAVING clause
- * @since 6.1
- */
- public boolean supportsHaving() {
- return false;
- }
-
- /**
- * Support indicates connector can accept the SUM aggregate function
- * @since 3.1 SP2
- */
- public boolean supportsAggregatesSum() {
- return false;
- }
-
- /**
- * Support indicates connector can accept the AVG aggregate function
- * @since 3.1 SP2
- */
- public boolean supportsAggregatesAvg() {
- return false;
- }
-
- /**
- * Support indicates connector can accept the MIN aggregate function
- * @since 3.1 SP2
- */
- public boolean supportsAggregatesMin() {
- return false;
- }
-
- /**
- * Support indicates connector can accept the MAX aggregate function
- * @since 3.1 SP2
- */
- public boolean supportsAggregatesMax() {
- return false;
- }
-
- /**
- * Support indicates connector can accept the COUNT aggregate function
- * @since 3.1 SP2
- */
- public boolean supportsAggregatesCount() {
- return false;
- }
-
- /**
- * Support indicates connector can accept the COUNT(*) aggregate function
- * @since 3.1 SP2
- */
- public boolean supportsAggregatesCountStar() {
- return false;
- }
-
- /**
- * Support indicates connector can accept DISTINCT within aggregate functions
- * @since 3.1 SP2
- */
- public boolean supportsAggregatesDistinct() {
- return false;
- }
-
- /**
- * Support indicates connector can accept STDDEV_POP, STDDEV_VAR, VAR_POP, VAR_SAMP
- * @since 7.1
- */
- public boolean supportsAggregatesEnhancedNumeric() {
- return false;
- }
-
- /**
- * Support indicates connector can accept scalar subqueries in the SELECT, WHERE, and
- * HAVING clauses
- * @since 4.0
- */
- public boolean supportsScalarSubqueries() {
- return false;
- }
-
- /**
- * Support indicates connector can accept correlated subqueries wherever subqueries
- * are accepted
- * @since 4.0
- */
- public boolean supportsCorrelatedSubqueries() {
- return false;
- }
-
- /**
- * Support indicates connector can accept queries with non-searched
- * CASE <expression> WHEN <expression> ... END
- * <br>NOT CURRENTLY USED - case is pushed down as searched case
- * @since 4.0
- */
- public boolean supportsCaseExpressions() {
- return false;
- }
-
- /**
- * Support indicates connector can accept queries with searched CASE WHEN <criteria> ... END
- * @since 4.0
- */
- public boolean supportsSearchedCaseExpressions() {
- return false;
- }
-
- /**
- * Support indicates that the connector supports the UNION of two queries.
- * @since 4.2
- */
- public boolean supportsUnions() {
- return false;
- }
-
- /**
- * Support indicates that the connector supports an ORDER BY on a SetQuery.
- * @since 5.6
- */
- public boolean supportsSetQueryOrderBy() {
- return false;
- }
-
- /**
- * Support indicates that the connector supports the INTERSECT of two queries.
- * @since 5.6
- */
- public boolean supportsIntersect() {
- return false;
- }
-
- /**
- * Support indicates that the connector supports the EXCEPT of two queries.
- * @since 5.6
- */
- public boolean supportsExcept() {
- return false;
- }
-
- /**
- * Get list of all supported function names. Arithmetic functions have names like
- * "+".
- * @since 3.1 SP3
- */
- public List<String> getSupportedFunctions() {
- return null;
- }
-
- public List<FunctionMethod> getPushDownFunctions(){
- return Collections.emptyList();
- }
-
- /**
- * Get the integer value representing the number of values allowed in an IN criteria
- * in the WHERE clause of a query
- * @since 5.0
- */
- @TranslatorProperty(display="Max number of IN predicate entries", advanced=true)
- public final int getMaxInCriteriaSize() {
- return maxInSize;
- }
-
- public void setMaxInCriteriaSize(int maxInSize) {
- this.maxInSize = maxInSize;
- }
-
- /**
- * Get the integer value representing the number of values allowed in an IN criteria
- * in the WHERE clause of a query
- * @since 5.0
- */
- @TranslatorProperty(display="Max number of dependent values across all IN predicates", advanced=true)
- public int getMaxDependentInPredicates() {
- return maxDependentInPredicates;
- }
-
- public void setMaxDependentInPredicates(int maxDependentInPredicates) {
- this.maxDependentInPredicates = maxDependentInPredicates;
- }
-
- /**
- * <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() {
- return false;
- }
-
- /**
- * Gets whether the connector can limit the number of rows returned by a query.
- * @since 5.0 SP1
- */
- public boolean supportsRowLimit() {
- return false;
- }
-
- /**
- * Gets whether the connector supports a SQL clause (similar to the LIMIT with an offset) that can return
- * result sets that start in the middle of the resulting rows returned by a query
- * @since 5.0 SP1
- */
- public boolean supportsRowOffset() {
- return false;
- }
-
- /**
- * The number of groups supported in the from clause. Added for a Sybase limitation.
- * @since 5.6
- * @return the number of groups supported in the from clause, or -1 if there is no limit
- */
- public int getMaxFromGroups() {
- return DEFAULT_MAX_FROM_GROUPS;
- }
-
- /**
- * Whether the source prefers to use ANSI style joins.
- * @since 6.0
- */
- public boolean useAnsiJoin() {
- return false;
- }
-
- /**
- * Whether the source supports queries without criteria.
- * @since 6.0
- */
- @TranslatorProperty(display="Requries Criteria", description="True, if this connector requires criteria on source queries", advanced=true)
- public final boolean requiresCriteria() {
- return requiresCriteria;
- }
-
- public void setRequiresCriteria(boolean requiresCriteria) {
- this.requiresCriteria = requiresCriteria;
- }
-
- /**
- * Whether the source supports {@link BatchedUpdates}
- * @since 6.0
- */
- public boolean supportsBatchedUpdates() {
- return false;
- }
-
- /**
- * Whether the source supports updates with multiple value sets
- * @since 6.0
- */
- public boolean supportsBulkUpdate() {
- return false;
- }
-
- /**
- * Support indicates that the connector can accept INSERTs with
- * values specified by a {@link SetQuery} or {@link Select}
- * @since 6.1
- */
- public boolean supportsInsertWithQueryExpression() {
- return false;
- }
-
- /**
- * Support indicates that the connector can accept INSERTs
- * with values specified by an {@link Iterator}
- * @since 7.1
- * @return
- */
- public boolean supportsInsertWithIterator() {
- return false;
- }
-
- public static <T> T getInstance(Class<T> expectedType, String className, Collection<?> ctorObjs, Class<? extends T> defaultClass) throws TranslatorException {
- try {
- if (className == null) {
- if (defaultClass == null) {
- throw new TranslatorException("Neither class name nor default class specified to create an instance"); //$NON-NLS-1$
- }
- return expectedType.cast(defaultClass.newInstance());
- }
- return expectedType.cast(ReflectionHelper.create(className, ctorObjs, Thread.currentThread().getContextClassLoader()));
- } catch (TeiidException e) {
- throw new TranslatorException(e);
- } catch (IllegalAccessException e) {
- throw new TranslatorException(e);
- } catch(InstantiationException e) {
- throw new TranslatorException(e);
- }
- }
-
- /**
- * Implement to provide metadata to the metadata for use by the engine. This is the
- * primary method of creating metadata for dynamic VDBs.
- * @param metadataFactory
- * @param conn
- * @throws TranslatorException
- */
- public void getMetadata(MetadataFactory metadataFactory, C conn) throws TranslatorException {
-
- }
-
- /**
- * Indicates if LOBs are usable after the execution is closed.
- * @return true if LOBs can be used after close
- * @since 7.2
- */
- public boolean areLobsUsableAfterClose() {
- return false;
- }
-
- /**
- * @return true if the WITH clause is supported
- * @since 7.2
- */
- public boolean supportsCommonTableExpressions() {
- return false;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionFactory.java (from rev 3218, trunk/api/src/main/java/org/teiid/translator/ExecutionFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/main/java/org/teiid/translator/ExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,864 @@
+/*
+ * 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;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.resource.ResourceException;
+import javax.resource.cci.Connection;
+import javax.resource.cci.ConnectionFactory;
+
+import org.teiid.core.TeiidException;
+import org.teiid.core.util.ReflectionHelper;
+import org.teiid.language.BatchedUpdates;
+import org.teiid.language.Call;
+import org.teiid.language.Command;
+import org.teiid.language.LanguageFactory;
+import org.teiid.language.QueryExpression;
+import org.teiid.language.Select;
+import org.teiid.language.SetQuery;
+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;
+
+
+
+/**
+ * <p>The primary entry point for a Translator. This class should be extended by the custom translator writer.</p>
+ *
+ * The deployer instantiates this class through reflection. So it is important to have no-arg constructor. Once constructed
+ * the "start" method is called. This class represents the basic capabilities of the translator.
+ */
+public class ExecutionFactory<F, C> {
+
+ public enum SupportedJoinCriteria {
+ /**
+ * Indicates that any supported criteria is allowed.
+ */
+ ANY,
+ /**
+ * Indicates that any simple comparison of elements is allowed.
+ */
+ THETA,
+ /**
+ * Indicates that only equality predicates of elements are allowed.
+ */
+ EQUI,
+ /**
+ * Indicates that only equality predicates between
+ * exactly one primary and foreign key is allowed per join.
+ */
+ KEY
+ }
+
+ public enum NullOrder {
+ HIGH,
+ LOW,
+ FIRST,
+ LAST,
+ UNKNOWN
+ }
+
+ public static final int DEFAULT_MAX_FROM_GROUPS = -1;
+ public static final int DEFAULT_MAX_IN_CRITERIA_SIZE = -1;
+
+ private static final TypeFacility TYPE_FACILITY = new TypeFacility();
+
+ /*
+ * Managed execution properties
+ */
+ private boolean immutable;
+ private boolean sourceRequired = true;
+
+ /*
+ * Support properties
+ */
+ private boolean supportsSelectDistinct;
+ private boolean supportsOuterJoins;
+ private SupportedJoinCriteria supportedJoinCriteria = SupportedJoinCriteria.ANY;
+ private boolean supportsOrderBy;
+ private boolean supportsInnerJoins;
+ private boolean supportsFullOuterJoins;
+ private boolean requiresCriteria;
+ 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
+ */
+ @SuppressWarnings("unused")
+ public void start() throws TranslatorException {
+ }
+
+ /**
+ * Defines if the Connector is read-only connector
+ * @return
+ */
+ @TranslatorProperty(display="Is Immutable",description="Is Immutable, True if the source never changes.",advanced=true)
+ public boolean isImmutable() {
+ return immutable;
+ }
+
+ public void setImmutable(boolean arg0) {
+ this.immutable = arg0;
+ }
+
+ /**
+ * 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.
+ *
+ * @deprecated
+ * @see #getConnection(Object, ExecutionContext)
+ * @param factory
+ * @return a connection
+ * @throws TranslatorException
+ */
+ @SuppressWarnings("unchecked")
+ public C getConnection(F factory) throws TranslatorException {
+ if (factory == null) {
+ return null;
+ }
+ if (factory instanceof ConnectionFactory) {
+ try {
+ return (C) ((ConnectionFactory)factory).getConnection();
+ } catch (ResourceException e) {
+ throw new TranslatorException(e);
+ }
+ }
+ throw new AssertionError("A connection factory was supplied, but no implementation was provided getConnection"); //$NON-NLS-1$
+ }
+
+ /**
+ * 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
+ * another type of connection.
+ *
+ * @param connection
+ * @param factory
+ */
+ public void closeConnection(C connection, F factory) {
+ if (connection == null) {
+ return;
+ }
+ if (connection instanceof Connection) {
+ try {
+ ((Connection)connection).close();
+ } catch (ResourceException e) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, e, "Error closing"); //$NON-NLS-1$
+ }
+ return;
+ }
+ throw new AssertionError("A connection was created, but no implementation provided for closeConnection"); //$NON-NLS-1$
+ }
+
+ /**
+ * Flag that indicates if a underlying source connection required for this execution factory to work
+ * @return
+ */
+ public boolean isSourceRequired() {
+ return sourceRequired;
+ }
+
+ public void setSourceRequired(boolean value) {
+ this.sourceRequired = value;
+ }
+
+ /**
+ * Obtain a reference to the default LanguageFactory that can be used to construct
+ * new language interface objects. This is typically needed when modifying the language
+ * objects passed to the connector or for testing when objects need to be created.
+ */
+ public LanguageFactory getLanguageFactory() {
+ return LanguageFactory.INSTANCE;
+ }
+
+ /**
+ * Obtain a reference to the type facility, which can be used to perform many type
+ * conversions supplied by the Connector API.
+ */
+ public TypeFacility getTypeFacility() {
+ return TYPE_FACILITY;
+ }
+
+ /**
+ * Create an execution object for the specified command
+ * @param command the command
+ * @param executionContext Provides information about the context that this command is
+ * executing within, such as the identifiers for the command being executed
+ * @param metadata Access to runtime metadata if needed to translate the command
+ * @param connection connection factory object to the data source
+ * @return An execution object that can use to execute the command
+ */
+ public Execution createExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, C connection) throws TranslatorException {
+ if (command instanceof QueryExpression) {
+ return createResultSetExecution((QueryExpression)command, executionContext, metadata, connection);
+ }
+ if (command instanceof Call) {
+ return createProcedureExecution((Call)command, executionContext, metadata, connection);
+ }
+ return createUpdateExecution(command, executionContext, metadata, connection);
+ }
+
+ @SuppressWarnings("unused")
+ public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, C connection) throws TranslatorException {
+ throw new TranslatorException("Unsupported Execution"); //$NON-NLS-1$
+ }
+
+ @SuppressWarnings("unused")
+ public ProcedureExecution createProcedureExecution(Call command, ExecutionContext executionContext, RuntimeMetadata metadata, C connection) throws TranslatorException {
+ throw new TranslatorException("Unsupported Execution");//$NON-NLS-1$
+ }
+
+ @SuppressWarnings("unused")
+ public UpdateExecution createUpdateExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, C connection) throws TranslatorException {
+ throw new TranslatorException("Unsupported Execution");//$NON-NLS-1$
+ }
+
+ /**
+ * Support indicates connector can accept queries with SELECT DISTINCT
+ * @since 3.1 SP2
+ */
+ @TranslatorProperty(display="Supports Select Distinct", description="True, if this connector supports SELECT DISTINCT", advanced=true)
+ public final boolean supportsSelectDistinct() {
+ return supportsSelectDistinct;
+ }
+
+ public void setSupportsSelectDistinct(boolean supportsSelectDistinct) {
+ this.supportsSelectDistinct = supportsSelectDistinct;
+ }
+
+ /**
+ * Support indicates connector can accept expressions other than element
+ * symbols in the SELECT clause. Specific supports for the expression
+ * type are still checked.
+ * @since 6.1.0
+ */
+ public boolean supportsSelectExpression() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept groups with aliases
+ * @since 3.1 SP2
+ */
+ public boolean supportsAliasedTable() {
+ return false;
+ }
+
+ /**
+ * Get the supported join criteria. A null return value will be treated
+ * as {@link SupportedJoinCriteria#ANY}
+ * @since 6.1.0
+ */
+ @TranslatorProperty(display="Supported Join Criteria", description="Returns one of any, theta, equi, or key", advanced=true)
+ public final SupportedJoinCriteria getSupportedJoinCriteria() {
+ return supportedJoinCriteria;
+ }
+
+ public void setSupportedJoinCriteria(
+ SupportedJoinCriteria supportedJoinCriteria) {
+ this.supportedJoinCriteria = supportedJoinCriteria;
+ }
+
+ /**
+ * Support indicates connector can accept inner or cross joins
+ * @since 6.1.0
+ */
+ @TranslatorProperty(display="Supports Inner Joins", description="True, if this connector supports inner joins", advanced=true)
+ public final boolean supportsInnerJoins() {
+ return supportsInnerJoins;
+ }
+
+ public void setSupportsInnerJoins(boolean supportsInnerJoins) {
+ this.supportsInnerJoins = supportsInnerJoins;
+ }
+
+ /**
+ * Support indicates connector can accept self-joins where a
+ * group is joined to itself with aliases. Connector must also support
+ * {@link #supportsAliasedTable()}.
+ * @since 3.1 SP2
+ */
+ public boolean supportsSelfJoins() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept left outer joins
+ * @since 3.1 SP2
+ */
+ @TranslatorProperty(display="Supports Outer Joins", description="True, if this connector supports outer joins", advanced=true)
+ public final boolean supportsOuterJoins() {
+ return supportsOuterJoins;
+ }
+
+ public void setSupportsOuterJoins(boolean supportsOuterJoins) {
+ this.supportsOuterJoins = supportsOuterJoins;
+ }
+
+ /**
+ * Support indicates connector can accept full outer joins
+ * @since 3.1 SP2
+ */
+ @TranslatorProperty(display="Supports Full Outer Joins", description="True, if this connector supports full outer joins", advanced=true)
+ public final boolean supportsFullOuterJoins() {
+ return supportsFullOuterJoins;
+ }
+
+ public void setSupportsFullOuterJoins(boolean supportsFullOuterJoins) {
+ this.supportsFullOuterJoins = supportsFullOuterJoins;
+ }
+
+ /**
+ * Support indicates connector can accept inline views (subqueries
+ * in the FROM clause).
+ * @since 4.1
+ */
+ public boolean supportsInlineViews() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts criteria of form (element BETWEEN constant AND constant)
+ * <br>NOT CURRENTLY USED - between is rewritten as compound compare criteria
+ * @since 4.0
+ */
+ public boolean supportsBetweenCriteria() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts criteria of form (element = constant)
+ * @since 3.1 SP2
+ */
+ public boolean supportsCompareCriteriaEquals() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts criteria of form (element <=|>= constant)
+ * <br>The query engine will may pushdown queries containing < or > if NOT is also
+ * supported.
+ * @since 3.1 SP2
+ */
+ public boolean supportsCompareCriteriaOrdered() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts criteria of form (element LIKE constant)
+ * @since 3.1 SP2
+ */
+ public boolean supportsLikeCriteria() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts criteria of form (element LIKE constant ESCAPE char)
+ * @since 3.1 SP2
+ */
+ public boolean supportsLikeCriteriaEscapeCharacter() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts criteria of form (element IN set)
+ * @since 3.1 SP2
+ */
+ public boolean supportsInCriteria() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts IN criteria with a subquery on the right side
+ * @since 4.0
+ */
+ public boolean supportsInCriteriaSubquery() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts criteria of form (element IS NULL)
+ * @since 3.1 SP2
+ */
+ public boolean supportsIsNullCriteria() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts logical criteria connected by OR
+ * @since 3.1 SP2
+ */
+ public boolean supportsOrCriteria() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts logical criteria NOT
+ * @since 3.1 SP2
+ */
+ public boolean supportsNotCriteria() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts the EXISTS criteria
+ * @since 4.0
+ */
+ public boolean supportsExistsCriteria() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts the quantified comparison criteria that
+ * use SOME
+ * @since 4.0
+ */
+ public boolean supportsQuantifiedCompareCriteriaSome() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts the quantified comparison criteria that
+ * use ALL
+ * @since 4.0
+ */
+ public boolean supportsQuantifiedCompareCriteriaAll() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector accepts ORDER BY clause, including multiple elements
+ * and ascending and descending sorts.
+ * @since 3.1 SP2
+ */
+ @TranslatorProperty(display="Supports ORDER BY", description="True, if this connector supports ORDER BY", advanced=true)
+ public final boolean supportsOrderBy() {
+ return supportsOrderBy;
+ }
+
+ public void setSupportsOrderBy(boolean supportsOrderBy) {
+ this.supportsOrderBy = supportsOrderBy;
+ }
+
+ /**
+ * Support indicates connector accepts ORDER BY clause with columns not from the select
+ * @since 6.2
+ * @return
+ */
+ public boolean supportsOrderByUnrelated() {
+ return false;
+ }
+
+ /**
+ * Returns the default null ordering
+ * @since 7.1
+ * @return the {@link NullOrder}
+ */
+ public NullOrder getDefaultNullOrder() {
+ return NullOrder.UNKNOWN;
+ }
+
+ /**
+ * Returns whether the database supports explicit join ordering.
+ * @since 7.1
+ * @return true if nulls first/last can be specified
+ */
+ public boolean supportsOrderByNullOrdering() {
+ return false;
+ }
+
+ /**
+ * Whether the source supports an explicit GROUP BY clause
+ * @since 6.1
+ */
+ public boolean supportsGroupBy() {
+ return false;
+ }
+
+ /**
+ * Whether the source supports the HAVING clause
+ * @since 6.1
+ */
+ public boolean supportsHaving() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept the SUM aggregate function
+ * @since 3.1 SP2
+ */
+ public boolean supportsAggregatesSum() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept the AVG aggregate function
+ * @since 3.1 SP2
+ */
+ public boolean supportsAggregatesAvg() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept the MIN aggregate function
+ * @since 3.1 SP2
+ */
+ public boolean supportsAggregatesMin() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept the MAX aggregate function
+ * @since 3.1 SP2
+ */
+ public boolean supportsAggregatesMax() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept the COUNT aggregate function
+ * @since 3.1 SP2
+ */
+ public boolean supportsAggregatesCount() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept the COUNT(*) aggregate function
+ * @since 3.1 SP2
+ */
+ public boolean supportsAggregatesCountStar() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept DISTINCT within aggregate functions
+ * @since 3.1 SP2
+ */
+ public boolean supportsAggregatesDistinct() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept STDDEV_POP, STDDEV_VAR, VAR_POP, VAR_SAMP
+ * @since 7.1
+ */
+ public boolean supportsAggregatesEnhancedNumeric() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept scalar subqueries in the SELECT, WHERE, and
+ * HAVING clauses
+ * @since 4.0
+ */
+ public boolean supportsScalarSubqueries() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept correlated subqueries wherever subqueries
+ * are accepted
+ * @since 4.0
+ */
+ public boolean supportsCorrelatedSubqueries() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept queries with non-searched
+ * CASE <expression> WHEN <expression> ... END
+ * <br>NOT CURRENTLY USED - case is pushed down as searched case
+ * @since 4.0
+ */
+ public boolean supportsCaseExpressions() {
+ return false;
+ }
+
+ /**
+ * Support indicates connector can accept queries with searched CASE WHEN <criteria> ... END
+ * @since 4.0
+ */
+ public boolean supportsSearchedCaseExpressions() {
+ return false;
+ }
+
+ /**
+ * Support indicates that the connector supports the UNION of two queries.
+ * @since 4.2
+ */
+ public boolean supportsUnions() {
+ return false;
+ }
+
+ /**
+ * Support indicates that the connector supports an ORDER BY on a SetQuery.
+ * @since 5.6
+ */
+ public boolean supportsSetQueryOrderBy() {
+ return false;
+ }
+
+ /**
+ * Support indicates that the connector supports the INTERSECT of two queries.
+ * @since 5.6
+ */
+ public boolean supportsIntersect() {
+ return false;
+ }
+
+ /**
+ * Support indicates that the connector supports the EXCEPT of two queries.
+ * @since 5.6
+ */
+ public boolean supportsExcept() {
+ return false;
+ }
+
+ /**
+ * Get list of all supported function names. Arithmetic functions have names like
+ * "+".
+ * @since 3.1 SP3
+ */
+ public List<String> getSupportedFunctions() {
+ 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 <translator name>.<function name>
+ * @see ExecutionFactory#addPushDownFunction(String, String, FunctionParameter, FunctionParameter...)
+ * @return
+ */
+ public List<FunctionMethod> getPushDownFunctions(){
+ 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
+ * @since 5.0
+ */
+ @TranslatorProperty(display="Max number of IN predicate entries", advanced=true)
+ public final int getMaxInCriteriaSize() {
+ return maxInSize;
+ }
+
+ public void setMaxInCriteriaSize(int maxInSize) {
+ this.maxInSize = maxInSize;
+ }
+
+ /**
+ * Get the integer value representing the number of values allowed in an IN criteria
+ * in the WHERE clause of a query
+ * @since 5.0
+ */
+ @TranslatorProperty(display="Max number of dependent values across all IN predicates", advanced=true)
+ public int getMaxDependentInPredicates() {
+ return maxDependentInPredicates;
+ }
+
+ public void setMaxDependentInPredicates(int maxDependentInPredicates) {
+ this.maxDependentInPredicates = maxDependentInPredicates;
+ }
+
+ /**
+ * <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() {
+ return false;
+ }
+
+ /**
+ * Gets whether the connector can limit the number of rows returned by a query.
+ * @since 5.0 SP1
+ */
+ public boolean supportsRowLimit() {
+ return false;
+ }
+
+ /**
+ * Gets whether the connector supports a SQL clause (similar to the LIMIT with an offset) that can return
+ * result sets that start in the middle of the resulting rows returned by a query
+ * @since 5.0 SP1
+ */
+ public boolean supportsRowOffset() {
+ return false;
+ }
+
+ /**
+ * The number of groups supported in the from clause. Added for a Sybase limitation.
+ * @since 5.6
+ * @return the number of groups supported in the from clause, or -1 if there is no limit
+ */
+ public int getMaxFromGroups() {
+ return DEFAULT_MAX_FROM_GROUPS;
+ }
+
+ /**
+ * Whether the source prefers to use ANSI style joins.
+ * @since 6.0
+ */
+ public boolean useAnsiJoin() {
+ return false;
+ }
+
+ /**
+ * Whether the source supports queries without criteria.
+ * @since 6.0
+ */
+ @TranslatorProperty(display="Requries Criteria", description="True, if this connector requires criteria on source queries", advanced=true)
+ public final boolean requiresCriteria() {
+ return requiresCriteria;
+ }
+
+ public void setRequiresCriteria(boolean requiresCriteria) {
+ this.requiresCriteria = requiresCriteria;
+ }
+
+ /**
+ * Whether the source supports {@link BatchedUpdates}
+ * @since 6.0
+ */
+ public boolean supportsBatchedUpdates() {
+ return false;
+ }
+
+ /**
+ * Whether the source supports updates with multiple value sets
+ * @since 6.0
+ */
+ public boolean supportsBulkUpdate() {
+ return false;
+ }
+
+ /**
+ * Support indicates that the connector can accept INSERTs with
+ * values specified by a {@link SetQuery} or {@link Select}
+ * @since 6.1
+ */
+ public boolean supportsInsertWithQueryExpression() {
+ return false;
+ }
+
+ /**
+ * Support indicates that the connector can accept INSERTs
+ * with values specified by an {@link Iterator}
+ * @since 7.1
+ * @return
+ */
+ public boolean supportsInsertWithIterator() {
+ return false;
+ }
+
+ public static <T> T getInstance(Class<T> expectedType, String className, Collection<?> ctorObjs, Class<? extends T> defaultClass) throws TranslatorException {
+ try {
+ if (className == null) {
+ if (defaultClass == null) {
+ throw new TranslatorException("Neither class name nor default class specified to create an instance"); //$NON-NLS-1$
+ }
+ return expectedType.cast(defaultClass.newInstance());
+ }
+ return expectedType.cast(ReflectionHelper.create(className, ctorObjs, Thread.currentThread().getContextClassLoader()));
+ } catch (TeiidException e) {
+ throw new TranslatorException(e);
+ } catch (IllegalAccessException e) {
+ throw new TranslatorException(e);
+ } catch(InstantiationException e) {
+ throw new TranslatorException(e);
+ }
+ }
+
+ /**
+ * Implement to provide metadata to the metadata for use by the engine. This is the
+ * primary method of creating metadata for dynamic VDBs.
+ * @param metadataFactory
+ * @param conn
+ * @throws TranslatorException
+ */
+ public void getMetadata(MetadataFactory metadataFactory, C conn) throws TranslatorException {
+
+ }
+
+ /**
+ * Indicates if LOBs are usable after the execution is closed.
+ * @return true if LOBs can be used after close
+ * @since 7.2
+ */
+ public boolean areLobsUsableAfterClose() {
+ return false;
+ }
+
+ /**
+ * @return true if the WITH clause is supported
+ * @since 7.2
+ */
+ public boolean supportsCommonTableExpressions() {
+ return false;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/api/src/test/java/org/teiid/logging/TestLogManager.java
===================================================================
--- trunk/api/src/test/java/org/teiid/logging/TestLogManager.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/test/java/org/teiid/logging/TestLogManager.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,159 +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.logging;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.teiid.logging.Logger;
-import org.teiid.logging.LogManager;
-import org.teiid.logging.MessageLevel;
-
-import junit.framework.TestCase;
-
-
-/**
- * This test case tests the LogManager.
- */
-public class TestLogManager extends TestCase {
-
- String context = "SomeContext"; //$NON-NLS-1$
-
- /**
- * Constructor for TestLogManager.
- * @param name
- */
- public TestLogManager(String name) {
- super(name);
- }
-
- @Override
- protected void setUp() throws Exception {
- ListLogger logger = new ListLogger();
- logger.setLogLevel(context, MessageLevel.DETAIL);
- LogManager.logListener = logger;
- }
-
- // =========================================================================
- // T E S T C A S E S
- // =========================================================================
-
- /*
- * Test for boolean isMessageToBeRecorded(String, int)
- */
- public void testIsMessageToBeRecordedString() {
- assertTrue(LogManager.isMessageToBeRecorded(context, MessageLevel.CRITICAL) );
-
- ListLogger cfg = (ListLogger)LogManager.logListener;
- cfg.setLogLevel(context, MessageLevel.NONE);
- assertFalse(LogManager.isMessageToBeRecorded(context, MessageLevel.CRITICAL) );
- }
-
- /**
- * Test that all msgs logged are equal and output in same order.
- */
- public void testLogMessage() throws Exception {
- ListLogger cfg = (ListLogger)LogManager.logListener;
- cfg.setLogLevel(context, MessageLevel.INFO );
-
- List<String> sentMsgList = new ArrayList<String>();
- sentMsgList.add("A message 1"); //$NON-NLS-1$
- sentMsgList.add("A message 2"); //$NON-NLS-1$
- sentMsgList.add("A message 3"); //$NON-NLS-1$
- sentMsgList.add("A message 4"); //$NON-NLS-1$
- 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);
- }
-
- List recevedMsgList = cfg.getLoggedMessages();
- assertEquals(sentMsgList.size(), recevedMsgList.size());
- assertEquals(sentMsgList, recevedMsgList);
- }
-
- /**
- *
- * A log listener that saves messages (IStatus)s in a
- * List for later comparison.
- */
- class ListLogger implements Logger {
- private List<String> messages = new ArrayList<String>();
- private Map<String, Integer> contextMap = new HashMap<String, Integer>();
- private int defaultLevel;
-
- public ListLogger() {
- }
-
- public void log(int level, String context, Object msg){
- this.messages.add(msg.toString());
- }
-
- public void log(int level, String context, Throwable t, Object msg) {
- this.messages.add(msg.toString());
- }
-
- public void shutdown() {
- messages.clear();
- messages = null;
-
- }
-
- public int size() {
- return this.messages.size();
- }
-
- public List getLoggedMessages() {
- return this.messages;
- }
-
- public Set<String> getContexts() {
- return this.contextMap.keySet();
- }
-
- public int getLogLevel(String context) {
- Integer level = this.contextMap.get(context);
- if (level != null) {
- return level;
- }
- return defaultLevel;
- }
-
- public void setLogLevel(String context, int logLevel) {
- this.contextMap.put(context, logLevel);
- }
-
- @Override
- public boolean isEnabled(String context, int msgLevel) {
- int level = getLogLevel(context);
- return level >= msgLevel;
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/api/src/test/java/org/teiid/logging/TestLogManager.java (from rev 3218, trunk/api/src/test/java/org/teiid/logging/TestLogManager.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/api/src/test/java/org/teiid/logging/TestLogManager.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/api/src/test/java/org/teiid/logging/TestLogManager.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,159 @@
+/*
+ * 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.logging;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.teiid.logging.Logger;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+
+import junit.framework.TestCase;
+
+
+/**
+ * This test case tests the LogManager.
+ */
+public class TestLogManager extends TestCase {
+
+ private static final String CONTEXT = "SomeContext"; //$NON-NLS-1$
+
+ /**
+ * Constructor for TestLogManager.
+ * @param name
+ */
+ public TestLogManager(String name) {
+ super(name);
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ ListLogger logger = new ListLogger();
+ logger.setLogLevel(CONTEXT, MessageLevel.DETAIL);
+ LogManager.logListener = logger;
+ }
+
+ // =========================================================================
+ // T E S T C A S E S
+ // =========================================================================
+
+ /*
+ * Test for boolean isMessageToBeRecorded(String, int)
+ */
+ public void testIsMessageToBeRecordedString() {
+ assertTrue(LogManager.isMessageToBeRecorded(CONTEXT, MessageLevel.CRITICAL) );
+
+ ListLogger cfg = (ListLogger)LogManager.logListener;
+ cfg.setLogLevel(CONTEXT, MessageLevel.NONE);
+ assertFalse(LogManager.isMessageToBeRecorded(CONTEXT, MessageLevel.CRITICAL) );
+ }
+
+ /**
+ * Test that all msgs logged are equal and output in same order.
+ */
+ public void testLogMessage() throws Exception {
+ ListLogger cfg = (ListLogger)LogManager.logListener;
+ cfg.setLogLevel(CONTEXT, MessageLevel.INFO );
+
+ List<String> sentMsgList = new ArrayList<String>();
+ sentMsgList.add("A message 1"); //$NON-NLS-1$
+ sentMsgList.add("A message 2"); //$NON-NLS-1$
+ sentMsgList.add("A message 3"); //$NON-NLS-1$
+ sentMsgList.add("A message 4"); //$NON-NLS-1$
+ sentMsgList.add("A message 5"); //$NON-NLS-1$
+ sentMsgList.add("A message 6"); //$NON-NLS-1$
+
+ for (Iterator<String> iter = sentMsgList.iterator(); iter.hasNext();) {
+ String msg = iter.next();
+ LogManager.logInfo(CONTEXT, msg);
+ }
+
+ List<String> recevedMsgList = cfg.getLoggedMessages();
+ assertEquals(sentMsgList.size(), recevedMsgList.size());
+ assertEquals(sentMsgList, recevedMsgList);
+ }
+
+ /**
+ *
+ * A log listener that saves messages (IStatus)s in a
+ * List for later comparison.
+ */
+ class ListLogger implements Logger {
+ private List<String> messages = new ArrayList<String>();
+ private Map<String, Integer> contextMap = new HashMap<String, Integer>();
+ private int defaultLevel;
+
+ public ListLogger() {
+ }
+
+ public void log(int level, String context, Object msg){
+ this.messages.add(msg.toString());
+ }
+
+ public void log(int level, String context, Throwable t, Object msg) {
+ this.messages.add(msg.toString());
+ }
+
+ public void shutdown() {
+ messages.clear();
+ messages = null;
+
+ }
+
+ public int size() {
+ return this.messages.size();
+ }
+
+ public List<String> getLoggedMessages() {
+ return this.messages;
+ }
+
+ public Set<String> getContexts() {
+ return this.contextMap.keySet();
+ }
+
+ public int getLogLevel(String context) {
+ Integer level = this.contextMap.get(context);
+ if (level != null) {
+ return level;
+ }
+ return defaultLevel;
+ }
+
+ public void setLogLevel(String context, int logLevel) {
+ this.contextMap.put(context, logLevel);
+ }
+
+ @Override
+ public boolean isEnabled(String context, int msgLevel) {
+ int level = getLogLevel(context);
+ return level >= msgLevel;
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,257 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
- <!-- Teiid Services -->
- <bean name="SessionService" class="org.teiid.services.SessionServiceImpl">
- <property name="VDBRepository"><inject bean="VDBRepository"/></property>
- <property name="securityHelper"><inject bean="SecurityHelper"/></property>
- <!-- Comma separated list of domains to be used to login into Teiid using JDBC connection-->
- <property name="securityDomains">teiid-security</property>
- <!-- security domain to be used with Admin API (please do not change this, as this should be same as profile service) -->
- <property name="adminSecurityDomain">jmx-console</property>
- <!-- Maximum number of sessions allowed by the system (default 5000) -->
- <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>
- </bean>
-
- <bean name="BufferService" class="org.teiid.services.BufferServiceImpl">
- <!-- Use disk for buffer management -->
- <property name="useDisk">true</property>
- <!-- Directory location for the buffer files -->
- <property name="diskDirectory">${jboss.server.temp.dir}/teiid</property>
- <!-- The max row count of a batch sent internally within the query processor. Should be <= the connectorBatchSize. (default 512) -->
- <property name="processorBatchSize">512</property>
- <!-- 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).
- See the admin guide for more.
- -->
- <property name="maxReserveBatchColumns">-1</property>
- <!--
- 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.
- -->
- <property name="maxProcessingBatchesColumns">-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) -->
- <property name="maxBufferSpace">51200</property>
- <!-- Max open buffer files (default 64) -->
- <property name="maxOpenFiles">64</property>
- </bean>
-
- <bean name="CacheFactory" class="org.teiid.cache.jboss.ClusterableCacheFactory">
- <property name="enabled">true</property>
- <property name="cacheManager">java:TeiidCacheManager</property>
- <property name="resultsetCacheName">teiid-resultset-cache</property>
- </bean>
-
- <!-- Configuration for result set caching.
- There will be 2 caches with these settings.
- One cache holds results that are specific to sessions.
- The other cache holds vdb scoped results and can
- be replicated.
- -->
- <bean name="ResultsetCacheConfig" class="org.teiid.cache.CacheConfiguration">
- <property name="name">ResultSetCacheConfig</property>
- <property name="enabled">true</property>
- <!-- Max Entries allowed (default 1024) -->
- <property name="maxEntries">1024</property>
- <!-- Max age in seconds (default 7200 - 2 hours) -->
- <property name="maxAgeInSeconds">7200</property>
- <!-- Max staleness in seconds. Modifications are based upon data updates
- -1 indicates no max. (default 60 - 1 minute) -->
- <property name="maxStaleness">60</property>
- <!-- Allowed values are LRU, EXPIRATION.
- Setting this value to LRU will cause cache hint TTL values
- to be ignored. (default EXPIRATION) -->
- <property name="type">EXPIRATION</property>
- <property name="location">resultset</property>
- </bean>
-
- <!-- Configuration for prepared plan caching. (local memory only)
- -->
- <bean name="PreparedPlanCacheConfig" class="org.teiid.cache.CacheConfiguration">
- <property name="name">PreparedPlanCacheConfig</property>
- <!-- Max Entries allowed (default 512) -->
- <property name="maxEntries">512</property>
- <!-- Max age in seconds (default 28800 - 8 hours) -->
- <property name="maxAgeInSeconds">28800</property>
- <!-- Max staleness in seconds. Modifications are based upon costing/metadata updates
- -1 indicates no max. (default 0) -->
- <property name="maxStaleness">0</property>
- </bean>
-
- <bean name="RuntimeEngineDeployer" class="org.teiid.jboss.deployers.RuntimeEngineDeployer">
- <property name="jndiName">teiid/engine-deployer</property>
- <property name="profileService"><inject bean="ProfileService"/></property>
- <property name="jdbcSocketConfiguration"><inject bean="JdbcSocketConfiguration"/></property>
- <property name="adminSocketConfiguration"><inject bean="AdminSocketConfiguration"/></property>
- <property name="odbcSocketConfiguration"><inject bean="OdbcSocketConfiguration"/></property>
- <property name="workManager"><inject bean="WorkManager"/></property>
- <property name="XATerminator"><inject bean="TransactionManager" property="XATerminator"/></property>
- <property name="transactionManager"><inject bean="TransactionManager" property="transactionManager"/></property>
- <property name="sessionService"><inject bean="SessionService"/></property>
- <property name="bufferService"><inject bean="BufferService"/></property>
- <property name="securityHelper"><inject bean="SecurityHelper"/></property>
- <property name="VDBRepository"><inject bean="VDBRepository"/></property>
- <property name="VDBStatusChecker"><inject bean="VDBStatusChecker"/></property>
- <property name="cacheFactory"><inject bean="CacheFactory"/></property>
- <property name="resultsetCacheConfig"><inject bean="ResultsetCacheConfig"/></property>
- <property name="preparedPlanCacheConfig"><inject bean="PreparedPlanCacheConfig"/></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. -->
- <property name="maxActivePlans">20</property>
- <!-- 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. -->
- <property name="userRequestSourceConcurrency">0</property>
- <!-- Query processor time slice, in milliseconds. (default 2000) -->
- <property name="timeSliceInMilli">2000</property>
- <!-- Maximum allowed fetch size, set via JDBC. User requested value ignored above this value. (default 20480) -->
- <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)-->
- <property name="maxSourceRows">-1</property>
- <!-- 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) -->
- <property name="exceptionOnMaxSourceRows">true</property>
- <!-- Maximum size of lob allowed through ODBC connection in bytes (default 5MB) -->
- <property name="maxODBCLobSizeAllowed">5242880</property>
- <!-- The JNDI name of the Teiid Event Distributor -->
- <property name="eventDistributorName">teiid/event-distributor</property>
- <!-- 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>
-
- <!-- JDBC Socket connection properties (SSL see below) -->
- <bean name="JdbcSocketConfiguration" class="org.teiid.transport.SocketConfiguration">
- <property name="name">JdbcSocketConfiguration</property>
- <property name="enabled">true</property>
- <property name="bindAddress">${jboss.bind.address}</property>
- <property name="portNumber">31000</property>
- <!-- 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. -->
- <property name="maxSocketThreads">0</property>
- <!-- SO_RCVBUF size, 0 indicates that system default should be used (default 0) -->
- <property name="inputBufferSize">0</property>
- <!-- SO_SNDBUF size, 0 indicates that system default should be used (default 0) -->
- <property name="outputBufferSize">0</property>
- <property name="SSLConfiguration"><inject bean="JdbcSslConfiguration"/></property>
- </bean>
-
- <bean name="JdbcSslConfiguration" class="org.teiid.transport.SSLConfiguration">
- <!-- 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
- -->
- <property name="mode">login</property>
- <property name="keystoreFilename">cert.keystore</property>
- <property name="keystorePassword">passwd</property>
- <property name="keystoreType">JKS</property>
- <property name="sslProtocol">SSLv3</property>
- <property name="keymanagementAlgorithm">false</property>
- <property name="truststoreFilename">cert.truststore</property>
- <property name="truststorePassword">passwd</property>
- <!-- 1-way, 2-way, anonymous -->
- <property name="authenticationMode">1-way</property>
- </bean>
-
- <!-- Admin Socket connection settings (SSL see below) -->
- <bean name="AdminSocketConfiguration" class="org.teiid.transport.SocketConfiguration">
- <property name="name">AdminSocketConfiguration</property>
- <property name="enabled">true</property>
- <property name="bindAddress">${jboss.bind.address}</property>
- <property name="portNumber">31443</property>
- <!-- Max number of threads dedicated to Admin request processing.
- Zero indicates the system default of max available processors. (default 4) -->
- <property name="maxSocketThreads">4</property>
- <!-- SO_RCVBUF size, 0 indicates that system default should be used (default 0) -->
- <property name="inputBufferSize">0</property>
- <!-- SO_SNDBUF size, 0 indicates that system default should be used (default 0) -->
- <property name="outputBufferSize">0</property>
- <property name="SSLConfiguration"><inject bean="AdminSslConfiguration"/></property>
- </bean>
-
- <bean name="AdminSslConfiguration" class="org.teiid.transport.SSLConfiguration">
- <!-- 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
- -->
- <property name="mode">enabled</property>
- <property name="keystoreFilename">cert.keystore</property>
- <property name="keystorePassword">passwd</property>
- <property name="keystoreType">JKS</property>
- <property name="sslProtocol">SSLv3</property>
- <property name="keymanagementAlgorithm">false</property>
- <property name="truststoreFilename">cert.truststore</property>
- <property name="truststorePassword">passwd</property>
- <!-- 1-way, 2-way, anonymous -->
- <property name="authenticationMode">anonymous</property>
- </bean>
-
- <!-- JDBC Socket connection properties (SSL see below) -->
- <bean name="OdbcSocketConfiguration" class="org.teiid.transport.SocketConfiguration">
- <property name="name">OdbcSocketConfiguration</property>
- <property name="enabled">true</property>
- <property name="bindAddress">${jboss.bind.address}</property>
- <property name="portNumber">35432</property>
- <!-- Max number of threads dedicated to ODBC request processing.
- Zero indicates the system default of max available processors. (default 0) -->
- <property name="maxSocketThreads">0</property>
- <!-- SO_RCVBUF size, 0 indicates that system default should be used (default 0) -->
- <property name="inputBufferSize">0</property>
- <!-- SO_SNDBUF size, 0 indicates that system default should be used (default 0) -->
- <property name="outputBufferSize">0</property>
- <property name="SSLConfiguration"><inject bean="OdbcSslConfiguration"/></property>
- </bean>
-
- <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
- -->
- <property name="mode">disabled</property>
- <property name="keystoreFilename">cert.keystore</property>
- <property name="keystorePassword">passwd</property>
- <property name="keystoreType">JKS</property>
- <property name="sslProtocol">SSLv3</property>
- <property name="keymanagementAlgorithm">false</property>
- <property name="truststoreFilename">cert.truststore</property>
- <property name="truststorePassword">passwd</property>
- <!-- 1-way, 2-way, anonymous -->
- <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 -->
- <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>
- </login-module>
- </authentication>
- </application-policy>
-
-</deployment>
Copied: tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml (from rev 3218, trunk/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,257 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+
+ <!-- Teiid Services -->
+ <bean name="SessionService" class="org.teiid.services.SessionServiceImpl">
+ <property name="VDBRepository"><inject bean="VDBRepository"/></property>
+ <property name="securityHelper"><inject bean="SecurityHelper"/></property>
+ <!-- Comma separated list of domains to be used to login into Teiid using JDBC connection-->
+ <property name="securityDomains">teiid-security</property>
+ <!-- security domain to be used with Admin API (please do not change this, as this should be same as profile service) -->
+ <property name="adminSecurityDomain">jmx-console</property>
+ <!-- Maximum number of sessions allowed by the system (default 5000) -->
+ <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>
+ </bean>
+
+ <bean name="BufferService" class="org.teiid.services.BufferServiceImpl">
+ <!-- Use disk for buffer management -->
+ <property name="useDisk">true</property>
+ <!-- Directory location for the buffer files -->
+ <property name="diskDirectory">${jboss.server.temp.dir}/teiid</property>
+ <!-- The max row count of a batch sent internally within the query processor. Should be <= the connectorBatchSize. (default 512) -->
+ <property name="processorBatchSize">512</property>
+ <!-- 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).
+ See the admin guide for more.
+ -->
+ <property name="maxReserveBatchColumns">-1</property>
+ <!--
+ 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.
+ -->
+ <property name="maxProcessingBatchesColumns">-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) -->
+ <property name="maxBufferSpace">51200</property>
+ <!-- Max open buffer files (default 64) -->
+ <property name="maxOpenFiles">64</property>
+ </bean>
+
+ <bean name="CacheFactory" class="org.teiid.cache.jboss.ClusterableCacheFactory">
+ <property name="enabled">true</property>
+ <property name="cacheManager">java:TeiidCacheManager</property>
+ <property name="resultsetCacheName">teiid-resultset-cache</property>
+ </bean>
+
+ <!-- Configuration for result set caching.
+ There will be 2 caches with these settings.
+ One cache holds results that are specific to sessions.
+ The other cache holds vdb scoped results and can
+ be replicated.
+ -->
+ <bean name="ResultsetCacheConfig" class="org.teiid.cache.CacheConfiguration">
+ <property name="name">ResultSetCacheConfig</property>
+ <property name="enabled">true</property>
+ <!-- Max Entries allowed (default 1024) -->
+ <property name="maxEntries">1024</property>
+ <!-- Max age in seconds (default 7200 - 2 hours) -->
+ <property name="maxAgeInSeconds">7200</property>
+ <!-- Max staleness in seconds. Modifications are based upon data updates
+ -1 indicates no max. (default 60 - 1 minute) -->
+ <property name="maxStaleness">60</property>
+ <!-- Allowed values are LRU, EXPIRATION.
+ Setting this value to LRU will cause cache hint TTL values
+ to be ignored. (default EXPIRATION) -->
+ <property name="type">EXPIRATION</property>
+ <property name="location">resultset</property>
+ </bean>
+
+ <!-- Configuration for prepared plan caching. (local memory only)
+ -->
+ <bean name="PreparedPlanCacheConfig" class="org.teiid.cache.CacheConfiguration">
+ <property name="name">PreparedPlanCacheConfig</property>
+ <!-- Max Entries allowed (default 512) -->
+ <property name="maxEntries">512</property>
+ <!-- Max age in seconds (default 28800 - 8 hours) -->
+ <property name="maxAgeInSeconds">28800</property>
+ <!-- Max staleness in seconds. Modifications are based upon costing/metadata updates
+ -1 indicates no max. (default 0) -->
+ <property name="maxStaleness">0</property>
+ </bean>
+
+ <bean name="RuntimeEngineDeployer" class="org.teiid.jboss.deployers.RuntimeEngineDeployer">
+ <property name="jndiName">teiid/engine-deployer</property>
+ <property name="profileService"><inject bean="ProfileService"/></property>
+ <property name="jdbcSocketConfiguration"><inject bean="JdbcSocketConfiguration"/></property>
+ <property name="adminSocketConfiguration"><inject bean="AdminSocketConfiguration"/></property>
+ <property name="odbcSocketConfiguration"><inject bean="OdbcSocketConfiguration"/></property>
+ <property name="workManager"><inject bean="WorkManager"/></property>
+ <property name="XATerminator"><inject bean="TransactionManager" property="XATerminator"/></property>
+ <property name="transactionManager"><inject bean="TransactionManager" property="transactionManager"/></property>
+ <property name="sessionService"><inject bean="SessionService"/></property>
+ <property name="bufferService"><inject bean="BufferService"/></property>
+ <property name="securityHelper"><inject bean="SecurityHelper"/></property>
+ <property name="VDBRepository"><inject bean="VDBRepository"/></property>
+ <property name="VDBStatusChecker"><inject bean="VDBStatusChecker"/></property>
+ <property name="cacheFactory"><inject bean="CacheFactory"/></property>
+ <property name="resultsetCacheConfig"><inject bean="ResultsetCacheConfig"/></property>
+ <property name="preparedPlanCacheConfig"><inject bean="PreparedPlanCacheConfig"/></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. -->
+ <property name="maxActivePlans">20</property>
+ <!-- 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. -->
+ <property name="userRequestSourceConcurrency">0</property>
+ <!-- Query processor time slice, in milliseconds. (default 2000) -->
+ <property name="timeSliceInMilli">2000</property>
+ <!-- Maximum allowed fetch size, set via JDBC. User requested value ignored above this value. (default 20480) -->
+ <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)-->
+ <property name="maxSourceRows">-1</property>
+ <!-- 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) -->
+ <property name="exceptionOnMaxSourceRows">true</property>
+ <!-- Maximum size of lob allowed through ODBC connection in bytes (default 5MB) -->
+ <property name="maxODBCLobSizeAllowed">5242880</property>
+ <!-- The JNDI name of the Teiid Event Distributor -->
+ <property name="eventDistributorName">teiid/event-distributor</property>
+ <!-- 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>
+
+ <!-- JDBC Socket connection properties (SSL see below) -->
+ <bean name="JdbcSocketConfiguration" class="org.teiid.transport.SocketConfiguration">
+ <property name="name">JdbcSocketConfiguration</property>
+ <property name="enabled">true</property>
+ <property name="bindAddress">${jboss.bind.address}</property>
+ <property name="portNumber">31000</property>
+ <!-- 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. -->
+ <property name="maxSocketThreads">0</property>
+ <!-- SO_RCVBUF size, 0 indicates that system default should be used (default 0) -->
+ <property name="inputBufferSize">0</property>
+ <!-- SO_SNDBUF size, 0 indicates that system default should be used (default 0) -->
+ <property name="outputBufferSize">0</property>
+ <property name="SSLConfiguration"><inject bean="JdbcSslConfiguration"/></property>
+ </bean>
+
+ <bean name="JdbcSslConfiguration" class="org.teiid.transport.SSLConfiguration">
+ <!-- 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
+ -->
+ <property name="mode">login</property>
+ <property name="keystoreFilename">cert.keystore</property>
+ <property name="keystorePassword">passwd</property>
+ <property name="keystoreType">JKS</property>
+ <property name="sslProtocol">SSLv3</property>
+ <property name="keymanagementAlgorithm">false</property>
+ <property name="truststoreFilename">cert.truststore</property>
+ <property name="truststorePassword">passwd</property>
+ <!-- 1-way, 2-way, anonymous -->
+ <property name="authenticationMode">1-way</property>
+ </bean>
+
+ <!-- Admin Socket connection settings (SSL see below) -->
+ <bean name="AdminSocketConfiguration" class="org.teiid.transport.SocketConfiguration">
+ <property name="name">AdminSocketConfiguration</property>
+ <property name="enabled">true</property>
+ <property name="bindAddress">${jboss.bind.address}</property>
+ <property name="portNumber">31443</property>
+ <!-- Max number of threads dedicated to Admin request processing.
+ Zero indicates the system default of max available processors. (default 4) -->
+ <property name="maxSocketThreads">4</property>
+ <!-- SO_RCVBUF size, 0 indicates that system default should be used (default 0) -->
+ <property name="inputBufferSize">0</property>
+ <!-- SO_SNDBUF size, 0 indicates that system default should be used (default 0) -->
+ <property name="outputBufferSize">0</property>
+ <property name="SSLConfiguration"><inject bean="AdminSslConfiguration"/></property>
+ </bean>
+
+ <bean name="AdminSslConfiguration" class="org.teiid.transport.SSLConfiguration">
+ <!-- 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
+ -->
+ <property name="mode">enabled</property>
+ <property name="keystoreFilename">cert.keystore</property>
+ <property name="keystorePassword">passwd</property>
+ <property name="keystoreType">JKS</property>
+ <property name="sslProtocol">SSLv3</property>
+ <property name="keymanagementAlgorithm">false</property>
+ <property name="truststoreFilename">cert.truststore</property>
+ <property name="truststorePassword">passwd</property>
+ <!-- 1-way, 2-way, anonymous -->
+ <property name="authenticationMode">anonymous</property>
+ </bean>
+
+ <!-- JDBC Socket connection properties (SSL see below) -->
+ <bean name="OdbcSocketConfiguration" class="org.teiid.transport.SocketConfiguration">
+ <property name="name">OdbcSocketConfiguration</property>
+ <property name="enabled">true</property>
+ <property name="bindAddress">${jboss.bind.address}</property>
+ <property name="portNumber">35432</property>
+ <!-- Max number of threads dedicated to ODBC request processing.
+ Zero indicates the system default of max available processors. (default 0) -->
+ <property name="maxSocketThreads">0</property>
+ <!-- SO_RCVBUF size, 0 indicates that system default should be used (default 0) -->
+ <property name="inputBufferSize">0</property>
+ <!-- SO_SNDBUF size, 0 indicates that system default should be used (default 0) -->
+ <property name="outputBufferSize">0</property>
+ <property name="SSLConfiguration"><inject bean="OdbcSslConfiguration"/></property>
+ </bean>
+
+ <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 if the client supports SSL
+ -->
+ <property name="mode">disabled</property>
+ <property name="keystoreFilename">cert.keystore</property>
+ <property name="keystorePassword">passwd</property>
+ <property name="keystoreType">JKS</property>
+ <property name="sslProtocol">SSLv3</property>
+ <property name="keymanagementAlgorithm">false</property>
+ <property name="truststoreFilename">cert.truststore</property>
+ <property name="truststorePassword">passwd</property>
+ <!-- 1-way, 2-way, anonymous -->
+ <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 -->
+ <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>
+ </login-module>
+ </authentication>
+ </application-policy>
+
+</deployment>
Deleted: tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/teiid-releasenotes.html
===================================================================
--- trunk/build/kits/jboss-container/teiid-releasenotes.html 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/teiid-releasenotes.html 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,228 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-<HTML>
-<HEAD>
- <META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=utf-8">
- <TITLE>Teiid ${project.version} Release Notes</TITLE>
- <META NAME="CHANGEDBY" CONTENT="Steve Hawkins">
- </STYLE>
-</HEAD>
-<BODY LANG="en-US" DIR="LTR">
-<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.
-
-<H2>Overview</H2>
-<UL>
- <LI><A HREF="#Highlights">Highlights</A>
- <LI><A HREF="#Compatibility">Compatibility Issues</A>
- <LI><A HREF="#Configuration">Configuration Issues</A>
- <LI><A HREF="#Other">Other Issues</A>
- <LI><A HREF="#LibraryUpdates">Thirdparty Library Updates</A>
- <LI><A HREF="#Details">Detailed Release Notes</A>
- <LI><A HREF="#Documentation">Additional Docs and Help</A>
- <LI><A HREF="#Licenses">Licenses</A>
- <LI><A HREF="#About">About JBoss</A>
-</UL>
-<H2><A NAME="Highlights"></A>Highlights</H2>
-
-<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.
-</ul>
-
-<h4>from 7.3</h4>
-<ul>
- <li>SYS.PROPERTIES has a new column, ClobValue, to get values exceeding the max string length
- <li>SYS.COLUMNS has two new columns to get statistical information: DistinctCount and NullCount
- <li>ARRAY_AGG is now a reserved word</li>
- <li>The use of an IN procedure parameter with the name "source_name" in a multi-source model, will now be treated the parameter that controls which source
- the procedure will execute against.
- <li>Dynamic VDB functions injected via ExecutionFactory.getPushdownFunctions are now scoped to the SYS schema and have a fully qualified name that includes their source type. For example, instead of oracle_model.relate - which was only valid against the oracle_model source, there is now the SYS.oracle_sdo.relate function that is valid for all Oracle sources. Any fully-qualified reference to these functions will need updated.
-</ul>
-
-<h4>from 7.2</h4>
-<ul>
- <li>The default JDBC credentials are user/user - not admin/teiid
- <li>Unordered limits are no longer pushed through conditions, dup removal, or UNION not all. This prevents the possibility of getting less results than the logical intent of the limit.
-</ul>
-
-<h4>from 7.1</h4>
-<ul>
- <li>Subqueries are no longer allowed to be SELECT INTO.
- <li>INSERT/UPDATE/DELETE cannot be used to create implicit return cursors in non-update virtual procedures. You can instead use "UPDATE ...; SELECT VARIABLES.ROWCOUNT;".
- <li>The SYSADMIN schema was created to hold procedures and tables that should not be generally accessible. SYS and pg_catalog are now always accessible - permissions do not apply to these schemas. The SYS.getBinaryVDBResource, SYS.getCharacterVDBResource, and SYS.getVDBResourcePaths have been replaced with the
- SYSADMIN.VDBResources table. The Matviews table and the refreshMatView/refreshMatViewRow procedures were also moved into SYSADMIN.
- <li>Overwriting an existing VDB will cause old connections to be terminated. Production systems should rely on VDB versioning.
- <li>The jdbc:metamatrix JDBC URL prefix is no longer accepted. Use jdbc:teiid instead.
- <li>Model visibility no longer restricts access to tables and procedures. Setting visible to false will only hide entries from system tables. Data roles should be used to restrict data access.
- <li>Admin API "getWorkManagerStats" methods renamed to "getWorkerPoolStats". Also, "setRuntimeProperty" and "getProcesses" methods were removed.
- <li>By default the "ENV" system function is now turned off. To enable it, edit the teiid-jboss-beans.xml configuration file.
- <li>The use of VARIABLES.ROWCOUNT is now reserved.
- <li>Exec statements of the form "var = EXEC foo()" are only valid if the procedure foo has a return parameter.
- <li>Cache hint now supports "scope" definition. For ex: /* cache(scope:user) */ select * from T1; This hint will override the computed scope based on the query.
-</ul>
-<h4>from 7.0</h4>
-<ul>
- <li>The term data policy was replaced with data role. The AdminAPI methods for adding role mappings have changed from addRoleToDataPolicy and removeRoleFromDataPolicy to addDataRoleMapping and removeDataRoleMapping respectively.
-</ul>
-<h4>from 6.2</h4>
-<ul>
- <li>The connector API has changed substantially. Custom connectors need to be retargeted to the new Translator API. See <a href="https://jira.jboss.org/browse/TEIID-1003">TEIID-1003</a> and the <a href="teiid-docs/teiid_developers_guide.pdf">Developer's Guide</a> for more information.
- <li>Connector bindings are no longer valid. Use the Designer Tooling or see the AdminShell download for a migration utility.
- <li>Calling out to web services and xml processing has been dramatically simplified and improved, but is a breaking change from prior releases.
- XML/Relational processing has been replaced by XMLTABLE, retrieving XML from file has been replaced by the File Translator/Resource Adapter, and
- web service calls have been replaced by the WS Translator/Resource Adapter. See <a href="https://jira.jboss.org/browse/TEIID-1118">TEIID-1118</a>, <a href="https://jira.jboss.org/browse/TEIID-1114">TEIID-1114</a>, and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
- <li>The direct usage of XQuery has been replaced with the XMLQuery function.
- <li>The text connector file processing has been replaced with the TEXTTABLE function. See <a href="https://jira.jboss.org/browse/TEIID-1102">TEIID-1102</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information
- <li>Double quoted values are now parsed as identifiers by default. See <a href="https://jira.jboss.org/browse/TEIID-145">TEIID-145</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
- <li>The system information schema has changed from System to SYS. The tables and table structures have also changed. See <a href="https://jira.jboss.org/browse/TEIID-871">TEIID-871</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
- <li>Client control over query plans has changed. OPTION PLANONLY, DEBUG, and SHOWPLAN are no longer allowed. This behavior should not be controlled by the SET statement, SET SHOWPLAN (ON|OFF|DEBUG) and SET NOEXEC (ON|OFF). Usage of the client PlanNode class will also need to be updated.
- <li>Teiid specific JDBC client interfaces and methods have changed. In general these custom features have mostly been moved to other more standard locations or been removed. See <a href="https://jira.jboss.org/browse/TEIID-1020">TEIID-1020</a> and the <a href="teiid-docs/teiid_client_developers_guide.pdf">Client Developers</a> guide for more information.
- <li>Teiid's reserved words have changed. Many of the Teiid specific reserved words have become non-reserved words. All of SQL Foundation and SQL/MED 2003, and SQL/XML from SQL 2006 reserved words have been added as reserved words. It is generally required to double quote all reserved words. It is advisable to double quote all non-reserved words as well. The use of the INPUT qualifier for procedure inputs has been deprecated in favor of INPUTS. The use of the USING qualifier for dynamic SQL inputs has been deprecated in favor of DVARS.
- <li>The AdminApi has been redesigned for use with the new Translator/JCA split and for deployment in JBoss AS.
- <li>The AdminShell is based on Groovy. Most BeanShell syntax is also valid in Groovy, but there are extensive changes in the AdminAPI that may necessitate rewriting scripts.
- <li>OPTION NO CACHE <table list> will now only by-pass cache for the given tables at their immediate view layer. Previously all caches would have transitively been skipped. See <a href="https://jira.jboss.org/browse/TEIID-900">TEIID-900</a> for more information.
- <li>Nan and +-Infinity are no longer allowed as numerical results by default. This may be changed via the system property org.teiid.allowNanInfinity.
- <li>The scale of BigDecimal values is now adjusted to allow for more intuitive results. Conversion from floating numeric types will preserve the approximate scale and division results will allow for additional scale. See <a href="https://jira.jboss.org/browse/TEIID-159">TEIID-159</a> for more information.
- <li>The 7.0 client is not compatible with 6.x or vice versa. It is expected that 7.0 clients will be compatible with 7.x releases for standard JDBC operations.
-</ul>
-
-<h2><a name="Configuration">Configuration Issues</a></h2>
-
-See the <a href="teiid-docs/teiid_admin_guide.pdf">Admin Guide</a> for more on configuration and installation.
-
-<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.
- <LI>The prepared plan cache is now configured via the PreparedPlanCacheConfig bean, rather than through properties on the RuntimeEngineDeployer
- <LI>SocketConfiguration.maxSocketThreads will interpret a setting of 0 to mean use the system default of max available processors. Both the ODBC and JDBC transports now default to the 0 setting.
- <LI>maxReserveBatchColumns and maxProcessingBatchesColumns will interpret a setting of -1 to mean auto-calculate acceptable values given the max heap and other information. See the admin guide for more.
- <LI>The default for org.teiid.useValueCache has changed to false, since typical installations will not greatly benefit from the additional lookup cost.
- <LI>The property RuntimeEngineDeployer.allowFunctionCallsByDefault was added so that Teiid 7.4 behavior is compatible with Teiid 7.3. Set this property to false to require permissions for function calls when data roles are enabled.
-</ul>
-
-<h4>from 7.2</h4>
-<ul>
- <LI>Temporary tables can now be restricted by data roles. Use the data-role attribute allow-create-temporary-tables to explicitly enable or disable the usage of temporary tables.
-There is also a allowCreateTemporaryTablesByDefault property in the teiid-jboss-beans.xml to control whether usage is allowed by default. For compatibility with prior 7.x releases, the default is to allow
-temporary table access.
-</ul>
-
-<h4>from 7.1</h4>
-<ul>
- <li>Teiid clients now allow the usage of anonymous SSL by default.
- This changes allows the admin port (default 31443) to use anonymous SSL by default, rather than just securing login traffic.
- Admin clients should therefore use the mms protocol instead of mm. This will encrypt all admin traffic and ensure that any passwords in configuration files will
- be encrypted in transit. See the Admin Guide to upgrade from anonymous SSL to 1-way or 2-way authentication.
- The config properties sslEnabled and clientEncryptionEnabled for SSLConfiguration beans have been combined to a single property mode, that can have the values disabled|login|enabled.
- <li>Apache CXF is now expected to be used as the web services stack provider through JBossWS-CXF. See the Admin Guide for instructions on
- installing CXF for use with Teiid's Salesforce and web service connectors. The WS Resource Adapter's -ds.xml files should no longer use
- WSSecurityConfigURL and WSSecurityConfigName, rather they should be ConfigFile and ConfigName respectively. The property values should no longer
- refer to jboss-wsse-client.xml, but instead they should reference a CXF Spring configuration file and particular port configuration. See the Admin Guide
- for more on using CXF configuration files.
- <li>The default for data role checking is now "true". However only VDBs with data roles will have roles enforced.
- <li>The default prepared plan cache size was increased to 512, since it is targeted by internal plans as well.
-</ul>
-
-<h4>from 7.0</h4>
-<ul>
- <li>The property to enable data roles in teiid-jboss-beans.xml has changed from useEntitlements to useDataRoles.
- <li>Rar file names no longer contain version numbers. -ds.xml files should be updated from connector-XXX-version.rar to teiid-connector-XXX.rar
- <li>Code table relate configuration properties have been removed. Code tables are now implemented as materialized views.
-</ul>
-
-<h4>from 6.2</h4>
-<ul>
- <li>A JBoss AS instance is now required. Embedded mode is also currently not supported.</li>
- <li>Engine configuration is now handled through the admin console or deploy/teiid/teiid-jboss-beans.xml
- <li>Logging is now done through the container's log4j instance. Any Teiid specific logging changes, see the conf/jboss-teiid-log4j.xml, need to be incorporated into the master jboss-log4j.xml.
-</ul>
-
-<h2><a name="Other">Other Issues</a></h2>
-<ul>
- <li>TEIID-1170 - correlated subqueries are not allowed in UPDATEs or DELETEs against internal Teiid tables (internal materialized views or temporary tables).
- <li>TEIID-1281 - Negative start indexing is not supported by DB2 and Derby databases. Usage of the Teiid SUBSTRING against these sources should not use negative start values.
- <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.
-</ul>
-<h4>from 7.0</h4>
-<ul>
- <li>Fixed xsd type handling for SQL/XML and XML document models. xsd:date, xsd:dateTime, and xsd:time types will now all be displayed using the GMT timezone (Z). SQL types, such as timestamp, used for an XMLTABLE column will now expect their values to be in the form of the corresponding xsd type.
-</ul>
-<h4>From 6.2</h4>
-<ul>
- <li>Start time is now significantly longer due to the container deployment. However many operations can be performed on configruation files that will trigger a redeployment without the need for a restart.
- <li>Inversion of parse, format, and convert system functions is not used if it can be narrowing. In situations where a predicate has the form: parseTime(column, 'format') = {t 'time value'} may lead to reduced performance, since
- the parseTime function cannot be pushed down. This should be addressed in future releases.
-</ul>
-
-<h2><a name="LibraryUpdates">Thirdparty Library Updates</a></h2>
-
-The following components have been updated:
-<h4>From 7.1</h4>
-<ul>
- <li>json-simple 1.1 was added.
- <li>Netty was upgraded to 3.2.1
-</ul>
-<h4>From 7.0</h4>
-<ul>
- <li>Direct integration of JBossCache jars was removed.
- <li>Netty was upgraded to 3.2.0
- <li>JDOM was removed.
-</ul>
-<h4>From 6.2</h4>
-<ul>
- <li>Netty was upgraded to 3.1.5
- <li>Saxon was upgraded to 9.1.0.8
- <li>A 5.1 container's version of Arjuna is newer than what was previously included in Teiid 6.x.
- <li>Various other dependencies have been removed as they are no longer needed or now provided by the container.
-</ul>
-
-<h2><a name="Details">Detailed Release Notes</a></h2>
- Detailed Release Notes - Teiid - Version ${project.version}
-
-<h2><a name="Documentation">Documentation and Help</a></h2>
-
-The <a href="http://www.jboss.org/teiid/">Teiid community project</a> is hosted on jboss.org.
-Documentation and help may be obtained from the local distribution under <a href="teiid-docs">teiid-docs</a> or the following locations.
-<ul>
-
-<li><a href="http://www.jboss.org/teiid/docs">Online Documentation</a></li>
-<li><a href="https://community.jboss.org/wiki/TheTeiidProject">Wiki</a></li>
-<li><a href="http://jira.jboss.org/jira/browse/TEIID">JIRA</a></li>
-<li><a href="http://community.jboss.org/en/teiid?view=discussions">Forums</a></li>
-</ul>
-
-
-<h2><a name="Licenses">Licenses</a></h2>
-
-<p>Teiid is licensed under the <a href="LICENSE-lgpl-2.1.txt">LGPL</a>. The
-license texts for Teiid and the thirdparty components it uses may be found in the <a href="teiid-docs/licenses">teiid-docs/licenses</a>
-directory of the distribution.
-
-</p>
-
-<h2><a name="About">About JBoss, a
-division of Red Hat</a></h2>
-
-<p>JBoss, a division of <a href="http://www.redhat.com/jboss/">Red
-Hat</a>, is in the business of
-providing
-superior technical support to our customers. Our goal is to make
-Professional Open Source™ the <b>SAFE
-CHOICE</b>
-for you. We accomplish this by backing up our open source Java products
-with technical support services that are delivered by the core
-developers themselves. We can help you to train your staff and provide
-you with support at every stage of the application lifecycle - from
-development and integration through deployment and maintenance. Visit
-the <a href="http://www.jboss.com/services/index">JBoss
-Services</a> page for more
-information.</p>
-
-</BODY>
-</HTML>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/teiid-releasenotes.html (from rev 3218, trunk/build/kits/jboss-container/teiid-releasenotes.html)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/teiid-releasenotes.html (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/build/kits/jboss-container/teiid-releasenotes.html 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,234 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<HTML>
+<HEAD>
+ <META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=utf-8">
+ <TITLE>Teiid ${project.version} Release Notes</TITLE>
+ <META NAME="CHANGEDBY" CONTENT="Steve Hawkins">
+ </STYLE>
+</HEAD>
+<BODY LANG="en-US" DIR="LTR">
+<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.
+
+<H2>Overview</H2>
+<UL>
+ <LI><A HREF="#Highlights">Highlights</A>
+ <LI><A HREF="#Compatibility">Compatibility Issues</A>
+ <LI><A HREF="#Configuration">Configuration Issues</A>
+ <LI><A HREF="#Other">Other Issues</A>
+ <LI><A HREF="#LibraryUpdates">Thirdparty Library Updates</A>
+ <LI><A HREF="#Details">Detailed Release Notes</A>
+ <LI><A HREF="#Documentation">Additional Docs and Help</A>
+ <LI><A HREF="#Licenses">Licenses</A>
+ <LI><A HREF="#About">About JBoss</A>
+</UL>
+<H2><A NAME="Highlights"></A>Highlights</H2>
+<UL>
+ <LI><B>Subquery optimization control</B> - added the DJ hint to indicate that a subquery should be the independent side of a dependent join.
+ <LI><B>MAKEIND Hint</B> - The MAKEIND hint can be used to indicate that the other side of the join should be made dependent.
+ <LI><B>ODBC SSL</B> - added support for SSL encrypted ODBC connections.
+ <LI><B>Reauthentication Statement</B> - SET SESSION AUTHORIZATION can now be used to perform a reauthentication via JDBC or ODBC.
+</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.3</h4>
+<ul>
+ <li>SYS.PROPERTIES has a new column, ClobValue, to get values exceeding the max string length
+ <li>SYS.COLUMNS has two new columns to get statistical information: DistinctCount and NullCount
+ <li>ARRAY_AGG is now a reserved word</li>
+ <li>The use of an IN procedure parameter with the name "source_name" in a multi-source model, will now be treated the parameter that controls which source
+ the procedure will execute against.
+ <li>Dynamic VDB functions injected via ExecutionFactory.getPushdownFunctions are now scoped to the SYS schema and have a fully qualified name that includes their source type. For example, instead of oracle_model.relate - which was only valid against the oracle_model source, there is now the SYS.oracle_sdo.relate function that is valid for all Oracle sources. Any fully-qualified reference to these functions will need updated.
+</ul>
+
+<h4>from 7.2</h4>
+<ul>
+ <li>The default JDBC credentials are user/user - not admin/teiid
+ <li>Unordered limits are no longer pushed through conditions, dup removal, or UNION not all. This prevents the possibility of getting less results than the logical intent of the limit.
+</ul>
+
+<h4>from 7.1</h4>
+<ul>
+ <li>Subqueries are no longer allowed to be SELECT INTO.
+ <li>INSERT/UPDATE/DELETE cannot be used to create implicit return cursors in non-update virtual procedures. You can instead use "UPDATE ...; SELECT VARIABLES.ROWCOUNT;".
+ <li>The SYSADMIN schema was created to hold procedures and tables that should not be generally accessible. SYS and pg_catalog are now always accessible - permissions do not apply to these schemas. The SYS.getBinaryVDBResource, SYS.getCharacterVDBResource, and SYS.getVDBResourcePaths have been replaced with the
+ SYSADMIN.VDBResources table. The Matviews table and the refreshMatView/refreshMatViewRow procedures were also moved into SYSADMIN.
+ <li>Overwriting an existing VDB will cause old connections to be terminated. Production systems should rely on VDB versioning.
+ <li>The jdbc:metamatrix JDBC URL prefix is no longer accepted. Use jdbc:teiid instead.
+ <li>Model visibility no longer restricts access to tables and procedures. Setting visible to false will only hide entries from system tables. Data roles should be used to restrict data access.
+ <li>Admin API "getWorkManagerStats" methods renamed to "getWorkerPoolStats". Also, "setRuntimeProperty" and "getProcesses" methods were removed.
+ <li>By default the "ENV" system function is now turned off. To enable it, edit the teiid-jboss-beans.xml configuration file.
+ <li>The use of VARIABLES.ROWCOUNT is now reserved.
+ <li>Exec statements of the form "var = EXEC foo()" are only valid if the procedure foo has a return parameter.
+ <li>Cache hint now supports "scope" definition. For ex: /* cache(scope:user) */ select * from T1; This hint will override the computed scope based on the query.
+</ul>
+<h4>from 7.0</h4>
+<ul>
+ <li>The term data policy was replaced with data role. The AdminAPI methods for adding role mappings have changed from addRoleToDataPolicy and removeRoleFromDataPolicy to addDataRoleMapping and removeDataRoleMapping respectively.
+</ul>
+<h4>from 6.2</h4>
+<ul>
+ <li>The connector API has changed substantially. Custom connectors need to be retargeted to the new Translator API. See <a href="https://jira.jboss.org/browse/TEIID-1003">TEIID-1003</a> and the <a href="teiid-docs/teiid_developers_guide.pdf">Developer's Guide</a> for more information.
+ <li>Connector bindings are no longer valid. Use the Designer Tooling or see the AdminShell download for a migration utility.
+ <li>Calling out to web services and xml processing has been dramatically simplified and improved, but is a breaking change from prior releases.
+ XML/Relational processing has been replaced by XMLTABLE, retrieving XML from file has been replaced by the File Translator/Resource Adapter, and
+ web service calls have been replaced by the WS Translator/Resource Adapter. See <a href="https://jira.jboss.org/browse/TEIID-1118">TEIID-1118</a>, <a href="https://jira.jboss.org/browse/TEIID-1114">TEIID-1114</a>, and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
+ <li>The direct usage of XQuery has been replaced with the XMLQuery function.
+ <li>The text connector file processing has been replaced with the TEXTTABLE function. See <a href="https://jira.jboss.org/browse/TEIID-1102">TEIID-1102</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information
+ <li>Double quoted values are now parsed as identifiers by default. See <a href="https://jira.jboss.org/browse/TEIID-145">TEIID-145</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
+ <li>The system information schema has changed from System to SYS. The tables and table structures have also changed. See <a href="https://jira.jboss.org/browse/TEIID-871">TEIID-871</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
+ <li>Client control over query plans has changed. OPTION PLANONLY, DEBUG, and SHOWPLAN are no longer allowed. This behavior should not be controlled by the SET statement, SET SHOWPLAN (ON|OFF|DEBUG) and SET NOEXEC (ON|OFF). Usage of the client PlanNode class will also need to be updated.
+ <li>Teiid specific JDBC client interfaces and methods have changed. In general these custom features have mostly been moved to other more standard locations or been removed. See <a href="https://jira.jboss.org/browse/TEIID-1020">TEIID-1020</a> and the <a href="teiid-docs/teiid_client_developers_guide.pdf">Client Developers</a> guide for more information.
+ <li>Teiid's reserved words have changed. Many of the Teiid specific reserved words have become non-reserved words. All of SQL Foundation and SQL/MED 2003, and SQL/XML from SQL 2006 reserved words have been added as reserved words. It is generally required to double quote all reserved words. It is advisable to double quote all non-reserved words as well. The use of the INPUT qualifier for procedure inputs has been deprecated in favor of INPUTS. The use of the USING qualifier for dynamic SQL inputs has been deprecated in favor of DVARS.
+ <li>The AdminApi has been redesigned for use with the new Translator/JCA split and for deployment in JBoss AS.
+ <li>The AdminShell is based on Groovy. Most BeanShell syntax is also valid in Groovy, but there are extensive changes in the AdminAPI that may necessitate rewriting scripts.
+ <li>OPTION NO CACHE <table list> will now only by-pass cache for the given tables at their immediate view layer. Previously all caches would have transitively been skipped. See <a href="https://jira.jboss.org/browse/TEIID-900">TEIID-900</a> for more information.
+ <li>Nan and +-Infinity are no longer allowed as numerical results by default. This may be changed via the system property org.teiid.allowNanInfinity.
+ <li>The scale of BigDecimal values is now adjusted to allow for more intuitive results. Conversion from floating numeric types will preserve the approximate scale and division results will allow for additional scale. See <a href="https://jira.jboss.org/browse/TEIID-159">TEIID-159</a> for more information.
+ <li>The 7.0 client is not compatible with 6.x or vice versa. It is expected that 7.0 clients will be compatible with 7.x releases for standard JDBC operations.
+</ul>
+
+<h2><a name="Configuration">Configuration Issues</a></h2>
+
+See the <a href="teiid-docs/teiid_admin_guide.pdf">Admin Guide</a> for more on configuration and installation.
+
+<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.
+ <LI>The prepared plan cache is now configured via the PreparedPlanCacheConfig bean, rather than through properties on the RuntimeEngineDeployer
+ <LI>SocketConfiguration.maxSocketThreads will interpret a setting of 0 to mean use the system default of max available processors. Both the ODBC and JDBC transports now default to the 0 setting.
+ <LI>maxReserveBatchColumns and maxProcessingBatchesColumns will interpret a setting of -1 to mean auto-calculate acceptable values given the max heap and other information. See the admin guide for more.
+ <LI>The default for org.teiid.useValueCache has changed to false, since typical installations will not greatly benefit from the additional lookup cost.
+ <LI>The property RuntimeEngineDeployer.allowFunctionCallsByDefault was added so that Teiid 7.4 behavior is compatible with Teiid 7.3. Set this property to false to require permissions for function calls when data roles are enabled.
+</ul>
+
+<h4>from 7.2</h4>
+<ul>
+ <LI>Temporary tables can now be restricted by data roles. Use the data-role attribute allow-create-temporary-tables to explicitly enable or disable the usage of temporary tables.
+There is also a allowCreateTemporaryTablesByDefault property in the teiid-jboss-beans.xml to control whether usage is allowed by default. For compatibility with prior 7.x releases, the default is to allow
+temporary table access.
+</ul>
+
+<h4>from 7.1</h4>
+<ul>
+ <li>Teiid clients now allow the usage of anonymous SSL by default.
+ This changes allows the admin port (default 31443) to use anonymous SSL by default, rather than just securing login traffic.
+ Admin clients should therefore use the mms protocol instead of mm. This will encrypt all admin traffic and ensure that any passwords in configuration files will
+ be encrypted in transit. See the Admin Guide to upgrade from anonymous SSL to 1-way or 2-way authentication.
+ The config properties sslEnabled and clientEncryptionEnabled for SSLConfiguration beans have been combined to a single property mode, that can have the values disabled|login|enabled.
+ <li>Apache CXF is now expected to be used as the web services stack provider through JBossWS-CXF. See the Admin Guide for instructions on
+ installing CXF for use with Teiid's Salesforce and web service connectors. The WS Resource Adapter's -ds.xml files should no longer use
+ WSSecurityConfigURL and WSSecurityConfigName, rather they should be ConfigFile and ConfigName respectively. The property values should no longer
+ refer to jboss-wsse-client.xml, but instead they should reference a CXF Spring configuration file and particular port configuration. See the Admin Guide
+ for more on using CXF configuration files.
+ <li>The default for data role checking is now "true". However only VDBs with data roles will have roles enforced.
+ <li>The default prepared plan cache size was increased to 512, since it is targeted by internal plans as well.
+</ul>
+
+<h4>from 7.0</h4>
+<ul>
+ <li>The property to enable data roles in teiid-jboss-beans.xml has changed from useEntitlements to useDataRoles.
+ <li>Rar file names no longer contain version numbers. -ds.xml files should be updated from connector-XXX-version.rar to teiid-connector-XXX.rar
+ <li>Code table relate configuration properties have been removed. Code tables are now implemented as materialized views.
+</ul>
+
+<h4>from 6.2</h4>
+<ul>
+ <li>A JBoss AS instance is now required. Embedded mode is also currently not supported.</li>
+ <li>Engine configuration is now handled through the admin console or deploy/teiid/teiid-jboss-beans.xml
+ <li>Logging is now done through the container's log4j instance. Any Teiid specific logging changes, see the conf/jboss-teiid-log4j.xml, need to be incorporated into the master jboss-log4j.xml.
+</ul>
+
+<h2><a name="Other">Other Issues</a></h2>
+<ul>
+ <li>TEIID-1170 - correlated subqueries are not allowed in UPDATEs or DELETEs against internal Teiid tables (internal materialized views or temporary tables).
+ <li>TEIID-1281 - Negative start indexing is not supported by DB2 and Derby databases. Usage of the Teiid SUBSTRING against these sources should not use negative start values.
+ <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.
+</ul>
+<h4>from 7.0</h4>
+<ul>
+ <li>Fixed xsd type handling for SQL/XML and XML document models. xsd:date, xsd:dateTime, and xsd:time types will now all be displayed using the GMT timezone (Z). SQL types, such as timestamp, used for an XMLTABLE column will now expect their values to be in the form of the corresponding xsd type.
+</ul>
+<h4>From 6.2</h4>
+<ul>
+ <li>Start time is now significantly longer due to the container deployment. However many operations can be performed on configruation files that will trigger a redeployment without the need for a restart.
+ <li>Inversion of parse, format, and convert system functions is not used if it can be narrowing. In situations where a predicate has the form: parseTime(column, 'format') = {t 'time value'} may lead to reduced performance, since
+ the parseTime function cannot be pushed down. This should be addressed in future releases.
+</ul>
+
+<h2><a name="LibraryUpdates">Thirdparty Library Updates</a></h2>
+
+The following components have been updated:
+<h4>From 7.1</h4>
+<ul>
+ <li>json-simple 1.1 was added.
+ <li>Netty was upgraded to 3.2.1
+</ul>
+<h4>From 7.0</h4>
+<ul>
+ <li>Direct integration of JBossCache jars was removed.
+ <li>Netty was upgraded to 3.2.0
+ <li>JDOM was removed.
+</ul>
+<h4>From 6.2</h4>
+<ul>
+ <li>Netty was upgraded to 3.1.5
+ <li>Saxon was upgraded to 9.1.0.8
+ <li>A 5.1 container's version of Arjuna is newer than what was previously included in Teiid 6.x.
+ <li>Various other dependencies have been removed as they are no longer needed or now provided by the container.
+</ul>
+
+<h2><a name="Details">Detailed Release Notes</a></h2>
+ Detailed Release Notes - Teiid - Version ${project.version}
+
+<h2><a name="Documentation">Documentation and Help</a></h2>
+
+The <a href="http://www.jboss.org/teiid/">Teiid community project</a> is hosted on jboss.org.
+Documentation and help may be obtained from the local distribution under <a href="teiid-docs">teiid-docs</a> or the following locations.
+<ul>
+
+<li><a href="http://www.jboss.org/teiid/docs">Online Documentation</a></li>
+<li><a href="https://community.jboss.org/wiki/TheTeiidProject">Wiki</a></li>
+<li><a href="http://jira.jboss.org/jira/browse/TEIID">JIRA</a></li>
+<li><a href="http://community.jboss.org/en/teiid?view=discussions">Forums</a></li>
+</ul>
+
+
+<h2><a name="Licenses">Licenses</a></h2>
+
+<p>Teiid is licensed under the <a href="LICENSE-lgpl-2.1.txt">LGPL</a>. The
+license texts for Teiid and the thirdparty components it uses may be found in the <a href="teiid-docs/licenses">teiid-docs/licenses</a>
+directory of the distribution.
+
+</p>
+
+<h2><a name="About">About JBoss, a
+division of Red Hat</a></h2>
+
+<p>JBoss, a division of <a href="http://www.redhat.com/jboss/">Red
+Hat</a>, is in the business of
+providing
+superior technical support to our customers. Our goal is to make
+Professional Open Source™ the <b>SAFE
+CHOICE</b>
+for you. We accomplish this by backing up our open source Java products
+with technical support services that are delivered by the core
+developers themselves. We can help you to train your staff and provide
+you with support at every stage of the application lifecycle - from
+development and integration through deployment and maintenance. Visit
+the <a href="http://www.jboss.com/services/index">JBoss
+Services</a> page for more
+information.</p>
+
+</BODY>
+</HTML>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/build/pom.xml
===================================================================
--- trunk/build/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/build/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,136 +0,0 @@
-<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</artifactId>
- <name>Build</name>
- <description>Teiid Build</description>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client-jdk15</artifactId>
- <version>${version}</version>
- </dependency>
- <dependency>
- <groupId>net.sf.retrotranslator</groupId>
- <artifactId>retrotranslator-runtime</artifactId>
- <version>1.2.9</version>
- </dependency>
-
- <dependency>
- <groupId>net.sf.retrotranslator</groupId>
- <artifactId>retrotranslator-transformer</artifactId>
- <version>1.2.9</version>
- </dependency>
- </dependencies>
- <build>
- <outputDirectory>target/kits</outputDirectory>
- <resources>
- <resource>
- <directory>kits</directory>
- <filtering>true</filtering>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- <include>**/*.sh</include>
- <include>**/*.bat</include>
- <include>**/*.html</include>
- </includes>
- </resource>
- <resource>
- <directory>kits</directory>
- <filtering>false</filtering>
- <excludes>
- <exclude>**/*.xml</exclude>
- <exclude>**/*.properties</exclude>
- <exclude>**/*.sh</exclude>
- <exclude>**/*.bat</exclude>
- <exclude>**/*.html</exclude>
- </excludes>
- </resource>
- </resources>
- <pluginManagement>
- <plugins>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- </plugin>
- </plugins>
- </pluginManagement>
- <plugins>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
-
- <configuration>
- <descriptors>
- <descriptor>assembly/client-jar.xml</descriptor>
- <descriptor>assembly/jboss-container/dist.xml</descriptor>
- <descriptor>assembly/adminshell/adminshell-dist.xml</descriptor>
- </descriptors>
- </configuration>
-
- <executions>
- <execution>
- <id>create-assemblies</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-
- <profiles>
- <profile>
- <!--
- This profile is activated manually, as in "mvn ... -P release ..."
- -->
- <id>release</id>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <configuration>
- <descriptors>
- <descriptor>assembly/src.xml</descriptor>
- <descriptor>assembly/docs.xml</descriptor>
- <descriptor>assembly/client-jar.xml</descriptor>
- <descriptor>assembly/jboss-container/dist.xml</descriptor>
- <descriptor>assembly/adminshell/adminshell-dist.xml</descriptor>
- </descriptors>
- </configuration>
- </plugin>
-
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>exec-maven-plugin</artifactId>
- <version>1.1.1</version>
- <executions>
- <execution>
- <phase>package</phase>
- <goals>
- <goal>java</goal>
- </goals>
- <configuration>
- <mainClass>net.sf.retrotranslator.transformer.Retrotranslator</mainClass>
- <arguments>
- <argument>-srcjar</argument>
- <argument>${pom.basedir}/target/teiid-${pom.version}-client.jar</argument>
- <argument>-destjar</argument>
- <argument>${pom.basedir}/target/teiid-${pom.version}-client-jdk15.jar</argument>
- <argument>-embed</argument>
- <argument>org.teiid.retroruntime</argument>
- </arguments>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/build/pom.xml (from rev 3220, trunk/build/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/build/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/build/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,136 @@
+<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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>teiid</artifactId>
+ <name>Build</name>
+ <description>Teiid Build</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client-jdk15</artifactId>
+ <version>${version}</version>
+ </dependency>
+ <dependency>
+ <groupId>net.sf.retrotranslator</groupId>
+ <artifactId>retrotranslator-runtime</artifactId>
+ <version>1.2.9</version>
+ </dependency>
+
+ <dependency>
+ <groupId>net.sf.retrotranslator</groupId>
+ <artifactId>retrotranslator-transformer</artifactId>
+ <version>1.2.9</version>
+ </dependency>
+ </dependencies>
+ <build>
+ <outputDirectory>target/kits</outputDirectory>
+ <resources>
+ <resource>
+ <directory>kits</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.xml</include>
+ <include>**/*.properties</include>
+ <include>**/*.sh</include>
+ <include>**/*.bat</include>
+ <include>**/*.html</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>kits</directory>
+ <filtering>false</filtering>
+ <excludes>
+ <exclude>**/*.xml</exclude>
+ <exclude>**/*.properties</exclude>
+ <exclude>**/*.sh</exclude>
+ <exclude>**/*.bat</exclude>
+ <exclude>**/*.html</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+
+ <configuration>
+ <descriptors>
+ <descriptor>assembly/client-jar.xml</descriptor>
+ <descriptor>assembly/jboss-container/dist.xml</descriptor>
+ <descriptor>assembly/adminshell/adminshell-dist.xml</descriptor>
+ </descriptors>
+ </configuration>
+
+ <executions>
+ <execution>
+ <id>create-assemblies</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+ <profiles>
+ <profile>
+ <!--
+ This profile is activated manually, as in "mvn ... -P release ..."
+ -->
+ <id>release</id>
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <configuration>
+ <descriptors>
+ <descriptor>assembly/src.xml</descriptor>
+ <descriptor>assembly/docs.xml</descriptor>
+ <descriptor>assembly/client-jar.xml</descriptor>
+ <descriptor>assembly/jboss-container/dist.xml</descriptor>
+ <descriptor>assembly/adminshell/adminshell-dist.xml</descriptor>
+ </descriptors>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>exec-maven-plugin</artifactId>
+ <version>1.1.1</version>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>java</goal>
+ </goals>
+ <configuration>
+ <mainClass>net.sf.retrotranslator.transformer.Retrotranslator</mainClass>
+ <arguments>
+ <argument>-srcjar</argument>
+ <argument>${pom.basedir}/target/teiid-${pom.version}-client.jar</argument>
+ <argument>-destjar</argument>
+ <argument>${pom.basedir}/target/teiid-${pom.version}-client-jdk15.jar</argument>
+ <argument>-embed</argument>
+ <argument>org.teiid.retroruntime</argument>
+ </arguments>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/pom.xml
===================================================================
--- trunk/cache-jbosscache/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,39 +0,0 @@
-<?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-cache-jbosscache</artifactId>
- <name>JBoss Cache</name>
- <description>JBossCache provider.</description>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-engine</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.cache</groupId>
- <artifactId>jbosscache-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.man</groupId>
- <artifactId>jboss-managed</artifactId>
- <scope>provided</scope>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/pom.xml (from rev 3220, trunk/cache-jbosscache/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,39 @@
+<?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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>teiid-cache-jbosscache</artifactId>
+ <name>JBoss Cache</name>
+ <description>JBossCache provider.</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-engine</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.cache</groupId>
+ <artifactId>jbosscache-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.man</groupId>
+ <artifactId>jboss-managed</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java
===================================================================
--- trunk/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,173 +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.events.jboss;
-
-import java.io.Serializable;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.util.Vector;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-import org.jboss.util.naming.Util;
-import org.jgroups.Address;
-import org.jgroups.Channel;
-import org.jgroups.JChannelFactory;
-import org.jgroups.ReceiverAdapter;
-import org.jgroups.View;
-import org.jgroups.blocks.GroupRequest;
-import org.jgroups.blocks.MethodCall;
-import org.jgroups.blocks.RpcDispatcher;
-import org.teiid.events.EventDistributor;
-
-public class JGroupsEventDistributor extends ReceiverAdapter implements Serializable {
-
- private static final long serialVersionUID = -1140683411842561358L;
-
- private transient JChannelFactory channelFactory;
- private String multiplexerStack;
- private String clusterName;
- private String jndiName;
- private String localEventDistributorName;
-
- private transient EventDistributor proxyEventDistributor;
- private transient EventDistributor localEventDistributor;
-
- private transient Channel channel;
- private transient RpcDispatcher rpcDispatcher;
- private transient Vector<Address> members;
-
- public JChannelFactory getChannelFactory() {
- return channelFactory;
- }
-
- public void setJndiName(String jndiName) {
- this.jndiName = jndiName;
- }
-
- public String getJndiName() {
- return jndiName;
- }
-
- public String getLocalEventDistributorName() {
- return localEventDistributorName;
- }
-
- public void setLocalEventDistributorName(String localEventDistributorName) {
- this.localEventDistributorName = localEventDistributorName;
- }
-
- public String getMultiplexerStack() {
- return multiplexerStack;
- }
-
- public String getClusterName() {
- return clusterName;
- }
-
- public void setChannelFactory(JChannelFactory channelFactory) {
- this.channelFactory = channelFactory;
- }
-
- public void setClusterName(String clusterName) {
- this.clusterName = clusterName;
- }
-
- public void setMultiplexerStack(String multiplexerStack) {
- this.multiplexerStack = multiplexerStack;
- }
-
- public void start() throws Exception {
- if (this.channelFactory == null) {
- return; //no need to distribute events
- }
- channel = this.channelFactory.createMultiplexerChannel(this.multiplexerStack, null);
- 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;
- }
- });
- //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() {
-
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- EventDistributor local = getLocalEventDistributor();
- if (local == null) {
- return null;
- }
- return method.invoke(local, args);
- }
- }));
- rpcDispatcher.setDeadlockDetection(false);
- if (jndiName != null) {
- final InitialContext ic = new InitialContext();
- Util.bind(ic, jndiName, proxyEventDistributor);
- }
- }
-
- private EventDistributor getLocalEventDistributor() {
- if (localEventDistributor == null && this.localEventDistributorName != null) {
- try {
- Context ctx = new InitialContext();
- return (EventDistributor) ctx.lookup(this.localEventDistributorName);
- } catch (NamingException e) {
- return null;
- }
- }
- return localEventDistributor;
- }
-
- @Override
- public void viewAccepted(View newView) {
- Vector<Address> new_members = new Vector<Address>(newView.getMembers());
- new_members.remove(this.channel.getLocalAddress());
- this.members = new_members;
- }
-
- public void stop() {
- if (jndiName != null) {
- final InitialContext ic ;
- try {
- ic = new InitialContext() ;
- Util.unbind(ic, jndiName) ;
- } catch (final NamingException ne) {
- }
- }
- if (this.channel != null) {
- this.channel.close();
- this.rpcDispatcher.stop();
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java (from rev 3218, trunk/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,178 @@
+/*
+ * 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.events.jboss;
+
+import java.io.Serializable;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.util.Vector;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+import org.jboss.util.naming.Util;
+import org.jgroups.Address;
+import org.jgroups.Channel;
+import org.jgroups.ChannelFactory;
+import org.jgroups.ReceiverAdapter;
+import org.jgroups.View;
+import org.jgroups.blocks.GroupRequest;
+import org.jgroups.blocks.MethodCall;
+import org.jgroups.blocks.RpcDispatcher;
+import org.teiid.events.EventDistributor;
+
+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 ChannelFactory channelFactory;
+ private String multiplexerStack;
+ private String clusterName;
+ private String jndiName;
+ private String localEventDistributorName;
+
+ private transient EventDistributor proxyEventDistributor;
+ private transient EventDistributor localEventDistributor;
+
+ private transient Channel channel;
+ private transient RpcDispatcher rpcDispatcher;
+ private transient Vector<Address> members;
+
+ public ChannelFactory getChannelFactory() {
+ return channelFactory;
+ }
+
+ public void setJndiName(String jndiName) {
+ this.jndiName = jndiName;
+ }
+
+ public String getJndiName() {
+ return jndiName;
+ }
+
+ public String getLocalEventDistributorName() {
+ return localEventDistributorName;
+ }
+
+ public void setLocalEventDistributorName(String localEventDistributorName) {
+ this.localEventDistributorName = localEventDistributorName;
+ }
+
+ public String getMultiplexerStack() {
+ return multiplexerStack;
+ }
+
+ public String getClusterName() {
+ return clusterName;
+ }
+
+ public void setChannelFactory(ChannelFactory channelFactory) {
+ this.channelFactory = channelFactory;
+ }
+
+ public void setClusterName(String clusterName) {
+ this.clusterName = clusterName;
+ }
+
+ public void setMultiplexerStack(String multiplexerStack) {
+ this.multiplexerStack = multiplexerStack;
+ }
+
+ public void start() throws Exception {
+ if (this.channelFactory == null) {
+ return; //no need to distribute events
+ }
+ channel = this.channelFactory.createMultiplexerChannel(this.multiplexerStack, "teiid-events"); //$NON-NLS-1$
+ channel.connect(this.clusterName);
+ 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() {
+
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable {
+ EventDistributor local = getLocalEventDistributor();
+ if (local == null) {
+ return null;
+ }
+ return method.invoke(local, args);
+ }
+ }));
+ rpcDispatcher.setDeadlockDetection(false);
+ if (jndiName != null) {
+ final InitialContext ic = new InitialContext();
+ Util.bind(ic, jndiName, proxyEventDistributor);
+ }
+ }
+
+ private EventDistributor getLocalEventDistributor() {
+ if (localEventDistributor == null && this.localEventDistributorName != null) {
+ try {
+ Context ctx = new InitialContext();
+ return (EventDistributor) ctx.lookup(this.localEventDistributorName);
+ } catch (NamingException e) {
+ return null;
+ }
+ }
+ return localEventDistributor;
+ }
+
+ @Override
+ public void viewAccepted(View newView) {
+ Vector<Address> new_members = new Vector<Address>(newView.getMembers());
+ new_members.remove(this.channel.getLocalAddress());
+ this.members = new_members;
+ }
+
+ public void stop() {
+ if (jndiName != null) {
+ final InitialContext ic ;
+ try {
+ ic = new InitialContext() ;
+ Util.unbind(ic, jndiName) ;
+ } catch (final NamingException ne) {
+ }
+ }
+ if (this.channel != null) {
+ this.channel.close();
+ this.rpcDispatcher.stop();
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/client/pom.xml
===================================================================
--- trunk/client/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/client/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,28 +0,0 @@
-<?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-client</artifactId>
- <name>Client</name>
- <description>Contains the packages related to communication, administrative api,
- sessioning and transport level messaging.</description>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <type>test-jar</type>
- </dependency>
- <dependency>
- <groupId>org.jboss.man</groupId>
- <artifactId>jboss-managed</artifactId>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/client/pom.xml (from rev 3220, trunk/client/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/client/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/client/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,28 @@
+<?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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>teiid-client</artifactId>
+ <name>Client</name>
+ <description>Contains the packages related to communication, administrative api,
+ sessioning and transport level messaging.</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.man</groupId>
+ <artifactId>jboss-managed</artifactId>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/Session.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/Session.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/Session.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,105 +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.adminapi;
-
-
-/**
- * A Session is a lasting connection between a client and a Teiid System.
- *
- * A user may be allowed to have multiple sessions active simultaneously.
- *
- */
-public interface Session extends AdminObject {
-
- /**
- * Get the Last time Client has check to see if the server is still available
- *
- * @return Date of the last ping to the server.
- */
- public long getLastPingTime();
-
-
- /**
- * Get the Application Name
- *
- * @return String of the Application Name
- */
- public String getApplicationName();
-
- /**
- * Get the unique Teiid session
- * within a given Teiid System
- *
- * @return String of the Session ID
- */
- public String getSessionId();
-
- /**
- * Get User Name for this Session
- *
- * @return String of UserName
- */
- public String getUserName();
-
- /**
- * Get the VDB Name for this Session
- *
- * @return String name of the VDB
- */
- public String getVDBName();
-
- /**
- * Get the VDB Version for this Session
- *
- * @return String name/number of the VDB Version
- */
- public int getVDBVersion();
-
- /**
- * Get the IPAddress for this Session. Note this value is reported from the client.
- * @return
- */
- public String getIPAddress();
-
-
- /**
- * Get the host name of the machine the client is
- * accessing from. Note this value is reported from the client.
- * @return
- */
- public String getClientHostName();
-
- /**
- * Get the time the {@link Session} was created.
- * @return
- */
- public long getCreatedTime();
-
-
- /**
- * Security Domain user logged into currently
- * @return
- */
- public String getSecurityDomain();
-
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/Session.java (from rev 3218, trunk/client/src/main/java/org/teiid/adminapi/Session.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/Session.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/Session.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,110 @@
+/*
+ * 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.adminapi;
+
+
+/**
+ * A Session represents a single connection between a client and the server.
+ *
+ * A user is allowed to have multiple sessions active simultaneously.
+ */
+public interface Session extends AdminObject {
+
+ /**
+ * Get the Last time Client has check to see if the server is still available
+ *
+ * @return Date of the last ping to the server.
+ */
+ public long getLastPingTime();
+
+
+ /**
+ * Get the Application Name
+ *
+ * @return String of the Application Name
+ */
+ public String getApplicationName();
+
+ /**
+ * Get the unique Teiid session
+ * within a given Teiid System
+ *
+ * @return String of the Session ID
+ */
+ public String getSessionId();
+
+ /**
+ * Get User Name for this Session
+ *
+ * @return String of UserName
+ */
+ public String getUserName();
+
+ /**
+ * Get the VDB Name for this Session
+ *
+ * @return String name of the VDB
+ */
+ public String getVDBName();
+
+ /**
+ * Get the VDB Version for this Session
+ *
+ * @return String name/number of the VDB Version
+ */
+ public int getVDBVersion();
+
+ /**
+ * Get the IPAddress for this Session. Note this value is reported from the client.
+ * @return
+ */
+ public String getIPAddress();
+
+
+ /**
+ * Get the host name of the machine the client is
+ * accessing from. Note this value is reported from the client.
+ * @return
+ */
+ 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
+ */
+ public long getCreatedTime();
+
+
+ /**
+ * Security Domain user logged into currently
+ * @return
+ */
+ public String getSecurityDomain();
+
+}
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadata.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/impl/SessionMetadata.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadata.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,221 +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.adminapi.impl;
-
-import java.util.Date;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-
-import org.jboss.managed.api.annotation.ManagementProperty;
-import org.jboss.metatype.api.annotations.MetaMapping;
-import org.teiid.adminapi.Session;
-import org.teiid.client.security.SessionToken;
-
-
-
-/**
- * Add and delete properties also in the Mapper class for correct wrapping for profile service.
- */
- at MetaMapping(SessionMetadataMapper.class)
-public class SessionMetadata extends AdminObjectImpl implements Session {
-
- private static final long serialVersionUID = 918638989081830034L;
- private String applicationName;
- private long lastPingTime = System.currentTimeMillis();
- private long createdTime;
- private String ipAddress;
- private String clientHostName;
- private String userName;
- private String vdbName;
- private int vdbVersion;
- private String sessionId;
- private String securityDomain;
-
- //server session state
- private transient VDBMetaData vdb;
- private transient SessionToken sessionToken;
- private transient LoginContext loginContext;
- private transient Object securityContext;
- private transient boolean embedded;
-
- @Override
- @ManagementProperty(description="Application assosiated with Session", readOnly=true)
- public String getApplicationName() {
- return this.applicationName;
- }
-
- public void setApplicationName(String applicationName) {
- this.applicationName = applicationName;
- }
-
- @Override
- @ManagementProperty(description="When session created", readOnly=true)
- public long getCreatedTime() {
- return this.createdTime;
- }
-
- public void setCreatedTime(long createdTime) {
- this.createdTime = createdTime;
- }
-
- @Override
- @ManagementProperty(description="Host name from where the session created", readOnly=true)
- public String getClientHostName() {
- return this.clientHostName;
- }
-
- public void setClientHostName(String clientHostname) {
- this.clientHostName = clientHostname;
- }
-
- @Override
- @ManagementProperty(description="IP address from where session is created", readOnly=true)
- public String getIPAddress() {
- return this.ipAddress;
- }
-
- public void setIPAddress(String ipAddress) {
- this.ipAddress = ipAddress;
- }
-
- @Override
- @ManagementProperty(description="Last ping time", readOnly=true)
- public long getLastPingTime() {
- return this.lastPingTime;
- }
-
- public void setLastPingTime(long lastPingTime) {
- this.lastPingTime = lastPingTime;
- }
-
- @Override
- @ManagementProperty(description="Session ID", readOnly=true)
- public String getSessionId() {
- return this.sessionId;
- }
-
- public void setSessionId(String sessionId) {
- this.sessionId = sessionId;
- }
-
- @Override
- @ManagementProperty(description="User name assosiated with session", readOnly=true)
- public String getUserName() {
- return this.userName;
- }
-
- public void setUserName(String userName) {
- this.userName = userName;
- }
-
- @Override
- @ManagementProperty(description="VDB name assosiated with session", readOnly=true)
- public String getVDBName() {
- return this.vdbName;
- }
-
- public void setVDBName(String vdbName) {
- this.vdbName = vdbName;
- }
-
- @Override
- @ManagementProperty(description="VDB version name assosiated with session", readOnly=true)
- public int getVDBVersion() {
- return this.vdbVersion;
- }
-
- public void setVDBVersion(int vdbVersion) {
- this.vdbVersion = vdbVersion;
- }
-
- @Override
- @ManagementProperty(description="Security Domain that session logged into", readOnly=true)
- public String getSecurityDomain() {
- return this.securityDomain;
- }
-
- public void setSecurityDomain(String domain) {
- this.securityDomain = domain;
- }
-
- @SuppressWarnings("nls")
- public String toString() {
- StringBuilder str = new StringBuilder();
- str.append("session: sessionid=").append(sessionId);
- str.append("; userName=").append(userName);
- str.append("; vdbName=").append(vdbName);
- str.append("; vdbVersion=").append(vdbVersion);
- str.append("; createdTime=").append(new Date(createdTime));
- str.append("; applicationName=").append(applicationName);
- str.append("; clientHostName=").append(clientHostName);
- str.append("; IPAddress=").append(ipAddress);
- str.append("; securityDomain=").append(securityDomain);
- str.append("; lastPingTime=").append(new Date(lastPingTime));
- return str.toString();
- }
-
- public VDBMetaData getVdb() {
- return vdb;
- }
-
- public void setVdb(VDBMetaData vdb) {
- this.vdb = vdb;
- }
-
- public SessionToken getSessionToken() {
- return sessionToken;
- }
-
- public void setSessionToken(SessionToken sessionToken) {
- this.sessionToken = sessionToken;
- }
-
- public LoginContext getLoginContext() {
- return loginContext;
- }
-
- public void setLoginContext(LoginContext loginContext) {
- this.loginContext = loginContext;
- }
-
- public Object getSecurityContext() {
- return securityContext;
- }
-
- public void setSecurityContext(Object securityContext) {
- this.securityContext = securityContext;
- }
-
- public Subject getSubject() {
- return this.loginContext.getSubject();
- }
-
- public void setEmbedded(boolean embedded) {
- this.embedded = embedded;
- }
-
- public boolean isEmbedded() {
- return embedded;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadata.java (from rev 3218, trunk/client/src/main/java/org/teiid/adminapi/impl/SessionMetadata.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadata.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadata.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,236 @@
+/*
+ * 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.adminapi.impl;
+
+import java.util.Date;
+
+import javax.security.auth.Subject;
+import javax.security.auth.login.LoginContext;
+
+import org.jboss.managed.api.annotation.ManagementProperty;
+import org.jboss.metatype.api.annotations.MetaMapping;
+import org.teiid.adminapi.Session;
+import org.teiid.client.security.SessionToken;
+
+
+
+/**
+ * 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 */
+ at MetaMapping(SessionMetadataMapper.class)
+public class SessionMetadata extends AdminObjectImpl implements Session {
+
+ private static final long serialVersionUID = 918638989081830034L;
+ private String applicationName;
+ private long lastPingTime = System.currentTimeMillis();
+ private long createdTime;
+ private String ipAddress;
+ private String clientHostName;
+ private String clientHardwareAddress;
+ private String userName;
+ private String vdbName;
+ private int vdbVersion;
+ private String sessionId;
+ private String securityDomain;
+
+ //server session state
+ private transient VDBMetaData vdb;
+ private transient SessionToken sessionToken;
+ private transient LoginContext loginContext;
+ private transient Object securityContext;
+ private transient boolean embedded;
+
+ @Override
+ @ManagementProperty(description="Application associated with Session", readOnly=true)
+ public String getApplicationName() {
+ return this.applicationName;
+ }
+
+ public void setApplicationName(String applicationName) {
+ this.applicationName = applicationName;
+ }
+
+ @Override
+ @ManagementProperty(description="When session created", readOnly=true)
+ public long getCreatedTime() {
+ return this.createdTime;
+ }
+
+ public void setCreatedTime(long createdTime) {
+ this.createdTime = createdTime;
+ }
+
+ @Override
+ @ManagementProperty(description="Host name from where the session created", readOnly=true)
+ public String getClientHostName() {
+ return this.clientHostName;
+ }
+
+ public void setClientHostName(String clientHostname) {
+ this.clientHostName = clientHostname;
+ }
+
+ @Override
+ @ManagementProperty(description="IP address of session client", readOnly=true)
+ public String getIPAddress() {
+ return this.ipAddress;
+ }
+
+ public void setIPAddress(String ipAddress) {
+ this.ipAddress = ipAddress;
+ }
+
+ @Override
+ @ManagementProperty(description="Last ping time", readOnly=true)
+ public long getLastPingTime() {
+ return this.lastPingTime;
+ }
+
+ public void setLastPingTime(long lastPingTime) {
+ this.lastPingTime = lastPingTime;
+ }
+
+ @Override
+ @ManagementProperty(description="Session ID", readOnly=true)
+ public String getSessionId() {
+ return this.sessionId;
+ }
+
+ public void setSessionId(String sessionId) {
+ this.sessionId = sessionId;
+ }
+
+ @Override
+ @ManagementProperty(description="User name associated with session", readOnly=true)
+ public String getUserName() {
+ return this.userName;
+ }
+
+ public void setUserName(String userName) {
+ this.userName = userName;
+ }
+
+ @Override
+ @ManagementProperty(description="VDB name associated with session", readOnly=true)
+ public String getVDBName() {
+ return this.vdbName;
+ }
+
+ public void setVDBName(String vdbName) {
+ this.vdbName = vdbName;
+ }
+
+ @Override
+ @ManagementProperty(description="VDB version name associated with session", readOnly=true)
+ public int getVDBVersion() {
+ return this.vdbVersion;
+ }
+
+ public void setVDBVersion(int vdbVersion) {
+ this.vdbVersion = vdbVersion;
+ }
+
+ @Override
+ @ManagementProperty(description="Security Domain that session logged into", readOnly=true)
+ public String getSecurityDomain() {
+ return this.securityDomain;
+ }
+
+ public void setSecurityDomain(String domain) {
+ this.securityDomain = domain;
+ }
+
+ @SuppressWarnings("nls")
+ public String toString() {
+ StringBuilder str = new StringBuilder();
+ str.append("session: sessionid=").append(sessionId);
+ str.append("; userName=").append(userName);
+ str.append("; vdbName=").append(vdbName);
+ str.append("; vdbVersion=").append(vdbVersion);
+ 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));
+ return str.toString();
+ }
+
+ public VDBMetaData getVdb() {
+ return vdb;
+ }
+
+ public void setVdb(VDBMetaData vdb) {
+ this.vdb = vdb;
+ }
+
+ public SessionToken getSessionToken() {
+ return sessionToken;
+ }
+
+ public void setSessionToken(SessionToken sessionToken) {
+ this.sessionToken = sessionToken;
+ }
+
+ public LoginContext getLoginContext() {
+ return loginContext;
+ }
+
+ public void setLoginContext(LoginContext loginContext) {
+ this.loginContext = loginContext;
+ }
+
+ public Object getSecurityContext() {
+ return securityContext;
+ }
+
+ public void setSecurityContext(Object securityContext) {
+ this.securityContext = securityContext;
+ }
+
+ public Subject getSubject() {
+ return this.loginContext.getSubject();
+ }
+
+ public void setEmbedded(boolean embedded) {
+ this.embedded = embedded;
+ }
+
+ public boolean isEmbedded() {
+ return embedded;
+ }
+
+ @Override
+ @ManagementProperty(description="Hardware address reported by the client", readOnly=true)
+ public String getClientHardwareAddress() {
+ return this.clientHardwareAddress;
+ }
+
+ public void setClientHardwareAddress(String clientHardwareAddress) {
+ this.clientHardwareAddress = clientHardwareAddress;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadataMapper.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/impl/SessionMetadataMapper.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadataMapper.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,124 +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.adminapi.impl;
-
-import java.lang.reflect.Type;
-
-import org.jboss.metatype.api.types.CompositeMetaType;
-import org.jboss.metatype.api.types.MetaType;
-import org.jboss.metatype.api.types.SimpleMetaType;
-import org.jboss.metatype.api.values.CompositeValue;
-import org.jboss.metatype.api.values.CompositeValueSupport;
-import org.jboss.metatype.api.values.MetaValue;
-import org.jboss.metatype.api.values.MetaValueFactory;
-import org.jboss.metatype.api.values.SimpleValueSupport;
-import org.jboss.metatype.plugins.types.MutableCompositeMetaType;
-import org.jboss.metatype.spi.values.MetaMapper;
-
-public class SessionMetadataMapper extends MetaMapper<SessionMetadata> {
- private static final String SECURITY_DOMAIN = "securityDomain"; //$NON-NLS-1$
- private static final String VDB_VERSION = "VDBVersion"; //$NON-NLS-1$
- private static final String VDB_NAME = "VDBName"; //$NON-NLS-1$
- private static final String USER_NAME = "userName"; //$NON-NLS-1$
- private static final String SESSION_ID = "sessionId"; //$NON-NLS-1$
- private static final String LAST_PING_TIME = "lastPingTime"; //$NON-NLS-1$
- private static final String IP_ADDRESS = "IPAddress"; //$NON-NLS-1$
- private static final String CLIENT_HOST_NAME = "clientHostName"; //$NON-NLS-1$
- private static final String CREATED_TIME = "createdTime"; //$NON-NLS-1$
- private static final String APPLICATION_NAME = "applicationName"; //$NON-NLS-1$
- private static final MutableCompositeMetaType metaType;
- private static final MetaValueFactory metaValueFactory = MetaValueFactory.getInstance();
-
- static {
- metaType = new MutableCompositeMetaType(SessionMetadata.class.getName(), "The Session domain meta data"); //$NON-NLS-1$
- metaType.addItem(APPLICATION_NAME, APPLICATION_NAME, SimpleMetaType.STRING);
- metaType.addItem(CREATED_TIME, CREATED_TIME, SimpleMetaType.LONG_PRIMITIVE);
- metaType.addItem(CLIENT_HOST_NAME, CLIENT_HOST_NAME, SimpleMetaType.STRING);
- metaType.addItem(IP_ADDRESS, IP_ADDRESS, SimpleMetaType.STRING);
- metaType.addItem(LAST_PING_TIME, LAST_PING_TIME, SimpleMetaType.LONG_PRIMITIVE);
- metaType.addItem(SESSION_ID, SESSION_ID, SimpleMetaType.STRING);
- metaType.addItem(USER_NAME, USER_NAME, SimpleMetaType.STRING);
- metaType.addItem(VDB_NAME, VDB_NAME, SimpleMetaType.STRING);
- metaType.addItem(VDB_VERSION, VDB_VERSION, SimpleMetaType.INTEGER_PRIMITIVE);
- metaType.addItem(SECURITY_DOMAIN, SECURITY_DOMAIN, SimpleMetaType.STRING);
- metaType.freeze();
- }
-
- @Override
- public Type mapToType() {
- return SessionMetadata.class;
- }
-
- @Override
- public MetaType getMetaType() {
- return metaType;
- }
-
- @Override
- public MetaValue createMetaValue(MetaType metaType, SessionMetadata object) {
- if (object == null)
- return null;
- if (metaType instanceof CompositeMetaType) {
- CompositeMetaType composite = (CompositeMetaType) metaType;
- CompositeValueSupport session = new CompositeValueSupport(composite);
-
- session.set(APPLICATION_NAME, SimpleValueSupport.wrap(object.getApplicationName()));
- session.set(CREATED_TIME, SimpleValueSupport.wrap(object.getCreatedTime()));
- session.set(CLIENT_HOST_NAME, SimpleValueSupport.wrap(object.getClientHostName()));
- session.set(IP_ADDRESS, SimpleValueSupport.wrap(object.getIPAddress()));
- session.set(LAST_PING_TIME, SimpleValueSupport.wrap(object.getLastPingTime()));
- session.set(SESSION_ID, SimpleValueSupport.wrap(object.getSessionId()));
- session.set(USER_NAME, SimpleValueSupport.wrap(object.getUserName()));
- session.set(VDB_NAME,SimpleValueSupport.wrap(object.getVDBName()));
- session.set(VDB_VERSION, SimpleValueSupport.wrap(object.getVDBVersion()));
- session.set(SECURITY_DOMAIN, SimpleValueSupport.wrap(object.getSecurityDomain()));
-
- return session;
- }
- throw new IllegalArgumentException("Cannot convert session " + object); //$NON-NLS-1$
- }
-
- @Override
- public SessionMetadata unwrapMetaValue(MetaValue metaValue) {
- if (metaValue == null)
- return null;
-
- if (metaValue instanceof CompositeValue) {
- CompositeValue compositeValue = (CompositeValue) metaValue;
-
- SessionMetadata session = new SessionMetadata();
- session.setApplicationName((String) metaValueFactory.unwrap(compositeValue.get(APPLICATION_NAME)));
- session.setCreatedTime((Long) metaValueFactory.unwrap(compositeValue.get(CREATED_TIME)));
- session.setClientHostName((String) metaValueFactory.unwrap(compositeValue.get(CLIENT_HOST_NAME)));
- session.setIPAddress((String) metaValueFactory.unwrap(compositeValue.get(IP_ADDRESS)));
- session.setLastPingTime((Long) metaValueFactory.unwrap(compositeValue.get(LAST_PING_TIME)));
- session.setSessionId((String) metaValueFactory.unwrap(compositeValue.get(SESSION_ID)));
- session.setUserName((String) metaValueFactory.unwrap(compositeValue.get(USER_NAME)));
- session.setVDBName((String) metaValueFactory.unwrap(compositeValue.get(VDB_NAME)));
- session.setVDBVersion((Integer) metaValueFactory.unwrap(compositeValue.get(VDB_VERSION)));
- session.setSecurityDomain((String) metaValueFactory.unwrap(compositeValue.get(SECURITY_DOMAIN)));
- return session;
- }
- throw new IllegalStateException("Unable to unwrap session " + metaValue); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadataMapper.java (from rev 3218, trunk/client/src/main/java/org/teiid/adminapi/impl/SessionMetadataMapper.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadataMapper.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/SessionMetadataMapper.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,127 @@
+/*
+ * 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.adminapi.impl;
+
+import java.lang.reflect.Type;
+
+import org.jboss.metatype.api.types.CompositeMetaType;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.types.SimpleMetaType;
+import org.jboss.metatype.api.values.CompositeValue;
+import org.jboss.metatype.api.values.CompositeValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.MetaValueFactory;
+import org.jboss.metatype.api.values.SimpleValueSupport;
+import org.jboss.metatype.plugins.types.MutableCompositeMetaType;
+import org.jboss.metatype.spi.values.MetaMapper;
+
+public class SessionMetadataMapper extends MetaMapper<SessionMetadata> {
+ private static final String SECURITY_DOMAIN = "securityDomain"; //$NON-NLS-1$
+ private static final String VDB_VERSION = "VDBVersion"; //$NON-NLS-1$
+ private static final String VDB_NAME = "VDBName"; //$NON-NLS-1$
+ private static final String USER_NAME = "userName"; //$NON-NLS-1$
+ private static final String SESSION_ID = "sessionId"; //$NON-NLS-1$
+ private static final String LAST_PING_TIME = "lastPingTime"; //$NON-NLS-1$
+ private static final String IP_ADDRESS = "IPAddress"; //$NON-NLS-1$
+ private static final String CLIENT_HOST_NAME = "clientHostName"; //$NON-NLS-1$
+ private static final String CLIENT_MAC = "clientMAC"; //$NON-NLS-1$
+ private static final String CREATED_TIME = "createdTime"; //$NON-NLS-1$
+ private static final String APPLICATION_NAME = "applicationName"; //$NON-NLS-1$
+ private static final MutableCompositeMetaType metaType;
+ private static final MetaValueFactory metaValueFactory = MetaValueFactory.getInstance();
+
+ static {
+ metaType = new MutableCompositeMetaType(SessionMetadata.class.getName(), "The Session domain meta data"); //$NON-NLS-1$
+ metaType.addItem(APPLICATION_NAME, APPLICATION_NAME, SimpleMetaType.STRING);
+ metaType.addItem(CREATED_TIME, CREATED_TIME, SimpleMetaType.LONG_PRIMITIVE);
+ metaType.addItem(CLIENT_HOST_NAME, CLIENT_HOST_NAME, SimpleMetaType.STRING);
+ metaType.addItem(IP_ADDRESS, IP_ADDRESS, SimpleMetaType.STRING);
+ metaType.addItem(LAST_PING_TIME, LAST_PING_TIME, SimpleMetaType.LONG_PRIMITIVE);
+ metaType.addItem(SESSION_ID, SESSION_ID, SimpleMetaType.STRING);
+ metaType.addItem(USER_NAME, USER_NAME, SimpleMetaType.STRING);
+ metaType.addItem(VDB_NAME, VDB_NAME, SimpleMetaType.STRING);
+ metaType.addItem(VDB_VERSION, VDB_VERSION, SimpleMetaType.INTEGER_PRIMITIVE);
+ metaType.addItem(SECURITY_DOMAIN, SECURITY_DOMAIN, SimpleMetaType.STRING);
+ metaType.addItem(CLIENT_MAC, CLIENT_MAC, SimpleMetaType.STRING);
+ metaType.freeze();
+ }
+
+ @Override
+ public Type mapToType() {
+ return SessionMetadata.class;
+ }
+
+ @Override
+ public MetaType getMetaType() {
+ return metaType;
+ }
+
+ @Override
+ public MetaValue createMetaValue(MetaType metaType, SessionMetadata object) {
+ if (object == null)
+ return null;
+ if (metaType instanceof CompositeMetaType) {
+ CompositeMetaType composite = (CompositeMetaType) metaType;
+ CompositeValueSupport session = new CompositeValueSupport(composite);
+
+ session.set(APPLICATION_NAME, SimpleValueSupport.wrap(object.getApplicationName()));
+ session.set(CREATED_TIME, SimpleValueSupport.wrap(object.getCreatedTime()));
+ session.set(CLIENT_HOST_NAME, SimpleValueSupport.wrap(object.getClientHostName()));
+ session.set(IP_ADDRESS, SimpleValueSupport.wrap(object.getIPAddress()));
+ session.set(LAST_PING_TIME, SimpleValueSupport.wrap(object.getLastPingTime()));
+ session.set(SESSION_ID, SimpleValueSupport.wrap(object.getSessionId()));
+ session.set(USER_NAME, SimpleValueSupport.wrap(object.getUserName()));
+ session.set(VDB_NAME,SimpleValueSupport.wrap(object.getVDBName()));
+ session.set(VDB_VERSION, SimpleValueSupport.wrap(object.getVDBVersion()));
+ session.set(SECURITY_DOMAIN, SimpleValueSupport.wrap(object.getSecurityDomain()));
+ session.set(CLIENT_MAC, SimpleValueSupport.wrap(object.getSecurityDomain()));
+ return session;
+ }
+ throw new IllegalArgumentException("Cannot convert session " + object); //$NON-NLS-1$
+ }
+
+ @Override
+ public SessionMetadata unwrapMetaValue(MetaValue metaValue) {
+ if (metaValue == null)
+ return null;
+
+ if (metaValue instanceof CompositeValue) {
+ CompositeValue compositeValue = (CompositeValue) metaValue;
+
+ SessionMetadata session = new SessionMetadata();
+ session.setApplicationName((String) metaValueFactory.unwrap(compositeValue.get(APPLICATION_NAME)));
+ session.setCreatedTime((Long) metaValueFactory.unwrap(compositeValue.get(CREATED_TIME)));
+ session.setClientHostName((String) metaValueFactory.unwrap(compositeValue.get(CLIENT_HOST_NAME)));
+ session.setIPAddress((String) metaValueFactory.unwrap(compositeValue.get(IP_ADDRESS)));
+ session.setLastPingTime((Long) metaValueFactory.unwrap(compositeValue.get(LAST_PING_TIME)));
+ session.setSessionId((String) metaValueFactory.unwrap(compositeValue.get(SESSION_ID)));
+ session.setUserName((String) metaValueFactory.unwrap(compositeValue.get(USER_NAME)));
+ session.setVDBName((String) metaValueFactory.unwrap(compositeValue.get(VDB_NAME)));
+ session.setVDBVersion((Integer) metaValueFactory.unwrap(compositeValue.get(VDB_VERSION)));
+ session.setSecurityDomain((String) metaValueFactory.unwrap(compositeValue.get(SECURITY_DOMAIN)));
+ session.setClientHardwareAddress((String) metaValueFactory.unwrap(compositeValue.get(CLIENT_MAC)));
+ return session;
+ }
+ throw new IllegalStateException("Unable to unwrap session " + metaValue); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java
===================================================================
--- trunk/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1015 +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.jdbc;
-
-import java.sql.Array;
-import java.sql.Blob;
-import java.sql.CallableStatement;
-import java.sql.Clob;
-import java.sql.Connection;
-import java.sql.NClob;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLClientInfoException;
-import java.sql.SQLException;
-import java.sql.SQLWarning;
-import java.sql.SQLXML;
-import java.sql.Savepoint;
-import java.sql.Statement;
-import java.sql.Struct;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.transaction.xa.Xid;
-
-import org.teiid.client.DQP;
-import org.teiid.client.plan.Annotation;
-import org.teiid.client.plan.PlanNode;
-import org.teiid.client.util.ResultsFuture;
-import org.teiid.client.xa.XATransactionException;
-import org.teiid.client.xa.XidImpl;
-import org.teiid.core.util.SqlUtil;
-import org.teiid.net.CommunicationException;
-import org.teiid.net.ConnectionException;
-import org.teiid.net.ServerConnection;
-import org.teiid.net.TeiidURL;
-import org.teiid.net.socket.SocketServerConnection;
-
-/**
- * Teiid's Connection implementation.
- */
-public class ConnectionImpl extends WrapperImpl implements TeiidConnection {
- private static Logger logger = Logger.getLogger("org.teiid.jdbc"); //$NON-NLS-1$
-
- public static final int DEFAULT_ISOLATION = Connection.TRANSACTION_READ_COMMITTED;
-
- // constant value giving product name
- private final static String SERVER_NAME = "Teiid Server"; //$NON-NLS-1$
- private final static String EMBEDDED_NAME = "Teiid Embedded"; //$NON-NLS-1$
-
- // Unique request ID generator
- private long requestIDGenerator;
-
- // url used to create the connection
- private String url;
-
- // properties object containing the connection properties.
- protected Properties propInfo;
-
- // status of connection object
- private boolean closed = false;
- // determines if a statement executed should be immediately committed.
- private boolean autoCommitFlag = true;
- private boolean inLocalTxn;
-
- // collection of all open statements on this connection
- private Collection<StatementImpl> statements = new ArrayList<StatementImpl>();
- // cached DatabaseMetadata
- private DatabaseMetaDataImpl dbmm;
-
- //Xid for participating in TXN
- private XidImpl transactionXid;
-
- // Flag to represent if the connection state needs to be readOnly, default value false.
- private boolean readOnly = false;
-
- private boolean disableLocalTransactions = false;
- private DQP dqp;
- protected ServerConnection serverConn;
- private int transactionIsolation = DEFAULT_ISOLATION;
-
- // the last query plan description
- private PlanNode currentPlanDescription;
- // the last query debug log
- private String debugLog;
- // the last query annotations
- private Collection<Annotation> annotations;
- private Properties connectionProps;
-
- public ConnectionImpl(ServerConnection serverConn, Properties info, String url) {
- this.connectionProps = info;
- this.serverConn = serverConn;
- this.url = url;
- this.dqp = serverConn.getService(DQP.class);
-
- logger.fine(JDBCPlugin.Util.getString("MMConnection.Session_success")); //$NON-NLS-1$
- logConnectionProperties(url, info);
-
- setExecutionProperties(info);
-
- this.disableLocalTransactions = Boolean.valueOf(this.propInfo.getProperty(ExecutionProperties.DISABLE_LOCAL_TRANSACTIONS)).booleanValue();
- }
-
- boolean isInLocalTxn() {
- return inLocalTxn;
- }
-
- private void setExecutionProperties(Properties info) {
- this.propInfo = new Properties();
-
- String overrideProp = info.getProperty(ExecutionProperties.PROP_TXN_AUTO_WRAP);
- if ( overrideProp == null || overrideProp.trim().length() == 0 ) {
- propInfo.put(ExecutionProperties.PROP_TXN_AUTO_WRAP, ExecutionProperties.TXN_WRAP_DETECT);
- }
-
- String defaultFetchSize = info.getProperty(ExecutionProperties.PROP_FETCH_SIZE);
- if (defaultFetchSize != null) {
- propInfo.put(ExecutionProperties.PROP_FETCH_SIZE, defaultFetchSize);
- } else {
- propInfo.put(ExecutionProperties.PROP_FETCH_SIZE, String.valueOf(BaseDataSource.DEFAULT_FETCH_SIZE));
- }
-
- String partialResultsMode = info.getProperty(ExecutionProperties.PROP_PARTIAL_RESULTS_MODE);
- if (partialResultsMode != null) {
- propInfo.put(ExecutionProperties.PROP_PARTIAL_RESULTS_MODE, partialResultsMode);
- } else {
- propInfo.put(ExecutionProperties.PROP_PARTIAL_RESULTS_MODE, BaseDataSource.DEFAULT_PARTIAL_RESULTS_MODE);
- }
-
- String resultSetCacheMode = info.getProperty(ExecutionProperties.RESULT_SET_CACHE_MODE);
- if (resultSetCacheMode != null) {
- propInfo.put(ExecutionProperties.RESULT_SET_CACHE_MODE, resultSetCacheMode);
- } else {
- propInfo.put(ExecutionProperties.RESULT_SET_CACHE_MODE, BaseDataSource.DEFAULT_RESULT_SET_CACHE_MODE);
- }
-
- String ansiQuotes = info.getProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS);
- if (ansiQuotes != null) {
- propInfo.put(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS, ansiQuotes);
- } else {
- propInfo.put(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS, Boolean.TRUE.toString());
- }
-
- for (String key : info.stringPropertyNames()) {
- for (String prop : JDBCURL.EXECUTION_PROPERTIES) {
- if (prop.equalsIgnoreCase(key)) {
- propInfo.setProperty(key, info.getProperty(key));
- break;
- }
- }
- }
- }
-
- public Collection<Annotation> getAnnotations() {
- return annotations;
- }
-
- public void setAnnotations(Collection<Annotation> annotations) {
- this.annotations = annotations;
- }
-
- public String getDebugLog() {
- return debugLog;
- }
-
- public void setDebugLog(String debugLog) {
- this.debugLog = debugLog;
- }
-
- public PlanNode getCurrentPlanDescription() {
- return currentPlanDescription;
- }
-
- public void setCurrentPlanDescription(PlanNode currentPlanDescription) {
- this.currentPlanDescription = currentPlanDescription;
- }
-
- protected Properties getExecutionProperties() {
- return this.propInfo;
- }
-
- DQP getDQP() {
- return this.dqp;
- }
-
- /**
- * Remove password & trusted token and log all other properties
- * @param connUrl - URL used to connect to server
- * @param info - properties object supplied
- */
- private void logConnectionProperties(String connUrl, Properties info) {
- StringBuffer modifiedUrl = new StringBuffer();
-
- // If we have valid URL
- if (connUrl != null) {
- // We need wipe out the password here, before we write to the log
- int startIndex = connUrl.indexOf("password="); //$NON-NLS-1$
- if (startIndex != -1) {
- modifiedUrl.append(connUrl.substring(0, startIndex));
- modifiedUrl.append("password=***"); //$NON-NLS-1$
- int endIndex = connUrl.indexOf(";", startIndex+9); //$NON-NLS-1$
- if (endIndex != -1) {
- modifiedUrl.append(";").append(connUrl.substring(endIndex)); //$NON-NLS-1$
- }
- }
- logger.fine("Connection Url="+modifiedUrl); //$NON-NLS-1$
- }
-
- // Now clone the properties object and remove password and trusted token
- if (info != null) {
- Enumeration enumeration = info.keys();
- while (enumeration.hasMoreElements()) {
- String key = (String)enumeration.nextElement();
- Object anObj = info.get(key);
- // Log each property except for password and token.
- if (!TeiidURL.CONNECTION.PASSWORD.equalsIgnoreCase(key)) {
- logger.fine(key+"="+anObj); //$NON-NLS-1$
- }
- }
- }
- }
-
- String getUrl() {
- return this.url;
- }
-
- /**
- * Connection identifier of this connection
- * @return identifier
- * @throws SQLException
- */
- public String getConnectionId() {
- return this.serverConn.getLogonResult().getSessionID();
- }
-
- long currentRequestId() {
- return requestIDGenerator;
- }
-
- /**
- * Generate the next unique requestID for matching up requests with responses.
- * These IDs should be unique only in the context of a ServerConnection instance.
- * @return Request ID
- */
- long nextRequestID() {
- return requestIDGenerator++;
- }
-
- public void clearWarnings() throws SQLException {
- // do nothing
- }
-
- public void close() throws SQLException {
- Throwable firstException = null;
-
- if(closed) {
- return;
- }
-
- try {
- // close any statements that were created on this connection
- try {
- closeStatements();
- } catch (SQLException se) {
- firstException = se;
- } finally {
- this.serverConn.close();
- if ( firstException != null )
- throw (SQLException)firstException;
- }
- } catch (SQLException se) {
- throw TeiidSQLException.create(se, JDBCPlugin.Util.getString("MMConnection.Err_connection_close", se.getMessage())); //$NON-NLS-1$
- } finally {
- logger.fine(JDBCPlugin.Util.getString("MMConnection.Connection_close_success")); //$NON-NLS-1$
- // set the status of the connection to closed
- closed = true;
- }
- }
-
- /**
- * <p>
- * Close all the statements open on this connection
- * </p>
- *
- * @throws SQLException
- * server statement object could not be closed.
- */
- void closeStatements() throws SQLException {
- // Closing the statement will cause the
- // MMConnection.closeStatement() method to be called,
- // which will modify this.statements. So, we do this iteration
- // in a separate safe copy of the list
- List<StatementImpl> statementsSafe = new ArrayList<StatementImpl>(this.statements);
- SQLException ex = null;
- for (StatementImpl statement : statementsSafe) {
- try {
- statement.close();
- } catch (SQLException e) {
- ex = e;
- }
- }
- if (ex != null) {
- throw TeiidSQLException.create(ex, JDBCPlugin.Util.getString("MMConnection.Err_closing_stmts")); //$NON-NLS-1$
- }
- }
-
- /**
- * Called by MMStatement to notify the connection that the
- * statement has been closed.
- * @param statement
- */
- void closeStatement(Statement statement) {
- this.statements.remove(statement);
- }
-
- /**
- * <p>This method makes any changes involved in a transaction permanent and releases
- * any locks held by the connection object. This is only used when auto-commit
- * is set to false.</p>
- * @throws SQLException if the transaction had been rolled back or marked to roll back.
- */
- public void commit() throws SQLException {
- checkConnection();
- if (!autoCommitFlag) {
- try {
- directCommit();
- } finally {
- inLocalTxn = false;
- }
- }
- }
-
- private void directCommit() throws SQLException {
- if (inLocalTxn) {
- try {
- ResultsFuture<?> future = this.dqp.commit();
- future.get();
- } catch (Exception e) {
- throw TeiidSQLException.create(e);
- }
- logger.fine(JDBCPlugin.Util.getString("MMConnection.Commit_success")); //$NON-NLS-1$
- }
- }
-
- void beginLocalTxnIfNeeded() throws SQLException {
- if (this.transactionXid != null || inLocalTxn || this.autoCommitFlag || disableLocalTransactions) {
- return;
- }
- try {
- try {
- this.dqp.begin();
- } catch (XATransactionException e) {
- throw TeiidSQLException.create(e);
- }
- inLocalTxn = true;
- } finally {
- if (!inLocalTxn) {
- autoCommitFlag = true;
- }
- }
- }
-
- public StatementImpl createStatement() throws SQLException {
- return createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
- }
-
- /**
- * <p>Creates a Statement object that will produce ResultSet objects of the type
- * resultSetType and concurrency level resultSetConcurrency.</p>
- * @param intvalue indicating the ResultSet's type
- * @param intValue indicating the ResultSet's concurrency
- * @return Statement object.
- */
- public StatementImpl createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
- //Check to see the connection is open
- checkConnection();
-
- validateResultSetType(resultSetType);
- validateResultSetConcurrency(resultSetConcurrency);
-
- // add the statement object to the map
- StatementImpl newStatement = StatementImpl.newInstance(this, resultSetType, resultSetConcurrency);
- statements.add(newStatement);
-
- return newStatement;
- }
-
- /**
- * @param resultSetType
- * @throws TeiidSQLException
- * @since 4.3
- */
- private void validateResultSetType(int resultSetType) throws TeiidSQLException {
- if (resultSetType == ResultSet.TYPE_SCROLL_SENSITIVE ) {
- String msg = JDBCPlugin.Util.getString("MMConnection.Scrollable_type_not_supported", "ResultSet.TYPE_SCROLL_SENSITIVE"); //$NON-NLS-1$ //$NON-NLS-2$
- throw new TeiidSQLException(msg);
- }
- }
-
- /**
- * @param resultSetConcurrency
- * @throws TeiidSQLException
- * @since 4.3
- */
- private void validateResultSetConcurrency(int resultSetConcurrency) throws TeiidSQLException {
- if (resultSetConcurrency == ResultSet.CONCUR_UPDATABLE) {
- String msg = JDBCPlugin.Util.getString("MMConnection.Concurrency_type_not_supported", "ResultSet.CONCUR_UPDATABLE"); //$NON-NLS-1$ //$NON-NLS-2$
- throw new TeiidSQLException(msg);
- }
- }
-
- public boolean getAutoCommit() throws SQLException {
- //Check to see the connection is open
- checkConnection();
- return autoCommitFlag;
- }
-
- public String getCatalog() throws SQLException {
- //Check to see the connection is open
- checkConnection();
- //catalogs are not supported
- return this.serverConn.getLogonResult().getVdbName();
- }
-
- /**
- * <p>This method gets the ServerConnection object wrapped by this object.</p>
- * @return ServerConnection object
- */
- ServerConnection getServerConnection() throws SQLException {
- //Check to see the connection is open
- checkConnection();
- return serverConn;
- }
-
- String getVDBName() throws SQLException {
- //Check to see the connection is open
- checkConnection();
- //get the virtual database name to which we are connected.
-
- return this.serverConn.getLogonResult().getVdbName();
- }
-
- public int getVDBVersion() throws SQLException {
- checkConnection();
- return this.serverConn.getLogonResult().getVdbVersion();
- }
-
- /**
- * Get's the name of the user who got this connection.
- * @return Sring object giving the user name
- * @throws SQLException if the connection is closed
- */
- String getUserName() throws SQLException {
- checkConnection();
-
- return this.serverConn.getLogonResult().getUserName();
- }
-
- public DatabaseMetaDataImpl getMetaData() throws SQLException {
- //Check to see the connection is open
- checkConnection();
-
- if (dbmm == null) {
- dbmm = new DatabaseMetaDataImpl(this);
- }
- return dbmm;
- }
-
- /**
- * Get the database name that this connection is representing
- * @return String name of the database
- */
- public String getDatabaseName() {
- if (this.serverConn instanceof SocketServerConnection) {
- return SERVER_NAME;
- }
- return EMBEDDED_NAME;
- }
-
- /**
- * Retrieves the current holdability of ResultSet objects created using this Connection object.
- * @param holdability int indicating the holdability
- * @return int holdability
- * @throws SQLException
- */
- public int getHoldability() throws SQLException {
- return ResultSet.HOLD_CURSORS_OVER_COMMIT;
- }
-
- public int getTransactionIsolation() throws SQLException {
- return this.transactionIsolation;
- }
-
- /**
- * Retreives the type map associated with this Connection object. The type map
- * contains entries for undefined types. This method always returns an empty
- * map since it is not possible to add entries to this type map
- * @return map containing undefined types(empty)
- * @throws SQLException, should never occur
- */
- public Map getTypeMap() throws SQLException {
- //Check to see the connection is open
- checkConnection();
- return new HashMap();
- }
-
- /**
- * <p>This method will return the first warning reported by calls on this connection,
- * or null if none exist.</p>
- * @return A SQLWarning object if there are any warnings.
- * @throws SQLException, should never occur
- */
- public SQLWarning getWarnings() throws SQLException {
- //Check to see the connection is open
- checkConnection();
- return null; // we don't have any warnings
- }
-
- /**
- * <p>This method will return whether this connection is closed or not.</p>
- * @return booleanvalue indicating if the connection is closed
- * @throws SQLException, should never occur
- */
- public boolean isClosed() throws SQLException {
- return closed;
- }
-
- public boolean isReadOnly() throws SQLException {
- return readOnly;
- }
-
- public String nativeSQL(String sql) throws SQLException {
- // return the string argument without any modifications.
- // escape syntaxes are directly supported in the server
- return sql;
- }
-
- /**
- * <p>Creates a CallableStatement object that contains sql and that will produce
- * ResultSet objects that are non-scrollable and non-updatable. A SQL stored
- * procedure call statement is handled by creating a CallableStatement for it.</p>
- * @param sql String(escape syntax) for invoking a stored procedure.
- * @return CallableStatement object that can be used to execute the storedProcedure
- * @throws SQLException if there is an error creating the callable statement object
- */
- public CallableStatement prepareCall(String sql) throws SQLException {
- //there is a problem setting the result set type to be non-scrollable
- //See defect 17768
- return prepareCall(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
- }
-
- /**
- * <p>Creates a CallableStatement object that contains a sql and that will produce
- * ResultSet objects of the type resultSetType and with a concurrency level of
- * resultSetConcurrency. A SQL stored procedure call statement is handled by
- * creating a CallableStatement for it.</p>
- * @param sql String(escape syntax) for invoking a stored procedure.
- * @param intvalue indicating the ResultSet's type
- * @param intValue indicating the ResultSet's concurrency
- * @return CallableStatement object that can be used to execute the storedProcedure
- */
- public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
- //Check to see the connection is open
- checkConnection();
-
- validateResultSetType(resultSetType);
- validateResultSetConcurrency(resultSetConcurrency);
- validateSQL(sql);
-
- // add the statement object to the map
- CallableStatementImpl newStatement = CallableStatementImpl.newInstance(this, sql, resultSetType, resultSetConcurrency);
- statements.add(newStatement);
- return newStatement;
- }
-
- /**
- * @param sql
- * @throws TeiidSQLException
- * @since 4.3
- */
- private void validateSQL(String sql) throws TeiidSQLException {
- if (sql == null) {
- String msg = JDBCPlugin.Util.getString("MMConnection.SQL_cannot_be_null"); //$NON-NLS-1$
- throw new TeiidSQLException(msg);
- }
- }
-
- public PreparedStatementImpl prepareStatement(String sql) throws SQLException {
- return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
- }
-
- /**
- * <p>Creates a PreparedStatement object that contains a sql and that will produce
- * ResultSet objects of the type resultSetType and with a concurrency level of
- * resultSetConcurrency.</p>
- * @param sql string representing a prepared statement
- * @param intvalue indicating the ResultSet's type
- * @param intValue indicating the ResultSet's concurrency
- * @return a PreparedStatement object
- */
- public PreparedStatementImpl prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
- //Check to see the connection is open
- checkConnection();
-
- validateResultSetType(resultSetType);
- validateResultSetConcurrency(resultSetConcurrency);
- validateSQL(sql);
-
- // add the statement object to the map
- PreparedStatementImpl newStatement = PreparedStatementImpl.newInstance(this, sql, resultSetType, resultSetConcurrency);
- statements.add(newStatement);
- return newStatement;
- }
-
- public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
- int resultSetHoldability ) throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public void rollback() throws SQLException {
- rollback(true);
- }
-
- /**
- * Rollback the current local transaction
- * @param startTxn
- * @throws SQLException
- */
- public void rollback(boolean startTxn) throws SQLException {
-
- //Check to see the connection is open
- checkConnection();
- if (!autoCommitFlag) {
- try {
- if (this.inLocalTxn) {
- this.inLocalTxn = false;
- try {
- ResultsFuture<?> future = this.dqp.rollback();
- future.get();
- } catch (Exception e) {
- throw TeiidSQLException.create(e);
- }
- logger.fine(JDBCPlugin.Util.getString("MMConnection.Rollback_success")); //$NON-NLS-1$
- }
- } finally {
- if (startTxn) {
- this.inLocalTxn = false;
- }
- else {
- this.autoCommitFlag = true;
- }
- }
- }
- }
-
- public ResultsFuture<?> submitSetAutoCommitTrue(boolean commit) throws SQLException {
- //Check to see the connection is open
- checkConnection();
-
- if (this.autoCommitFlag) {
- return ResultsFuture.NULL_FUTURE;
- }
-
- this.autoCommitFlag = true;
-
- try {
- if (commit) {
- return dqp.commit();
- }
- return dqp.rollback();
- } catch (XATransactionException e) {
- throw TeiidSQLException.create(e);
- }
- }
-
- public void setAutoCommit(boolean autoCommit) throws SQLException {
- //Check to see the connection is open
- checkConnection();
-
- if (autoCommit == this.autoCommitFlag) {
- return;
- }
-
- this.autoCommitFlag = autoCommit;
-
- if (autoCommit) {
- directCommit();
- } else {
- inLocalTxn = false;
- }
- }
-
- /**
- * <p>Teiid does not allow setting a catalog through a connection. This
- * method silently ignores the request as per the specification.</p>
- * @param The string values which sets the catalog name on the connection.
- * @throws SQLException This should never occur.
- */
- public void setCatalog(String catalog) throws SQLException {
- // do nothing, silently ignore the request
- }
-
- /**
- * @param A boolean value specifying whether the connection is readonly.
- * @throws throws SQLException.
- */
- public void setReadOnly(boolean readOnly) throws SQLException {
- if (this.readOnly == readOnly) {
- return;
- }
- // During transaction do not allow to change this flag
- if (!autoCommitFlag || this.transactionXid != null) {
- throw new TeiidSQLException(JDBCPlugin.Util.getString("MMStatement.Invalid_During_Transaction", "setReadOnly(" + readOnly + ")"));//$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$
- }
- this.readOnly = readOnly;
- }
-
- /**
- * <p> This utility method checks if the jdbc connection is closed and
- * throws an exception if it is closed. </p>
- * @throws SQLException if the connection object is closed.
- */
- void checkConnection() throws SQLException{
- //Check to see the connection is closed and proceed if it is not
- if (closed) {
- throw new TeiidSQLException(JDBCPlugin.Util.getString("MMConnection.Cant_use_closed_connection")); //$NON-NLS-1$
- }
- }
-
- protected void commitTransaction(XidImpl arg0, boolean arg1) throws SQLException {
- checkConnection();
- transactionXid = null;
- this.autoCommitFlag = true;
- try {
- ResultsFuture<?> future = this.dqp.commit(arg0, arg1);
- future.get();
- } catch (Exception e) {
- throw TeiidSQLException.create(e);
- }
- }
-
- protected void endTransaction(XidImpl arg0, int arg1) throws SQLException {
- checkConnection();
- this.autoCommitFlag = true;
- try {
- ResultsFuture<?> future = this.dqp.end(arg0, arg1);
- future.get();
- } catch (Exception e) {
- throw TeiidSQLException.create(e);
- }
- }
-
- protected void forgetTransaction(XidImpl arg0) throws SQLException {
- checkConnection();
- try {
- ResultsFuture<?> future = this.dqp.forget(arg0);
- future.get();
- } catch (Exception e) {
- throw TeiidSQLException.create(e);
- }
- }
-
- protected int prepareTransaction(XidImpl arg0) throws SQLException {
- checkConnection();
- transactionXid = null;
- try {
- ResultsFuture<Integer> future = this.dqp.prepare(arg0);
- return future.get();
- } catch (Exception e) {
- throw TeiidSQLException.create(e);
- }
- }
-
- protected Xid[] recoverTransaction(int arg0) throws SQLException {
- checkConnection();
- try {
- ResultsFuture<Xid[]> future = this.dqp.recover(arg0);
- return future.get();
- } catch (Exception e) {
- throw TeiidSQLException.create(e);
- }
- }
-
- protected void rollbackTransaction(XidImpl arg0) throws SQLException {
- checkConnection();
- transactionXid = null;
- this.autoCommitFlag = true;
- try {
- ResultsFuture<?> future = this.dqp.rollback(arg0);
- future.get();
- } catch (Exception e) {
- throw TeiidSQLException.create(e);
- }
- }
-
- protected void startTransaction(XidImpl arg0, int arg1, int timeout) throws SQLException {
- checkConnection();
- try {
- ResultsFuture<?> future = this.dqp.start(arg0, arg1, timeout);
- future.get();
- } catch (Exception e) {
- throw TeiidSQLException.create(e);
- }
- transactionXid = arg0;
- this.autoCommitFlag = false;
- }
-
- protected XidImpl getTransactionXid() {
- return transactionXid;
- }
-
- public boolean isValid(int timeout) throws SQLException {
- return this.getServerConnection().isOpen(timeout * 1000);
- }
-
- public void recycleConnection() {
- try {
- //close all open statements
- this.closeStatements();
- } catch (SQLException e) {
- logger.log(Level.WARNING, JDBCPlugin.Util.getString("MMXAConnection.rolling_back_error"), e); //$NON-NLS-1$
- }
- try {
- //rollback if still in a transaction
- if (!this.getAutoCommit()) {
- logger.warning(JDBCPlugin.Util.getString("MMXAConnection.rolling_back")); //$NON-NLS-1$
-
- if (this.getTransactionXid() == null) {
- this.rollback(false);
- } else {
- this.rollbackTransaction(getTransactionXid());
- }
- }
- } catch (SQLException e) {
- logger.log(Level.WARNING, JDBCPlugin.Util.getString("MMXAConnection.rolling_back_error"), e); //$NON-NLS-1$
- }
-
- this.serverConn.cleanUp();
- }
-
- public boolean isSameProcess(ConnectionImpl conn) throws CommunicationException {
- return this.serverConn.isSameInstance(conn.serverConn);
- }
-
- public void setClientInfo(Properties properties)
- throws SQLClientInfoException {
- }
-
- public void setClientInfo(String name, String value)
- throws SQLClientInfoException {
- }
-
- public Properties getClientInfo() throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public String getClientInfo(String name) throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public Array createArrayOf(String typeName, Object[] elements)
- throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public Blob createBlob() throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public Clob createClob() throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public NClob createNClob() throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public SQLXML createSQLXML() throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public Statement createStatement(int resultSetType,
- int resultSetConcurrency, int resultSetHoldability)
- throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
-
- }
-
- public Struct createStruct(String typeName, Object[] attributes)
- throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public CallableStatement prepareCall(String sql, int resultSetType,
- int resultSetConcurrency, int resultSetHoldability)
- throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
-
- }
-
- public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
- throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
-
- }
-
- public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
- throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
-
- }
-
- public PreparedStatement prepareStatement(String sql, String[] columnNames)
- throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
-
- }
-
- public void releaseSavepoint(Savepoint savepoint) throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
-
- }
-
- public void rollback(Savepoint savepoint) throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
-
- }
-
- public void setHoldability(int holdability) throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public Savepoint setSavepoint() throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public Savepoint setSavepoint(String name) throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public void setTransactionIsolation(int level) throws SQLException {
- this.transactionIsolation = level;
- }
-
- public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- @Override
- public void changeUser(String userName, String newPassword)
- throws SQLException {
- //TODO: recycleConnection();
- Object oldName = null;
- Object oldPassword = null;
- if (userName != null) {
- oldName = this.connectionProps.put(TeiidURL.CONNECTION.USER_NAME, userName);
- } 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);
- }
- boolean success = false;
- try {
- this.serverConn.authenticate();
- success = true;
- } catch (ConnectionException e) {
- throw TeiidSQLException.create(e);
- } catch (CommunicationException e) {
- throw TeiidSQLException.create(e);
- } finally {
- if (!success) {
- if (oldName != null) {
- this.connectionProps.put(TeiidURL.CONNECTION.USER_NAME, oldName);
- } 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);
- }
- }
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java (from rev 3218, trunk/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1022 @@
+/*
+ * 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.jdbc;
+
+import java.sql.Array;
+import java.sql.Blob;
+import java.sql.CallableStatement;
+import java.sql.Clob;
+import java.sql.Connection;
+import java.sql.NClob;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLClientInfoException;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.sql.SQLXML;
+import java.sql.Savepoint;
+import java.sql.Statement;
+import java.sql.Struct;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.transaction.xa.Xid;
+
+import org.teiid.client.DQP;
+import org.teiid.client.plan.Annotation;
+import org.teiid.client.plan.PlanNode;
+import org.teiid.client.util.ResultsFuture;
+import org.teiid.client.xa.XATransactionException;
+import org.teiid.client.xa.XidImpl;
+import org.teiid.core.util.SqlUtil;
+import org.teiid.net.CommunicationException;
+import org.teiid.net.ConnectionException;
+import org.teiid.net.ServerConnection;
+import org.teiid.net.TeiidURL;
+import org.teiid.net.socket.SocketServerConnection;
+
+/**
+ * Teiid's Connection implementation.
+ */
+public class ConnectionImpl extends WrapperImpl implements TeiidConnection {
+ private static Logger logger = Logger.getLogger("org.teiid.jdbc"); //$NON-NLS-1$
+
+ public static final int DEFAULT_ISOLATION = Connection.TRANSACTION_READ_COMMITTED;
+
+ // constant value giving product name
+ private final static String SERVER_NAME = "Teiid Server"; //$NON-NLS-1$
+ private final static String EMBEDDED_NAME = "Teiid Embedded"; //$NON-NLS-1$
+
+ // Unique request ID generator
+ private long requestIDGenerator;
+
+ // url used to create the connection
+ private String url;
+
+ // properties object containing the connection properties.
+ protected Properties propInfo;
+
+ // status of connection object
+ private boolean closed = false;
+ // determines if a statement executed should be immediately committed.
+ private boolean autoCommitFlag = true;
+ private boolean inLocalTxn;
+
+ // collection of all open statements on this connection
+ private Collection<StatementImpl> statements = new ArrayList<StatementImpl>();
+ // cached DatabaseMetadata
+ private DatabaseMetaDataImpl dbmm;
+
+ //Xid for participating in TXN
+ private XidImpl transactionXid;
+
+ // Flag to represent if the connection state needs to be readOnly, default value false.
+ private boolean readOnly = false;
+
+ private boolean disableLocalTransactions = false;
+ private DQP dqp;
+ protected ServerConnection serverConn;
+ private int transactionIsolation = DEFAULT_ISOLATION;
+
+ // the last query plan description
+ private PlanNode currentPlanDescription;
+ // the last query debug log
+ private String debugLog;
+ // the last query annotations
+ private Collection<Annotation> annotations;
+ private Properties connectionProps;
+
+ public ConnectionImpl(ServerConnection serverConn, Properties info, String url) {
+ this.connectionProps = info;
+ this.serverConn = serverConn;
+ this.url = url;
+ this.dqp = serverConn.getService(DQP.class);
+
+ logger.fine(JDBCPlugin.Util.getString("MMConnection.Session_success")); //$NON-NLS-1$
+ logConnectionProperties(url, info);
+
+ setExecutionProperties(info);
+
+ this.disableLocalTransactions = Boolean.valueOf(this.propInfo.getProperty(ExecutionProperties.DISABLE_LOCAL_TRANSACTIONS)).booleanValue();
+ }
+
+ boolean isInLocalTxn() {
+ return inLocalTxn;
+ }
+
+ private void setExecutionProperties(Properties info) {
+ this.propInfo = new Properties();
+
+ String overrideProp = info.getProperty(ExecutionProperties.PROP_TXN_AUTO_WRAP);
+ if ( overrideProp == null || overrideProp.trim().length() == 0 ) {
+ propInfo.put(ExecutionProperties.PROP_TXN_AUTO_WRAP, ExecutionProperties.TXN_WRAP_DETECT);
+ }
+
+ String defaultFetchSize = info.getProperty(ExecutionProperties.PROP_FETCH_SIZE);
+ if (defaultFetchSize != null) {
+ propInfo.put(ExecutionProperties.PROP_FETCH_SIZE, defaultFetchSize);
+ } else {
+ propInfo.put(ExecutionProperties.PROP_FETCH_SIZE, String.valueOf(BaseDataSource.DEFAULT_FETCH_SIZE));
+ }
+
+ String partialResultsMode = info.getProperty(ExecutionProperties.PROP_PARTIAL_RESULTS_MODE);
+ if (partialResultsMode != null) {
+ propInfo.put(ExecutionProperties.PROP_PARTIAL_RESULTS_MODE, partialResultsMode);
+ } else {
+ propInfo.put(ExecutionProperties.PROP_PARTIAL_RESULTS_MODE, BaseDataSource.DEFAULT_PARTIAL_RESULTS_MODE);
+ }
+
+ String resultSetCacheMode = info.getProperty(ExecutionProperties.RESULT_SET_CACHE_MODE);
+ if (resultSetCacheMode != null) {
+ propInfo.put(ExecutionProperties.RESULT_SET_CACHE_MODE, resultSetCacheMode);
+ } else {
+ propInfo.put(ExecutionProperties.RESULT_SET_CACHE_MODE, BaseDataSource.DEFAULT_RESULT_SET_CACHE_MODE);
+ }
+
+ String ansiQuotes = info.getProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS);
+ if (ansiQuotes != null) {
+ propInfo.put(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS, ansiQuotes);
+ } else {
+ propInfo.put(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS, Boolean.TRUE.toString());
+ }
+
+ for (String key : info.stringPropertyNames()) {
+ for (String prop : JDBCURL.EXECUTION_PROPERTIES) {
+ if (prop.equalsIgnoreCase(key)) {
+ propInfo.setProperty(key, info.getProperty(key));
+ break;
+ }
+ }
+ }
+ }
+
+ public Collection<Annotation> getAnnotations() {
+ return annotations;
+ }
+
+ public void setAnnotations(Collection<Annotation> annotations) {
+ this.annotations = annotations;
+ }
+
+ public String getDebugLog() {
+ return debugLog;
+ }
+
+ public void setDebugLog(String debugLog) {
+ this.debugLog = debugLog;
+ }
+
+ public PlanNode getCurrentPlanDescription() {
+ return currentPlanDescription;
+ }
+
+ public void setCurrentPlanDescription(PlanNode currentPlanDescription) {
+ this.currentPlanDescription = currentPlanDescription;
+ }
+
+ protected Properties getExecutionProperties() {
+ return this.propInfo;
+ }
+
+ DQP getDQP() {
+ return this.dqp;
+ }
+
+ /**
+ * Remove password & trusted token and log all other properties
+ * @param connUrl - URL used to connect to server
+ * @param info - properties object supplied
+ */
+ private void logConnectionProperties(String connUrl, Properties info) {
+ StringBuffer modifiedUrl = new StringBuffer();
+
+ // If we have valid URL
+ if (connUrl != null) {
+ // We need wipe out the password here, before we write to the log
+ int startIndex = connUrl.indexOf("password="); //$NON-NLS-1$
+ if (startIndex != -1) {
+ modifiedUrl.append(connUrl.substring(0, startIndex));
+ modifiedUrl.append("password=***"); //$NON-NLS-1$
+ int endIndex = connUrl.indexOf(";", startIndex+9); //$NON-NLS-1$
+ if (endIndex != -1) {
+ modifiedUrl.append(";").append(connUrl.substring(endIndex)); //$NON-NLS-1$
+ }
+ }
+ logger.fine("Connection Url="+modifiedUrl); //$NON-NLS-1$
+ }
+
+ // Now clone the properties object and remove password and trusted token
+ if (info != null) {
+ Enumeration enumeration = info.keys();
+ while (enumeration.hasMoreElements()) {
+ String key = (String)enumeration.nextElement();
+ Object anObj = info.get(key);
+ // Log each property except for password and token.
+ if (!TeiidURL.CONNECTION.PASSWORD.equalsIgnoreCase(key)) {
+ logger.fine(key+"="+anObj); //$NON-NLS-1$
+ }
+ }
+ }
+ }
+
+ String getUrl() {
+ return this.url;
+ }
+
+ /**
+ * Connection identifier of this connection
+ * @return identifier
+ * @throws SQLException
+ */
+ public String getConnectionId() {
+ return this.serverConn.getLogonResult().getSessionID();
+ }
+
+ long currentRequestId() {
+ return requestIDGenerator;
+ }
+
+ /**
+ * Generate the next unique requestID for matching up requests with responses.
+ * These IDs should be unique only in the context of a ServerConnection instance.
+ * @return Request ID
+ */
+ long nextRequestID() {
+ return requestIDGenerator++;
+ }
+
+ public void clearWarnings() throws SQLException {
+ // do nothing
+ }
+
+ public void close() throws SQLException {
+ Throwable firstException = null;
+
+ if(closed) {
+ return;
+ }
+
+ try {
+ // close any statements that were created on this connection
+ try {
+ closeStatements();
+ } catch (SQLException se) {
+ firstException = se;
+ } finally {
+ this.serverConn.close();
+ if ( firstException != null )
+ throw (SQLException)firstException;
+ }
+ } catch (SQLException se) {
+ throw TeiidSQLException.create(se, JDBCPlugin.Util.getString("MMConnection.Err_connection_close", se.getMessage())); //$NON-NLS-1$
+ } finally {
+ logger.fine(JDBCPlugin.Util.getString("MMConnection.Connection_close_success")); //$NON-NLS-1$
+ // set the status of the connection to closed
+ closed = true;
+ }
+ }
+
+ /**
+ * <p>
+ * Close all the statements open on this connection
+ * </p>
+ *
+ * @throws SQLException
+ * server statement object could not be closed.
+ */
+ void closeStatements() throws SQLException {
+ // Closing the statement will cause the
+ // MMConnection.closeStatement() method to be called,
+ // which will modify this.statements. So, we do this iteration
+ // in a separate safe copy of the list
+ List<StatementImpl> statementsSafe = new ArrayList<StatementImpl>(this.statements);
+ SQLException ex = null;
+ for (StatementImpl statement : statementsSafe) {
+ try {
+ statement.close();
+ } catch (SQLException e) {
+ ex = e;
+ }
+ }
+ if (ex != null) {
+ throw TeiidSQLException.create(ex, JDBCPlugin.Util.getString("MMConnection.Err_closing_stmts")); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Called by MMStatement to notify the connection that the
+ * statement has been closed.
+ * @param statement
+ */
+ void closeStatement(Statement statement) {
+ this.statements.remove(statement);
+ }
+
+ /**
+ * <p>This method makes any changes involved in a transaction permanent and releases
+ * any locks held by the connection object. This is only used when auto-commit
+ * is set to false.</p>
+ * @throws SQLException if the transaction had been rolled back or marked to roll back.
+ */
+ public void commit() throws SQLException {
+ checkConnection();
+ if (!autoCommitFlag) {
+ try {
+ directCommit();
+ } finally {
+ inLocalTxn = false;
+ }
+ }
+ }
+
+ private void directCommit() throws SQLException {
+ if (inLocalTxn) {
+ try {
+ ResultsFuture<?> future = this.dqp.commit();
+ future.get();
+ } catch (Exception e) {
+ throw TeiidSQLException.create(e);
+ }
+ logger.fine(JDBCPlugin.Util.getString("MMConnection.Commit_success")); //$NON-NLS-1$
+ }
+ }
+
+ void beginLocalTxnIfNeeded() throws SQLException {
+ if (this.transactionXid != null || inLocalTxn || this.autoCommitFlag || disableLocalTransactions) {
+ return;
+ }
+ try {
+ try {
+ this.dqp.begin();
+ } catch (XATransactionException e) {
+ throw TeiidSQLException.create(e);
+ }
+ inLocalTxn = true;
+ } finally {
+ if (!inLocalTxn) {
+ autoCommitFlag = true;
+ }
+ }
+ }
+
+ public StatementImpl createStatement() throws SQLException {
+ return createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+ }
+
+ /**
+ * <p>Creates a Statement object that will produce ResultSet objects of the type
+ * resultSetType and concurrency level resultSetConcurrency.</p>
+ * @param intvalue indicating the ResultSet's type
+ * @param intValue indicating the ResultSet's concurrency
+ * @return Statement object.
+ */
+ public StatementImpl createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
+ //Check to see the connection is open
+ checkConnection();
+
+ validateResultSetType(resultSetType);
+ validateResultSetConcurrency(resultSetConcurrency);
+
+ // add the statement object to the map
+ StatementImpl newStatement = StatementImpl.newInstance(this, resultSetType, resultSetConcurrency);
+ statements.add(newStatement);
+
+ return newStatement;
+ }
+
+ /**
+ * @param resultSetType
+ * @throws TeiidSQLException
+ * @since 4.3
+ */
+ private void validateResultSetType(int resultSetType) throws TeiidSQLException {
+ if (resultSetType == ResultSet.TYPE_SCROLL_SENSITIVE ) {
+ String msg = JDBCPlugin.Util.getString("MMConnection.Scrollable_type_not_supported", "ResultSet.TYPE_SCROLL_SENSITIVE"); //$NON-NLS-1$ //$NON-NLS-2$
+ throw new TeiidSQLException(msg);
+ }
+ }
+
+ /**
+ * @param resultSetConcurrency
+ * @throws TeiidSQLException
+ * @since 4.3
+ */
+ private void validateResultSetConcurrency(int resultSetConcurrency) throws TeiidSQLException {
+ if (resultSetConcurrency == ResultSet.CONCUR_UPDATABLE) {
+ String msg = JDBCPlugin.Util.getString("MMConnection.Concurrency_type_not_supported", "ResultSet.CONCUR_UPDATABLE"); //$NON-NLS-1$ //$NON-NLS-2$
+ throw new TeiidSQLException(msg);
+ }
+ }
+
+ public boolean getAutoCommit() throws SQLException {
+ //Check to see the connection is open
+ checkConnection();
+ return autoCommitFlag;
+ }
+
+ public String getCatalog() throws SQLException {
+ //Check to see the connection is open
+ checkConnection();
+ //catalogs are not supported
+ return this.serverConn.getLogonResult().getVdbName();
+ }
+
+ /**
+ * <p>This method gets the ServerConnection object wrapped by this object.</p>
+ * @return ServerConnection object
+ */
+ ServerConnection getServerConnection() throws SQLException {
+ //Check to see the connection is open
+ checkConnection();
+ return serverConn;
+ }
+
+ String getVDBName() throws SQLException {
+ //Check to see the connection is open
+ checkConnection();
+ //get the virtual database name to which we are connected.
+
+ return this.serverConn.getLogonResult().getVdbName();
+ }
+
+ public int getVDBVersion() throws SQLException {
+ checkConnection();
+ return this.serverConn.getLogonResult().getVdbVersion();
+ }
+
+ /**
+ * Get's the name of the user who got this connection.
+ * @return Sring object giving the user name
+ * @throws SQLException if the connection is closed
+ */
+ String getUserName() throws SQLException {
+ checkConnection();
+
+ return this.serverConn.getLogonResult().getUserName();
+ }
+
+ public DatabaseMetaDataImpl getMetaData() throws SQLException {
+ //Check to see the connection is open
+ checkConnection();
+
+ if (dbmm == null) {
+ dbmm = new DatabaseMetaDataImpl(this);
+ }
+ return dbmm;
+ }
+
+ /**
+ * Get the database name that this connection is representing
+ * @return String name of the database
+ */
+ public String getDatabaseName() {
+ if (this.serverConn instanceof SocketServerConnection) {
+ return SERVER_NAME;
+ }
+ return EMBEDDED_NAME;
+ }
+
+ /**
+ * Retrieves the current holdability of ResultSet objects created using this Connection object.
+ * @param holdability int indicating the holdability
+ * @return int holdability
+ * @throws SQLException
+ */
+ public int getHoldability() throws SQLException {
+ return ResultSet.HOLD_CURSORS_OVER_COMMIT;
+ }
+
+ public int getTransactionIsolation() throws SQLException {
+ return this.transactionIsolation;
+ }
+
+ /**
+ * Retreives the type map associated with this Connection object. The type map
+ * contains entries for undefined types. This method always returns an empty
+ * map since it is not possible to add entries to this type map
+ * @return map containing undefined types(empty)
+ * @throws SQLException, should never occur
+ */
+ public Map getTypeMap() throws SQLException {
+ //Check to see the connection is open
+ checkConnection();
+ return new HashMap();
+ }
+
+ /**
+ * <p>This method will return the first warning reported by calls on this connection,
+ * or null if none exist.</p>
+ * @return A SQLWarning object if there are any warnings.
+ * @throws SQLException, should never occur
+ */
+ public SQLWarning getWarnings() throws SQLException {
+ //Check to see the connection is open
+ checkConnection();
+ return null; // we don't have any warnings
+ }
+
+ /**
+ * <p>This method will return whether this connection is closed or not.</p>
+ * @return booleanvalue indicating if the connection is closed
+ * @throws SQLException, should never occur
+ */
+ public boolean isClosed() throws SQLException {
+ return closed;
+ }
+
+ public boolean isReadOnly() throws SQLException {
+ return readOnly;
+ }
+
+ public String nativeSQL(String sql) throws SQLException {
+ // return the string argument without any modifications.
+ // escape syntaxes are directly supported in the server
+ return sql;
+ }
+
+ /**
+ * <p>Creates a CallableStatement object that contains sql and that will produce
+ * ResultSet objects that are non-scrollable and non-updatable. A SQL stored
+ * procedure call statement is handled by creating a CallableStatement for it.</p>
+ * @param sql String(escape syntax) for invoking a stored procedure.
+ * @return CallableStatement object that can be used to execute the storedProcedure
+ * @throws SQLException if there is an error creating the callable statement object
+ */
+ public CallableStatement prepareCall(String sql) throws SQLException {
+ //there is a problem setting the result set type to be non-scrollable
+ //See defect 17768
+ return prepareCall(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ }
+
+ /**
+ * <p>Creates a CallableStatement object that contains a sql and that will produce
+ * ResultSet objects of the type resultSetType and with a concurrency level of
+ * resultSetConcurrency. A SQL stored procedure call statement is handled by
+ * creating a CallableStatement for it.</p>
+ * @param sql String(escape syntax) for invoking a stored procedure.
+ * @param intvalue indicating the ResultSet's type
+ * @param intValue indicating the ResultSet's concurrency
+ * @return CallableStatement object that can be used to execute the storedProcedure
+ */
+ public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
+ //Check to see the connection is open
+ checkConnection();
+
+ validateResultSetType(resultSetType);
+ validateResultSetConcurrency(resultSetConcurrency);
+ validateSQL(sql);
+
+ // add the statement object to the map
+ CallableStatementImpl newStatement = CallableStatementImpl.newInstance(this, sql, resultSetType, resultSetConcurrency);
+ statements.add(newStatement);
+ return newStatement;
+ }
+
+ /**
+ * @param sql
+ * @throws TeiidSQLException
+ * @since 4.3
+ */
+ private void validateSQL(String sql) throws TeiidSQLException {
+ if (sql == null) {
+ String msg = JDBCPlugin.Util.getString("MMConnection.SQL_cannot_be_null"); //$NON-NLS-1$
+ throw new TeiidSQLException(msg);
+ }
+ }
+
+ public PreparedStatementImpl prepareStatement(String sql) throws SQLException {
+ return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+ }
+
+ /**
+ * <p>Creates a PreparedStatement object that contains a sql and that will produce
+ * ResultSet objects of the type resultSetType and with a concurrency level of
+ * resultSetConcurrency.</p>
+ * @param sql string representing a prepared statement
+ * @param intvalue indicating the ResultSet's type
+ * @param intValue indicating the ResultSet's concurrency
+ * @return a PreparedStatement object
+ */
+ public PreparedStatementImpl prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
+ //Check to see the connection is open
+ checkConnection();
+
+ validateResultSetType(resultSetType);
+ validateResultSetConcurrency(resultSetConcurrency);
+ validateSQL(sql);
+
+ // add the statement object to the map
+ PreparedStatementImpl newStatement = PreparedStatementImpl.newInstance(this, sql, resultSetType, resultSetConcurrency);
+ statements.add(newStatement);
+ return newStatement;
+ }
+
+ public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
+ int resultSetHoldability ) throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public void rollback() throws SQLException {
+ rollback(true);
+ }
+
+ /**
+ * Rollback the current local transaction
+ * @param startTxn
+ * @throws SQLException
+ */
+ public void rollback(boolean startTxn) throws SQLException {
+
+ //Check to see the connection is open
+ checkConnection();
+ if (!autoCommitFlag) {
+ try {
+ if (this.inLocalTxn) {
+ this.inLocalTxn = false;
+ try {
+ ResultsFuture<?> future = this.dqp.rollback();
+ future.get();
+ } catch (Exception e) {
+ throw TeiidSQLException.create(e);
+ }
+ logger.fine(JDBCPlugin.Util.getString("MMConnection.Rollback_success")); //$NON-NLS-1$
+ }
+ } finally {
+ if (startTxn) {
+ this.inLocalTxn = false;
+ }
+ else {
+ this.autoCommitFlag = true;
+ }
+ }
+ }
+ }
+
+ public ResultsFuture<?> submitSetAutoCommitTrue(boolean commit) throws SQLException {
+ //Check to see the connection is open
+ checkConnection();
+
+ if (this.autoCommitFlag) {
+ return ResultsFuture.NULL_FUTURE;
+ }
+
+ this.autoCommitFlag = true;
+
+ try {
+ if (commit) {
+ return dqp.commit();
+ }
+ return dqp.rollback();
+ } catch (XATransactionException e) {
+ throw TeiidSQLException.create(e);
+ }
+ }
+
+ public void setAutoCommit(boolean autoCommit) throws SQLException {
+ //Check to see the connection is open
+ checkConnection();
+
+ if (autoCommit == this.autoCommitFlag) {
+ return;
+ }
+
+ this.autoCommitFlag = autoCommit;
+
+ if (autoCommit) {
+ directCommit();
+ } else {
+ inLocalTxn = false;
+ }
+ }
+
+ /**
+ * <p>Teiid does not allow setting a catalog through a connection. This
+ * method silently ignores the request as per the specification.</p>
+ * @param The string values which sets the catalog name on the connection.
+ * @throws SQLException This should never occur.
+ */
+ public void setCatalog(String catalog) throws SQLException {
+ // do nothing, silently ignore the request
+ }
+
+ /**
+ * @param A boolean value specifying whether the connection is readonly.
+ * @throws throws SQLException.
+ */
+ public void setReadOnly(boolean readOnly) throws SQLException {
+ if (this.readOnly == readOnly) {
+ return;
+ }
+ // During transaction do not allow to change this flag
+ if (!autoCommitFlag || this.transactionXid != null) {
+ throw new TeiidSQLException(JDBCPlugin.Util.getString("MMStatement.Invalid_During_Transaction", "setReadOnly(" + readOnly + ")"));//$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$
+ }
+ this.readOnly = readOnly;
+ }
+
+ /**
+ * <p> This utility method checks if the jdbc connection is closed and
+ * throws an exception if it is closed. </p>
+ * @throws SQLException if the connection object is closed.
+ */
+ void checkConnection() throws SQLException{
+ //Check to see the connection is closed and proceed if it is not
+ if (closed) {
+ throw new TeiidSQLException(JDBCPlugin.Util.getString("MMConnection.Cant_use_closed_connection")); //$NON-NLS-1$
+ }
+ }
+
+ protected void commitTransaction(XidImpl arg0, boolean arg1) throws SQLException {
+ checkConnection();
+ transactionXid = null;
+ this.autoCommitFlag = true;
+ try {
+ ResultsFuture<?> future = this.dqp.commit(arg0, arg1);
+ future.get();
+ } catch (Exception e) {
+ throw TeiidSQLException.create(e);
+ }
+ }
+
+ protected void endTransaction(XidImpl arg0, int arg1) throws SQLException {
+ checkConnection();
+ this.autoCommitFlag = true;
+ try {
+ ResultsFuture<?> future = this.dqp.end(arg0, arg1);
+ future.get();
+ } catch (Exception e) {
+ throw TeiidSQLException.create(e);
+ }
+ }
+
+ protected void forgetTransaction(XidImpl arg0) throws SQLException {
+ checkConnection();
+ try {
+ ResultsFuture<?> future = this.dqp.forget(arg0);
+ future.get();
+ } catch (Exception e) {
+ throw TeiidSQLException.create(e);
+ }
+ }
+
+ protected int prepareTransaction(XidImpl arg0) throws SQLException {
+ checkConnection();
+ transactionXid = null;
+ try {
+ ResultsFuture<Integer> future = this.dqp.prepare(arg0);
+ return future.get();
+ } catch (Exception e) {
+ throw TeiidSQLException.create(e);
+ }
+ }
+
+ protected Xid[] recoverTransaction(int arg0) throws SQLException {
+ checkConnection();
+ try {
+ ResultsFuture<Xid[]> future = this.dqp.recover(arg0);
+ return future.get();
+ } catch (Exception e) {
+ throw TeiidSQLException.create(e);
+ }
+ }
+
+ protected void rollbackTransaction(XidImpl arg0) throws SQLException {
+ checkConnection();
+ transactionXid = null;
+ this.autoCommitFlag = true;
+ try {
+ ResultsFuture<?> future = this.dqp.rollback(arg0);
+ future.get();
+ } catch (Exception e) {
+ throw TeiidSQLException.create(e);
+ }
+ }
+
+ protected void startTransaction(XidImpl arg0, int arg1, int timeout) throws SQLException {
+ checkConnection();
+ try {
+ ResultsFuture<?> future = this.dqp.start(arg0, arg1, timeout);
+ future.get();
+ } catch (Exception e) {
+ throw TeiidSQLException.create(e);
+ }
+ transactionXid = arg0;
+ this.autoCommitFlag = false;
+ }
+
+ protected XidImpl getTransactionXid() {
+ return transactionXid;
+ }
+
+ public boolean isValid(int timeout) throws SQLException {
+ return this.getServerConnection().isOpen(timeout * 1000);
+ }
+
+ public void recycleConnection() {
+ try {
+ //close all open statements
+ this.closeStatements();
+ } catch (SQLException e) {
+ logger.log(Level.WARNING, JDBCPlugin.Util.getString("MMXAConnection.rolling_back_error"), e); //$NON-NLS-1$
+ }
+ try {
+ //rollback if still in a transaction
+ if (!this.getAutoCommit()) {
+ logger.warning(JDBCPlugin.Util.getString("MMXAConnection.rolling_back")); //$NON-NLS-1$
+
+ if (this.getTransactionXid() == null) {
+ this.rollback(false);
+ } else {
+ this.rollbackTransaction(getTransactionXid());
+ }
+ }
+ } catch (SQLException e) {
+ logger.log(Level.WARNING, JDBCPlugin.Util.getString("MMXAConnection.rolling_back_error"), e); //$NON-NLS-1$
+ }
+
+ this.serverConn.cleanUp();
+ }
+
+ public boolean isSameProcess(ConnectionImpl conn) throws CommunicationException {
+ return this.serverConn.isSameInstance(conn.serverConn);
+ }
+
+ public void setClientInfo(Properties properties)
+ throws SQLClientInfoException {
+ }
+
+ public void setClientInfo(String name, String value)
+ throws SQLClientInfoException {
+ }
+
+ public Properties getClientInfo() throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public String getClientInfo(String name) throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public Array createArrayOf(String typeName, Object[] elements)
+ throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public Blob createBlob() throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public Clob createClob() throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public NClob createNClob() throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public SQLXML createSQLXML() throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public Statement createStatement(int resultSetType,
+ int resultSetConcurrency, int resultSetHoldability)
+ throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+
+ }
+
+ public Struct createStruct(String typeName, Object[] attributes)
+ throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public CallableStatement prepareCall(String sql, int resultSetType,
+ int resultSetConcurrency, int resultSetHoldability)
+ throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+
+ }
+
+ public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
+ throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+
+ }
+
+ public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
+ throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+
+ }
+
+ public PreparedStatement prepareStatement(String sql, String[] columnNames)
+ throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+
+ }
+
+ public void releaseSavepoint(Savepoint savepoint) throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+
+ }
+
+ public void rollback(Savepoint savepoint) throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+
+ }
+
+ public void setHoldability(int holdability) throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public Savepoint setSavepoint() throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public Savepoint setSavepoint(String name) throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public void setTransactionIsolation(int level) throws SQLException {
+ this.transactionIsolation = level;
+ }
+
+ public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
+ 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 {
+ //TODO: recycleConnection();
+ Object oldName = null;
+ Object oldPassword = null;
+ if (userName != null) {
+ oldName = this.connectionProps.put(TeiidURL.CONNECTION.USER_NAME, userName);
+ } else {
+ oldName = this.connectionProps.remove(TeiidURL.CONNECTION.USER_NAME);
+ }
+ oldPassword = setPassword(newPassword);
+ boolean success = false;
+ try {
+ this.serverConn.authenticate();
+ success = true;
+ } catch (ConnectionException e) {
+ throw TeiidSQLException.create(e);
+ } catch (CommunicationException e) {
+ throw TeiidSQLException.create(e);
+ } finally {
+ if (!success) {
+ if (oldName != null) {
+ this.connectionProps.put(TeiidURL.CONNECTION.USER_NAME, oldName);
+ } else {
+ this.connectionProps.remove(TeiidURL.CONNECTION.USER_NAME);
+ }
+ setPassword(oldPassword);
+ }
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java
===================================================================
--- trunk/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,67 +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.jdbc;
-
-import java.sql.SQLException;
-import java.util.Arrays;
-import java.util.Properties;
-
-import org.teiid.core.TeiidException;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.core.util.ReflectionHelper;
-import org.teiid.net.CommunicationException;
-import org.teiid.net.ConnectionException;
-import org.teiid.net.ServerConnection;
-
-
-public class EmbeddedProfile implements ConnectionProfile {
-
- /**
- * 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.
- * @return Connection object created
- * @throws SQLException if it is unable to establish a connection
- */
- public ConnectionImpl connect(String url, Properties info)
- throws TeiidSQLException {
- try {
- ServerConnection sc = createServerConnection(info);
- return new ConnectionImpl(sc, info, url);
- } catch (TeiidRuntimeException e) {
- throw TeiidSQLException.create(e);
- } catch (ConnectionException e) {
- throw TeiidSQLException.create(e);
- } catch (CommunicationException e) {
- throw TeiidSQLException.create(e);
- } catch (TeiidException e) {
- throw TeiidSQLException.create(e);
- }
- }
-
- 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$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java (from rev 3218, trunk/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,70 @@
+/*
+ * 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.jdbc;
+
+import java.sql.SQLException;
+import java.util.Arrays;
+import java.util.Properties;
+
+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;
+import org.teiid.net.ServerConnection;
+
+
+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.
+ * @return Connection object created
+ * @throws SQLException if it is unable to establish a connection
+ */
+ public ConnectionImpl connect(String url, Properties info)
+ throws TeiidSQLException {
+ try {
+ ServerConnection sc = createServerConnection(info);
+ return new ConnectionImpl(sc, info, url);
+ } catch (TeiidRuntimeException e) {
+ throw TeiidSQLException.create(e);
+ } catch (ConnectionException e) {
+ throw TeiidSQLException.create(e);
+ } catch (CommunicationException e) {
+ throw TeiidSQLException.create(e);
+ } catch (TeiidException e) {
+ throw TeiidSQLException.create(e);
+ }
+ }
+
+ protected ServerConnection createServerConnection(Properties info)
+ throws TeiidException {
+ return (ServerConnection)ReflectionHelper.create("org.teiid.transport.LocalServerConnection", Arrays.asList(info, PropertiesUtils.getBooleanProperty(info, USE_CALLING_THREAD, true)), Thread.currentThread().getContextClassLoader()); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/JDBCURL.java
===================================================================
--- trunk/client/src/main/java/org/teiid/jdbc/JDBCURL.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/JDBCURL.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,304 +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.jdbc;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.teiid.net.TeiidURL;
-
-/**
- * @since 4.3
- */
-public class JDBCURL {
- private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$
- public static final String JDBC_PROTOCOL = "jdbc:teiid:"; //$NON-NLS-1$
-
- static final String URL_PATTERN = JDBC_PROTOCOL + "([\\w-\\.]+)(?:@([^;]*))?(;.*)?"; //$NON-NLS-1$
- static Pattern urlPattern = Pattern.compile(URL_PATTERN);
-
- public static final Set<String> EXECUTION_PROPERTIES = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(
- ExecutionProperties.PROP_TXN_AUTO_WRAP,
- ExecutionProperties.PROP_PARTIAL_RESULTS_MODE,
- ExecutionProperties.RESULT_SET_CACHE_MODE,
- ExecutionProperties.ANSI_QUOTED_IDENTIFIERS,
- ExecutionProperties.SQL_OPTION_SHOWPLAN,
- ExecutionProperties.NOEXEC,
- ExecutionProperties.PROP_FETCH_SIZE,
- ExecutionProperties.PROP_XML_FORMAT,
- ExecutionProperties.PROP_XML_VALIDATION,
- ExecutionProperties.DISABLE_LOCAL_TRANSACTIONS)));
-
- public static final Set<String> KNOWN_PROPERTIES = getKnownProperties();
-
- private static Set<String> getKnownProperties() {
- Set<String> props = new HashSet<String>(Arrays.asList(
- BaseDataSource.APP_NAME,
- BaseDataSource.VDB_NAME,
- BaseDataSource.VERSION,
- BaseDataSource.VDB_VERSION,
- BaseDataSource.USER_NAME,
- BaseDataSource.PASSWORD,
- TeiidURL.CONNECTION.AUTO_FAILOVER,
- TeiidURL.CONNECTION.DISCOVERY_STRATEGY,
- TeiidURL.CONNECTION.PASSTHROUGH_AUTHENTICATION));
- props.addAll(EXECUTION_PROPERTIES);
- return Collections.unmodifiableSet(props);
- }
-
- private String vdbName;
- private String connectionURL;
- private Properties properties = new Properties();
-
- public enum ConnectionType {
- Embedded,
- Socket
- }
-
- public static ConnectionType acceptsUrl(String url) {
- Matcher m = urlPattern.matcher(url);
- if (m.matches()) {
- return m.group(2) != null?ConnectionType.Socket:ConnectionType.Embedded;
- }
- return null;
- }
-
- private String urlString;
-
- public JDBCURL(String jdbcURL) {
- parseURL(jdbcURL);
- }
-
- public JDBCURL(String vdbName, String connectionURL, Properties props) {
- if (vdbName == null || vdbName.trim().length() == 0) {
- throw new IllegalArgumentException();
- }
- this.vdbName = vdbName;
- this.connectionURL = connectionURL;
- if (props != null) {
- normalizeProperties(props, this.properties);
- }
- }
-
- public String getVDBName() {
- return vdbName;
- }
-
- public String getConnectionURL() {
- return connectionURL;
- }
-
- public Properties getProperties() {
- // Make a copy of the properties object, including any non-string values that may be contained in the map.
- Properties newProps = new Properties();
- newProps.putAll(this.properties);
- return newProps;
- }
-
- private void parseURL(String jdbcURL) {
- if (jdbcURL == null) {
- throw new IllegalArgumentException();
- }
- // Trim extra spaces
- jdbcURL = jdbcURL.trim();
- if (jdbcURL.length() == 0) {
- throw new IllegalArgumentException();
- }
-
- Matcher m = urlPattern.matcher(jdbcURL);
- if (!m.matches()) {
- throw new IllegalArgumentException();
- }
- vdbName = m.group(1);
- connectionURL = m.group(2);
- if (connectionURL != null) {
- connectionURL = connectionURL.trim();
- }
- String props = m.group(3);
- if (props != null) {
- parseConnectionProperties(props, this.properties);
- }
- }
-
- public static void parseConnectionProperties(String connectionInfo, Properties p) {
- String[] connectionParts = connectionInfo.split(";"); //$NON-NLS-1$
- if (connectionParts.length != 0) {
- // The rest should be connection params
- for (int i = 0; i < connectionParts.length; i++) {
- parseConnectionProperty(connectionParts[i], p);
- }
- }
- }
-
- static void parseConnectionProperty(String connectionProperty, Properties p) {
- if (connectionProperty.length() == 0) {
- // Be tolerant of double-semicolons and dangling semicolons
- return;
- } else if(connectionProperty.length() < 3) {
- // key=value must have at least 3 characters
- throw new IllegalArgumentException();
- }
- int firstEquals = connectionProperty.indexOf('=');
- if(firstEquals < 1) {
- throw new IllegalArgumentException();
- }
- String key = connectionProperty.substring(0, firstEquals).trim();
- String value = connectionProperty.substring(firstEquals+1).trim();
- if(value.indexOf('=') >= 0) {
- throw new IllegalArgumentException();
- }
- addNormalizedProperty(key, getValidValue(value), p);
- }
-
- public String getJDBCURL() {
- if (urlString == null) {
- StringBuffer buf = new StringBuffer(JDBC_PROTOCOL)
- .append(vdbName);
- if (this.connectionURL != null) {
- buf.append('@').append(connectionURL);
- }
- for (Iterator i = properties.entrySet().iterator(); i.hasNext();) {
- Map.Entry entry = (Map.Entry)i.next();
- if (entry.getValue() instanceof String) {
- // get only the string properties, because a non-string property could not have been set on the url.
- buf.append(';')
- .append(entry.getKey())
- .append('=')
- .append(entry.getValue());
- }
- }
- urlString = buf.toString();
- }
- return urlString;
- }
-
- public String getProperty(String key) {
- return properties.getProperty(key);
- }
-
- public String getUserName() {
- return properties.getProperty(BaseDataSource.USER_NAME);
- }
-
- public String getPassword() {
- return properties.getProperty(BaseDataSource.PASSWORD);
- }
-
- public String getVDBVersion() {
- if (properties.contains(BaseDataSource.VDB_VERSION)) {
- return properties.getProperty(BaseDataSource.VDB_VERSION);
- }
- return properties.getProperty(BaseDataSource.VERSION);
- }
-
- public String getTransactionAutowrapMode() {
- return properties.getProperty(ExecutionProperties.PROP_TXN_AUTO_WRAP);
- }
-
- public String getPartialResultsMode() {
- return properties.getProperty(ExecutionProperties.PROP_PARTIAL_RESULTS_MODE);
- }
-
- public String getResultSetCacheMode() {
- return properties.getProperty(ExecutionProperties.RESULT_SET_CACHE_MODE);
- }
-
- public String getAnsiQuotedIdentifiers() {
- return properties.getProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS);
- }
-
- public String getFetchSize() {
- return properties.getProperty(ExecutionProperties.PROP_FETCH_SIZE);
- }
-
- public String getXMLFormat() {
- return properties.getProperty(ExecutionProperties.PROP_XML_FORMAT);
- }
-
- public String getXMLValidation() {
- return properties.getProperty(ExecutionProperties.PROP_XML_VALIDATION);
- }
-
- public String getTransparentFailover() {
- return properties.getProperty(TeiidURL.CONNECTION.AUTO_FAILOVER);
- }
-
- public String getDisableLocalTransactions() {
- return properties.getProperty(ExecutionProperties.DISABLE_LOCAL_TRANSACTIONS);
- }
-
- public String toString() {
- return getJDBCURL();
- }
-
- private static void normalizeProperties(Properties source, Properties target) {
- for (Enumeration e = source.propertyNames(); e.hasMoreElements();) {
- String key = (String)e.nextElement();
- addNormalizedProperty(key, source.get(key), target);
- }
- }
-
- public static void addNormalizedProperty(String key, Object value, Properties target) {
- String validKey = getValidKey(key);
-
- // now add the normalized key and value into the properties object.
- target.put(validKey, value);
- }
-
- public static String getValidKey(String key) {
- for (String prop : KNOWN_PROPERTIES) {
- if (prop.equalsIgnoreCase(key)) {
- return prop;
- }
- }
- return key;
- }
-
- private static Object getValidValue(Object value) {
- if (value instanceof String) {
- try {
- // Decode the value of the property if incase they were encoded.
- return URLDecoder.decode((String)value, UTF_8);
- } catch (UnsupportedEncodingException e) {
- // use the original value
- }
- }
- return value;
- }
-
- public static Properties normalizeProperties(Properties props) {
- normalizeProperties(props, props);
- return props;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/JDBCURL.java (from rev 3218, trunk/client/src/main/java/org/teiid/jdbc/JDBCURL.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/JDBCURL.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/JDBCURL.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,305 @@
+/*
+ * 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.jdbc;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.teiid.net.TeiidURL;
+
+/**
+ * @since 4.3
+ */
+public class JDBCURL {
+ private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$
+ public static final String JDBC_PROTOCOL = "jdbc:teiid:"; //$NON-NLS-1$
+
+ static final String URL_PATTERN = JDBC_PROTOCOL + "([\\w-\\.]+)(?:@([^;]*))?(;.*)?"; //$NON-NLS-1$
+ static Pattern urlPattern = Pattern.compile(URL_PATTERN);
+
+ public static final Set<String> EXECUTION_PROPERTIES = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(
+ ExecutionProperties.PROP_TXN_AUTO_WRAP,
+ ExecutionProperties.PROP_PARTIAL_RESULTS_MODE,
+ ExecutionProperties.RESULT_SET_CACHE_MODE,
+ ExecutionProperties.ANSI_QUOTED_IDENTIFIERS,
+ ExecutionProperties.SQL_OPTION_SHOWPLAN,
+ ExecutionProperties.NOEXEC,
+ ExecutionProperties.PROP_FETCH_SIZE,
+ ExecutionProperties.PROP_XML_FORMAT,
+ ExecutionProperties.PROP_XML_VALIDATION,
+ EmbeddedProfile.USE_CALLING_THREAD,
+ ExecutionProperties.DISABLE_LOCAL_TRANSACTIONS)));
+
+ public static final Set<String> KNOWN_PROPERTIES = getKnownProperties();
+
+ private static Set<String> getKnownProperties() {
+ Set<String> props = new HashSet<String>(Arrays.asList(
+ BaseDataSource.APP_NAME,
+ BaseDataSource.VDB_NAME,
+ BaseDataSource.VERSION,
+ BaseDataSource.VDB_VERSION,
+ BaseDataSource.USER_NAME,
+ BaseDataSource.PASSWORD,
+ TeiidURL.CONNECTION.AUTO_FAILOVER,
+ TeiidURL.CONNECTION.DISCOVERY_STRATEGY,
+ TeiidURL.CONNECTION.PASSTHROUGH_AUTHENTICATION));
+ props.addAll(EXECUTION_PROPERTIES);
+ return Collections.unmodifiableSet(props);
+ }
+
+ private String vdbName;
+ private String connectionURL;
+ private Properties properties = new Properties();
+
+ public enum ConnectionType {
+ Embedded,
+ Socket
+ }
+
+ public static ConnectionType acceptsUrl(String url) {
+ Matcher m = urlPattern.matcher(url);
+ if (m.matches()) {
+ return m.group(2) != null?ConnectionType.Socket:ConnectionType.Embedded;
+ }
+ return null;
+ }
+
+ private String urlString;
+
+ public JDBCURL(String jdbcURL) {
+ parseURL(jdbcURL);
+ }
+
+ public JDBCURL(String vdbName, String connectionURL, Properties props) {
+ if (vdbName == null || vdbName.trim().length() == 0) {
+ throw new IllegalArgumentException();
+ }
+ this.vdbName = vdbName;
+ this.connectionURL = connectionURL;
+ if (props != null) {
+ normalizeProperties(props, this.properties);
+ }
+ }
+
+ public String getVDBName() {
+ return vdbName;
+ }
+
+ public String getConnectionURL() {
+ return connectionURL;
+ }
+
+ public Properties getProperties() {
+ // Make a copy of the properties object, including any non-string values that may be contained in the map.
+ Properties newProps = new Properties();
+ newProps.putAll(this.properties);
+ return newProps;
+ }
+
+ private void parseURL(String jdbcURL) {
+ if (jdbcURL == null) {
+ throw new IllegalArgumentException();
+ }
+ // Trim extra spaces
+ jdbcURL = jdbcURL.trim();
+ if (jdbcURL.length() == 0) {
+ throw new IllegalArgumentException();
+ }
+
+ Matcher m = urlPattern.matcher(jdbcURL);
+ if (!m.matches()) {
+ throw new IllegalArgumentException();
+ }
+ vdbName = m.group(1);
+ connectionURL = m.group(2);
+ if (connectionURL != null) {
+ connectionURL = connectionURL.trim();
+ }
+ String props = m.group(3);
+ if (props != null) {
+ parseConnectionProperties(props, this.properties);
+ }
+ }
+
+ public static void parseConnectionProperties(String connectionInfo, Properties p) {
+ String[] connectionParts = connectionInfo.split(";"); //$NON-NLS-1$
+ if (connectionParts.length != 0) {
+ // The rest should be connection params
+ for (int i = 0; i < connectionParts.length; i++) {
+ parseConnectionProperty(connectionParts[i], p);
+ }
+ }
+ }
+
+ static void parseConnectionProperty(String connectionProperty, Properties p) {
+ if (connectionProperty.length() == 0) {
+ // Be tolerant of double-semicolons and dangling semicolons
+ return;
+ } else if(connectionProperty.length() < 3) {
+ // key=value must have at least 3 characters
+ throw new IllegalArgumentException();
+ }
+ int firstEquals = connectionProperty.indexOf('=');
+ if(firstEquals < 1) {
+ throw new IllegalArgumentException();
+ }
+ String key = connectionProperty.substring(0, firstEquals).trim();
+ String value = connectionProperty.substring(firstEquals+1).trim();
+ if(value.indexOf('=') >= 0) {
+ throw new IllegalArgumentException();
+ }
+ addNormalizedProperty(key, getValidValue(value), p);
+ }
+
+ public String getJDBCURL() {
+ if (urlString == null) {
+ StringBuffer buf = new StringBuffer(JDBC_PROTOCOL)
+ .append(vdbName);
+ if (this.connectionURL != null) {
+ buf.append('@').append(connectionURL);
+ }
+ for (Iterator i = properties.entrySet().iterator(); i.hasNext();) {
+ Map.Entry entry = (Map.Entry)i.next();
+ if (entry.getValue() instanceof String) {
+ // get only the string properties, because a non-string property could not have been set on the url.
+ buf.append(';')
+ .append(entry.getKey())
+ .append('=')
+ .append(entry.getValue());
+ }
+ }
+ urlString = buf.toString();
+ }
+ return urlString;
+ }
+
+ public String getProperty(String key) {
+ return properties.getProperty(key);
+ }
+
+ public String getUserName() {
+ return properties.getProperty(BaseDataSource.USER_NAME);
+ }
+
+ public String getPassword() {
+ return properties.getProperty(BaseDataSource.PASSWORD);
+ }
+
+ public String getVDBVersion() {
+ if (properties.contains(BaseDataSource.VDB_VERSION)) {
+ return properties.getProperty(BaseDataSource.VDB_VERSION);
+ }
+ return properties.getProperty(BaseDataSource.VERSION);
+ }
+
+ public String getTransactionAutowrapMode() {
+ return properties.getProperty(ExecutionProperties.PROP_TXN_AUTO_WRAP);
+ }
+
+ public String getPartialResultsMode() {
+ return properties.getProperty(ExecutionProperties.PROP_PARTIAL_RESULTS_MODE);
+ }
+
+ public String getResultSetCacheMode() {
+ return properties.getProperty(ExecutionProperties.RESULT_SET_CACHE_MODE);
+ }
+
+ public String getAnsiQuotedIdentifiers() {
+ return properties.getProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS);
+ }
+
+ public String getFetchSize() {
+ return properties.getProperty(ExecutionProperties.PROP_FETCH_SIZE);
+ }
+
+ public String getXMLFormat() {
+ return properties.getProperty(ExecutionProperties.PROP_XML_FORMAT);
+ }
+
+ public String getXMLValidation() {
+ return properties.getProperty(ExecutionProperties.PROP_XML_VALIDATION);
+ }
+
+ public String getTransparentFailover() {
+ return properties.getProperty(TeiidURL.CONNECTION.AUTO_FAILOVER);
+ }
+
+ public String getDisableLocalTransactions() {
+ return properties.getProperty(ExecutionProperties.DISABLE_LOCAL_TRANSACTIONS);
+ }
+
+ public String toString() {
+ return getJDBCURL();
+ }
+
+ private static void normalizeProperties(Properties source, Properties target) {
+ for (Enumeration e = source.propertyNames(); e.hasMoreElements();) {
+ String key = (String)e.nextElement();
+ addNormalizedProperty(key, source.get(key), target);
+ }
+ }
+
+ public static void addNormalizedProperty(String key, Object value, Properties target) {
+ String validKey = getValidKey(key);
+
+ // now add the normalized key and value into the properties object.
+ target.put(validKey, value);
+ }
+
+ public static String getValidKey(String key) {
+ for (String prop : KNOWN_PROPERTIES) {
+ if (prop.equalsIgnoreCase(key)) {
+ return prop;
+ }
+ }
+ return key;
+ }
+
+ private static Object getValidValue(Object value) {
+ if (value instanceof String) {
+ try {
+ // Decode the value of the property if incase they were encoded.
+ return URLDecoder.decode((String)value, UTF_8);
+ } catch (UnsupportedEncodingException e) {
+ // use the original value
+ }
+ }
+ return value;
+ }
+
+ public static Properties normalizeProperties(Properties props) {
+ normalizeProperties(props, props);
+ return props;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/StatementImpl.java
===================================================================
--- trunk/client/src/main/java/org/teiid/jdbc/StatementImpl.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/StatementImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1226 +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.jdbc;
-
-import java.io.Serializable;
-import java.lang.ref.WeakReference;
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.SQLException;
-import java.sql.SQLWarning;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-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;
-import java.util.regex.Pattern;
-
-import org.teiid.client.DQP;
-import org.teiid.client.RequestMessage;
-import org.teiid.client.ResultsMessage;
-import org.teiid.client.RequestMessage.ResultsMode;
-import org.teiid.client.RequestMessage.ShowPlan;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.client.metadata.ResultsMetadataConstants;
-import org.teiid.client.metadata.ResultsMetadataDefaults;
-import org.teiid.client.plan.Annotation;
-import org.teiid.client.plan.PlanNode;
-import org.teiid.client.util.ResultsFuture;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.JDBCSQLTypeInfo;
-import org.teiid.core.types.SQLXMLImpl;
-import org.teiid.core.util.SqlUtil;
-import org.teiid.core.util.StringUtil;
-import org.teiid.jdbc.CancellationTimer.CancelTask;
-
-
-public class StatementImpl extends WrapperImpl implements TeiidStatement {
- private static Logger logger = Logger.getLogger("org.teiid.jdbc"); //$NON-NLS-1$
-
- static CancellationTimer cancellationTimer = new CancellationTimer("Teiid Statement Timeout"); //$NON-NLS-1$
-
- private static final class QueryTimeoutCancelTask extends CancelTask {
- private WeakReference<StatementImpl> ref;
- private QueryTimeoutCancelTask(long delay, StatementImpl stmt) {
- super(delay);
- this.ref = new WeakReference<StatementImpl>(stmt);
- }
-
- @Override
- public void run() {
- StatementImpl stmt = ref.get();
- if (stmt != null) {
- stmt.timeoutOccurred();
- }
- }
- }
-
- enum State {
- RUNNING,
- DONE,
- TIMED_OUT,
- CANCELLED
- }
- protected static final int NO_TIMEOUT = 0;
-
- // integer indicating no maximum limit - used in some metadata-ish methods.
- private static final int NO_LIMIT = 0;
-
- //######## Configuration state #############
- private ConnectionImpl driverConnection;
- private Properties execProps;
-
- // fetch size value. This is the default fetch size used by the server
- private int fetchSize = BaseDataSource.DEFAULT_FETCH_SIZE;
-
- // the fetch direction
- private int fetchDirection = ResultSet.FETCH_FORWARD;
-
- // the result set type
- private int resultSetType = ResultSet.TYPE_FORWARD_ONLY;
- private int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY;
-
- //######## Processing state #############
-
- // boolean to indicate if this statement object is closed
- private boolean isClosed = false;
-
- // Differentiate timeout from cancel in blocking asynch operation
- protected volatile State commandStatus = State.RUNNING;
-
- // number of seconds for the query to timeout.
- protected long queryTimeoutMS = NO_TIMEOUT;
-
- //########## Per-execution state ########
-
- // ID for current request
- protected long currentRequestID = -1;
-
- // the last query plan description
- private PlanNode currentPlanDescription;
-
- // the last query debug log
- private String debugLog;
-
- // the last query annotations
- private Collection<Annotation> annotations;
-
- // resultSet object produced by execute methods on the statement.
- protected volatile ResultSetImpl resultSet;
-
- private List<Exception> serverWarnings;
-
- // the per-execution security payload
- private Serializable payload;
-
- /** List of INSERT, UPDATE, DELETE AND SELECT INTO commands */
- private List batchedUpdates;
-
- /** Array of update counts as returned by executeBatch() */
- protected int[] updateCounts;
-
- /** default Calendar instance for converting date/time/timestamp values */
- private Calendar defaultCalendar;
- /** Max rows to be returned by executing the statement */
- private int maxRows = NO_LIMIT;
- private int maxFieldSize = NO_LIMIT;
-
- //Map<out/inout/return param index --> index in results>
- 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 SHOW_STATEMENT = Pattern.compile("\\s*show\\s+(\\w*);?", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
- /**
- * Factory Constructor
- * @param driverConnection
- * @param resultSetType
- * @param resultSetConcurrency
- */
- static StatementImpl newInstance(ConnectionImpl driverConnection, int resultSetType, int resultSetConcurrency) {
- return new StatementImpl(driverConnection, resultSetType, resultSetConcurrency);
- }
-
- /**
- * MMStatement Constructor.
- * @param driverConnection
- * @param resultSetType
- * @param resultSetConcurrency
- */
- StatementImpl(ConnectionImpl driverConnection, int resultSetType, int resultSetConcurrency) {
- this.driverConnection = driverConnection;
- this.resultSetType = resultSetType;
- this.resultSetConcurrency = resultSetConcurrency;
- this.execProps = new Properties(this.driverConnection.getExecutionProperties());
-
- // Set initial fetch size
- String fetchSizeStr = this.execProps.getProperty(ExecutionProperties.PROP_FETCH_SIZE);
- if(fetchSizeStr != null) {
- try {
- this.fetchSize = Integer.parseInt(fetchSizeStr);
- } catch(Exception e) {
- // silently failover to default
- }
- }
- String queryTimeoutStr = this.execProps.getProperty(ExecutionProperties.QUERYTIMEOUT);
- if(queryTimeoutStr != null) {
- try {
- this.queryTimeoutMS = Integer.parseInt(fetchSizeStr)*1000;
- } catch(Exception e) {
- // silently failover to default
- }
- }
- }
-
- protected DQP getDQP() {
- return this.driverConnection.getDQP();
- }
-
- protected ConnectionImpl getMMConnection() {
- return this.driverConnection;
- }
-
- protected TimeZone getServerTimeZone() throws SQLException {
- return this.driverConnection.getServerConnection().getLogonResult().getTimeZone();
- }
-
- /**
- * Reset all per-execution state - this should be done before executing
- * a new command.
- */
- protected void resetExecutionState() throws SQLException {
- this.currentRequestID = -1;
-
- this.currentPlanDescription = null;
- this.debugLog = null;
- this.annotations = null;
-
- if ( this.resultSet != null ) {
- this.resultSet.close();
- this.resultSet = null;
- }
-
- this.serverWarnings = null;
-
- this.batchedUpdates = null;
- this.updateCounts = null;
- this.outParamIndexMap.clear();
- }
-
- /**
- * 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.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
- * than the exception in the exception in the conditionalWait(), which results in
- * the statement.executeQuery() call throwing the server's exception instead of the
- * one generated by the conditionalWait() method.
- */
- commandStatus = State.CANCELLED;
- 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();
-
- // clear all the warnings on this statement, after this, getWarnings() should return null
- 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();
- }
-
- /**
- * 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;
- }
-
- // close the the server's statement object (if necessary)
- if(resultSet != null) {
- resultSet.close();
- resultSet = null;
- }
-
- isClosed = true;
-
- // Remove link from connection to statement
- this.driverConnection.closeStatement(this);
-
- logger.fine(JDBCPlugin.Util.getString("MMStatement.Close_stmt_success")); //$NON-NLS-1$
- }
-
- /**
- * <p> This utility method checks if the jdbc statement is closed and
- * throws an exception if it is closed. </p>
- * @throws SQLException if the statement object is closed.
- */
- protected void checkStatement() throws TeiidSQLException {
- //Check to see the connection is closed and proceed if it is not
- if ( isClosed ) {
- throw new TeiidSQLException(JDBCPlugin.Util.getString("MMStatement.Stmt_closed")); //$NON-NLS-1$
- }
- }
-
- public ResultsFuture<Boolean> submitExecute(String sql) throws SQLException {
- return executeSql(new String[] {sql}, false, ResultsMode.EITHER, false);
- }
-
- @Override
- public boolean execute(String sql) throws SQLException {
- executeSql(new String[] {sql}, false, ResultsMode.EITHER, true);
- return hasResultSet();
- }
-
- @Override
- public int[] executeBatch() throws SQLException {
- if (batchedUpdates == null || batchedUpdates.isEmpty()) {
- return new int[0];
- }
- String[] commands = (String[])batchedUpdates.toArray(new String[batchedUpdates.size()]);
- executeSql(commands, true, ResultsMode.UPDATECOUNT, true);
- return updateCounts;
- }
-
- @Override
- public ResultSet executeQuery(String sql) throws SQLException {
- executeSql(new String[] {sql}, false, ResultsMode.RESULTSET, true);
- return resultSet;
- }
-
- @Override
- public int executeUpdate(String sql) throws SQLException {
- String[] commands = new String[] {sql};
- executeSql(commands, false, ResultsMode.UPDATECOUNT, true);
- return this.updateCounts[0];
- }
-
- protected boolean hasResultSet() throws SQLException {
- return resultSet != null && resultSet.getMetaData().getColumnCount() > 0;
- }
-
- protected void createResultSet(ResultsMessage resultsMsg) throws SQLException {
- //create out/return parameter index map if there is any
- List listOfParameters = resultsMsg.getParameters();
- if(listOfParameters != null){
- //get the size of result set
- int resultSetSize = 0;
- Iterator iteratorOfParameters = listOfParameters.iterator();
- while(iteratorOfParameters.hasNext()){
- ParameterInfo parameter = (ParameterInfo)iteratorOfParameters.next();
- if(parameter.getType() == ParameterInfo.RESULT_SET){
- resultSetSize = parameter.getNumColumns();
- //one ResultSet only
- break;
- }
- }
-
- //return needs to be the first
- int index = 0; //index in user call - {?=call sp(?)}
- int count = 0;
- iteratorOfParameters = listOfParameters.iterator();
- while(iteratorOfParameters.hasNext()){
- ParameterInfo parameter = (ParameterInfo)iteratorOfParameters.next();
- if(parameter.getType() == ParameterInfo.RETURN_VALUE){
- count++;
- index++;
- outParamIndexMap.put(new Integer(index), new Integer(resultSetSize + count));
- break;
- }
- }
-
- iteratorOfParameters = listOfParameters.iterator();
- while(iteratorOfParameters.hasNext()){
- ParameterInfo parameter = (ParameterInfo)iteratorOfParameters.next();
- if(parameter.getType() != ParameterInfo.RETURN_VALUE && parameter.getType() != ParameterInfo.RESULT_SET){
- index++;
- if(parameter.getType() == ParameterInfo.OUT || parameter.getType() == ParameterInfo.INOUT){
- count++;
- outParamIndexMap.put(new Integer(index), new Integer(resultSetSize + count));
- }
- }
- }
- }
-
- resultSet = new ResultSetImpl(resultsMsg, this, null, outParamIndexMap.size());
- resultSet.setMaxFieldSize(this.maxFieldSize);
- }
-
- @SuppressWarnings("unchecked")
- protected ResultsFuture<Boolean> executeSql(String[] commands, boolean isBatchedCommand, ResultsMode resultsMode, boolean synch)
- throws SQLException {
- checkStatement();
- resetExecutionState();
- if (logger.isLoggable(Level.FINER)) {
- logger.finer("Executing: requestID " + getCurrentRequestID() + " commands: " + Arrays.toString(commands) + " expecting: " + resultsMode); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- if (commands.length == 1) {
- Matcher match = SET_STATEMENT.matcher(commands[0]);
- if (match.matches()) {
- if (resultsMode == ResultsMode.RESULTSET) {
- throw new TeiidSQLException(JDBCPlugin.Util.getString("StatementImpl.set_result_set")); //$NON-NLS-1$
- }
- String key = match.group(1);
- String value = match.group(2);
- if (ExecutionProperties.NEWINSTANCE.equalsIgnoreCase(key) && Boolean.valueOf(value)) {
- this.getMMConnection().getServerConnection().cleanUp();
- } else {
- JDBCURL.addNormalizedProperty(key, value, this.driverConnection.getExecutionProperties());
- }
- this.updateCounts = new int[] {0};
- return booleanFuture(true);
- }
- match = TRANSACTION_STATEMENT.matcher(commands[0]);
- if (match.matches()) {
- logger.finer("Executing as transaction statement"); //$NON-NLS-1$
- if (resultsMode == ResultsMode.RESULTSET) {
- throw new TeiidSQLException(JDBCPlugin.Util.getString("StatementImpl.set_result_set")); //$NON-NLS-1$
- }
- String command = match.group(1);
- Boolean commit = null;
- if (StringUtil.startsWithIgnoreCase(command, "start")) { //$NON-NLS-1$
- //TODO: this should force a start and through an exception if we're already in a txn
- this.getConnection().setAutoCommit(false);
- } else if (command.equalsIgnoreCase("commit")) { //$NON-NLS-1$
- commit = true;
- if (synch) {
- this.getConnection().setAutoCommit(true);
- }
- } else if (command.equalsIgnoreCase("rollback")) { //$NON-NLS-1$
- commit = false;
- if (synch) {
- this.getConnection().rollback(false);
- }
- }
- this.updateCounts = new int[] {0};
- if (commit != null && !synch) {
- ResultsFuture<?> pending = this.getConnection().submitSetAutoCommitTrue(commit);
- final ResultsFuture<Boolean> result = new ResultsFuture<Boolean>();
- pending.addCompletionListener(new ResultsFuture.CompletionListener() {
- @Override
- public void onCompletion(ResultsFuture future) {
- try {
- future.get();
- result.getResultsReceiver().receiveResults(false);
- } catch (Throwable t) {
- result.getResultsReceiver().exceptionOccurred(t);
- }
- }
- });
- return result;
- }
- return booleanFuture(false);
- }
- match = SHOW_STATEMENT.matcher(commands[0]);
- if (match.matches()) {
- logger.finer("Executing as show statement"); //$NON-NLS-1$
- if (resultsMode == ResultsMode.UPDATECOUNT) {
- throw new TeiidSQLException(JDBCPlugin.Util.getString("StatementImpl.show_update_count")); //$NON-NLS-1$
- }
- String show = match.group(1);
- if (show.equalsIgnoreCase("PLAN")) { //$NON-NLS-1$
- List<ArrayList<Object>> records = new ArrayList<ArrayList<Object>>(1);
- PlanNode plan = driverConnection.getCurrentPlanDescription();
- if (plan != null) {
- ArrayList<Object> row = new ArrayList<Object>(3);
- row.add(DataTypeTransformer.getClob(plan.toString()));
- row.add(new SQLXMLImpl(plan.toXml()));
- row.add(DataTypeTransformer.getClob(driverConnection.getDebugLog()));
- records.add(row);
- }
- createResultSet(records, new String[] {"PLAN_TEXT", "PLAN_XML", "DEBUG_LOG"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- new String[] {JDBCSQLTypeInfo.CLOB, JDBCSQLTypeInfo.XML, JDBCSQLTypeInfo.CLOB});
- return booleanFuture(true);
- }
- if (show.equalsIgnoreCase("ANNOTATIONS")) { //$NON-NLS-1$
- List<ArrayList<Object>> records = new ArrayList<ArrayList<Object>>(1);
- Collection<Annotation> annos = driverConnection.getAnnotations();
- for (Annotation annotation : annos) {
- ArrayList<Object> row = new ArrayList<Object>(4);
- row.add(annotation.getCategory());
- row.add(annotation.getPriority().name());
- row.add(annotation.getAnnotation());
- row.add(annotation.getResolution());
- records.add(row);
- }
- createResultSet(records, new String[] {"CATEGORY", "PRIORITY", "ANNOTATION", "RESOLUTION"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- new String[] {JDBCSQLTypeInfo.STRING, JDBCSQLTypeInfo.STRING, JDBCSQLTypeInfo.STRING, JDBCSQLTypeInfo.STRING});
- return booleanFuture(true);
- }
- if (show.equalsIgnoreCase("ALL")) { //$NON-NLS-1$
- List<ArrayList<Object>> records = new ArrayList<ArrayList<Object>>(1);
- for (String key : driverConnection.getExecutionProperties().stringPropertyNames()) {
- ArrayList<Object> row = new ArrayList<Object>(4);
- row.add(key);
- row.add(driverConnection.getExecutionProperties().get(key));
- records.add(row);
- }
- createResultSet(records, new String[] {"NAME", "VALUE"}, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] {JDBCSQLTypeInfo.STRING, JDBCSQLTypeInfo.STRING});
- return booleanFuture(true);
- }
- List<List<String>> records = Collections.singletonList(Collections.singletonList(driverConnection.getExecutionProperties().getProperty(JDBCURL.getValidKey(show))));
- createResultSet(records, new String[] {show}, new String[] {JDBCSQLTypeInfo.STRING});
- return booleanFuture(true);
- }
- }
-
- 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>() {
- @Override
- public void onCompletion(ResultsFuture<ResultsMessage> future) {
- try {
- postReceiveResults(reqMessage, future.get());
- result.getResultsReceiver().receiveResults(hasResultSet());
- } catch (Throwable t) {
- result.getResultsReceiver().exceptionOccurred(t);
- }
- }
- });
- if (synch) {
- try {
- if (queryTimeoutMS > 0) {
- pendingResult.get(queryTimeoutMS, TimeUnit.MILLISECONDS);
- } else {
- pendingResult.get();
- }
- result.get(); //throw an exception if needed
- return result;
- } catch (ExecutionException e) {
- if (e.getCause() instanceof SQLException) {
- throw (SQLException)e.getCause();
- }
- 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$
- }
- return result;
- }
-
- private ResultsFuture<ResultsMessage> execute(final RequestMessage reqMsg, boolean synch) throws SQLException,
- TeiidSQLException {
- this.getConnection().beginLocalTxnIfNeeded();
- this.currentRequestID = this.driverConnection.nextRequestID();
- // Create a request message
- reqMsg.setExecutionPayload(this.payload);
- reqMsg.setCursorType(this.resultSetType);
- reqMsg.setFetchSize(this.fetchSize);
- reqMsg.setRowLimit(this.maxRows);
- reqMsg.setTransactionIsolation(this.driverConnection.getTransactionIsolation());
-
- // Get connection properties and set them onto request message
- copyPropertiesToRequest(reqMsg);
-
- reqMsg.setExecutionId(this.currentRequestID);
-
- ResultsFuture.CompletionListener<ResultsMessage> compeletionListener = null;
- if (queryTimeoutMS > 0 && !synch) {
- final CancelTask c = new QueryTimeoutCancelTask(queryTimeoutMS, this);
- cancellationTimer.add(c);
- compeletionListener = new ResultsFuture.CompletionListener<ResultsMessage>() {
- @Override
- public void onCompletion(ResultsFuture<ResultsMessage> future) {
- cancellationTimer.remove(c);
- }
- };
- }
-
- ResultsFuture<ResultsMessage> pendingResult = null;
- try {
- pendingResult = this.getDQP().executeRequest(this.currentRequestID, reqMsg);
- } catch (TeiidException e) {
- throw TeiidSQLException.create(e);
- }
- if (compeletionListener != null) {
- pendingResult.addCompletionListener(compeletionListener);
- }
- return pendingResult;
- }
-
- public static ResultsFuture<Boolean> booleanFuture(boolean isTrue) {
- ResultsFuture<Boolean> rs = new ResultsFuture<Boolean>();
- rs.getResultsReceiver().receiveResults(isTrue);
- return rs;
- }
-
- private void postReceiveResults(RequestMessage reqMessage,
- ResultsMessage resultsMsg) throws TeiidSQLException, SQLException {
- commandStatus = State.DONE;
- // warnings thrown
- List resultsWarning = resultsMsg.getWarnings();
-
- setAnalysisInfo(resultsMsg);
-
- if (resultsMsg.getException() != null) {
- throw TeiidSQLException.create(resultsMsg.getException());
- }
-
- // save warnings if have any
- if (resultsWarning != null) {
- accumulateWarnings(resultsWarning);
- }
-
- if (resultsMsg.isUpdateResult()) {
- List[] results = resultsMsg.getResults();
- this.updateCounts = new int[results.length];
- for (int i = 0; i < results.length; i++) {
- 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$
- }
- // In update scenarios close the statement implicitly
- try {
- getDQP().closeRequest(getCurrentRequestID());
- } catch (TeiidProcessingException e) {
- throw TeiidSQLException.create(e);
- } catch (TeiidComponentException e) {
- throw TeiidSQLException.create(e);
- }
- } else {
- createResultSet(resultsMsg);
- }
-
- logger.fine(JDBCPlugin.Util.getString("MMStatement.Success_query", reqMessage.getCommandString())); //$NON-NLS-1$
- }
-
- protected RequestMessage createRequestMessage(String[] commands,
- boolean isBatchedCommand, ResultsMode resultsMode) {
- RequestMessage reqMessage = new RequestMessage();
- reqMessage.setCommands(commands);
- reqMessage.setBatchedUpdate(isBatchedCommand);
- reqMessage.setResultsMode(resultsMode);
- return reqMessage;
- }
-
- /**
- * Retreives the fetch direction this Statement object set as a performance hint
- * to the driver. The int returned will be one of the following constants from
- * the ResultSet interface: FETCH_FORWARD, FETCH_REVERSE, or FETCH_UNKNOWN.
- * @return int value indicating the direction in which results need to be fetched
- * @throws SQLException should never occur.
- */
- public int getFetchDirection() throws SQLException {
- return this.fetchDirection;
- }
-
- /**
- * Retreives the fetch size this Statement object set as a performance hint
- * to the driver. This is the number of rows the server fetches at a time when
- * the result set needs more rows.
- * @return int value indicating the number of rows the server fetches
- * @throws SQLException should never occur.
- */
- public int getFetchSize() throws SQLException {
- return fetchSize;
- }
-
- /**
- * Retreives the maximum number of bytes that a result set column may contain.
- * @return int value giving the maximum size of a field
- * @throws SQLException should never occur.
- */
- public int getMaxFieldSize() throws SQLException {
- return maxFieldSize;
- }
-
- /**
- * Retrives the maximum number of rows that a ResultSet object may contain.
- * If the limit is exceeded the excess rows are dropped.
- * @return Max limit on rows on ResultSet.
- * @throws SQLException should never iccure.
- */
- public int getMaxRows() throws SQLException {
- return maxRows;
- }
-
- /**
- * Moves to this Statement object's next result, returns true if
- * it is a ResultSet object, and implicitly closes any current
- * ResultSet object(s) obtained with the method #getResultSet.
- * @return true if the next result is a ResultSet object;
- * false if it is an update count or there are no more results
- * @throws SQLException if there is an error in database.
- */
- public boolean getMoreResults() throws SQLException {
- //Check to see the statement is closed and throw an exception
- checkStatement();
-
- // close any current ResultSet
- if ( resultSet != null ) {
- resultSet.close();
- resultSet = null;
- }
- // set the existing update count to -1
- // indicating that there are no more results
- this.updateCounts = null;
- return false;
- }
-
- /**
- * Moves to this Statement object's next result, deals with any current
- * ResultSet object(s) according to the instructions specified by the
- * given flag, and returns true if the next result is a ResultSet object.
- * @param current flag that gives instruction on what should happen
- * to current ResultSet objects obtained using the method getResultSet(
- * CLOSE_CURRENT_RESULT, KEEP_CURRENT_RESULT, or CLOSE_ALL_RESULTS).
- * @return true if the next result is a ResultSet object; false if it
- * is an update count or there are no more results
- * @throws SQLException if there is an error in database.
- */
- public boolean getMoreResults(int current) throws SQLException {
- checkStatement();
-
- /*if (current == CLOSE_ALL_RESULTS || current == CLOSE_CURRENT_RESULT) {
- // since MetaMatrix only supports one ResultSet per statement,
- // these two cases are handled the same way.
- if (resultSet != null) {
- resultSet.close();
- }
- } else if (current == KEEP_CURRENT_RESULT) {
- // do nothing
- }
-
- rowsAffected = -1;
- */
- return false;
- }
-
-
- /**
- * Return the number of seconds the driver will wait for a statement object
- * to execute
- * @return int value giving the query timeout in seconds
- * @throws SQLException should never occur
- */
- public int getQueryTimeout() throws SQLException {
- //Check to see the statement is closed and throw an exception
- checkStatement();
- return (int)this.queryTimeoutMS/1000;
- }
-
- /**
- * Returns a ResultSet object that was produced by a call to the method execute.
- * We currently do not support execute method which could return multiple result
- * sets.
- * @return ResultSet object giving the next available ResultSet
- * @throws SQLException should never occur
- */
- public ResultSetImpl getResultSet() throws SQLException {
- //Check to see the statement is closed and throw an exception
- checkStatement();
- if (!hasResultSet()) {
- return null;
- }
- return resultSet;
- }
-
- /**
- * Retrieves the concurrency mode for the ResultSet objects generated from
- * queries that this Statement object executes. All ResultSets are currently
- * read only.
- * @return intvalue giving the ResultSet concurrency
- * @throws SQLException should never occur
- */
- public int getResultSetConcurrency() throws SQLException {
- return this.resultSetConcurrency;
- }
-
- /**
- * Retrieves the type of the ResultSet objects generated from queries that this
- * statement executes.
- * @return int value indicating the type of the ResultSet
- * @throws SQLException should never occur
- */
- public int getResultSetType() {
- return this.resultSetType;
- }
-
- /**
- * This method returns the number of rows affected by a statement modifying a table.
- * @return Number of rows affected.
- * @throws SQLException should never occur
- */
- public int getUpdateCount() throws SQLException {
- checkStatement();
- if (this.updateCounts == null) {
- return -1;
- }
- return this.updateCounts[0];
- }
-
- protected void accumulateWarnings(List<Exception> serverWarnings) {
- if (serverWarnings == null || serverWarnings.isEmpty()) {
- return;
- }
- if (this.serverWarnings == null) {
- this.serverWarnings = new ArrayList<Exception>();
- }
- this.serverWarnings.addAll(serverWarnings);
- }
-
- /**
- * This method returns warnings returned by server.
- * @return null value as there are no warnings
- * @throws SQLException should never occur
- */
- public SQLWarning getWarnings() throws SQLException {
- //Check to see the statement is closed and throw an exception
- checkStatement();
-
- if (serverWarnings != null && serverWarnings.size() != 0) {
- return WarningUtil.convertWarnings(serverWarnings);
- }
- return null;
- }
-
- /**
- * This method enbles/disables escape processing. When escape processing is
- * enabled the driver will scan any escape syntax and do escape substitution
- * before sending the escaped sql statement to the server
- * @param enable boolean value indicating if the escape processing should be turned on
- * @throws SQLException should never occur
- */
- public void setEscapeProcessing(boolean enable) throws SQLException {
- //Check to see the statement is closed and throw an exception
- checkStatement();
- // do nothing, escape processing is always enabled.
- }
-
- public void setFetchDirection(int direction) throws SQLException {
- checkStatement();
- }
-
- public void setFetchSize(int rows) throws SQLException {
- //Check to see the statement is closed and throw an exception
- checkStatement();
- if ( rows < 0 ) {
- String msg = JDBCPlugin.Util.getString("MMStatement.Invalid_fetch_size"); //$NON-NLS-1$
- throw new TeiidSQLException(msg);
- }
- // sets the fetch size on this statement
- if (rows == 0) {
- this.fetchSize = BaseDataSource.DEFAULT_FETCH_SIZE;
- } else {
- this.fetchSize = rows;
- }
- }
-
- /**
- * Sets the limit on the maximum number of rows in a ResultSet object. This
- * method is currently implemented to throw an exception as it is not possible
- * to limit the number of rows.
- * @param maxRows int value indicating maximum rows that can be returned in a ResultSet
- */
- public void setMaxRows(int maxRows) throws SQLException {
- //Check to see the statement is closed and throw an exception
- checkStatement();
- this.maxRows = maxRows;
- }
-
- /**
- * This sets to seconds the time limit for the number of seconds for a driver
- * to wait for a statement object to be executed.
- * @param seconds Maximum number of seconds for a statement object to execute.
- * throws SQLException, should never occur
- */
- public void setQueryTimeout(int seconds) throws SQLException {
- //Check to see the statement is closed and throw an exception
- checkStatement();
- if (seconds >= 0) {
- queryTimeoutMS = seconds*1000;
- }
- else {
- throw new TeiidSQLException(JDBCPlugin.Util.getString("MMStatement.Bad_timeout_value")); //$NON-NLS-1$
- }
- }
-
- void setQueryTimeoutMS(int queryTimeoutMS) {
- this.queryTimeoutMS = queryTimeoutMS;
- }
-
- /**
- * Helper method for copy the connection properties to request message.
- * @param res Request message that these properties to be copied to.
- * @throws TeiidSQLException
- */
- protected void copyPropertiesToRequest(RequestMessage res) throws TeiidSQLException {
- // Get partial mode
- String partial = getExecutionProperty(ExecutionProperties.PROP_PARTIAL_RESULTS_MODE);
- res.setPartialResults(Boolean.valueOf(partial).booleanValue());
-
- // Get xml validation mode
- String validate = getExecutionProperty(ExecutionProperties.PROP_XML_VALIDATION);
- if(validate == null) {
- res.setValidationMode(false);
- } else {
- res.setValidationMode(Boolean.valueOf(validate).booleanValue());
- }
-
- // Get xml format mode
- String format = getExecutionProperty(ExecutionProperties.PROP_XML_FORMAT);
- res.setXMLFormat(format);
-
- // Get transaction auto-wrap mode
- String txnAutoWrapMode = getExecutionProperty(ExecutionProperties.PROP_TXN_AUTO_WRAP);
- try {
- res.setTxnAutoWrapMode(txnAutoWrapMode);
- } catch (TeiidProcessingException e) {
- throw TeiidSQLException.create(e);
- }
-
- // Get result set cache mode
- String rsCache = getExecutionProperty(ExecutionProperties.RESULT_SET_CACHE_MODE);
- res.setUseResultSetCache(Boolean.valueOf(rsCache).booleanValue());
-
- res.setAnsiQuotedIdentifiers(Boolean.valueOf(
- getExecutionProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS))
- .booleanValue());
- String showPlan = getExecutionProperty(ExecutionProperties.SQL_OPTION_SHOWPLAN);
- if (showPlan != null) {
- try {
- res.setShowPlan(ShowPlan.valueOf(showPlan.toUpperCase()));
- } catch (IllegalArgumentException e) {
-
- }
- }
- String noExec = getExecutionProperty(ExecutionProperties.NOEXEC);
- if (noExec != null) {
- res.setNoExec(noExec.equalsIgnoreCase("ON")); //$NON-NLS-1$
- }
- }
-
- /**
- * Ends the command and sets the status to TIMED_OUT.
- */
- protected void timeoutOccurred() {
- if (this.commandStatus != State.RUNNING) {
- return;
- }
- logger.warning(JDBCPlugin.Util.getString("MMStatement.Timeout_ocurred_in_Statement.")); //$NON-NLS-1$
- try {
- cancel();
- commandStatus = State.TIMED_OUT;
- queryTimeoutMS = NO_TIMEOUT;
- currentRequestID = -1;
- if (this.resultSet != null) {
- this.resultSet.close();
- }
- } catch (SQLException se) {
- logger.log(Level.SEVERE, JDBCPlugin.Util.getString("MMStatement.Error_timing_out."), se); //$NON-NLS-1$
- }
- }
-
- protected void cancelRequest() throws SQLException {
- checkStatement();
-
- try {
- this.getDQP().cancelRequest(currentRequestID);
- } catch (TeiidProcessingException e) {
- throw TeiidSQLException.create(e);
- } catch (TeiidComponentException e) {
- throw TeiidSQLException.create(e);
- }
- }
-
- /**
- * Set the per-statement security payload. This optional payload will
- * accompany each request to the data source(s) so that the connector
- * will have access to it.
- * <br>Once the payload is set, it will be used for each statment
- * execution until it is set to <code>null</code>, a new payload is set on
- * the statement or the statement is closed.</br>
- *
- * <p>To remove an existing payload from a statement, call this method
- * with a <code>null</code> argument.</p>
- * @param payload The payload that is to accompany requests executed
- * from this statement.
- * @since 4.2
- */
- public void setPayload(Serializable payload) {
- this.payload = payload;
- }
-
- public void setExecutionProperty(String name, String value) {
- this.execProps.setProperty(name, value);
- }
-
- public String getExecutionProperty(String name) {
- return this.execProps.getProperty(name);
- }
-
- long getCurrentRequestID() {
- return this.currentRequestID;
- }
-
- /**
- * Get Query plan description.
- * If the Statement has a resultSet, we get the plan description from the result set
- * If that plan description is null, though, we return the very first plan description
- * that was created from the resultsMessage in the method: setAnalysisInfo.
- * The plan description from the result set can be null if the resultsMsg stored in the
- * result set hasn't been created when getPlanDescription is called.
- * @return Query plan description, if it exists, otherwise null
- */
- public PlanNode getPlanDescription() {
- if(this.resultSet != null) {
- return this.resultSet.getUpdatedPlanDescription();
- }
- if(currentPlanDescription != null) {
- return this.currentPlanDescription;
- }
- return null;
- }
-
- /**
- * Get query planner debug log.
- * @return Query planner debug log, or null if it doesn't exist
- */
- public String getDebugLog() {
- return this.debugLog;
- }
-
- /**
- * Get annotations
- * @return Query planner annotations - Collection of Annotation
- */
- public Collection<Annotation> getAnnotations() {
- return this.annotations;
- }
-
- public String getRequestIdentifier() {
- if(this.currentRequestID >= 0) {
- return Long.toString(this.currentRequestID);
- }
- return null;
- }
-
- /**
- * Check is the statement is closed. Used primarily by the unit tests.
- * @return true if the statement is closed; false otherwise.
- */
- public boolean isClosed() {
- return this.isClosed;
- }
-
- protected void setAnalysisInfo(ResultsMessage resultsMsg) {
- this.debugLog = resultsMsg.getDebugLog();
- this.currentPlanDescription = resultsMsg.getPlanDescription();
- this.annotations = resultsMsg.getAnnotations();
- this.driverConnection.setDebugLog(debugLog);
- this.driverConnection.setCurrentPlanDescription(currentPlanDescription);
- this.driverConnection.setAnnotations(annotations);
- }
-
- Calendar getDefaultCalendar() {
- if (defaultCalendar == null) {
- defaultCalendar = Calendar.getInstance();
- }
- return defaultCalendar;
- }
-
- void setDefaultCalendar(Calendar cal) {
- this.defaultCalendar = cal;
- }
-
- public boolean isPoolable() throws SQLException {
- checkStatement();
- return false;
- }
-
- public void setPoolable(boolean arg0) throws SQLException {
- checkStatement();
- }
-
- public ConnectionImpl getConnection() throws SQLException {
- return this.driverConnection;
- }
-
- public boolean execute(String sql, int autoGeneratedKeys)
- throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public boolean execute(String sql, int[] columnIndexes) throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public boolean execute(String sql, String[] columnNames)
- throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public int executeUpdate(String sql, int autoGeneratedKeys)
- throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public int executeUpdate(String sql, int[] columnIndexes)
- throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public int executeUpdate(String sql, String[] columnNames)
- throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public ResultSet getGeneratedKeys() throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public int getResultSetHoldability() throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public void setCursorName(String name) throws SQLException {
- throw SqlUtil.createFeatureNotSupportedException();
- }
-
- public void setMaxFieldSize(int max) throws SQLException {
- checkStatement();
- if ( max < 0 ) {
- throw new TeiidSQLException(JDBCPlugin.Util.getString("MMStatement.Invalid_field_size", max)); //$NON-NLS-1$
- }
- this.maxFieldSize = max;
- }
-
- ResultSetImpl createResultSet(List records, String[] columnNames, String[] dataTypes) throws SQLException {
- Map[] metadata = new Map[columnNames.length];
- for (int i = 0; i < columnNames.length; i++) {
- metadata[i] = getColumnMetadata(null, columnNames[i], dataTypes[i], ResultsMetadataConstants.NULL_TYPES.UNKNOWN, driverConnection);
- }
- return createResultSet(records, metadata);
- }
-
- ResultSetImpl createResultSet(List records, Map[] columnMetadata) throws SQLException {
- ResultSetMetaData rsmd = new ResultSetMetaDataImpl(new MetadataProvider(columnMetadata));
-
- return createResultSet(records, rsmd);
- }
-
- ResultSetImpl createResultSet(List records, ResultSetMetaData rsmd) throws SQLException {
- rsmd.getScale(1); //force the load of the metadata
- ResultsMessage resultsMsg = createDummyResultsMessage(null, null, records);
- resultSet = new ResultSetImpl(resultsMsg, this, rsmd, 0);
- resultSet.setMaxFieldSize(this.maxFieldSize);
- return resultSet;
- }
-
- static ResultsMessage createDummyResultsMessage(String[] columnNames, String[] dataTypes, List records) {
- ResultsMessage resultsMsg = new ResultsMessage();
- resultsMsg.setColumnNames(columnNames);
- resultsMsg.setDataTypes(dataTypes);
- resultsMsg.setFirstRow(1);
- resultsMsg.setLastRow(records.size());
- resultsMsg.setFinalRow(records.size());
- resultsMsg.setResults((List[])records.toArray(new List[records.size()]));
- return resultsMsg;
- }
-
- static Map<Integer, Object> getColumnMetadata(String tableName, String columnName, String dataType, Integer nullable, ConnectionImpl driverConnection) throws SQLException {
- return getColumnMetadata(tableName, columnName, dataType, nullable, ResultsMetadataConstants.SEARCH_TYPES.UNSEARCHABLE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, driverConnection);
- }
-
- static Map<Integer, Object> getColumnMetadata(String tableName, String columnName, String dataType, Integer nullable, Integer searchable, Boolean writable, Boolean signed, Boolean caseSensitive, ConnectionImpl driverConnection) throws SQLException {
-
- // map that would contain metadata details
- Map<Integer, Object> metadataMap = new HashMap<Integer, Object>();
-
- /*******************************************************
- HardCoding Column metadata details for the given column
- ********************************************************/
-
- metadataMap.put(ResultsMetadataConstants.VIRTUAL_DATABASE_NAME, driverConnection.getVDBName());
- metadataMap.put(ResultsMetadataConstants.GROUP_NAME, tableName);
- metadataMap.put(ResultsMetadataConstants.ELEMENT_NAME, columnName);
- metadataMap.put(ResultsMetadataConstants.DATA_TYPE, dataType);
- metadataMap.put(ResultsMetadataConstants.PRECISION, ResultsMetadataDefaults.getDefaultPrecision(dataType));
- metadataMap.put(ResultsMetadataConstants.RADIX, new Integer(10));
- metadataMap.put(ResultsMetadataConstants.SCALE, new Integer(0));
- metadataMap.put(ResultsMetadataConstants.AUTO_INCREMENTING, Boolean.FALSE);
- metadataMap.put(ResultsMetadataConstants.CASE_SENSITIVE, caseSensitive);
- metadataMap.put(ResultsMetadataConstants.NULLABLE, nullable);
- metadataMap.put(ResultsMetadataConstants.SEARCHABLE, searchable);
- metadataMap.put(ResultsMetadataConstants.SIGNED, signed);
- metadataMap.put(ResultsMetadataConstants.WRITABLE, writable);
- metadataMap.put(ResultsMetadataConstants.CURRENCY, Boolean.FALSE);
- metadataMap.put(ResultsMetadataConstants.DISPLAY_SIZE, ResultsMetadataDefaults.getMaxDisplaySize(dataType));
-
- return metadataMap;
- }
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/StatementImpl.java (from rev 3218, trunk/client/src/main/java/org/teiid/jdbc/StatementImpl.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/StatementImpl.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/jdbc/StatementImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1238 @@
+/*
+ * 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.jdbc;
+
+import java.io.Serializable;
+import java.lang.ref.WeakReference;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+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;
+import java.util.regex.Pattern;
+
+import org.teiid.client.DQP;
+import org.teiid.client.RequestMessage;
+import org.teiid.client.ResultsMessage;
+import org.teiid.client.RequestMessage.ResultsMode;
+import org.teiid.client.RequestMessage.ShowPlan;
+import org.teiid.client.metadata.ParameterInfo;
+import org.teiid.client.metadata.ResultsMetadataConstants;
+import org.teiid.client.metadata.ResultsMetadataDefaults;
+import org.teiid.client.plan.Annotation;
+import org.teiid.client.plan.PlanNode;
+import org.teiid.client.util.ResultsFuture;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.JDBCSQLTypeInfo;
+import org.teiid.core.types.SQLXMLImpl;
+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 {
+ private static Logger logger = Logger.getLogger("org.teiid.jdbc"); //$NON-NLS-1$
+
+ static CancellationTimer cancellationTimer = new CancellationTimer("Teiid Statement Timeout"); //$NON-NLS-1$
+
+ private static final class QueryTimeoutCancelTask extends CancelTask {
+ private WeakReference<StatementImpl> ref;
+ private QueryTimeoutCancelTask(long delay, StatementImpl stmt) {
+ super(delay);
+ this.ref = new WeakReference<StatementImpl>(stmt);
+ }
+
+ @Override
+ public void run() {
+ StatementImpl stmt = ref.get();
+ if (stmt != null) {
+ stmt.timeoutOccurred();
+ }
+ }
+ }
+
+ enum State {
+ RUNNING,
+ DONE,
+ TIMED_OUT,
+ CANCELLED
+ }
+ protected static final int NO_TIMEOUT = 0;
+
+ // integer indicating no maximum limit - used in some metadata-ish methods.
+ private static final int NO_LIMIT = 0;
+
+ //######## Configuration state #############
+ private ConnectionImpl driverConnection;
+ private Properties execProps;
+
+ // fetch size value. This is the default fetch size used by the server
+ private int fetchSize = BaseDataSource.DEFAULT_FETCH_SIZE;
+
+ // the fetch direction
+ private int fetchDirection = ResultSet.FETCH_FORWARD;
+
+ // the result set type
+ private int resultSetType = ResultSet.TYPE_FORWARD_ONLY;
+ private int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY;
+
+ //######## Processing state #############
+
+ // boolean to indicate if this statement object is closed
+ private boolean isClosed = false;
+
+ // Differentiate timeout from cancel in blocking asynch operation
+ protected volatile State commandStatus = State.RUNNING;
+
+ // number of seconds for the query to timeout.
+ protected long queryTimeoutMS = NO_TIMEOUT;
+
+ //########## Per-execution state ########
+
+ // ID for current request
+ protected long currentRequestID = -1;
+
+ // the last query plan description
+ private PlanNode currentPlanDescription;
+
+ // the last query debug log
+ private String debugLog;
+
+ // the last query annotations
+ private Collection<Annotation> annotations;
+
+ // resultSet object produced by execute methods on the statement.
+ protected volatile ResultSetImpl resultSet;
+
+ private List<Exception> serverWarnings;
+
+ // the per-execution security payload
+ private Serializable payload;
+
+ /** List of INSERT, UPDATE, DELETE AND SELECT INTO commands */
+ private List batchedUpdates;
+
+ /** Array of update counts as returned by executeBatch() */
+ protected int[] updateCounts;
+
+ /** default Calendar instance for converting date/time/timestamp values */
+ private Calendar defaultCalendar;
+ /** Max rows to be returned by executing the statement */
+ private int maxRows = NO_LIMIT;
+ private int maxFieldSize = NO_LIMIT;
+
+ //Map<out/inout/return param index --> index in results>
+ 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+((?: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
+ * @param driverConnection
+ * @param resultSetType
+ * @param resultSetConcurrency
+ */
+ static StatementImpl newInstance(ConnectionImpl driverConnection, int resultSetType, int resultSetConcurrency) {
+ return new StatementImpl(driverConnection, resultSetType, resultSetConcurrency);
+ }
+
+ /**
+ * MMStatement Constructor.
+ * @param driverConnection
+ * @param resultSetType
+ * @param resultSetConcurrency
+ */
+ StatementImpl(ConnectionImpl driverConnection, int resultSetType, int resultSetConcurrency) {
+ this.driverConnection = driverConnection;
+ this.resultSetType = resultSetType;
+ this.resultSetConcurrency = resultSetConcurrency;
+ this.execProps = new Properties(this.driverConnection.getExecutionProperties());
+
+ // Set initial fetch size
+ String fetchSizeStr = this.execProps.getProperty(ExecutionProperties.PROP_FETCH_SIZE);
+ if(fetchSizeStr != null) {
+ try {
+ this.fetchSize = Integer.parseInt(fetchSizeStr);
+ } catch(Exception e) {
+ // silently failover to default
+ }
+ }
+ String queryTimeoutStr = this.execProps.getProperty(ExecutionProperties.QUERYTIMEOUT);
+ if(queryTimeoutStr != null) {
+ try {
+ this.queryTimeoutMS = Integer.parseInt(fetchSizeStr)*1000;
+ } catch(Exception e) {
+ // silently failover to default
+ }
+ }
+ }
+
+ protected DQP getDQP() {
+ return this.driverConnection.getDQP();
+ }
+
+ protected ConnectionImpl getMMConnection() {
+ return this.driverConnection;
+ }
+
+ protected TimeZone getServerTimeZone() throws SQLException {
+ return this.driverConnection.getServerConnection().getLogonResult().getTimeZone();
+ }
+
+ /**
+ * Reset all per-execution state - this should be done before executing
+ * a new command.
+ */
+ protected void resetExecutionState() throws SQLException {
+ this.currentRequestID = -1;
+
+ this.currentPlanDescription = null;
+ this.debugLog = null;
+ this.annotations = null;
+
+ if ( this.resultSet != null ) {
+ this.resultSet.close();
+ this.resultSet = null;
+ }
+
+ this.serverWarnings = null;
+
+ this.batchedUpdates = null;
+ this.updateCounts = null;
+ this.outParamIndexMap.clear();
+ }
+
+ /**
+ * 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.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
+ * than the exception in the exception in the conditionalWait(), which results in
+ * the statement.executeQuery() call throwing the server's exception instead of the
+ * one generated by the conditionalWait() method.
+ */
+ commandStatus = State.CANCELLED;
+ 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();
+
+ // clear all the warnings on this statement, after this, getWarnings() should return null
+ 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();
+ }
+
+ /**
+ * 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;
+ }
+
+ // close the the server's statement object (if necessary)
+ if(resultSet != null) {
+ resultSet.close();
+ resultSet = null;
+ }
+
+ isClosed = true;
+
+ // Remove link from connection to statement
+ this.driverConnection.closeStatement(this);
+
+ logger.fine(JDBCPlugin.Util.getString("MMStatement.Close_stmt_success")); //$NON-NLS-1$
+ }
+
+ /**
+ * <p> This utility method checks if the jdbc statement is closed and
+ * throws an exception if it is closed. </p>
+ * @throws SQLException if the statement object is closed.
+ */
+ protected void checkStatement() throws TeiidSQLException {
+ //Check to see the connection is closed and proceed if it is not
+ if ( isClosed ) {
+ throw new TeiidSQLException(JDBCPlugin.Util.getString("MMStatement.Stmt_closed")); //$NON-NLS-1$
+ }
+ }
+
+ public ResultsFuture<Boolean> submitExecute(String sql) throws SQLException {
+ return executeSql(new String[] {sql}, false, ResultsMode.EITHER, false);
+ }
+
+ @Override
+ public boolean execute(String sql) throws SQLException {
+ executeSql(new String[] {sql}, false, ResultsMode.EITHER, true);
+ return hasResultSet();
+ }
+
+ @Override
+ public int[] executeBatch() throws SQLException {
+ if (batchedUpdates == null || batchedUpdates.isEmpty()) {
+ return new int[0];
+ }
+ String[] commands = (String[])batchedUpdates.toArray(new String[batchedUpdates.size()]);
+ executeSql(commands, true, ResultsMode.UPDATECOUNT, true);
+ return updateCounts;
+ }
+
+ @Override
+ public ResultSet executeQuery(String sql) throws SQLException {
+ executeSql(new String[] {sql}, false, ResultsMode.RESULTSET, true);
+ return resultSet;
+ }
+
+ @Override
+ public int executeUpdate(String sql) throws SQLException {
+ String[] commands = new String[] {sql};
+ executeSql(commands, false, ResultsMode.UPDATECOUNT, true);
+ return this.updateCounts[0];
+ }
+
+ protected boolean hasResultSet() throws SQLException {
+ return resultSet != null && resultSet.getMetaData().getColumnCount() > 0;
+ }
+
+ protected void createResultSet(ResultsMessage resultsMsg) throws SQLException {
+ //create out/return parameter index map if there is any
+ List listOfParameters = resultsMsg.getParameters();
+ if(listOfParameters != null){
+ //get the size of result set
+ int resultSetSize = 0;
+ Iterator iteratorOfParameters = listOfParameters.iterator();
+ while(iteratorOfParameters.hasNext()){
+ ParameterInfo parameter = (ParameterInfo)iteratorOfParameters.next();
+ if(parameter.getType() == ParameterInfo.RESULT_SET){
+ resultSetSize = parameter.getNumColumns();
+ //one ResultSet only
+ break;
+ }
+ }
+
+ //return needs to be the first
+ int index = 0; //index in user call - {?=call sp(?)}
+ int count = 0;
+ iteratorOfParameters = listOfParameters.iterator();
+ while(iteratorOfParameters.hasNext()){
+ ParameterInfo parameter = (ParameterInfo)iteratorOfParameters.next();
+ if(parameter.getType() == ParameterInfo.RETURN_VALUE){
+ count++;
+ index++;
+ outParamIndexMap.put(new Integer(index), new Integer(resultSetSize + count));
+ break;
+ }
+ }
+
+ iteratorOfParameters = listOfParameters.iterator();
+ while(iteratorOfParameters.hasNext()){
+ ParameterInfo parameter = (ParameterInfo)iteratorOfParameters.next();
+ if(parameter.getType() != ParameterInfo.RETURN_VALUE && parameter.getType() != ParameterInfo.RESULT_SET){
+ index++;
+ if(parameter.getType() == ParameterInfo.OUT || parameter.getType() == ParameterInfo.INOUT){
+ count++;
+ outParamIndexMap.put(new Integer(index), new Integer(resultSetSize + count));
+ }
+ }
+ }
+ }
+
+ resultSet = new ResultSetImpl(resultsMsg, this, null, outParamIndexMap.size());
+ resultSet.setMaxFieldSize(this.maxFieldSize);
+ }
+
+ @SuppressWarnings("unchecked")
+ protected ResultsFuture<Boolean> executeSql(String[] commands, boolean isBatchedCommand, ResultsMode resultsMode, boolean synch)
+ throws SQLException {
+ checkStatement();
+ resetExecutionState();
+ if (logger.isLoggable(Level.FINER)) {
+ logger.finer("Executing: requestID " + getCurrentRequestID() + " commands: " + Arrays.toString(commands) + " expecting: " + resultsMode); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ if (commands.length == 1) {
+ Matcher match = SET_STATEMENT.matcher(commands[0]);
+ if (match.matches()) {
+ if (resultsMode == ResultsMode.RESULTSET) {
+ throw new TeiidSQLException(JDBCPlugin.Util.getString("StatementImpl.set_result_set")); //$NON-NLS-1$
+ }
+ String key = match.group(1);
+ String value = match.group(2);
+ 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());
+ }
+ this.updateCounts = new int[] {0};
+ return booleanFuture(true);
+ }
+ match = TRANSACTION_STATEMENT.matcher(commands[0]);
+ if (match.matches()) {
+ logger.finer("Executing as transaction statement"); //$NON-NLS-1$
+ if (resultsMode == ResultsMode.RESULTSET) {
+ throw new TeiidSQLException(JDBCPlugin.Util.getString("StatementImpl.set_result_set")); //$NON-NLS-1$
+ }
+ String command = match.group(1);
+ Boolean commit = null;
+ if (StringUtil.startsWithIgnoreCase(command, "start")) { //$NON-NLS-1$
+ //TODO: this should force a start and through an exception if we're already in a txn
+ this.getConnection().setAutoCommit(false);
+ } else if (command.equalsIgnoreCase("commit")) { //$NON-NLS-1$
+ commit = true;
+ if (synch) {
+ this.getConnection().setAutoCommit(true);
+ }
+ } else if (command.equalsIgnoreCase("rollback")) { //$NON-NLS-1$
+ commit = false;
+ if (synch) {
+ this.getConnection().rollback(false);
+ }
+ }
+ this.updateCounts = new int[] {0};
+ if (commit != null && !synch) {
+ ResultsFuture<?> pending = this.getConnection().submitSetAutoCommitTrue(commit);
+ final ResultsFuture<Boolean> result = new ResultsFuture<Boolean>();
+ pending.addCompletionListener(new ResultsFuture.CompletionListener() {
+ @Override
+ public void onCompletion(ResultsFuture future) {
+ try {
+ future.get();
+ result.getResultsReceiver().receiveResults(false);
+ } catch (Throwable t) {
+ result.getResultsReceiver().exceptionOccurred(t);
+ }
+ }
+ });
+ return result;
+ }
+ return booleanFuture(false);
+ }
+ match = SHOW_STATEMENT.matcher(commands[0]);
+ if (match.matches()) {
+ logger.finer("Executing as show statement"); //$NON-NLS-1$
+ if (resultsMode == ResultsMode.UPDATECOUNT) {
+ throw new TeiidSQLException(JDBCPlugin.Util.getString("StatementImpl.show_update_count")); //$NON-NLS-1$
+ }
+ String show = match.group(1);
+ if (show.equalsIgnoreCase("PLAN")) { //$NON-NLS-1$
+ List<ArrayList<Object>> records = new ArrayList<ArrayList<Object>>(1);
+ PlanNode plan = driverConnection.getCurrentPlanDescription();
+ if (plan != null) {
+ ArrayList<Object> row = new ArrayList<Object>(3);
+ row.add(DataTypeTransformer.getClob(plan.toString()));
+ row.add(new SQLXMLImpl(plan.toXml()));
+ row.add(DataTypeTransformer.getClob(driverConnection.getDebugLog()));
+ records.add(row);
+ }
+ createResultSet(records, new String[] {"PLAN_TEXT", "PLAN_XML", "DEBUG_LOG"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ new String[] {JDBCSQLTypeInfo.CLOB, JDBCSQLTypeInfo.XML, JDBCSQLTypeInfo.CLOB});
+ return booleanFuture(true);
+ }
+ if (show.equalsIgnoreCase("ANNOTATIONS")) { //$NON-NLS-1$
+ List<ArrayList<Object>> records = new ArrayList<ArrayList<Object>>(1);
+ Collection<Annotation> annos = driverConnection.getAnnotations();
+ for (Annotation annotation : annos) {
+ ArrayList<Object> row = new ArrayList<Object>(4);
+ row.add(annotation.getCategory());
+ row.add(annotation.getPriority().name());
+ row.add(annotation.getAnnotation());
+ row.add(annotation.getResolution());
+ records.add(row);
+ }
+ createResultSet(records, new String[] {"CATEGORY", "PRIORITY", "ANNOTATION", "RESOLUTION"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ new String[] {JDBCSQLTypeInfo.STRING, JDBCSQLTypeInfo.STRING, JDBCSQLTypeInfo.STRING, JDBCSQLTypeInfo.STRING});
+ return booleanFuture(true);
+ }
+ if (show.equalsIgnoreCase("ALL")) { //$NON-NLS-1$
+ List<ArrayList<Object>> records = new ArrayList<ArrayList<Object>>(1);
+ for (String key : driverConnection.getExecutionProperties().stringPropertyNames()) {
+ ArrayList<Object> row = new ArrayList<Object>(4);
+ row.add(key);
+ row.add(driverConnection.getExecutionProperties().get(key));
+ records.add(row);
+ }
+ createResultSet(records, new String[] {"NAME", "VALUE"}, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] {JDBCSQLTypeInfo.STRING, JDBCSQLTypeInfo.STRING});
+ return booleanFuture(true);
+ }
+ List<List<String>> records = Collections.singletonList(Collections.singletonList(driverConnection.getExecutionProperties().getProperty(JDBCURL.getValidKey(show))));
+ createResultSet(records, new String[] {show}, new String[] {JDBCSQLTypeInfo.STRING});
+ return booleanFuture(true);
+ }
+ }
+
+ final RequestMessage reqMessage = createRequestMessage(commands, isBatchedCommand, resultsMode);
+ ResultsFuture<ResultsMessage> pendingResult = execute(reqMessage, synch);
+ final ResultsFuture<Boolean> result = new ResultsFuture<Boolean>();
+ pendingResult.addCompletionListener(new ResultsFuture.CompletionListener<ResultsMessage>() {
+ @Override
+ public void onCompletion(ResultsFuture<ResultsMessage> future) {
+ try {
+ postReceiveResults(reqMessage, future.get());
+ result.getResultsReceiver().receiveResults(hasResultSet());
+ } catch (Throwable t) {
+ result.getResultsReceiver().exceptionOccurred(t);
+ }
+ }
+ });
+ if (synch) {
+ try {
+ if (queryTimeoutMS > 0) {
+ pendingResult.get(queryTimeoutMS, TimeUnit.MILLISECONDS);
+ } else {
+ pendingResult.get();
+ }
+ result.get(); //throw an exception if needed
+ return result;
+ } catch (ExecutionException e) {
+ if (e.getCause() instanceof SQLException) {
+ throw (SQLException)e.getCause();
+ }
+ 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$
+ }
+ return result;
+ }
+
+ private ResultsFuture<ResultsMessage> execute(final RequestMessage reqMsg, boolean synch) throws SQLException,
+ TeiidSQLException {
+ this.getConnection().beginLocalTxnIfNeeded();
+ this.currentRequestID = this.driverConnection.nextRequestID();
+ // Create a request message
+ reqMsg.setExecutionPayload(this.payload);
+ reqMsg.setCursorType(this.resultSetType);
+ 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) {
+ final CancelTask c = new QueryTimeoutCancelTask(queryTimeoutMS, this);
+ cancellationTimer.add(c);
+ compeletionListener = new ResultsFuture.CompletionListener<ResultsMessage>() {
+ @Override
+ public void onCompletion(ResultsFuture<ResultsMessage> future) {
+ cancellationTimer.remove(c);
+ }
+ };
+ }
+
+ ResultsFuture<ResultsMessage> pendingResult = null;
+ try {
+ pendingResult = this.getDQP().executeRequest(this.currentRequestID, reqMsg);
+ } catch (TeiidException e) {
+ throw TeiidSQLException.create(e);
+ }
+ if (compeletionListener != null) {
+ pendingResult.addCompletionListener(compeletionListener);
+ }
+ return pendingResult;
+ }
+
+ public static ResultsFuture<Boolean> booleanFuture(boolean isTrue) {
+ ResultsFuture<Boolean> rs = new ResultsFuture<Boolean>();
+ rs.getResultsReceiver().receiveResults(isTrue);
+ return rs;
+ }
+
+ private void postReceiveResults(RequestMessage reqMessage,
+ ResultsMessage resultsMsg) throws TeiidSQLException, SQLException {
+ commandStatus = State.DONE;
+ // warnings thrown
+ List resultsWarning = resultsMsg.getWarnings();
+
+ setAnalysisInfo(resultsMsg);
+
+ if (resultsMsg.getException() != null) {
+ throw TeiidSQLException.create(resultsMsg.getException());
+ }
+
+ // save warnings if have any
+ if (resultsWarning != null) {
+ accumulateWarnings(resultsWarning);
+ }
+
+ if (resultsMsg.isUpdateResult()) {
+ List[] results = resultsMsg.getResults();
+ this.updateCounts = new int[results.length];
+ for (int i = 0; i < results.length; i++) {
+ updateCounts[i] = (Integer)results[i].get(0);
+ }
+ if (logger.isLoggable(Level.FINER)) {
+ logger.finer("Recieved update counts: " + Arrays.toString(updateCounts)); //$NON-NLS-1$
+ }
+ // In update scenarios close the statement implicitly
+ try {
+ getDQP().closeRequest(getCurrentRequestID());
+ } catch (TeiidProcessingException e) {
+ throw TeiidSQLException.create(e);
+ } catch (TeiidComponentException e) {
+ throw TeiidSQLException.create(e);
+ }
+ } else {
+ createResultSet(resultsMsg);
+ }
+
+ logger.fine(JDBCPlugin.Util.getString("MMStatement.Success_query", reqMessage.getCommandString())); //$NON-NLS-1$
+ }
+
+ protected RequestMessage createRequestMessage(String[] commands,
+ boolean isBatchedCommand, ResultsMode resultsMode) {
+ RequestMessage reqMessage = new RequestMessage();
+ reqMessage.setCommands(commands);
+ reqMessage.setBatchedUpdate(isBatchedCommand);
+ reqMessage.setResultsMode(resultsMode);
+ return reqMessage;
+ }
+
+ /**
+ * Retreives the fetch direction this Statement object set as a performance hint
+ * to the driver. The int returned will be one of the following constants from
+ * the ResultSet interface: FETCH_FORWARD, FETCH_REVERSE, or FETCH_UNKNOWN.
+ * @return int value indicating the direction in which results need to be fetched
+ * @throws SQLException should never occur.
+ */
+ public int getFetchDirection() throws SQLException {
+ return this.fetchDirection;
+ }
+
+ /**
+ * Retreives the fetch size this Statement object set as a performance hint
+ * to the driver. This is the number of rows the server fetches at a time when
+ * the result set needs more rows.
+ * @return int value indicating the number of rows the server fetches
+ * @throws SQLException should never occur.
+ */
+ public int getFetchSize() throws SQLException {
+ return fetchSize;
+ }
+
+ /**
+ * Retreives the maximum number of bytes that a result set column may contain.
+ * @return int value giving the maximum size of a field
+ * @throws SQLException should never occur.
+ */
+ public int getMaxFieldSize() throws SQLException {
+ return maxFieldSize;
+ }
+
+ /**
+ * Retrives the maximum number of rows that a ResultSet object may contain.
+ * If the limit is exceeded the excess rows are dropped.
+ * @return Max limit on rows on ResultSet.
+ * @throws SQLException should never iccure.
+ */
+ public int getMaxRows() throws SQLException {
+ return maxRows;
+ }
+
+ /**
+ * Moves to this Statement object's next result, returns true if
+ * it is a ResultSet object, and implicitly closes any current
+ * ResultSet object(s) obtained with the method #getResultSet.
+ * @return true if the next result is a ResultSet object;
+ * false if it is an update count or there are no more results
+ * @throws SQLException if there is an error in database.
+ */
+ public boolean getMoreResults() throws SQLException {
+ //Check to see the statement is closed and throw an exception
+ checkStatement();
+
+ // close any current ResultSet
+ if ( resultSet != null ) {
+ resultSet.close();
+ resultSet = null;
+ }
+ // set the existing update count to -1
+ // indicating that there are no more results
+ this.updateCounts = null;
+ return false;
+ }
+
+ /**
+ * Moves to this Statement object's next result, deals with any current
+ * ResultSet object(s) according to the instructions specified by the
+ * given flag, and returns true if the next result is a ResultSet object.
+ * @param current flag that gives instruction on what should happen
+ * to current ResultSet objects obtained using the method getResultSet(
+ * CLOSE_CURRENT_RESULT, KEEP_CURRENT_RESULT, or CLOSE_ALL_RESULTS).
+ * @return true if the next result is a ResultSet object; false if it
+ * is an update count or there are no more results
+ * @throws SQLException if there is an error in database.
+ */
+ public boolean getMoreResults(int current) throws SQLException {
+ checkStatement();
+
+ /*if (current == CLOSE_ALL_RESULTS || current == CLOSE_CURRENT_RESULT) {
+ // since MetaMatrix only supports one ResultSet per statement,
+ // these two cases are handled the same way.
+ if (resultSet != null) {
+ resultSet.close();
+ }
+ } else if (current == KEEP_CURRENT_RESULT) {
+ // do nothing
+ }
+
+ rowsAffected = -1;
+ */
+ return false;
+ }
+
+
+ /**
+ * Return the number of seconds the driver will wait for a statement object
+ * to execute
+ * @return int value giving the query timeout in seconds
+ * @throws SQLException should never occur
+ */
+ public int getQueryTimeout() throws SQLException {
+ //Check to see the statement is closed and throw an exception
+ checkStatement();
+ return (int)this.queryTimeoutMS/1000;
+ }
+
+ /**
+ * Returns a ResultSet object that was produced by a call to the method execute.
+ * We currently do not support execute method which could return multiple result
+ * sets.
+ * @return ResultSet object giving the next available ResultSet
+ * @throws SQLException should never occur
+ */
+ public ResultSetImpl getResultSet() throws SQLException {
+ //Check to see the statement is closed and throw an exception
+ checkStatement();
+ if (!hasResultSet()) {
+ return null;
+ }
+ return resultSet;
+ }
+
+ /**
+ * Retrieves the concurrency mode for the ResultSet objects generated from
+ * queries that this Statement object executes. All ResultSets are currently
+ * read only.
+ * @return intvalue giving the ResultSet concurrency
+ * @throws SQLException should never occur
+ */
+ public int getResultSetConcurrency() throws SQLException {
+ return this.resultSetConcurrency;
+ }
+
+ /**
+ * Retrieves the type of the ResultSet objects generated from queries that this
+ * statement executes.
+ * @return int value indicating the type of the ResultSet
+ * @throws SQLException should never occur
+ */
+ public int getResultSetType() {
+ return this.resultSetType;
+ }
+
+ /**
+ * This method returns the number of rows affected by a statement modifying a table.
+ * @return Number of rows affected.
+ * @throws SQLException should never occur
+ */
+ public int getUpdateCount() throws SQLException {
+ checkStatement();
+ if (this.updateCounts == null) {
+ return -1;
+ }
+ return this.updateCounts[0];
+ }
+
+ protected void accumulateWarnings(List<Exception> serverWarnings) {
+ if (serverWarnings == null || serverWarnings.isEmpty()) {
+ return;
+ }
+ if (this.serverWarnings == null) {
+ this.serverWarnings = new ArrayList<Exception>();
+ }
+ this.serverWarnings.addAll(serverWarnings);
+ }
+
+ /**
+ * This method returns warnings returned by server.
+ * @return null value as there are no warnings
+ * @throws SQLException should never occur
+ */
+ public SQLWarning getWarnings() throws SQLException {
+ //Check to see the statement is closed and throw an exception
+ checkStatement();
+
+ if (serverWarnings != null && serverWarnings.size() != 0) {
+ return WarningUtil.convertWarnings(serverWarnings);
+ }
+ return null;
+ }
+
+ /**
+ * This method enbles/disables escape processing. When escape processing is
+ * enabled the driver will scan any escape syntax and do escape substitution
+ * before sending the escaped sql statement to the server
+ * @param enable boolean value indicating if the escape processing should be turned on
+ * @throws SQLException should never occur
+ */
+ public void setEscapeProcessing(boolean enable) throws SQLException {
+ //Check to see the statement is closed and throw an exception
+ checkStatement();
+ // do nothing, escape processing is always enabled.
+ }
+
+ public void setFetchDirection(int direction) throws SQLException {
+ checkStatement();
+ }
+
+ public void setFetchSize(int rows) throws SQLException {
+ //Check to see the statement is closed and throw an exception
+ checkStatement();
+ if ( rows < 0 ) {
+ String msg = JDBCPlugin.Util.getString("MMStatement.Invalid_fetch_size"); //$NON-NLS-1$
+ throw new TeiidSQLException(msg);
+ }
+ // sets the fetch size on this statement
+ if (rows == 0) {
+ this.fetchSize = BaseDataSource.DEFAULT_FETCH_SIZE;
+ } else {
+ this.fetchSize = rows;
+ }
+ }
+
+ /**
+ * Sets the limit on the maximum number of rows in a ResultSet object. This
+ * method is currently implemented to throw an exception as it is not possible
+ * to limit the number of rows.
+ * @param maxRows int value indicating maximum rows that can be returned in a ResultSet
+ */
+ public void setMaxRows(int maxRows) throws SQLException {
+ //Check to see the statement is closed and throw an exception
+ checkStatement();
+ this.maxRows = maxRows;
+ }
+
+ /**
+ * This sets to seconds the time limit for the number of seconds for a driver
+ * to wait for a statement object to be executed.
+ * @param seconds Maximum number of seconds for a statement object to execute.
+ * throws SQLException, should never occur
+ */
+ public void setQueryTimeout(int seconds) throws SQLException {
+ //Check to see the statement is closed and throw an exception
+ checkStatement();
+ if (seconds >= 0) {
+ queryTimeoutMS = seconds*1000;
+ }
+ else {
+ throw new TeiidSQLException(JDBCPlugin.Util.getString("MMStatement.Bad_timeout_value")); //$NON-NLS-1$
+ }
+ }
+
+ void setQueryTimeoutMS(int queryTimeoutMS) {
+ this.queryTimeoutMS = queryTimeoutMS;
+ }
+
+ /**
+ * Helper method for copy the connection properties to request message.
+ * @param res Request message that these properties to be copied to.
+ * @throws TeiidSQLException
+ */
+ protected void copyPropertiesToRequest(RequestMessage res) throws TeiidSQLException {
+ // Get partial mode
+ String partial = getExecutionProperty(ExecutionProperties.PROP_PARTIAL_RESULTS_MODE);
+ res.setPartialResults(Boolean.valueOf(partial).booleanValue());
+
+ // Get xml validation mode
+ String validate = getExecutionProperty(ExecutionProperties.PROP_XML_VALIDATION);
+ if(validate == null) {
+ res.setValidationMode(false);
+ } else {
+ res.setValidationMode(Boolean.valueOf(validate).booleanValue());
+ }
+
+ // Get xml format mode
+ String format = getExecutionProperty(ExecutionProperties.PROP_XML_FORMAT);
+ res.setXMLFormat(format);
+
+ // Get transaction auto-wrap mode
+ String txnAutoWrapMode = getExecutionProperty(ExecutionProperties.PROP_TXN_AUTO_WRAP);
+ try {
+ res.setTxnAutoWrapMode(txnAutoWrapMode);
+ } catch (TeiidProcessingException e) {
+ throw TeiidSQLException.create(e);
+ }
+
+ // Get result set cache mode
+ String rsCache = getExecutionProperty(ExecutionProperties.RESULT_SET_CACHE_MODE);
+ res.setUseResultSetCache(Boolean.valueOf(rsCache).booleanValue());
+
+ res.setAnsiQuotedIdentifiers(Boolean.valueOf(
+ getExecutionProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS))
+ .booleanValue());
+ String showPlan = getExecutionProperty(ExecutionProperties.SQL_OPTION_SHOWPLAN);
+ if (showPlan != null) {
+ try {
+ res.setShowPlan(ShowPlan.valueOf(showPlan.toUpperCase()));
+ } catch (IllegalArgumentException e) {
+
+ }
+ }
+ String noExec = getExecutionProperty(ExecutionProperties.NOEXEC);
+ if (noExec != null) {
+ res.setNoExec(noExec.equalsIgnoreCase("ON")); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Ends the command and sets the status to TIMED_OUT.
+ */
+ protected void timeoutOccurred() {
+ if (this.commandStatus != State.RUNNING) {
+ return;
+ }
+ logger.warning(JDBCPlugin.Util.getString("MMStatement.Timeout_ocurred_in_Statement.")); //$NON-NLS-1$
+ try {
+ cancel();
+ commandStatus = State.TIMED_OUT;
+ queryTimeoutMS = NO_TIMEOUT;
+ currentRequestID = -1;
+ if (this.resultSet != null) {
+ this.resultSet.close();
+ }
+ } catch (SQLException se) {
+ logger.log(Level.SEVERE, JDBCPlugin.Util.getString("MMStatement.Error_timing_out."), se); //$NON-NLS-1$
+ }
+ }
+
+ protected void cancelRequest() throws SQLException {
+ checkStatement();
+
+ try {
+ this.getDQP().cancelRequest(currentRequestID);
+ } catch (TeiidProcessingException e) {
+ throw TeiidSQLException.create(e);
+ } catch (TeiidComponentException e) {
+ throw TeiidSQLException.create(e);
+ }
+ }
+
+ /**
+ * Set the per-statement security payload. This optional payload will
+ * accompany each request to the data source(s) so that the connector
+ * will have access to it.
+ * <br>Once the payload is set, it will be used for each statment
+ * execution until it is set to <code>null</code>, a new payload is set on
+ * the statement or the statement is closed.</br>
+ *
+ * <p>To remove an existing payload from a statement, call this method
+ * with a <code>null</code> argument.</p>
+ * @param payload The payload that is to accompany requests executed
+ * from this statement.
+ * @since 4.2
+ */
+ public void setPayload(Serializable payload) {
+ this.payload = payload;
+ }
+
+ public void setExecutionProperty(String name, String value) {
+ this.execProps.setProperty(name, value);
+ }
+
+ public String getExecutionProperty(String name) {
+ return this.execProps.getProperty(name);
+ }
+
+ long getCurrentRequestID() {
+ return this.currentRequestID;
+ }
+
+ /**
+ * Get Query plan description.
+ * If the Statement has a resultSet, we get the plan description from the result set
+ * If that plan description is null, though, we return the very first plan description
+ * that was created from the resultsMessage in the method: setAnalysisInfo.
+ * The plan description from the result set can be null if the resultsMsg stored in the
+ * result set hasn't been created when getPlanDescription is called.
+ * @return Query plan description, if it exists, otherwise null
+ */
+ public PlanNode getPlanDescription() {
+ if(this.resultSet != null) {
+ return this.resultSet.getUpdatedPlanDescription();
+ }
+ if(currentPlanDescription != null) {
+ return this.currentPlanDescription;
+ }
+ return null;
+ }
+
+ /**
+ * Get query planner debug log.
+ * @return Query planner debug log, or null if it doesn't exist
+ */
+ public String getDebugLog() {
+ return this.debugLog;
+ }
+
+ /**
+ * Get annotations
+ * @return Query planner annotations - Collection of Annotation
+ */
+ public Collection<Annotation> getAnnotations() {
+ return this.annotations;
+ }
+
+ public String getRequestIdentifier() {
+ if(this.currentRequestID >= 0) {
+ return Long.toString(this.currentRequestID);
+ }
+ return null;
+ }
+
+ /**
+ * Check is the statement is closed. Used primarily by the unit tests.
+ * @return true if the statement is closed; false otherwise.
+ */
+ public boolean isClosed() {
+ return this.isClosed;
+ }
+
+ protected void setAnalysisInfo(ResultsMessage resultsMsg) {
+ this.debugLog = resultsMsg.getDebugLog();
+ this.currentPlanDescription = resultsMsg.getPlanDescription();
+ this.annotations = resultsMsg.getAnnotations();
+ this.driverConnection.setDebugLog(debugLog);
+ this.driverConnection.setCurrentPlanDescription(currentPlanDescription);
+ this.driverConnection.setAnnotations(annotations);
+ }
+
+ Calendar getDefaultCalendar() {
+ if (defaultCalendar == null) {
+ defaultCalendar = Calendar.getInstance();
+ }
+ return defaultCalendar;
+ }
+
+ void setDefaultCalendar(Calendar cal) {
+ this.defaultCalendar = cal;
+ }
+
+ public boolean isPoolable() throws SQLException {
+ checkStatement();
+ return false;
+ }
+
+ public void setPoolable(boolean arg0) throws SQLException {
+ checkStatement();
+ }
+
+ public ConnectionImpl getConnection() throws SQLException {
+ return this.driverConnection;
+ }
+
+ public boolean execute(String sql, int autoGeneratedKeys)
+ throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public boolean execute(String sql, int[] columnIndexes) throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public boolean execute(String sql, String[] columnNames)
+ throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public int executeUpdate(String sql, int autoGeneratedKeys)
+ throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public int executeUpdate(String sql, int[] columnIndexes)
+ throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public int executeUpdate(String sql, String[] columnNames)
+ throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public ResultSet getGeneratedKeys() throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public int getResultSetHoldability() throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public void setCursorName(String name) throws SQLException {
+ throw SqlUtil.createFeatureNotSupportedException();
+ }
+
+ public void setMaxFieldSize(int max) throws SQLException {
+ checkStatement();
+ if ( max < 0 ) {
+ throw new TeiidSQLException(JDBCPlugin.Util.getString("MMStatement.Invalid_field_size", max)); //$NON-NLS-1$
+ }
+ this.maxFieldSize = max;
+ }
+
+ ResultSetImpl createResultSet(List records, String[] columnNames, String[] dataTypes) throws SQLException {
+ Map[] metadata = new Map[columnNames.length];
+ for (int i = 0; i < columnNames.length; i++) {
+ metadata[i] = getColumnMetadata(null, columnNames[i], dataTypes[i], ResultsMetadataConstants.NULL_TYPES.UNKNOWN, driverConnection);
+ }
+ return createResultSet(records, metadata);
+ }
+
+ ResultSetImpl createResultSet(List records, Map[] columnMetadata) throws SQLException {
+ ResultSetMetaData rsmd = new ResultSetMetaDataImpl(new MetadataProvider(columnMetadata));
+
+ return createResultSet(records, rsmd);
+ }
+
+ ResultSetImpl createResultSet(List records, ResultSetMetaData rsmd) throws SQLException {
+ rsmd.getScale(1); //force the load of the metadata
+ ResultsMessage resultsMsg = createDummyResultsMessage(null, null, records);
+ resultSet = new ResultSetImpl(resultsMsg, this, rsmd, 0);
+ resultSet.setMaxFieldSize(this.maxFieldSize);
+ return resultSet;
+ }
+
+ static ResultsMessage createDummyResultsMessage(String[] columnNames, String[] dataTypes, List records) {
+ ResultsMessage resultsMsg = new ResultsMessage();
+ resultsMsg.setColumnNames(columnNames);
+ resultsMsg.setDataTypes(dataTypes);
+ resultsMsg.setFirstRow(1);
+ resultsMsg.setLastRow(records.size());
+ resultsMsg.setFinalRow(records.size());
+ resultsMsg.setResults((List[])records.toArray(new List[records.size()]));
+ return resultsMsg;
+ }
+
+ static Map<Integer, Object> getColumnMetadata(String tableName, String columnName, String dataType, Integer nullable, ConnectionImpl driverConnection) throws SQLException {
+ return getColumnMetadata(tableName, columnName, dataType, nullable, ResultsMetadataConstants.SEARCH_TYPES.UNSEARCHABLE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, driverConnection);
+ }
+
+ static Map<Integer, Object> getColumnMetadata(String tableName, String columnName, String dataType, Integer nullable, Integer searchable, Boolean writable, Boolean signed, Boolean caseSensitive, ConnectionImpl driverConnection) throws SQLException {
+
+ // map that would contain metadata details
+ Map<Integer, Object> metadataMap = new HashMap<Integer, Object>();
+
+ /*******************************************************
+ HardCoding Column metadata details for the given column
+ ********************************************************/
+
+ metadataMap.put(ResultsMetadataConstants.VIRTUAL_DATABASE_NAME, driverConnection.getVDBName());
+ metadataMap.put(ResultsMetadataConstants.GROUP_NAME, tableName);
+ metadataMap.put(ResultsMetadataConstants.ELEMENT_NAME, columnName);
+ metadataMap.put(ResultsMetadataConstants.DATA_TYPE, dataType);
+ metadataMap.put(ResultsMetadataConstants.PRECISION, ResultsMetadataDefaults.getDefaultPrecision(dataType));
+ metadataMap.put(ResultsMetadataConstants.RADIX, new Integer(10));
+ metadataMap.put(ResultsMetadataConstants.SCALE, new Integer(0));
+ metadataMap.put(ResultsMetadataConstants.AUTO_INCREMENTING, Boolean.FALSE);
+ metadataMap.put(ResultsMetadataConstants.CASE_SENSITIVE, caseSensitive);
+ metadataMap.put(ResultsMetadataConstants.NULLABLE, nullable);
+ metadataMap.put(ResultsMetadataConstants.SEARCHABLE, searchable);
+ metadataMap.put(ResultsMetadataConstants.SIGNED, signed);
+ metadataMap.put(ResultsMetadataConstants.WRITABLE, writable);
+ metadataMap.put(ResultsMetadataConstants.CURRENCY, Boolean.FALSE);
+ metadataMap.put(ResultsMetadataConstants.DISPLAY_SIZE, ResultsMetadataDefaults.getMaxDisplaySize(dataType));
+
+ return metadataMap;
+ }
+}
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/TeiidURL.java
===================================================================
--- trunk/client/src/main/java/org/teiid/net/TeiidURL.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/TeiidURL.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,332 +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.net;
-
-import java.net.MalformedURLException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.StringTokenizer;
-
-import org.teiid.core.util.StringUtil;
-import org.teiid.jdbc.JDBCPlugin;
-
-
-/**
- * Class defines the URL in the Teiid.
- *
- * @since 4.2
- */
-public class TeiidURL {
-
- public static interface JDBC {
- // constant indicating Virtual database name
- public static final String VDB_NAME = "VirtualDatabaseName"; //$NON-NLS-1$
- // constant indicating Virtual database version
- public static final String VDB_VERSION = "VirtualDatabaseVersion"; //$NON-NLS-1$
- // constant for vdb version part of serverURL
- public static final String VERSION = "version"; //$NON-NLS-1$
- }
-
- 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$
- /**
- * If true, will automatically select a new server instance after a communication exception.
- * @since 5.6
- */
- public static final String AUTO_FAILOVER = "autoFailover"; //$NON-NLS-1$
-
- /**
- * A plugable discovery strategy for the client. Defaults to using the AdminApi.
- */
- public static final String DISCOVERY_STRATEGY = "discoveryStategy"; //$NON-NLS-1$
-
- public static final String SERVER_URL = "serverURL"; //$NON-NLS-1$
- /**
- * Non-secure Protocol.
- */
- public static final String NON_SECURE_PROTOCOL = "mm"; //$NON-NLS-1$
- /**
- * Secure Protocol.
- */
- public static final String SECURE_PROTOCOL = "mms"; //$NON-NLS-1$
- // name of the application which is obtaining connection
- public static final String APP_NAME = "ApplicationName"; //$NON-NLS-1$
- // constant for username part of url
- public static final String USER_NAME = "user"; //$NON-NLS-1$
- // constant for password part of url
- public static final String PASSWORD = "password"; //$NON-NLS-1$
-
- public static final String ADMIN = "admin"; //$NON-NLS-1$
-
- public static final String PASSTHROUGH_AUTHENTICATION = "PassthroughAuthentication"; //$NON-NLS-1$
- }
-
- public static final String DOT_DELIMITER = "."; //$NON-NLS-1$
- public static final String DOUBLE_SLASH_DELIMITER = "//"; //$NON-NLS-1$
- public static final String COMMA_DELIMITER = ","; //$NON-NLS-1$
-
- public static final String COLON_DELIMITER = ":"; //$NON-NLS-1$
- public static final String BACKSLASH_DELIMITER = "\\"; //$NON-NLS-1$
- public static final String DEFAULT_PROTOCOL= TeiidURL.CONNECTION.NON_SECURE_PROTOCOL + "://"; //$NON-NLS-1$
- public static final String SECURE_PROTOCOL= TeiidURL.CONNECTION.SECURE_PROTOCOL + "://"; //$NON-NLS-1$
-
- public static final String INVALID_FORMAT_SERVER = JDBCPlugin.Util.getString("MMURL.INVALID_FORMAT"); //$NON-NLS-1$
- /*
- * appserver URL
- */
- private String appServerURL;
- /*
- * List of <code> HostData </code> in a cluster
- */
- private List<HostInfo> hosts = new ArrayList<HostInfo>();
-
- private boolean usingSSL = false;
-
- /**
- * Create an MMURL from the server URL. For use by the server-side.
- * @param serverURL Expected format: mm[s]://server1:port1[,server2:port2]
- * @throws MalformedURLException
- * @since 4.2
- */
- public TeiidURL(String serverURL) throws MalformedURLException {
- if (serverURL == null) {
- throw new MalformedURLException(INVALID_FORMAT_SERVER);
- }
- if (StringUtil.startsWithIgnoreCase(serverURL, SECURE_PROTOCOL)) {
- usingSSL = true;
- } else if (!StringUtil.startsWithIgnoreCase(serverURL, DEFAULT_PROTOCOL)) {
- throw new MalformedURLException(INVALID_FORMAT_SERVER);
- }
-
- appServerURL = serverURL;
- parseServerURL(serverURL.substring(usingSSL?SECURE_PROTOCOL.length():DEFAULT_PROTOCOL.length()), INVALID_FORMAT_SERVER);
- }
-
- public TeiidURL(String host, int port, boolean secure) {
- usingSSL = secure;
- if(host.startsWith("[")) { //$NON-NLS-1$
- host = host.substring(1, host.indexOf(']'));
- }
- hosts.add(new HostInfo(host, port));
- }
-
- /**
- * Validates that a server URL is in the correct format.
- * @param serverURL Expected format: mm[s]://server1:port1[,server2:port2]
- * @since 4.2
- */
- public static boolean isValidServerURL(String serverURL) {
- boolean valid = true;
- try {
- new TeiidURL(serverURL);
- } catch (Exception e) {
- valid = false;
- }
-
- return valid;
- }
-
- public List<HostInfo> getHostInfo() {
- return hosts;
- }
-
- /**
- * Get a list of hosts
- *
- * @return string of host separated by commas
- * @since 4.2
- */
- public String getHosts() {
- StringBuffer hostList = new StringBuffer(""); //$NON-NLS-1$
- if( hosts != null) {
- Iterator<HostInfo> iterator = hosts.iterator();
- while (iterator.hasNext()) {
- HostInfo element = iterator.next();
- hostList.append(element.getHostName());
- if( iterator.hasNext()) {
- hostList.append(COMMA_DELIMITER);
- }
- }
- }
- return hostList.toString();
- }
-
- /**
- * Get a list of ports
- *
- * @return string of ports seperated by commas
- * @since 4.2
- */
- public String getPorts() {
- StringBuffer portList = new StringBuffer(""); //$NON-NLS-1$
- if( hosts != null) {
- Iterator<HostInfo> iterator = hosts.iterator();
- while (iterator.hasNext()) {
- HostInfo element = iterator.next();
- portList.append(element.getPortNumber());
- if( iterator.hasNext()) {
- portList.append(COMMA_DELIMITER);
- }
- }
- }
- return portList.toString();
- }
-
- /**
- * @param url
- * @throws MalformedURLException
- * @since 4.2
- */
- private void parseServerURL(String serverURL, String exceptionMessage) throws MalformedURLException {
- StringTokenizer st = new StringTokenizer(serverURL, COMMA_DELIMITER);
- if (!st.hasMoreTokens()) {
- throw new MalformedURLException(exceptionMessage);
- }
- while (st.hasMoreTokens()) {
- String nextToken = st.nextToken();
- nextToken = nextToken.trim();
- String host = ""; //$NON-NLS-1$
- String port = ""; //$NON-NLS-1$
- if (nextToken.startsWith("[")) { //$NON-NLS-1$
- int hostEnd = nextToken.indexOf("]:"); //$NON-NLS-1$
- if (hostEnd == -1) {
- throw new MalformedURLException(JDBCPlugin.Util.getString("TeiidURL.invalid_ipv6_hostport", nextToken, exceptionMessage)); //$NON-NLS-1$
- }
- host = nextToken.substring(1, hostEnd);
- port = nextToken.substring(hostEnd+2);
- }
- else {
- int hostEnd = nextToken.indexOf(":"); //$NON-NLS-1$
- if (hostEnd == -1) {
- throw new MalformedURLException(JDBCPlugin.Util.getString("TeiidURL.invalid_hostport", nextToken, exceptionMessage)); //$NON-NLS-1$
- }
- host = nextToken.substring(0, hostEnd);
- port = nextToken.substring(hostEnd+1);
- }
- host = host.trim();
- port = port.trim();
- if (host.equals("") || port.equals("")) { //$NON-NLS-1$ //$NON-NLS-2$
- throw new MalformedURLException(JDBCPlugin.Util.getString("TeiidURL.invalid_hostport", nextToken, exceptionMessage)); //$NON-NLS-1$
- }
- int portNumber = validatePort(port);
- HostInfo hostInfo = new HostInfo(host, portNumber);
- hosts.add(hostInfo);
- }
- }
-
- public static int validatePort(String port) throws MalformedURLException {
- int portNumber;
- try {
- portNumber = Integer.parseInt(port);
- } catch (NumberFormatException nfe) {
- throw new MalformedURLException(JDBCPlugin.Util.getString("TeiidURL.non_numeric_port", port)); //$NON-NLS-1$
- }
- String msg = validatePort(portNumber);
- if (msg != null) {
- throw new MalformedURLException(msg);
- }
- return portNumber;
- }
-
- public static String validatePort(int portNumber) {
- if (portNumber < 0 || portNumber > 0xFFFF) {
- return JDBCPlugin.Util.getString("TeiidURL.port_out_of_range", portNumber); //$NON-NLS-1$
- }
- return null;
- }
-
- /**
- * Get the Application Server URL
- *
- * @return String for connection to the Server
- * @since 4.2
- */
- public String getAppServerURL() {
- if (appServerURL == null) {
- StringBuffer sb = new StringBuffer();
- if (usingSSL) {
- sb.append(SECURE_PROTOCOL);
- } else {
- sb.append(DEFAULT_PROTOCOL);
- }
- Iterator<HostInfo> iter = hosts.iterator();
- while (iter.hasNext()) {
- HostInfo host = iter.next();
-
- boolean ipv6HostName = host.getHostName().indexOf(':') != -1;
- if (ipv6HostName) {
- sb.append('[');
- }
- sb.append(host.getHostName());
- if (ipv6HostName) {
- sb.append(']');
- }
- sb.append(COLON_DELIMITER);
- sb.append(host.getPortNumber());
- if (iter.hasNext()) {
- sb.append(COMMA_DELIMITER);
- }
- }
- appServerURL = sb.toString();
- }
- return appServerURL;
- }
-
- /**
- * @see java.lang.Object#toString()
- * @since 4.2
- */
- public String toString() {
- return getAppServerURL();
- }
-
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- * @since 4.2
- */
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (!(obj instanceof TeiidURL)) {
- return false;
- }
- TeiidURL url = (TeiidURL)obj;
- return (appServerURL.equals(url.getAppServerURL()));
- }
-
- /**
- * @see java.lang.Object#hashCode()
- * @since 4.2
- */
- public int hashCode() {
- return appServerURL.hashCode();
- }
-
- public boolean isUsingSSL() {
- return usingSSL;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/TeiidURL.java (from rev 3218, trunk/client/src/main/java/org/teiid/net/TeiidURL.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/TeiidURL.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/TeiidURL.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,333 @@
+/*
+ * 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.net;
+
+import java.net.MalformedURLException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import org.teiid.core.util.StringUtil;
+import org.teiid.jdbc.JDBCPlugin;
+
+
+/**
+ * Class defines the URL in the Teiid.
+ *
+ * @since 4.2
+ */
+public class TeiidURL {
+
+ public static interface JDBC {
+ // constant indicating Virtual database name
+ public static final String VDB_NAME = "VirtualDatabaseName"; //$NON-NLS-1$
+ // constant indicating Virtual database version
+ public static final String VDB_VERSION = "VirtualDatabaseVersion"; //$NON-NLS-1$
+ // constant for vdb version part of serverURL
+ public static final String VERSION = "version"; //$NON-NLS-1$
+ }
+
+ 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
+ */
+ public static final String AUTO_FAILOVER = "autoFailover"; //$NON-NLS-1$
+
+ /**
+ * A plugable discovery strategy for the client. Defaults to using the AdminApi.
+ */
+ public static final String DISCOVERY_STRATEGY = "discoveryStategy"; //$NON-NLS-1$
+
+ public static final String SERVER_URL = "serverURL"; //$NON-NLS-1$
+ /**
+ * Non-secure Protocol.
+ */
+ public static final String NON_SECURE_PROTOCOL = "mm"; //$NON-NLS-1$
+ /**
+ * Secure Protocol.
+ */
+ public static final String SECURE_PROTOCOL = "mms"; //$NON-NLS-1$
+ // name of the application which is obtaining connection
+ public static final String APP_NAME = "ApplicationName"; //$NON-NLS-1$
+ // constant for username part of url
+ public static final String USER_NAME = "user"; //$NON-NLS-1$
+ // constant for password part of url
+ public static final String PASSWORD = "password"; //$NON-NLS-1$
+
+ public static final String ADMIN = "admin"; //$NON-NLS-1$
+
+ public static final String PASSTHROUGH_AUTHENTICATION = "PassthroughAuthentication"; //$NON-NLS-1$
+ }
+
+ public static final String DOT_DELIMITER = "."; //$NON-NLS-1$
+ public static final String DOUBLE_SLASH_DELIMITER = "//"; //$NON-NLS-1$
+ public static final String COMMA_DELIMITER = ","; //$NON-NLS-1$
+
+ public static final String COLON_DELIMITER = ":"; //$NON-NLS-1$
+ public static final String BACKSLASH_DELIMITER = "\\"; //$NON-NLS-1$
+ public static final String DEFAULT_PROTOCOL= TeiidURL.CONNECTION.NON_SECURE_PROTOCOL + "://"; //$NON-NLS-1$
+ public static final String SECURE_PROTOCOL= TeiidURL.CONNECTION.SECURE_PROTOCOL + "://"; //$NON-NLS-1$
+
+ public static final String INVALID_FORMAT_SERVER = JDBCPlugin.Util.getString("MMURL.INVALID_FORMAT"); //$NON-NLS-1$
+ /*
+ * appserver URL
+ */
+ private String appServerURL;
+ /*
+ * List of <code> HostData </code> in a cluster
+ */
+ private List<HostInfo> hosts = new ArrayList<HostInfo>();
+
+ private boolean usingSSL = false;
+
+ /**
+ * Create an MMURL from the server URL. For use by the server-side.
+ * @param serverURL Expected format: mm[s]://server1:port1[,server2:port2]
+ * @throws MalformedURLException
+ * @since 4.2
+ */
+ public TeiidURL(String serverURL) throws MalformedURLException {
+ if (serverURL == null) {
+ throw new MalformedURLException(INVALID_FORMAT_SERVER);
+ }
+ if (StringUtil.startsWithIgnoreCase(serverURL, SECURE_PROTOCOL)) {
+ usingSSL = true;
+ } else if (!StringUtil.startsWithIgnoreCase(serverURL, DEFAULT_PROTOCOL)) {
+ throw new MalformedURLException(INVALID_FORMAT_SERVER);
+ }
+
+ appServerURL = serverURL;
+ parseServerURL(serverURL.substring(usingSSL?SECURE_PROTOCOL.length():DEFAULT_PROTOCOL.length()), INVALID_FORMAT_SERVER);
+ }
+
+ public TeiidURL(String host, int port, boolean secure) {
+ usingSSL = secure;
+ if(host.startsWith("[")) { //$NON-NLS-1$
+ host = host.substring(1, host.indexOf(']'));
+ }
+ hosts.add(new HostInfo(host, port));
+ }
+
+ /**
+ * Validates that a server URL is in the correct format.
+ * @param serverURL Expected format: mm[s]://server1:port1[,server2:port2]
+ * @since 4.2
+ */
+ public static boolean isValidServerURL(String serverURL) {
+ boolean valid = true;
+ try {
+ new TeiidURL(serverURL);
+ } catch (Exception e) {
+ valid = false;
+ }
+
+ return valid;
+ }
+
+ public List<HostInfo> getHostInfo() {
+ return hosts;
+ }
+
+ /**
+ * Get a list of hosts
+ *
+ * @return string of host separated by commas
+ * @since 4.2
+ */
+ public String getHosts() {
+ StringBuffer hostList = new StringBuffer(""); //$NON-NLS-1$
+ if( hosts != null) {
+ Iterator<HostInfo> iterator = hosts.iterator();
+ while (iterator.hasNext()) {
+ HostInfo element = iterator.next();
+ hostList.append(element.getHostName());
+ if( iterator.hasNext()) {
+ hostList.append(COMMA_DELIMITER);
+ }
+ }
+ }
+ return hostList.toString();
+ }
+
+ /**
+ * Get a list of ports
+ *
+ * @return string of ports seperated by commas
+ * @since 4.2
+ */
+ public String getPorts() {
+ StringBuffer portList = new StringBuffer(""); //$NON-NLS-1$
+ if( hosts != null) {
+ Iterator<HostInfo> iterator = hosts.iterator();
+ while (iterator.hasNext()) {
+ HostInfo element = iterator.next();
+ portList.append(element.getPortNumber());
+ if( iterator.hasNext()) {
+ portList.append(COMMA_DELIMITER);
+ }
+ }
+ }
+ return portList.toString();
+ }
+
+ /**
+ * @param url
+ * @throws MalformedURLException
+ * @since 4.2
+ */
+ private void parseServerURL(String serverURL, String exceptionMessage) throws MalformedURLException {
+ StringTokenizer st = new StringTokenizer(serverURL, COMMA_DELIMITER);
+ if (!st.hasMoreTokens()) {
+ throw new MalformedURLException(exceptionMessage);
+ }
+ while (st.hasMoreTokens()) {
+ String nextToken = st.nextToken();
+ nextToken = nextToken.trim();
+ String host = ""; //$NON-NLS-1$
+ String port = ""; //$NON-NLS-1$
+ if (nextToken.startsWith("[")) { //$NON-NLS-1$
+ int hostEnd = nextToken.indexOf("]:"); //$NON-NLS-1$
+ if (hostEnd == -1) {
+ throw new MalformedURLException(JDBCPlugin.Util.getString("TeiidURL.invalid_ipv6_hostport", nextToken, exceptionMessage)); //$NON-NLS-1$
+ }
+ host = nextToken.substring(1, hostEnd);
+ port = nextToken.substring(hostEnd+2);
+ }
+ else {
+ int hostEnd = nextToken.indexOf(":"); //$NON-NLS-1$
+ if (hostEnd == -1) {
+ throw new MalformedURLException(JDBCPlugin.Util.getString("TeiidURL.invalid_hostport", nextToken, exceptionMessage)); //$NON-NLS-1$
+ }
+ host = nextToken.substring(0, hostEnd);
+ port = nextToken.substring(hostEnd+1);
+ }
+ host = host.trim();
+ port = port.trim();
+ if (host.equals("") || port.equals("")) { //$NON-NLS-1$ //$NON-NLS-2$
+ throw new MalformedURLException(JDBCPlugin.Util.getString("TeiidURL.invalid_hostport", nextToken, exceptionMessage)); //$NON-NLS-1$
+ }
+ int portNumber = validatePort(port);
+ HostInfo hostInfo = new HostInfo(host, portNumber);
+ hosts.add(hostInfo);
+ }
+ }
+
+ public static int validatePort(String port) throws MalformedURLException {
+ int portNumber;
+ try {
+ portNumber = Integer.parseInt(port);
+ } catch (NumberFormatException nfe) {
+ throw new MalformedURLException(JDBCPlugin.Util.getString("TeiidURL.non_numeric_port", port)); //$NON-NLS-1$
+ }
+ String msg = validatePort(portNumber);
+ if (msg != null) {
+ throw new MalformedURLException(msg);
+ }
+ return portNumber;
+ }
+
+ public static String validatePort(int portNumber) {
+ if (portNumber < 0 || portNumber > 0xFFFF) {
+ return JDBCPlugin.Util.getString("TeiidURL.port_out_of_range", portNumber); //$NON-NLS-1$
+ }
+ return null;
+ }
+
+ /**
+ * Get the Application Server URL
+ *
+ * @return String for connection to the Server
+ * @since 4.2
+ */
+ public String getAppServerURL() {
+ if (appServerURL == null) {
+ StringBuffer sb = new StringBuffer();
+ if (usingSSL) {
+ sb.append(SECURE_PROTOCOL);
+ } else {
+ sb.append(DEFAULT_PROTOCOL);
+ }
+ Iterator<HostInfo> iter = hosts.iterator();
+ while (iter.hasNext()) {
+ HostInfo host = iter.next();
+
+ boolean ipv6HostName = host.getHostName().indexOf(':') != -1;
+ if (ipv6HostName) {
+ sb.append('[');
+ }
+ sb.append(host.getHostName());
+ if (ipv6HostName) {
+ sb.append(']');
+ }
+ sb.append(COLON_DELIMITER);
+ sb.append(host.getPortNumber());
+ if (iter.hasNext()) {
+ sb.append(COMMA_DELIMITER);
+ }
+ }
+ appServerURL = sb.toString();
+ }
+ return appServerURL;
+ }
+
+ /**
+ * @see java.lang.Object#toString()
+ * @since 4.2
+ */
+ public String toString() {
+ return getAppServerURL();
+ }
+
+ /**
+ * @see java.lang.Object#equals(java.lang.Object)
+ * @since 4.2
+ */
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (!(obj instanceof TeiidURL)) {
+ return false;
+ }
+ TeiidURL url = (TeiidURL)obj;
+ return (appServerURL.equals(url.getAppServerURL()));
+ }
+
+ /**
+ * @see java.lang.Object#hashCode()
+ * @since 4.2
+ */
+ public int hashCode() {
+ return appServerURL.hashCode();
+ }
+
+ public boolean isUsingSSL() {
+ return usingSSL;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java
===================================================================
--- trunk/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,372 +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.net.socket;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.net.InetAddress;
-import java.net.MalformedURLException;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.teiid.client.security.ILogon;
-import org.teiid.client.security.InvalidSessionException;
-import org.teiid.client.security.SessionToken;
-import org.teiid.core.TeiidException;
-import org.teiid.core.util.PropertiesUtils;
-import org.teiid.core.util.ReflectionHelper;
-import org.teiid.net.CommunicationException;
-import org.teiid.net.ConnectionException;
-import org.teiid.net.HostInfo;
-import org.teiid.net.ServerConnection;
-import org.teiid.net.ServerConnectionFactory;
-import org.teiid.net.TeiidURL;
-
-
-/**
- * Responsible for creating socket based connections
- *
- * The comm approach is object based and layered. Connections manage failover and identity.
- * ServerInstances represent the service layer to a particular cluster member. ObjectChannels
- * abstract the underlying IO.
- *
- */
-public class SocketServerConnectionFactory implements ServerConnectionFactory, SocketServerInstanceFactory {
-
- private static final String URL = "URL"; //$NON-NLS-1$
-
- private static SocketServerConnectionFactory INSTANCE;
- private static Logger log = Logger.getLogger("org.teiid.client.sockets"); //$NON-NLS-1$
-
- private final class ShutdownHandler implements InvocationHandler {
- private final CachedInstance key;
-
- private ShutdownHandler(CachedInstance key) {
- this.key = key;
- }
-
- @Override
- public Object invoke(Object arg0, Method arg1, Object[] arg2)
- throws Throwable {
- if (arg1.getName().equals("shutdown")) { //$NON-NLS-1$
- CachedInstance purge = null;
- if (!key.actual.isOpen()) {
- return null; //nothing to do
- }
- synchronized (instancePool) {
- instancePool.put(key, key);
- if (instancePool.size() > maxCachedInstances) {
- Iterator<CachedInstance> iter = instancePool.keySet().iterator();
- purge = iter.next();
- iter.remove();
- }
- }
- if (purge != null) {
- purge.actual.shutdown();
- }
- return null;
- }
- try {
- return arg1.invoke(key.actual, arg2);
- } catch (InvocationTargetException e) {
- throw e.getTargetException();
- }
- }
- }
-
- private static class CachedInstance {
- HostInfo info;
- Integer instance;
- SocketServerInstance actual;
- SocketServerInstance proxy;
-
- public CachedInstance(HostInfo info) {
- this.info = info;
- }
-
- @Override
- public int hashCode() {
- return info.hashCode();
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof CachedInstance)) {
- return false;
- }
- CachedInstance other = (CachedInstance) obj;
- if (!info.equals(other.info)) {
- return false;
- }
- if (instance == null || other.instance == null) {
- return true;
- }
- return instance.equals(other.instance);
- }
- }
-
- private ObjectChannelFactory channelFactory;
- private Timer pingTimer;
-
- private HashMap<HostInfo, Set<SessionToken>> sessions = new HashMap<HostInfo, Set<SessionToken>>();
-
- //instance pooling
- private AtomicInteger instanceCount = new AtomicInteger();
- private Map<CachedInstance, CachedInstance> instancePool = new LinkedHashMap<CachedInstance, CachedInstance>();
-
- //config properties
- private long synchronousTtl = 120000l;
- private int maxCachedInstances=16;
-
- public static synchronized SocketServerConnectionFactory getInstance() {
- if (INSTANCE == null) {
- INSTANCE = new SocketServerConnectionFactory();
- Properties props = System.getProperties();
- InputStream is = SocketServerConnectionFactory.class.getResourceAsStream("/teiid-client-settings.properties"); //$NON-NLS-1$
- if (is != null) {
- props = new Properties(props);
- try {
- props.load(is);
- } catch (IOException e) {
-
- } finally {
- try {
- is.close();
- } catch (IOException e) {
- }
- }
- }
- INSTANCE.initialize(props);
- }
- return INSTANCE;
- }
-
- public SocketServerConnectionFactory() {
-
- }
-
- public void initialize(Properties info) {
- PropertiesUtils.setBeanProperties(this, info, "org.teiid.sockets"); //$NON-NLS-1$
- this.pingTimer = new Timer("SocketPing", true); //$NON-NLS-1$
- this.pingTimer.schedule(new TimerTask() {
-
- @Override
- public void run() {
- Set<Map.Entry<HostInfo, Set<SessionToken>>> sessionEntries = null;
- synchronized (sessions) {
- sessionEntries = new HashSet<Map.Entry<HostInfo, Set<SessionToken>>>(sessions.entrySet());
- }
- for (Map.Entry<HostInfo, Set<SessionToken>> entry : sessionEntries) {
- SocketServerInstance instance = null;
- HashSet<SessionToken> entries = null;
- synchronized (sessions) {
- entries = new HashSet<SessionToken>(entry.getValue());
- }
- try {
- instance = getServerInstance(entry.getKey());
- ILogon logon = instance.getService(ILogon.class);
- if ("7.1.1".compareTo(instance.getServerVersion()) > 0) { //$NON-NLS-1$
- for (SessionToken session : entries) {
- try {
- logon.assertIdentity(session);
- logon.ping();
- log.log(Level.FINER, "issueing ping for session:", session); //$NON-NLS-1$
- } catch (InvalidSessionException e) {
- }
- }
- } else {
- ArrayList<String> sessionStrings = new ArrayList<String>(entry.getValue().size());
- for (SessionToken session : entries) {
- sessionStrings.add(session.getSessionID());
- }
- logon.ping(sessionStrings);
- log.log(Level.FINER, "issueing ping for sessions:", sessionStrings); //$NON-NLS-1$
- }
- } catch (Exception e) {
- log.log(Level.WARNING, "Error performing keep-alive ping", e); //$NON-NLS-1$
- } finally {
- if (instance != null) {
- instance.shutdown();
- }
- }
- }
- }
- }, ServerConnection.PING_INTERVAL, ServerConnection.PING_INTERVAL);
- this.channelFactory = new OioOjbectChannelFactory(info);
- }
-
- @Override
- public SocketServerInstance getServerInstance(HostInfo info) throws CommunicationException, IOException {
- CachedInstance key = null;
- boolean useCache = this.maxCachedInstances > 0;
- if (useCache) {
- CachedInstance instance = null;
- key = new CachedInstance(info);
- synchronized (instancePool) {
- instance = instancePool.remove(key);
- }
- if (instance != null) {
- ILogon logon = instance.actual.getService(ILogon.class);
- boolean valid = false;
- try {
- Future<?> success = logon.ping();
- success.get(this.channelFactory.getSoTimeout(), TimeUnit.MILLISECONDS);
- valid = true;
- } catch (Exception e) {
- log.log(Level.FINE, "Error performing ping, will select another instance", e); //$NON-NLS-1$
- }
- if (valid) {
- return instance.proxy;
- }
- instance.actual.shutdown();
- //technically we only want to remove instances with the same inetaddress
- while (true) {
- CachedInstance invalid = null;
- synchronized (instancePool) {
- invalid = instancePool.remove(key);
- }
- if (invalid == null) {
- break;
- }
- invalid.actual.shutdown();
- }
- }
- }
- SocketServerInstanceImpl ssii = new SocketServerInstanceImpl(info, getSynchronousTtl());
- ssii.connect(this.channelFactory);
- if (useCache) {
- key.actual = ssii;
- key.instance = instanceCount.getAndIncrement();
- //create a proxied socketserverinstance that will pool itself on shutdown
- key.proxy = (SocketServerInstance)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {SocketServerInstance.class}, new ShutdownHandler(key));
- return key.proxy;
- }
- return ssii;
- }
-
- /**
- * @param connectionProperties will be updated with additional information before logon
- */
- public SocketServerConnection getConnection(Properties connectionProperties) throws CommunicationException, ConnectionException {
-
- updateConnectionProperties(connectionProperties);
-
- TeiidURL url;
- try {
- url = new TeiidURL(connectionProperties.getProperty(TeiidURL.CONNECTION.SERVER_URL));
- } catch (MalformedURLException e1) {
- throw new ConnectionException(e1);
- }
-
- String discoveryStrategyName = connectionProperties.getProperty(TeiidURL.CONNECTION.DISCOVERY_STRATEGY, URL);
-
- ServerDiscovery discovery;
-
- if (URL.equalsIgnoreCase(discoveryStrategyName)) {
- discovery = new UrlServerDiscovery();
- } else {
- try {
- discovery = (ServerDiscovery)ReflectionHelper.create(discoveryStrategyName, null, this.getClass().getClassLoader());
- } catch (TeiidException e) {
- throw new ConnectionException(e);
- }
- }
-
- discovery.init(url, connectionProperties);
-
- return new SocketServerConnection(this, url.isUsingSSL(), discovery, connectionProperties);
- }
-
- static void updateConnectionProperties(Properties connectionProperties) {
- try {
- InetAddress addr = InetAddress.getLocalHost();
- connectionProperties.put(TeiidURL.CONNECTION.CLIENT_IP_ADDRESS, addr.getHostAddress());
- connectionProperties.put(TeiidURL.CONNECTION.CLIENT_HOSTNAME, addr.getCanonicalHostName());
- } catch (UnknownHostException err1) {
- connectionProperties.put(TeiidURL.CONNECTION.CLIENT_IP_ADDRESS, "UnknownClientAddress"); //$NON-NLS-1$
- }
- }
-
- public long getSynchronousTtl() {
- return synchronousTtl;
- }
-
- public void setSynchronousTtl(long synchronousTTL) {
- this.synchronousTtl = synchronousTTL;
- }
-
- public int getMaxCachedInstances() {
- return maxCachedInstances;
- }
-
- public void setMaxCachedInstances(int maxCachedInstances) {
- this.maxCachedInstances = maxCachedInstances;
- }
-
- @Override
- public void connected(SocketServerInstance instance, SessionToken session) {
- synchronized (sessions) {
- Set<SessionToken> instanceSessions = sessions.get(instance.getHostInfo());
- if (instanceSessions == null) {
- instanceSessions = new HashSet<SessionToken>();
- sessions.put(instance.getHostInfo(), instanceSessions);
- }
- instanceSessions.add(session);
- }
- }
-
- @Override
- public void disconnected(SocketServerInstance instance, SessionToken session) {
- synchronized (sessions) {
- Set<SessionToken> instanceSessions = sessions.get(instance.getHostInfo());
- if (instanceSessions != null) {
- instanceSessions.remove(session);
- if (instanceSessions.isEmpty()) {
- sessions.remove(instance.getHostInfo());
- }
- }
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java (from rev 3218, trunk/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,385 @@
+/*
+ * 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.net.socket;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+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;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.teiid.client.security.ILogon;
+import org.teiid.client.security.InvalidSessionException;
+import org.teiid.client.security.SessionToken;
+import org.teiid.core.TeiidException;
+import org.teiid.core.util.PropertiesUtils;
+import org.teiid.core.util.ReflectionHelper;
+import org.teiid.net.CommunicationException;
+import org.teiid.net.ConnectionException;
+import org.teiid.net.HostInfo;
+import org.teiid.net.ServerConnection;
+import org.teiid.net.ServerConnectionFactory;
+import org.teiid.net.TeiidURL;
+
+
+/**
+ * Responsible for creating socket based connections
+ *
+ * The comm approach is object based and layered. Connections manage failover and identity.
+ * ServerInstances represent the service layer to a particular cluster member. ObjectChannels
+ * abstract the underlying IO.
+ *
+ */
+public class SocketServerConnectionFactory implements ServerConnectionFactory, SocketServerInstanceFactory {
+
+ private static final String URL = "URL"; //$NON-NLS-1$
+
+ private static SocketServerConnectionFactory INSTANCE;
+ private static Logger log = Logger.getLogger("org.teiid.client.sockets"); //$NON-NLS-1$
+
+ private final class ShutdownHandler implements InvocationHandler {
+ private final CachedInstance key;
+
+ private ShutdownHandler(CachedInstance key) {
+ this.key = key;
+ }
+
+ @Override
+ public Object invoke(Object arg0, Method arg1, Object[] arg2)
+ throws Throwable {
+ if (arg1.getName().equals("shutdown")) { //$NON-NLS-1$
+ CachedInstance purge = null;
+ if (!key.actual.isOpen()) {
+ return null; //nothing to do
+ }
+ synchronized (instancePool) {
+ instancePool.put(key, key);
+ if (instancePool.size() > maxCachedInstances) {
+ Iterator<CachedInstance> iter = instancePool.keySet().iterator();
+ purge = iter.next();
+ iter.remove();
+ }
+ }
+ if (purge != null) {
+ purge.actual.shutdown();
+ }
+ return null;
+ }
+ try {
+ return arg1.invoke(key.actual, arg2);
+ } catch (InvocationTargetException e) {
+ throw e.getTargetException();
+ }
+ }
+ }
+
+ private static class CachedInstance {
+ HostInfo info;
+ Integer instance;
+ SocketServerInstance actual;
+ SocketServerInstance proxy;
+
+ public CachedInstance(HostInfo info) {
+ this.info = info;
+ }
+
+ @Override
+ public int hashCode() {
+ return info.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (!(obj instanceof CachedInstance)) {
+ return false;
+ }
+ CachedInstance other = (CachedInstance) obj;
+ if (!info.equals(other.info)) {
+ return false;
+ }
+ if (instance == null || other.instance == null) {
+ return true;
+ }
+ return instance.equals(other.instance);
+ }
+ }
+
+ private ObjectChannelFactory channelFactory;
+ private Timer pingTimer;
+
+ private HashMap<HostInfo, Set<SessionToken>> sessions = new HashMap<HostInfo, Set<SessionToken>>();
+
+ //instance pooling
+ private AtomicInteger instanceCount = new AtomicInteger();
+ private Map<CachedInstance, CachedInstance> instancePool = new LinkedHashMap<CachedInstance, CachedInstance>();
+
+ //config properties
+ private long synchronousTtl = 120000l;
+ private int maxCachedInstances=16;
+
+ public static synchronized SocketServerConnectionFactory getInstance() {
+ if (INSTANCE == null) {
+ INSTANCE = new SocketServerConnectionFactory();
+ Properties props = System.getProperties();
+ InputStream is = SocketServerConnectionFactory.class.getResourceAsStream("/teiid-client-settings.properties"); //$NON-NLS-1$
+ if (is != null) {
+ props = new Properties(props);
+ try {
+ props.load(is);
+ } catch (IOException e) {
+
+ } finally {
+ try {
+ is.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ INSTANCE.initialize(props);
+ }
+ return INSTANCE;
+ }
+
+ public SocketServerConnectionFactory() {
+
+ }
+
+ public void initialize(Properties info) {
+ PropertiesUtils.setBeanProperties(this, info, "org.teiid.sockets"); //$NON-NLS-1$
+ this.pingTimer = new Timer("SocketPing", true); //$NON-NLS-1$
+ this.pingTimer.schedule(new TimerTask() {
+
+ @Override
+ public void run() {
+ Set<Map.Entry<HostInfo, Set<SessionToken>>> sessionEntries = null;
+ synchronized (sessions) {
+ sessionEntries = new HashSet<Map.Entry<HostInfo, Set<SessionToken>>>(sessions.entrySet());
+ }
+ for (Map.Entry<HostInfo, Set<SessionToken>> entry : sessionEntries) {
+ SocketServerInstance instance = null;
+ HashSet<SessionToken> entries = null;
+ synchronized (sessions) {
+ entries = new HashSet<SessionToken>(entry.getValue());
+ }
+ try {
+ instance = getServerInstance(entry.getKey());
+ ILogon logon = instance.getService(ILogon.class);
+ if ("7.1.1".compareTo(instance.getServerVersion()) > 0) { //$NON-NLS-1$
+ for (SessionToken session : entries) {
+ try {
+ logon.assertIdentity(session);
+ logon.ping();
+ log.log(Level.FINER, "issueing ping for session:", session); //$NON-NLS-1$
+ } catch (InvalidSessionException e) {
+ }
+ }
+ } else {
+ ArrayList<String> sessionStrings = new ArrayList<String>(entry.getValue().size());
+ for (SessionToken session : entries) {
+ sessionStrings.add(session.getSessionID());
+ }
+ logon.ping(sessionStrings);
+ log.log(Level.FINER, "issueing ping for sessions:", sessionStrings); //$NON-NLS-1$
+ }
+ } catch (Exception e) {
+ log.log(Level.WARNING, "Error performing keep-alive ping", e); //$NON-NLS-1$
+ } finally {
+ if (instance != null) {
+ instance.shutdown();
+ }
+ }
+ }
+ }
+ }, ServerConnection.PING_INTERVAL, ServerConnection.PING_INTERVAL);
+ this.channelFactory = new OioOjbectChannelFactory(info);
+ }
+
+ @Override
+ public SocketServerInstance getServerInstance(HostInfo info) throws CommunicationException, IOException {
+ CachedInstance key = null;
+ boolean useCache = this.maxCachedInstances > 0;
+ if (useCache) {
+ CachedInstance instance = null;
+ key = new CachedInstance(info);
+ synchronized (instancePool) {
+ instance = instancePool.remove(key);
+ }
+ if (instance != null) {
+ ILogon logon = instance.actual.getService(ILogon.class);
+ boolean valid = false;
+ try {
+ Future<?> success = logon.ping();
+ success.get(this.channelFactory.getSoTimeout(), TimeUnit.MILLISECONDS);
+ valid = true;
+ } catch (Exception e) {
+ log.log(Level.FINE, "Error performing ping, will select another instance", e); //$NON-NLS-1$
+ }
+ if (valid) {
+ return instance.proxy;
+ }
+ instance.actual.shutdown();
+ //technically we only want to remove instances with the same inetaddress
+ while (true) {
+ CachedInstance invalid = null;
+ synchronized (instancePool) {
+ invalid = instancePool.remove(key);
+ }
+ if (invalid == null) {
+ break;
+ }
+ invalid.actual.shutdown();
+ }
+ }
+ }
+ SocketServerInstanceImpl ssii = new SocketServerInstanceImpl(info, getSynchronousTtl());
+ ssii.connect(this.channelFactory);
+ if (useCache) {
+ key.actual = ssii;
+ key.instance = instanceCount.getAndIncrement();
+ //create a proxied socketserverinstance that will pool itself on shutdown
+ key.proxy = (SocketServerInstance)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {SocketServerInstance.class}, new ShutdownHandler(key));
+ return key.proxy;
+ }
+ return ssii;
+ }
+
+ /**
+ * @param connectionProperties will be updated with additional information before logon
+ */
+ public SocketServerConnection getConnection(Properties connectionProperties) throws CommunicationException, ConnectionException {
+
+ updateConnectionProperties(connectionProperties);
+
+ TeiidURL url;
+ try {
+ url = new TeiidURL(connectionProperties.getProperty(TeiidURL.CONNECTION.SERVER_URL));
+ } catch (MalformedURLException e1) {
+ throw new ConnectionException(e1);
+ }
+
+ String discoveryStrategyName = connectionProperties.getProperty(TeiidURL.CONNECTION.DISCOVERY_STRATEGY, URL);
+
+ ServerDiscovery discovery;
+
+ if (URL.equalsIgnoreCase(discoveryStrategyName)) {
+ discovery = new UrlServerDiscovery();
+ } else {
+ try {
+ discovery = (ServerDiscovery)ReflectionHelper.create(discoveryStrategyName, null, this.getClass().getClassLoader());
+ } catch (TeiidException e) {
+ throw new ConnectionException(e);
+ }
+ }
+
+ discovery.init(url, connectionProperties);
+
+ return new SocketServerConnection(this, url.isUsingSSL(), discovery, connectionProperties);
+ }
+
+ static void updateConnectionProperties(Properties connectionProperties) {
+ try {
+ 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) {
+
+ }
+ }
+
+ public long getSynchronousTtl() {
+ return synchronousTtl;
+ }
+
+ public void setSynchronousTtl(long synchronousTTL) {
+ this.synchronousTtl = synchronousTTL;
+ }
+
+ public int getMaxCachedInstances() {
+ return maxCachedInstances;
+ }
+
+ public void setMaxCachedInstances(int maxCachedInstances) {
+ this.maxCachedInstances = maxCachedInstances;
+ }
+
+ @Override
+ public void connected(SocketServerInstance instance, SessionToken session) {
+ synchronized (sessions) {
+ Set<SessionToken> instanceSessions = sessions.get(instance.getHostInfo());
+ if (instanceSessions == null) {
+ instanceSessions = new HashSet<SessionToken>();
+ sessions.put(instance.getHostInfo(), instanceSessions);
+ }
+ instanceSessions.add(session);
+ }
+ }
+
+ @Override
+ public void disconnected(SocketServerInstance instance, SessionToken session) {
+ synchronized (sessions) {
+ Set<SessionToken> instanceSessions = sessions.get(instance.getHostInfo());
+ if (instanceSessions != null) {
+ instanceSessions.remove(session);
+ if (instanceSessions.isEmpty()) {
+ sessions.remove(instance.getHostInfo());
+ }
+ }
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestStatement.java
===================================================================
--- trunk/client/src/test/java/org/teiid/jdbc/TestStatement.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestStatement.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,122 +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.jdbc;
-
-import static org.junit.Assert.*;
-
-import java.sql.ResultSet;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Properties;
-
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.client.DQP;
-import org.teiid.client.RequestMessage;
-import org.teiid.client.ResultsMessage;
-import org.teiid.client.util.ResultsFuture;
-
- at SuppressWarnings("nls")
-public class TestStatement {
-
- @Test public void testBatchExecution() throws Exception {
- ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
- DQP dqp = Mockito.mock(DQP.class);
- ResultsFuture<ResultsMessage> results = new ResultsFuture<ResultsMessage>();
- Mockito.stub(dqp.executeRequest(Mockito.anyLong(), (RequestMessage)Mockito.anyObject())).toReturn(results);
- ResultsMessage rm = new ResultsMessage();
- rm.setResults(new List<?>[] {Arrays.asList(1), Arrays.asList(2)});
- rm.setUpdateResult(true);
- results.getResultsReceiver().receiveResults(rm);
- Mockito.stub(conn.getDQP()).toReturn(dqp);
- StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
- 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()));
- }
-
- @Test public void testSetStatement() 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 foo bar")); //$NON-NLS-1$
- assertEquals("bar", p.get("foo")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testPropertiesOverride() throws Exception {
- ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
- Properties p = new Properties();
- p.setProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS, Boolean.TRUE.toString());
- Mockito.stub(conn.getExecutionProperties()).toReturn(p);
- StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
- assertEquals(Boolean.TRUE.toString(), statement.getExecutionProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS));
- statement.setExecutionProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS, Boolean.FALSE.toString());
- assertEquals(Boolean.FALSE.toString(), statement.getExecutionProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS));
- assertEquals(Boolean.TRUE.toString(), p.getProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS));
- }
-
- @Test public void testTransactionStatements() 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("start transaction")); //$NON-NLS-1$
- Mockito.verify(conn).setAutoCommit(false);
- assertFalse(statement.execute("commit")); //$NON-NLS-1$
- Mockito.verify(conn).setAutoCommit(true);
- assertFalse(statement.execute("start transaction")); //$NON-NLS-1$
- assertFalse(statement.execute("rollback")); //$NON-NLS-1$
- Mockito.verify(conn).rollback(false);
- }
-
- @SuppressWarnings("unchecked")
- @Test public void testTransactionStatementsAsynch() throws Exception {
- ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
- Mockito.stub(conn.submitSetAutoCommitTrue(Mockito.anyBoolean())).toReturn((ResultsFuture)ResultsFuture.NULL_FUTURE);
- Properties p = new Properties();
- Mockito.stub(conn.getExecutionProperties()).toReturn(p);
- StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
- statement.submitExecute("start transaction"); //$NON-NLS-1$
- Mockito.verify(conn).setAutoCommit(false);
- statement.submitExecute("commit"); //$NON-NLS-1$
- Mockito.verify(conn).submitSetAutoCommitTrue(true);
- statement.submitExecute("start transaction"); //$NON-NLS-1$
- statement.submitExecute("rollback"); //$NON-NLS-1$
- Mockito.verify(conn).submitSetAutoCommitTrue(false);
- }
-
- @Test public void testAsynchTimeout() throws Exception {
- ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
- StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
- statement.setQueryTimeoutMS(1);
- DQP dqp = Mockito.mock(DQP.class);
- Mockito.stub(statement.getDQP()).toReturn(dqp);
- 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);
- Mockito.verify(dqp).cancelRequest(0);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestStatement.java (from rev 3218, trunk/client/src/test/java/org/teiid/jdbc/TestStatement.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestStatement.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestStatement.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,134 @@
+/*
+ * 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.jdbc;
+
+import static org.junit.Assert.*;
+
+import java.sql.ResultSet;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.client.DQP;
+import org.teiid.client.RequestMessage;
+import org.teiid.client.ResultsMessage;
+import org.teiid.client.util.ResultsFuture;
+
+ at SuppressWarnings("nls")
+public class TestStatement {
+
+ @Test public void testBatchExecution() throws Exception {
+ ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
+ DQP dqp = Mockito.mock(DQP.class);
+ ResultsFuture<ResultsMessage> results = new ResultsFuture<ResultsMessage>();
+ Mockito.stub(dqp.executeRequest(Mockito.anyLong(), (RequestMessage)Mockito.anyObject())).toReturn(results);
+ ResultsMessage rm = new ResultsMessage();
+ rm.setResults(new List<?>[] {Arrays.asList(1), Arrays.asList(2)});
+ rm.setUpdateResult(true);
+ results.getResultsReceiver().receiveResults(rm);
+ Mockito.stub(conn.getDQP()).toReturn(dqp);
+ StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+ 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()));
+ }
+
+ @Test public void testSetStatement() 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 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();
+ p.setProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS, Boolean.TRUE.toString());
+ Mockito.stub(conn.getExecutionProperties()).toReturn(p);
+ StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+ assertEquals(Boolean.TRUE.toString(), statement.getExecutionProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS));
+ statement.setExecutionProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS, Boolean.FALSE.toString());
+ assertEquals(Boolean.FALSE.toString(), statement.getExecutionProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS));
+ assertEquals(Boolean.TRUE.toString(), p.getProperty(ExecutionProperties.ANSI_QUOTED_IDENTIFIERS));
+ }
+
+ @Test public void testTransactionStatements() 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("start transaction")); //$NON-NLS-1$
+ Mockito.verify(conn).setAutoCommit(false);
+ assertFalse(statement.execute("commit")); //$NON-NLS-1$
+ Mockito.verify(conn).setAutoCommit(true);
+ assertFalse(statement.execute("start transaction")); //$NON-NLS-1$
+ assertFalse(statement.execute("rollback")); //$NON-NLS-1$
+ Mockito.verify(conn).rollback(false);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test public void testTransactionStatementsAsynch() throws Exception {
+ ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
+ Mockito.stub(conn.submitSetAutoCommitTrue(Mockito.anyBoolean())).toReturn((ResultsFuture)ResultsFuture.NULL_FUTURE);
+ Properties p = new Properties();
+ Mockito.stub(conn.getExecutionProperties()).toReturn(p);
+ StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+ statement.submitExecute("start transaction"); //$NON-NLS-1$
+ Mockito.verify(conn).setAutoCommit(false);
+ statement.submitExecute("commit"); //$NON-NLS-1$
+ Mockito.verify(conn).submitSetAutoCommitTrue(true);
+ statement.submitExecute("start transaction"); //$NON-NLS-1$
+ statement.submitExecute("rollback"); //$NON-NLS-1$
+ Mockito.verify(conn).submitSetAutoCommitTrue(false);
+ }
+
+ @Test public void testAsynchTimeout() throws Exception {
+ ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
+ StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+ statement.setQueryTimeoutMS(1);
+ DQP dqp = Mockito.mock(DQP.class);
+ Mockito.stub(statement.getDQP()).toReturn(dqp);
+ 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);
+ Mockito.verify(dqp).cancelRequest(0);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java
===================================================================
--- trunk/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,144 +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.jdbc;
-
-import static org.junit.Assert.*;
-
-import java.sql.DriverPropertyInfo;
-import java.util.Properties;
-
-import org.junit.Test;
-import org.teiid.net.TeiidURL;
-
-public class TestTeiidDriver {
- TeiidDriver drv = new TeiidDriver();
- public String localhost = "localhost"; //$NON-NLS-1$
-
- @Test public void testAccepts() throws Exception {
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:12345")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:12345;user=foo;password=bar")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb@/foo/blah/deploy.properties")); //$NON-NLS-1$
-
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:12345")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:12345;user=foo;password=bar")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb@/foo/blah/deploy.properties")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:8294601c-9fe9-4244-9499-4a012c5e1476_vdb")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:8294601c-9fe9-4244-9499-4a012c5e1476_vdb at mm://localhost:12345")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:test_vdb at mm://local-host:12345")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:test_vdb at mm://local_host:12345")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:test_vdb.1 at mm://local_host:12345")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:test_vdb.10 at mm://local_host:12345")); //$NON-NLS-1$
- }
-
- /** Valid format of urls*/
- @Test public void testAcceptsURL1() throws Exception {
- assertTrue(drv.acceptsURL("jdbc:teiid:jvdb at mm://localhost:1234")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234;version=x")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234,localhost2:12342,localhost3:12343")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234,localhost2:12342,localhost3:12343;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mms://localhost:1234;logLevel=1;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
- assertTrue(!drv.acceptsURL("jdbc:teiid:@mm://localhost:1234;logLevel=2;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234;logLevel=2;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log;autoCommitTxn=OFF;paritalResultsMode=true")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:jvdb at mms://localhost:1234")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234;version=x")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234,localhost2:12342,localhost3:12343")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mms://localhost:1234,localhost2:12342,localhost3:12343;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mms://localhost:1234;logLevel=2;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log;autoCommitTxn=OFF;paritalResultsMode=true")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://127.0.0.1:1234;logLevel=2")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mms://127.0.0.1:1234")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://127.0.0.1:1234,localhost.mydomain.com:63636;logLevel=2")); //$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://123.123.123.123:53535,127.0.0.1:1234")); //$NON-NLS-1$
-
- //DQP type
- assertTrue(drv.acceptsURL("jdbc:teiid:jvdb at c:/dqp.properties;version=1")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:jvdb@/foo/dqp.properties;version=1")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:jvdb at ../foo/dqp.properties;version=1")); //$NON-NLS-1$
-
- assertTrue(drv.acceptsURL("jdbc:teiid:jvdb at mm://localhost:port")); //$NON-NLS-1$
- assertTrue(drv.acceptsURL("jdbc:teiid:vdb at localhost:port;version=x")); //$NON-NLS-1$
- assertTrue(!drv.acceptsURL("jdbc:teiid:@localhost:1234")); //$NON-NLS-1$
- assertTrue(!drv.acceptsURL("jdbc:teiid:@localhost:1234,localhost2:12342,localhost3:12343")); //$NON-NLS-1$
- assertTrue(!drv.acceptsURL("jdbc:teiid:@localhost:1234;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
- assertTrue(!drv.acceptsURL("jdbc:teiid:@localhost:1234,localhost2:12342,localhost3:12343;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
- assertTrue(!drv.acceptsURL("jdbc:teiid:@localhost:1234;logLevel=1;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")); //$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$
- }
-
- /** Invalid format of urls*/
- @Test public void testAcceptsURL2() throws Exception {
- assertTrue(!drv.acceptsURL("jdbc:matamatrix:test")); //$NON-NLS-1$
- assertTrue(!drv.acceptsURL("metamatrix:test")); //$NON-NLS-1$
- assertTrue(!drv.acceptsURL("jdbc&matamatrix:test")); //$NON-NLS-1$
- assertTrue(!drv.acceptsURL("jdbc;metamatrix:test")); //$NON-NLS-1$
- }
-
- @Test public void testParseURL() throws Exception{
- Properties p = new Properties();
- TeiidDriver.parseURL("jdbc:teiid:BQT at mm://slwxp157:1234", p); //$NON-NLS-1$
- assertTrue(p.getProperty(BaseDataSource.VDB_NAME).equals("BQT")); //$NON-NLS-1$
- assertTrue(p.getProperty(TeiidURL.CONNECTION.SERVER_URL).equals("mm://slwxp157:1234")); //$NON-NLS-1$
- assertEquals(3, p.size());
- }
-
- @Test public void testParseURL2() throws Exception {
- Properties p = new Properties();
- TeiidDriver.parseURL("jdbc:teiid:BQT at mms://slwxp157:1234;version=3", p); //$NON-NLS-1$
- assertTrue(p.getProperty(BaseDataSource.VDB_NAME).equals("BQT")); //$NON-NLS-1$
- assertTrue(p.getProperty(BaseDataSource.VDB_VERSION).equals("3")); //$NON-NLS-1$
- assertTrue(p.getProperty(TeiidURL.CONNECTION.SERVER_URL).equals("mms://slwxp157:1234")); //$NON-NLS-1$
- assertTrue(p.getProperty(BaseDataSource.VERSION).equals("3")); //$NON-NLS-1$
- assertTrue(p.getProperty(BaseDataSource.APP_NAME).equals(BaseDataSource.DEFAULT_APP_NAME));
- assertEquals(5, p.size());
- }
-
- @Test public void testParseURL3() throws Exception{
- Properties p = new Properties();
- TeiidDriver.parseURL("jdbc:teiid:BQT at mm://slwxp157:1234,slntmm01:43401,sluxmm09:43302;version=4;autoCommitTxn=ON;partialResultsMode=YES;ApplicationName=Client", p); //$NON-NLS-1$
- assertTrue(p.getProperty(BaseDataSource.VDB_NAME).equals("BQT")); //$NON-NLS-1$
- assertTrue(p.getProperty(BaseDataSource.VDB_VERSION).equals("4")); //$NON-NLS-1$
- assertTrue(p.getProperty(ExecutionProperties.PROP_TXN_AUTO_WRAP).equals("ON")); //$NON-NLS-1$
- assertTrue(p.getProperty(ExecutionProperties.PROP_PARTIAL_RESULTS_MODE).equals("YES")); //$NON-NLS-1$
- assertTrue(p.getProperty(TeiidURL.CONNECTION.SERVER_URL).equals("mm://slwxp157:1234,slntmm01:43401,sluxmm09:43302")); //$NON-NLS-1$
- assertTrue(p.getProperty(BaseDataSource.VERSION).equals("4")); //$NON-NLS-1$
- assertTrue(p.getProperty(BaseDataSource.APP_NAME).equals("Client")); //$NON-NLS-1$
- assertEquals(7, p.size());
- }
-
- @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(false, info[0].required);
- assertEquals("ApplicationName", info[0].name); //$NON-NLS-1$
- assertEquals("x", info[0].value); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java (from rev 3218, trunk/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,144 @@
+/*
+ * 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.jdbc;
+
+import static org.junit.Assert.*;
+
+import java.sql.DriverPropertyInfo;
+import java.util.Properties;
+
+import org.junit.Test;
+import org.teiid.net.TeiidURL;
+
+public class TestTeiidDriver {
+ TeiidDriver drv = new TeiidDriver();
+ public String localhost = "localhost"; //$NON-NLS-1$
+
+ @Test public void testAccepts() throws Exception {
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:12345")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:12345;user=foo;password=bar")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb@/foo/blah/deploy.properties")); //$NON-NLS-1$
+
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:12345")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:12345;user=foo;password=bar")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb@/foo/blah/deploy.properties")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:8294601c-9fe9-4244-9499-4a012c5e1476_vdb")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:8294601c-9fe9-4244-9499-4a012c5e1476_vdb at mm://localhost:12345")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:test_vdb at mm://local-host:12345")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:test_vdb at mm://local_host:12345")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:test_vdb.1 at mm://local_host:12345")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:test_vdb.10 at mm://local_host:12345")); //$NON-NLS-1$
+ }
+
+ /** Valid format of urls*/
+ @Test public void testAcceptsURL1() throws Exception {
+ assertTrue(drv.acceptsURL("jdbc:teiid:jvdb at mm://localhost:1234")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234;version=x")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234,localhost2:12342,localhost3:12343")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234,localhost2:12342,localhost3:12343;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mms://localhost:1234;logLevel=1;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
+ assertTrue(!drv.acceptsURL("jdbc:teiid:@mm://localhost:1234;logLevel=2;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234;logLevel=2;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log;autoCommitTxn=OFF;paritalResultsMode=true")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:jvdb at mms://localhost:1234")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234;version=x")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234,localhost2:12342,localhost3:12343")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mms://localhost:1234,localhost2:12342,localhost3:12343;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mms://localhost:1234;logLevel=2;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log;autoCommitTxn=OFF;paritalResultsMode=true")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://127.0.0.1:1234;logLevel=2")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mms://127.0.0.1:1234")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://127.0.0.1:1234,localhost.mydomain.com:63636;logLevel=2")); //$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://123.123.123.123:53535,127.0.0.1:1234")); //$NON-NLS-1$
+
+ //DQP type
+ assertTrue(drv.acceptsURL("jdbc:teiid:jvdb at c:/dqp.properties;version=1")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:jvdb@/foo/dqp.properties;version=1")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:jvdb at ../foo/dqp.properties;version=1")); //$NON-NLS-1$
+
+ assertTrue(drv.acceptsURL("jdbc:teiid:jvdb at mm://localhost:port")); //$NON-NLS-1$
+ assertTrue(drv.acceptsURL("jdbc:teiid:vdb at localhost:port;version=x")); //$NON-NLS-1$
+ assertTrue(!drv.acceptsURL("jdbc:teiid:@localhost:1234")); //$NON-NLS-1$
+ assertTrue(!drv.acceptsURL("jdbc:teiid:@localhost:1234,localhost2:12342,localhost3:12343")); //$NON-NLS-1$
+ assertTrue(!drv.acceptsURL("jdbc:teiid:@localhost:1234;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
+ assertTrue(!drv.acceptsURL("jdbc:teiid:@localhost:1234,localhost2:12342,localhost3:12343;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
+ assertTrue(!drv.acceptsURL("jdbc:teiid:@localhost:1234;logLevel=1;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")); //$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$
+ }
+
+ /** Invalid format of urls*/
+ @Test public void testAcceptsURL2() throws Exception {
+ assertTrue(!drv.acceptsURL("jdbc:matamatrix:test")); //$NON-NLS-1$
+ assertTrue(!drv.acceptsURL("metamatrix:test")); //$NON-NLS-1$
+ assertTrue(!drv.acceptsURL("jdbc&matamatrix:test")); //$NON-NLS-1$
+ assertTrue(!drv.acceptsURL("jdbc;metamatrix:test")); //$NON-NLS-1$
+ }
+
+ @Test public void testParseURL() throws Exception{
+ Properties p = new Properties();
+ TeiidDriver.parseURL("jdbc:teiid:BQT at mm://slwxp157:1234", p); //$NON-NLS-1$
+ assertTrue(p.getProperty(BaseDataSource.VDB_NAME).equals("BQT")); //$NON-NLS-1$
+ assertTrue(p.getProperty(TeiidURL.CONNECTION.SERVER_URL).equals("mm://slwxp157:1234")); //$NON-NLS-1$
+ assertEquals(3, p.size());
+ }
+
+ @Test public void testParseURL2() throws Exception {
+ Properties p = new Properties();
+ TeiidDriver.parseURL("jdbc:teiid:BQT at mms://slwxp157:1234;version=3", p); //$NON-NLS-1$
+ assertTrue(p.getProperty(BaseDataSource.VDB_NAME).equals("BQT")); //$NON-NLS-1$
+ assertTrue(p.getProperty(BaseDataSource.VDB_VERSION).equals("3")); //$NON-NLS-1$
+ assertTrue(p.getProperty(TeiidURL.CONNECTION.SERVER_URL).equals("mms://slwxp157:1234")); //$NON-NLS-1$
+ assertTrue(p.getProperty(BaseDataSource.VERSION).equals("3")); //$NON-NLS-1$
+ assertTrue(p.getProperty(BaseDataSource.APP_NAME).equals(BaseDataSource.DEFAULT_APP_NAME));
+ assertEquals(5, p.size());
+ }
+
+ @Test public void testParseURL3() throws Exception{
+ Properties p = new Properties();
+ TeiidDriver.parseURL("jdbc:teiid:BQT at mm://slwxp157:1234,slntmm01:43401,sluxmm09:43302;version=4;autoCommitTxn=ON;partialResultsMode=YES;ApplicationName=Client", p); //$NON-NLS-1$
+ assertTrue(p.getProperty(BaseDataSource.VDB_NAME).equals("BQT")); //$NON-NLS-1$
+ assertTrue(p.getProperty(BaseDataSource.VDB_VERSION).equals("4")); //$NON-NLS-1$
+ assertTrue(p.getProperty(ExecutionProperties.PROP_TXN_AUTO_WRAP).equals("ON")); //$NON-NLS-1$
+ assertTrue(p.getProperty(ExecutionProperties.PROP_PARTIAL_RESULTS_MODE).equals("YES")); //$NON-NLS-1$
+ assertTrue(p.getProperty(TeiidURL.CONNECTION.SERVER_URL).equals("mm://slwxp157:1234,slntmm01:43401,sluxmm09:43302")); //$NON-NLS-1$
+ assertTrue(p.getProperty(BaseDataSource.VERSION).equals("4")); //$NON-NLS-1$
+ assertTrue(p.getProperty(BaseDataSource.APP_NAME).equals("Client")); //$NON-NLS-1$
+ assertEquals(7, p.size());
+ }
+
+ @Test public void testGetPropertyInfo1() throws Exception {
+ DriverPropertyInfo info[] = drv.getPropertyInfo("jdbc:teiid:vdb at mm://localhost:12345;applicationName=x", null); //$NON-NLS-1$
+
+ assertEquals(20, info.length);
+ assertEquals(false, info[0].required);
+ assertEquals("ApplicationName", info[0].name); //$NON-NLS-1$
+ assertEquals("x", info[0].value); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/client-jdk15/pom.xml
===================================================================
--- trunk/client-jdk15/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/client-jdk15/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,18 +0,0 @@
-<?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-client-jdk15</artifactId>
- <name>Client JDK15</name>
- <description>Contains the packages related retrotranslator that will convert 1.6 to 1.5</description>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- </dependency>
- </dependencies>
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/client-jdk15/pom.xml (from rev 3220, trunk/client-jdk15/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/client-jdk15/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/client-jdk15/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,18 @@
+<?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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>teiid-client-jdk15</artifactId>
+ <name>Client JDK15</name>
+ <description>Contains the packages related retrotranslator that will convert 1.6 to 1.5</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ </dependency>
+ </dependencies>
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/common-core/pom.xml
===================================================================
--- trunk/common-core/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/common-core/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,51 +0,0 @@
-<?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-common-core</artifactId>
- <name>Common Core</name>
- <description>Core shared library</description>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-antrun-plugin</artifactId>
- <executions>
- <execution>
- <phase>process-resources</phase>
- <configuration>
- <tasks>
- <tstamp />
- <replace dir="${project.build.outputDirectory}" token="@build-date@" value="${DSTAMP}">
- <include name="**/*.properties" />
- </replace>
- </tasks>
- </configuration>
- <goals>
- <goal>run</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- <includes>
- <include>**/*.properties</include>
- </includes>
- </resource>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>false</filtering>
- <excludes>
- <exclude>**/*.properties</exclude>
- </excludes>
- </resource>
- </resources>
- </build>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/common-core/pom.xml (from rev 3220, trunk/common-core/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/common-core/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/common-core/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,51 @@
+<?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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>teiid-common-core</artifactId>
+ <name>Common Core</name>
+ <description>Core shared library</description>
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <executions>
+ <execution>
+ <phase>process-resources</phase>
+ <configuration>
+ <tasks>
+ <tstamp />
+ <replace dir="${project.build.outputDirectory}" token="@build-date@" value="${DSTAMP}">
+ <include name="**/*.properties" />
+ </replace>
+ </tasks>
+ </configuration>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.properties</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>false</filtering>
+ <excludes>
+ <exclude>**/*.properties</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ </build>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/common-core/src/main/java/org/teiid/core/util/PropertiesUtils.java
===================================================================
--- trunk/common-core/src/main/java/org/teiid/core/util/PropertiesUtils.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/common-core/src/main/java/org/teiid/core/util/PropertiesUtils.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1017 +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.util;
-
-import java.io.BufferedReader;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.lang.reflect.Method;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.teiid.core.CorePlugin;
-import org.teiid.core.TeiidRuntimeException;
-
-
-
-/**
- * Static utility methods for common tasks having to do with
- * java.util.Properties.
- */
-public final class PropertiesUtils {
-
- public static class InvalidPropertyException extends TeiidRuntimeException {
-
- public InvalidPropertyException(String propertyName, String value, Class<?> expectedType, Throwable cause) {
- super(cause, CorePlugin.Util.getString("InvalidPropertyException.message", propertyName, value, expectedType.getSimpleName())); //$NON-NLS-1$
- }
-
- }
-
- /**
- * Returns a list of property names matching the given pattern. A '*' may be
- * given to match the pattern exactly up to the '*', then anything after.
- * Note: Should also implement matching with '?' which means match any single
- * char.
- * @param pattern The property name to match which may include a '*'.
- * @param props The properties to search.
- * @return The List of property names matching given pattern - may be empty
- * but never null.
- */
- public static List filter( String pattern, Properties props ) {
- boolean addAll = false;
- String searchStr = null;
- List propNames = new ArrayList();
- int globIndex = pattern.indexOf('*');
- if ( globIndex == -1 ) {
- searchStr = pattern;
- } else if ( globIndex == 0 ) {
- addAll = true;
- } else {
- searchStr = pattern.substring(0, globIndex);
- }
-
- Enumeration propNameEnum = props.propertyNames();
- while ( propNameEnum.hasMoreElements() ) {
- String name = (String) propNameEnum.nextElement();
- if ( name.startsWith(searchStr) || addAll ) {
- propNames.add(name);
- }
- }
-
- return propNames;
- }
-
-
- /**
- * Obtains from this source the list of all properties that match the pattern specified by the filter.
- * <p>
- * The filter is a string that may contain the '*' character as a wildcard one or more times
- * in the string. For example, the following filter:
- * <p>
- * <pre> *metamatrix.*</pre>
- * <p>
- * finds all properties that contain somewhere in the property name the string "metamatrix.".
- * @param filterPattern the string filter pattern that will be used to narrow the set of properties returned.
- * @param props The properties to search.
- * @return the enumeration of all of the property names of the primary source;
- * the enumeration may be empty if there is an error connecting to the property sources.
- */
- public static Properties getProperties(String filterPattern, Properties props) {
- Properties results = new Properties();
-
- boolean addAll = false;
- String searchStr = null;
- int globIndex = filterPattern.indexOf('*');
- if ( globIndex == -1 ) {
- searchStr = filterPattern;
- } else if ( globIndex == 0 ) {
- addAll = true;
- } else {
- searchStr = filterPattern.substring(0, globIndex);
- }
-
- Enumeration propNameEnum = props.propertyNames();
- while ( propNameEnum.hasMoreElements() ) {
- String name = (String) propNameEnum.nextElement();
- if ( name.startsWith(searchStr)) {
- Object value = props.get(name);
- if (value != null) {
- results.put(name.substring(searchStr.length()), value);
- }
- }
- else if (addAll) {
- results.put(name, props.get(name));
- }
- }
-
- return results;
- }
-
-
- /**
- * Performs a correct deep clone of the properties object by capturing
- * all properties in the default(s) and placing them directly into the
- * new Properties object. If the input is an instance of
- * <code>UnmodifiableProperties</code>, this method returns an
- * <code>UnmodifiableProperties</code> instance around a new (flattened)
- * copy of the underlying Properties object.
- */
- public static Properties clone( Properties props ) {
- return clone(props, null, false);
- }
-
- /**
- * Performs a correct deep clone of the properties object by capturing
- * all properties in the default(s) and placing them directly into the
- * new Properties object. If the input is an instance of
- * <code>UnmodifiableProperties</code>, this method returns an
- * <code>UnmodifiableProperties</code> instance around a new (flattened)
- * copy of the underlying Properties object.
- */
- public static Properties clone( Properties props, Properties defaults, boolean deepClone ) {
- Properties result = null;
- if ( defaults != null ) {
- if ( deepClone ) {
- defaults = clone(defaults);
- }
- result = new Properties(defaults);
- } else {
- result = new Properties();
- }
-
- putAll(result, props);
-
- return result;
- }
-
- /**
- * This method implements a 'compareTo' logic for two Properties objects,
- * equivalent to calling <code>p1.compareTo(p2)</code> if the
- * {@link java.util.Properties Properties} class implemented
- * {@link java.lang.Comparable Comparable} (which it does not).
- * @param p1 the first Properties instance to compare; may be null
- * @param p2 the second Properties instance to compare; may be null
- * @return a negative integer, zero, or a positive integer as <code>p1</code>
- * is less than, equal to, or greater than <code>p2</code>, respectively.
- */
- public static int compare( Properties p1, Properties p2 ) {
- if ( p1 != null ) {
- if ( p2 == null ) {
- return 1;
- }
- } else {
- if ( p2 != null ) {
- return -1;
- }
- return 0;
- }
-
-
- // Compare the number of property values ...
- int diff = p1.size() - p2.size();
- if ( diff != 0 ) {
- return diff;
- }
-
- // Iterate through the properties and compare values ...
- Map.Entry entry = null;
- Object p1Value = null;
- Object p2Value = null;
- Iterator iter = p1.entrySet().iterator();
- while ( iter.hasNext() ) {
- entry = (Map.Entry) iter.next();
- p1Value = entry.getValue();
- p2Value = p2.get(entry.getKey());
- if ( p1Value != null ) {
- if ( p2Value == null ) {
- return 1;
- }
- if ( p1Value instanceof Comparable ) {
- diff = ((Comparable)p1Value).compareTo(p2Value);
- } else {
- diff = p1Value.toString().compareTo(p2Value.toString());
- }
- if ( diff != 0 ) {
- return diff;
- }
- } else {
- if ( p2Value != null ) {
- return -1;
- }
- }
- }
- return 0;
- }
-
- /**
- * <p>This method is intended to replace the use of the <code>putAll</code>
- * method of <code>Properties</code> inherited from <code>java.util.Hashtable</code>.
- * The problem with that method is that, since it is inherited from
- * <code>Hashtable</code>, <i>default</i> properties are lost.
- * </p>
- * <p>For example, the following code
- * <pre><code>
- * Properties a;
- * Properties b;
- * //initialize ...
- * a.putAll(b);
- * </code></pre>
- * will fail <i>if</i> <code>b</code> had been constructed with a default
- * <code>Properties</code> object. Those defaults would be lost and
- * not added to <code>a</code>.</p>
- *
- * <p>The above code could be correctly performed with this method,
- * like this:
- * <pre><code>
- * Properties a;
- * Properties b;
- * //initialize ...
- * PropertiesUtils.putAll(a,b);
- * </code></pre>
- * In the above example, <code>a</code> is modified - properties are added to
- * it (note that if <code>a</code> has defaults they will remain unaffected.)
- * The properties from <code>b</code>, <i>including defaults</i>, will be
- * added to <code>a</code> using its <code>setProperty</code> method -
- * these new properties will overwrite any pre-existing ones of the same
- * name.
- * </p>
- *
- * @param addToThis This Properties object is modified; the properties
- * of the other parameter are added to this. The added property values
- * will replace any current property values of the same names.
- * @param withThese The properties (including defaults) of this
- * object are added to the "addToThis" parameter.
- */
- public static void putAll(Properties addToThis,
- Properties withThese) {
- if ( withThese != null && addToThis != null ) {
- Enumeration enumeration = withThese.propertyNames();
- while ( enumeration.hasMoreElements() ) {
- String propName = (String) enumeration.nextElement();
- Object propValue = withThese.get(propName);
- if ( propValue == null ) {
- //defaults can only be retrieved as strings
- propValue = withThese.getProperty(propName);
- }
- if ( propValue != null ) {
- addToThis.put(propName, propValue);
- }
- }
- }
- }
-
- public static void setOverrideProperies(Properties base, Properties override) {
- Enumeration overrideEnum = override.propertyNames();
- while (overrideEnum.hasMoreElements()) {
- String key = (String)overrideEnum.nextElement();
- String value = base.getProperty(key);
- String overRideValue = override.getProperty(key);
- if (value != null && !value.equals(overRideValue)) {
- base.setProperty(key, overRideValue);
- }
- }
- }
-
- public static int getIntProperty(Properties props, String propName, int defaultValue) throws InvalidPropertyException {
- String stringVal = props.getProperty(propName);
- if(stringVal == null) {
- return defaultValue;
- }
- stringVal = stringVal.trim();
- if (stringVal.length() == 0) {
- return defaultValue;
- }
- try {
- return Integer.parseInt(stringVal);
- } catch(NumberFormatException e) {
- throw new InvalidPropertyException(propName, stringVal, Integer.class, e);
- }
- }
-
- public static long getLongProperty(Properties props, String propName, long defaultValue) {
- String stringVal = props.getProperty(propName);
- if(stringVal == null) {
- return defaultValue;
- }
- stringVal = stringVal.trim();
- if (stringVal.length() == 0) {
- return defaultValue;
- }
- try {
- return Long.parseLong(stringVal);
- } catch(NumberFormatException e) {
- throw new InvalidPropertyException(propName, stringVal, Long.class, e);
- }
- }
-
- public static float getFloatProperty(Properties props, String propName, float defaultValue) {
- String stringVal = props.getProperty(propName);
- if(stringVal == null) {
- return defaultValue;
- }
- stringVal = stringVal.trim();
- if (stringVal.length() == 0) {
- return defaultValue;
- }
- try {
- return Float.parseFloat(stringVal);
- } catch(NumberFormatException e) {
- throw new InvalidPropertyException(propName, stringVal, Float.class, e);
- }
- }
-
- public static double getDoubleProperty(Properties props, String propName, double defaultValue) {
- String stringVal = props.getProperty(propName);
- if(stringVal == null) {
- return defaultValue;
- }
- stringVal = stringVal.trim();
- if (stringVal.length() == 0) {
- return defaultValue;
- }
- try {
- return Double.parseDouble(stringVal);
- } catch(NumberFormatException e) {
- throw new InvalidPropertyException(propName, stringVal, Double.class, e);
- }
- }
-
- public static boolean getBooleanProperty(Properties props, String propName, boolean defaultValue) {
- String stringVal = props.getProperty(propName);
- if(stringVal == null) {
- return defaultValue;
- }
- stringVal = stringVal.trim();
- if (stringVal.length() == 0) {
- return defaultValue;
- }
- try {
- return Boolean.valueOf(stringVal);
- } catch(NumberFormatException e) {
- throw new InvalidPropertyException(propName, stringVal, Float.class, e);
- }
- }
-
- /**
- * Read the header part of a properties file into a String.
- * @param fileName
- * @return
- * @throws IOException
- * @since 4.3
- */
- public static String loadHeader(String fileName) throws IOException {
- FileReader fr = null;
- BufferedReader br = null;
- try {
- fr = new FileReader(fileName);
- br = new BufferedReader(fr);
- String header = br.readLine();
- if (header != null && header.indexOf('#') == 0) {
- header = header.substring(1);
- }
- return header;
- } finally {
- if (br != null) {
- br.close();
- }
- if (fr != null) {
- fr.close();
- }
- }
- }
-
- public static Properties load(String fileName) throws IOException {
- InputStream is = null;
- try {
- Properties props = new Properties();
- is = new FileInputStream(fileName);
- props.load(is);
- return props;
- } finally {
- if (is != null) {
- is.close();
- }
- }
- }
-
- public static Properties loadFromURL(URL url) throws MalformedURLException, IOException {
- Properties result = new Properties();
- InputStream is = null;
- try {
- is = url.openStream();
- result.load(is);
- } finally {
- if (is != null) {
- is.close();
- }
- }
- return result;
- }
-
- public static Properties loadAsResource(Class clazz, String resourceName) throws IOException {
- InputStream is = null;
- Properties configProps = new Properties();
- try {
- is = clazz.getResourceAsStream(resourceName);
- ArgCheck.isNotNull(is);
- if (is != null) {
- configProps.load(is);
- }
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (Exception ce) {
-
- }
- }
- }
- return configProps;
- }
-
- public static Properties sort(Properties props) {
-
- List names = new ArrayList();
- Enumeration enumeration = props.propertyNames();
- while ( enumeration.hasMoreElements() ) {
- String name = (String) enumeration.nextElement();
- names.add(name);
- }
- Collections.sort(names);
-
- Properties newProps = new Properties();
- Iterator iter = names.iterator();
- while ( iter.hasNext() ) {
- String name = (String) iter.next();
- String propValue = props.getProperty(name);
- if ( propValue != null ) {
- newProps.setProperty(name, propValue);
- }
- }
- return newProps;
- }
-
-
- /**
- * Write the specified properties to the specified file,
- * with the specified header.
- * Results may not be sorted.
- * @param fileName
- * @param props
- * @param header
- * @throws IOException
- * @since 4.3
- */
- public static void print(String fileName, Properties props, String header) throws IOException {
- FileOutputStream stream = null;
- try {
- stream = new FileOutputStream(fileName);
- props.store(stream, header);
- stream.flush();
- } finally {
- try {
- if (stream != null) {
- stream.close();
- }
- } catch (Exception e) {
- }
- }
- }
-
-
-
- /**
- * Write the specified properties to the specified file,
- * with the specified header.
- * Results are sorted by property name.
- */
- public static void print( String fileName, Properties props ) throws IOException {
-
- FileOutputStream stream = null;
- PrintStream writer = null;
-
- try {
-
- stream = new FileOutputStream(fileName);
- writer = new PrintStream(stream);
-
- List names = new ArrayList();
- Enumeration enumeration = props.propertyNames();
- while ( enumeration.hasMoreElements() ) {
- String name = (String) enumeration.nextElement();
- names.add(name);
- }
- Collections.sort(names);
-
- StringBuffer sb;
-
- for (Iterator nIt=names.iterator(); nIt.hasNext(); ) {
- String name = (String) nIt.next();
-
- String value = props.getProperty(name);
-
- sb = new StringBuffer();
-
- sb.append(name);
- sb.append("="); //$NON-NLS-1$
- sb.append(value);
-
- writer.println(sb.toString());
- }
- writer.flush();
- } finally {
- try {
- if (writer != null) {
- writer.close();
- }
- } catch (Exception e){
-
- }
- try {
- if (stream != null) {
- stream.close();
- }
- } catch (Exception e){
-
- }
- }
-
-
- }
-
- public static void print( java.io.PrintStream stream, Properties props ) {
- if (props != null) {
- Collection sorted = sortPropertiesForPrinting(props);
- for (Iterator it=sorted.iterator(); it.hasNext(); ) {
- String value = (String) it.next();
- stream.println(value);
- }
- }
- }
-
- private static final String NEWLINE = "\n"; //$NON-NLS-1$
- public static String prettyPrint( Properties props ) {
- if (props != null) {
- Collection sorted = sortPropertiesForPrinting(props);
-
- StringBuffer outBuf = new StringBuffer();
-
- for (Iterator it=sorted.iterator(); it.hasNext(); ) {
- String value = (String) it.next();
- outBuf.append(value);
- outBuf.append(NEWLINE);
- }
-
- return outBuf.toString();
- }
- return ""; //$NON-NLS-1$
- }
-
- /**
- * Sorts the properties and returns a collection of entries
- * where each entry can be printed. Each entry will print in the
- * format of: Property: <code>name</code> = <code>value</code>
- */
-
- private static final String APREFIX = "Property '"; //$NON-NLS-1$
- private static final String AEQUAL = "'='"; //$NON-NLS-1$
- private static final String ASUFFIX = "'"; //$NON-NLS-1$
- private static final String TAB = "\t"; //$NON-NLS-1$
-
- public static Collection sortPropertiesForPrinting(Properties props) {
-
- Collection sortedProps = new ArrayList(props.size());
-
- List names = new ArrayList();
- Enumeration enumeration = props.propertyNames();
- while ( enumeration.hasMoreElements() ) {
- String name = (String) enumeration.nextElement();
- names.add(name);
- }
- Collections.sort(names);
-
- StringBuffer sb;
-
- for (Iterator nIt=names.iterator(); nIt.hasNext(); ) {
- String name = (String) nIt.next();
-
- String value = null;
- if (PasswordMaskUtil.doesNameEndWithPasswordSuffix(name)){
- value = PasswordMaskUtil.MASK_STRING;
- } else {
- value = props.getProperty(name);
- value= saveConvert(value, false);
- }
-
- name = saveConvert(name, true);
-
- sb = new StringBuffer(APREFIX);
-
- sb.append(name);
- sb.append(TAB);
- sb.append(AEQUAL);
- sb.append(value);
- sb.append(ASUFFIX);
-
-// sortedProps.add(APREFIX + name + TAB + AEQUAL + value + ASUFFIX);
- sortedProps.add(sb.toString());
- }
-
- return sortedProps;
-
- }
-
-// private static final String keyValueSeparators = "=: \t\r\n\f";
-
-// private static final String strictKeyValueSeparators = "=:";
-
- private static final String specialSaveChars = "=: \t\r\n\f#!"; //$NON-NLS-1$
-
-// private static final String whiteSpaceChars = " \t\r\n\f";
-
-
- /*
- * Converts unicodes to encoded \uxxxx
- * and writes out any of the characters in specialSaveChars
- * with a preceding slash
- */
- public static String saveConvert(String theString, boolean escapeSpace) {
- if ( theString == null ) {
- return ""; //$NON-NLS-1$
- }
- int len = theString.length();
- StringBuffer outBuffer = new StringBuffer(len*2);
-
- for(int x=0; x<len; x++) {
- char aChar = theString.charAt(x);
- switch(aChar) {
- case ' ':
- if (x == 0 || escapeSpace)
- outBuffer.append('\\');
-
- outBuffer.append(' ');
- break;
- case '\\':outBuffer.append('\\'); outBuffer.append('\\');
- break;
- case '\t':outBuffer.append('\\'); outBuffer.append('t');
- break;
- case '\n':outBuffer.append('\\'); outBuffer.append('n');
- break;
- case '\r':outBuffer.append('\\'); outBuffer.append('r');
- break;
- case '\f':outBuffer.append('\\'); outBuffer.append('f');
- break;
- default:
- if ((aChar < 0x0020) || (aChar > 0x007e)) {
- outBuffer.append('\\');
- outBuffer.append('u');
- outBuffer.append(toHex((aChar >> 12) & 0xF));
- outBuffer.append(toHex((aChar >> 8) & 0xF));
- outBuffer.append(toHex((aChar >> 4) & 0xF));
- outBuffer.append(toHex( aChar & 0xF));
- } else {
- if (specialSaveChars.indexOf(aChar) != -1)
- outBuffer.append('\\');
- outBuffer.append(aChar);
- }
- }
- }
- return outBuffer.toString();
- }
-
- /**
- * Convert a nibble to a hex character
- * @param nibble the nibble to convert.
- */
- private static char toHex(int nibble) {
- return hexDigit[(nibble & 0xF)];
- }
-
- /** A table of hex digits */
- private static final char[] hexDigit = {
- '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
- };
-
-
- public static final void copyProperty(Properties srcProperties, String srcPropName, Properties tgtProperties, String tgtPropName) {
- if(srcProperties == null || srcPropName == null || tgtProperties == null || tgtPropName == null) {
- return;
- }
-
- String value = srcProperties.getProperty(srcPropName);
- if(value != null) {
- tgtProperties.setProperty(tgtPropName, value);
- }
- }
-
- /**
- * The specialty of nested properties is, in a given property file
- * there can be values with pattern like "${...}"
- * <code>
- * key1=value1
- * key2=${key1}/value2
- * </code>
- * where the value of the <code>key2</code> should resolve to <code>value1/value2</code>
- * also if the property in the pattern <code>${..}</code> is not found in the loaded
- * properties, an exception is thrown. Multiple nesting is OK, however recursive nested is not supported.
- * @param original - Original properties to be resolved
- * @return resolved properties object.
- * @since 4.4
- */
- public static Properties resolveNestedProperties(Properties original) {
-
- for(Enumeration e = original.propertyNames(); e.hasMoreElements();) {
- String key = (String)e.nextElement();
- String value = original.getProperty(key);
-
- // this will take care of the if there are any non-string properties,
- // no nesting allowed on these.
- if (value == null) {
- continue;
- }
-
- boolean matched = true;
- boolean modified = false;
-
- while(matched) {
- // now match the pattern, then extract and find the value
- int start = value.indexOf("${"); //$NON-NLS-1$
- int end = start;
- if (start != -1) {
- end = value.indexOf('}', start);
- }
- matched = ((start != -1) && (end != -1));
- if (matched) {
- String nestedkey = value.substring(start+2, end);
- String nestedvalue = original.getProperty(nestedkey);
-
- // in cases where the key and the nestedkey are the same, this has to be bypassed
- // because it will cause an infinite loop, and because there will be no value
- // for the nestedkey that doesnt contain ${..} in the value
- if (key.equals(nestedkey)) {
- matched = false;
-
- } else {
-
-
- // this will handle case where we did not resolve, mark it blank
- if (nestedvalue == null) {
- throw new TeiidRuntimeException(CorePlugin.Util.getString("PropertiesUtils.failed_to_resolve_property", nestedkey)); //$NON-NLS-1$
- }
- value = value.substring(0,start)+nestedvalue+value.substring(end+1);
- modified = true;
- }
- }
- }
- if(modified) {
- original.setProperty(key, value);
- }
- }
- return original;
- }
-
- // ======================================================
- /**
- * Returns a boolean indicating whether the string matched the given pattern.
- * A '*' may be
- * given to match the pattern exactly up to the '*', then anything after.
- * We will also support a leading star, and match on anything that ends with
- * the string specified after the star.
- * Note: Should also implement matching with '?' which means match any single
- * char.
- * @param pattern The property name to match which may include a '*'.
- * @param props The properties to search.
- * @return The boolean - passed or failed
- * but never null.
- */
- public static boolean filterTest( String pattern, String sCandidate ) {
-
- // Vars for match strategy
- char chStar = '*';
-
- // Match rule booleans. Please note that 'bLeading'
- // and 'bTrailing' refer to the string we are searching for.
- // For example, if the strategy is bLeading, and the Match frag
- // is "wet", and the candidate string is "wetrust", it will pass.
- // Likewise if the strategy is bTrailing and the Match frag is
- // "rust" and the candidate string is "wetrust", it will pass.
- boolean bLeading = false;
- boolean bTrailing = false;
- boolean bFullMatch = false;
- boolean bAnywhere = false;
- boolean bAllMatch = false;
-
- boolean bPass = false;
-
- String sMatchFrag = ""; //$NON-NLS-1$
-// List propNames = new ArrayList();
-
-
- // 1. Analyze pattern to resolve match strategy
-
- // First ensure the pattern is safe to work with.
- // If the pattern is an empty string, set it to '*',
- // which means anything passes.
- pattern = pattern.trim();
- if ( pattern.length() == 0 )
- pattern = "*"; //$NON-NLS-1$
-
- int iFirstStar = pattern.indexOf( chStar );
- int iLastStar = pattern.lastIndexOf( chStar );
-
- // If there are any stars:
- if( (iFirstStar > -1) && ( iLastStar > -1 ) )
- {
- // and their positions are the same (same star, silly)
- if( iFirstStar == iLastStar )
- {
- // and this star is at the front:
- if( iFirstStar == 0 )
- {
- // and the pattern is only one byte long:
- if( pattern.length() == 1 )
- {
- // Then the pattern is a single '*',
- // and all will pass the match:
- bAllMatch = true;
- }
- else
- {
- // Or the pattern is a leading star followed
- // by a string:
- bTrailing = true;
- sMatchFrag = pattern.substring( 1 );
- }
- }
- else
- {
- // OR the star is NOT at the front, so the
- // pattern is a trailing star preceded by a string:
- bLeading = true;
- sMatchFrag = pattern.substring( 0, iLastStar );
-
- }
- }
- else
- {
- // They are not equal
- //sMatchStrategy = ANYWHERE;
- bAnywhere = true;
- sMatchFrag = pattern.substring( iFirstStar + 1, iLastStar );
- }
- }
- else
- {
- // there are no stars at all
- //sMatchStrategy = FULL_MATCH;
- bFullMatch = true;
- sMatchFrag = pattern;
- }
-
- // Now test the string
- String name = sCandidate;
- bPass = false;
-
- // force the match fragment and the test string to UPPER case
- String sMatchFragUpper = sMatchFrag.toUpperCase();
- String sNameUpper = name.toUpperCase();
-
- // Test all of the booleans. Only one should be true.
- if( bAllMatch ) {
- bPass = true;
- }
- else
- if( bAnywhere ) {
- if( sNameUpper.indexOf( sMatchFragUpper ) > -1 )
- bPass = true;
- }
- else
- if( bFullMatch ) {
- if( sNameUpper.equals( sMatchFragUpper ) )
- bPass = true;
- }
- else
- if( bLeading ) {
- if( sNameUpper.startsWith( sMatchFragUpper ) )
- bPass = true;
- }
- else
- if( bTrailing ) {
- if( sNameUpper.endsWith( sMatchFragUpper ) )
- bPass = true;
- }
-
- return bPass;
- }
-
- public static void setBeanProperties(Object bean, Properties props, String prefix) {
- // Move all prop names to lower case so we can use reflection to get
- // method names and look them up in the connection props.
- final Properties connProps = lowerCaseAllPropNames(props);
- final Method[] methods = bean.getClass().getMethods();
- for (int i = 0; i < methods.length; i++) {
- final Method method = methods[i];
- final String methodName = method.getName();
- // If setter ...
- if ( methodName.startsWith("set") && method.getParameterTypes().length == 1 ) { //$NON-NLS-1$
- // Get the property name
- final String propertyName = methodName.substring(3); // remove the "set"
- String shortName = propertyName.toLowerCase();
- String propertyValue = null;
- if (prefix != null) {
- propertyValue = connProps.getProperty(prefix + "." + shortName); //$NON-NLS-1$
- } else {
- propertyValue = connProps.getProperty(shortName);
- }
- if (propertyValue == null) {
- continue;
- }
- final Class<?> argType = method.getParameterTypes()[0];
- try {
- final Object[] params = new Object[] {StringUtil.valueOf(propertyValue, argType)};
- method.invoke(bean, params);
- } catch (Throwable e) {
- throw new InvalidPropertyException(propertyName, propertyValue, argType, e);
- }
- }
- }
- }
-
- public static void setBeanProperty(Object bean, String name, Object value) {
- if (value == null) {
- return;
- }
- name = name.toLowerCase();
- final Method[] methods = bean.getClass().getMethods();
- for (int i = 0; i < methods.length; i++) {
- final Method method = methods[i];
- final String methodName = method.getName();
- // If setter ...
- if ( methodName.startsWith("set") && method.getParameterTypes().length == 1 ) { //$NON-NLS-1$
- // Get the property name
- final String propertyName = methodName.substring(3); // remove the "set"
- String shortName = propertyName.toLowerCase();
- if (!shortName.equals(name)) {
- continue;
- }
- final Class<?> argType = method.getParameterTypes()[0];
- try {
- Object[] params = new Object[] {value};
- if (!argType.isAssignableFrom(value.getClass())) {
- params = new Object[] {StringUtil.valueOf(value.toString(), argType)};
- }
- method.invoke(bean, params);
- } catch (Throwable e) {
- throw new InvalidPropertyException(propertyName, value.toString(), argType, e);
- }
- }
- }
- }
-
- private static Properties lowerCaseAllPropNames(final Properties connectionProps) {
- final Properties lcProps = new Properties();
- final Enumeration<?> itr = connectionProps.propertyNames();
- while ( itr.hasMoreElements() ) {
- final String name = (String) itr.nextElement();
- String propValue = connectionProps.getProperty(name);
- if (propValue != null) {
- lcProps.setProperty(name.toLowerCase(), propValue);
- }
- }
- return lcProps;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/common-core/src/main/java/org/teiid/core/util/PropertiesUtils.java (from rev 3218, trunk/common-core/src/main/java/org/teiid/core/util/PropertiesUtils.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/common-core/src/main/java/org/teiid/core/util/PropertiesUtils.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/common-core/src/main/java/org/teiid/core/util/PropertiesUtils.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1017 @@
+/*
+ * 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.util;
+
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.lang.reflect.Method;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import org.teiid.core.CorePlugin;
+import org.teiid.core.TeiidRuntimeException;
+
+
+
+/**
+ * Static utility methods for common tasks having to do with
+ * java.util.Properties.
+ */
+public final class PropertiesUtils {
+
+ public static class InvalidPropertyException extends TeiidRuntimeException {
+
+ public InvalidPropertyException(String propertyName, String value, Class<?> expectedType, Throwable cause) {
+ super(cause, CorePlugin.Util.getString("InvalidPropertyException.message", propertyName, value, expectedType.getSimpleName())); //$NON-NLS-1$
+ }
+
+ }
+
+ /**
+ * Returns a list of property names matching the given pattern. A '*' may be
+ * given to match the pattern exactly up to the '*', then anything after.
+ * Note: Should also implement matching with '?' which means match any single
+ * char.
+ * @param pattern The property name to match which may include a '*'.
+ * @param props The properties to search.
+ * @return The List of property names matching given pattern - may be empty
+ * but never null.
+ */
+ public static List filter( String pattern, Properties props ) {
+ boolean addAll = false;
+ String searchStr = null;
+ List propNames = new ArrayList();
+ int globIndex = pattern.indexOf('*');
+ if ( globIndex == -1 ) {
+ searchStr = pattern;
+ } else if ( globIndex == 0 ) {
+ addAll = true;
+ } else {
+ searchStr = pattern.substring(0, globIndex);
+ }
+
+ Enumeration propNameEnum = props.propertyNames();
+ while ( propNameEnum.hasMoreElements() ) {
+ String name = (String) propNameEnum.nextElement();
+ if ( name.startsWith(searchStr) || addAll ) {
+ propNames.add(name);
+ }
+ }
+
+ return propNames;
+ }
+
+
+ /**
+ * Obtains from this source the list of all properties that match the pattern specified by the filter.
+ * <p>
+ * The filter is a string that may contain the '*' character as a wildcard one or more times
+ * in the string. For example, the following filter:
+ * <p>
+ * <pre> *metamatrix.*</pre>
+ * <p>
+ * finds all properties that contain somewhere in the property name the string "metamatrix.".
+ * @param filterPattern the string filter pattern that will be used to narrow the set of properties returned.
+ * @param props The properties to search.
+ * @return the enumeration of all of the property names of the primary source;
+ * the enumeration may be empty if there is an error connecting to the property sources.
+ */
+ public static Properties getProperties(String filterPattern, Properties props) {
+ Properties results = new Properties();
+
+ boolean addAll = false;
+ String searchStr = null;
+ int globIndex = filterPattern.indexOf('*');
+ if ( globIndex == -1 ) {
+ searchStr = filterPattern;
+ } else if ( globIndex == 0 ) {
+ addAll = true;
+ } else {
+ searchStr = filterPattern.substring(0, globIndex);
+ }
+
+ Enumeration propNameEnum = props.propertyNames();
+ while ( propNameEnum.hasMoreElements() ) {
+ String name = (String) propNameEnum.nextElement();
+ if ( name.startsWith(searchStr)) {
+ Object value = props.get(name);
+ if (value != null) {
+ results.put(name.substring(searchStr.length()), value);
+ }
+ }
+ else if (addAll) {
+ results.put(name, props.get(name));
+ }
+ }
+
+ return results;
+ }
+
+
+ /**
+ * Performs a correct deep clone of the properties object by capturing
+ * all properties in the default(s) and placing them directly into the
+ * new Properties object. If the input is an instance of
+ * <code>UnmodifiableProperties</code>, this method returns an
+ * <code>UnmodifiableProperties</code> instance around a new (flattened)
+ * copy of the underlying Properties object.
+ */
+ public static Properties clone( Properties props ) {
+ return clone(props, null, false);
+ }
+
+ /**
+ * Performs a correct deep clone of the properties object by capturing
+ * all properties in the default(s) and placing them directly into the
+ * new Properties object. If the input is an instance of
+ * <code>UnmodifiableProperties</code>, this method returns an
+ * <code>UnmodifiableProperties</code> instance around a new (flattened)
+ * copy of the underlying Properties object.
+ */
+ public static Properties clone( Properties props, Properties defaults, boolean deepClone ) {
+ Properties result = null;
+ if ( defaults != null ) {
+ if ( deepClone ) {
+ defaults = clone(defaults);
+ }
+ result = new Properties(defaults);
+ } else {
+ result = new Properties();
+ }
+
+ putAll(result, props);
+
+ return result;
+ }
+
+ /**
+ * This method implements a 'compareTo' logic for two Properties objects,
+ * equivalent to calling <code>p1.compareTo(p2)</code> if the
+ * {@link java.util.Properties Properties} class implemented
+ * {@link java.lang.Comparable Comparable} (which it does not).
+ * @param p1 the first Properties instance to compare; may be null
+ * @param p2 the second Properties instance to compare; may be null
+ * @return a negative integer, zero, or a positive integer as <code>p1</code>
+ * is less than, equal to, or greater than <code>p2</code>, respectively.
+ */
+ public static int compare( Properties p1, Properties p2 ) {
+ if ( p1 != null ) {
+ if ( p2 == null ) {
+ return 1;
+ }
+ } else {
+ if ( p2 != null ) {
+ return -1;
+ }
+ return 0;
+ }
+
+
+ // Compare the number of property values ...
+ int diff = p1.size() - p2.size();
+ if ( diff != 0 ) {
+ return diff;
+ }
+
+ // Iterate through the properties and compare values ...
+ Map.Entry entry = null;
+ Object p1Value = null;
+ Object p2Value = null;
+ Iterator iter = p1.entrySet().iterator();
+ while ( iter.hasNext() ) {
+ entry = (Map.Entry) iter.next();
+ p1Value = entry.getValue();
+ p2Value = p2.get(entry.getKey());
+ if ( p1Value != null ) {
+ if ( p2Value == null ) {
+ return 1;
+ }
+ if ( p1Value instanceof Comparable ) {
+ diff = ((Comparable)p1Value).compareTo(p2Value);
+ } else {
+ diff = p1Value.toString().compareTo(p2Value.toString());
+ }
+ if ( diff != 0 ) {
+ return diff;
+ }
+ } else {
+ if ( p2Value != null ) {
+ return -1;
+ }
+ }
+ }
+ return 0;
+ }
+
+ /**
+ * <p>This method is intended to replace the use of the <code>putAll</code>
+ * method of <code>Properties</code> inherited from <code>java.util.Hashtable</code>.
+ * The problem with that method is that, since it is inherited from
+ * <code>Hashtable</code>, <i>default</i> properties are lost.
+ * </p>
+ * <p>For example, the following code
+ * <pre><code>
+ * Properties a;
+ * Properties b;
+ * //initialize ...
+ * a.putAll(b);
+ * </code></pre>
+ * will fail <i>if</i> <code>b</code> had been constructed with a default
+ * <code>Properties</code> object. Those defaults would be lost and
+ * not added to <code>a</code>.</p>
+ *
+ * <p>The above code could be correctly performed with this method,
+ * like this:
+ * <pre><code>
+ * Properties a;
+ * Properties b;
+ * //initialize ...
+ * PropertiesUtils.putAll(a,b);
+ * </code></pre>
+ * In the above example, <code>a</code> is modified - properties are added to
+ * it (note that if <code>a</code> has defaults they will remain unaffected.)
+ * The properties from <code>b</code>, <i>including defaults</i>, will be
+ * added to <code>a</code> using its <code>setProperty</code> method -
+ * these new properties will overwrite any pre-existing ones of the same
+ * name.
+ * </p>
+ *
+ * @param addToThis This Properties object is modified; the properties
+ * of the other parameter are added to this. The added property values
+ * will replace any current property values of the same names.
+ * @param withThese The properties (including defaults) of this
+ * object are added to the "addToThis" parameter.
+ */
+ public static void putAll(Properties addToThis,
+ Properties withThese) {
+ if ( withThese != null && addToThis != null ) {
+ Enumeration enumeration = withThese.propertyNames();
+ while ( enumeration.hasMoreElements() ) {
+ String propName = (String) enumeration.nextElement();
+ Object propValue = withThese.get(propName);
+ if ( propValue == null ) {
+ //defaults can only be retrieved as strings
+ propValue = withThese.getProperty(propName);
+ }
+ if ( propValue != null ) {
+ addToThis.put(propName, propValue);
+ }
+ }
+ }
+ }
+
+ public static void setOverrideProperies(Properties base, Properties override) {
+ Enumeration overrideEnum = override.propertyNames();
+ while (overrideEnum.hasMoreElements()) {
+ String key = (String)overrideEnum.nextElement();
+ String value = base.getProperty(key);
+ String overRideValue = override.getProperty(key);
+ if (value != null && !value.equals(overRideValue)) {
+ base.setProperty(key, overRideValue);
+ }
+ }
+ }
+
+ public static int getIntProperty(Properties props, String propName, int defaultValue) throws InvalidPropertyException {
+ String stringVal = props.getProperty(propName);
+ if(stringVal == null) {
+ return defaultValue;
+ }
+ stringVal = stringVal.trim();
+ if (stringVal.length() == 0) {
+ return defaultValue;
+ }
+ try {
+ return Integer.parseInt(stringVal);
+ } catch(NumberFormatException e) {
+ throw new InvalidPropertyException(propName, stringVal, Integer.class, e);
+ }
+ }
+
+ public static long getLongProperty(Properties props, String propName, long defaultValue) {
+ String stringVal = props.getProperty(propName);
+ if(stringVal == null) {
+ return defaultValue;
+ }
+ stringVal = stringVal.trim();
+ if (stringVal.length() == 0) {
+ return defaultValue;
+ }
+ try {
+ return Long.parseLong(stringVal);
+ } catch(NumberFormatException e) {
+ throw new InvalidPropertyException(propName, stringVal, Long.class, e);
+ }
+ }
+
+ public static float getFloatProperty(Properties props, String propName, float defaultValue) {
+ String stringVal = props.getProperty(propName);
+ if(stringVal == null) {
+ return defaultValue;
+ }
+ stringVal = stringVal.trim();
+ if (stringVal.length() == 0) {
+ return defaultValue;
+ }
+ try {
+ return Float.parseFloat(stringVal);
+ } catch(NumberFormatException e) {
+ throw new InvalidPropertyException(propName, stringVal, Float.class, e);
+ }
+ }
+
+ public static double getDoubleProperty(Properties props, String propName, double defaultValue) {
+ String stringVal = props.getProperty(propName);
+ if(stringVal == null) {
+ return defaultValue;
+ }
+ stringVal = stringVal.trim();
+ if (stringVal.length() == 0) {
+ return defaultValue;
+ }
+ try {
+ return Double.parseDouble(stringVal);
+ } catch(NumberFormatException e) {
+ throw new InvalidPropertyException(propName, stringVal, Double.class, e);
+ }
+ }
+
+ public static boolean getBooleanProperty(Properties props, String propName, boolean defaultValue) {
+ String stringVal = props.getProperty(propName);
+ if(stringVal == null) {
+ return defaultValue;
+ }
+ stringVal = stringVal.trim();
+ if (stringVal.length() == 0) {
+ return defaultValue;
+ }
+ try {
+ return Boolean.valueOf(stringVal);
+ } catch(NumberFormatException e) {
+ throw new InvalidPropertyException(propName, stringVal, Float.class, e);
+ }
+ }
+
+ /**
+ * Read the header part of a properties file into a String.
+ * @param fileName
+ * @return
+ * @throws IOException
+ * @since 4.3
+ */
+ public static String loadHeader(String fileName) throws IOException {
+ FileReader fr = null;
+ BufferedReader br = null;
+ try {
+ fr = new FileReader(fileName);
+ br = new BufferedReader(fr);
+ String header = br.readLine();
+ if (header != null && header.indexOf('#') == 0) {
+ header = header.substring(1);
+ }
+ return header;
+ } finally {
+ if (br != null) {
+ br.close();
+ }
+ if (fr != null) {
+ fr.close();
+ }
+ }
+ }
+
+ public static Properties load(String fileName) throws IOException {
+ InputStream is = null;
+ try {
+ Properties props = new Properties();
+ is = new FileInputStream(fileName);
+ props.load(is);
+ return props;
+ } finally {
+ if (is != null) {
+ is.close();
+ }
+ }
+ }
+
+ public static Properties loadFromURL(URL url) throws MalformedURLException, IOException {
+ Properties result = new Properties();
+ InputStream is = null;
+ try {
+ is = url.openStream();
+ result.load(is);
+ } finally {
+ if (is != null) {
+ is.close();
+ }
+ }
+ return result;
+ }
+
+ public static Properties loadAsResource(Class clazz, String resourceName) throws IOException {
+ InputStream is = null;
+ Properties configProps = new Properties();
+ try {
+ is = clazz.getResourceAsStream(resourceName);
+ ArgCheck.isNotNull(is);
+ if (is != null) {
+ configProps.load(is);
+ }
+ } finally {
+ if (is != null) {
+ try {
+ is.close();
+ } catch (Exception ce) {
+
+ }
+ }
+ }
+ return configProps;
+ }
+
+ public static Properties sort(Properties props) {
+
+ List names = new ArrayList();
+ Enumeration enumeration = props.propertyNames();
+ while ( enumeration.hasMoreElements() ) {
+ String name = (String) enumeration.nextElement();
+ names.add(name);
+ }
+ Collections.sort(names);
+
+ Properties newProps = new Properties();
+ Iterator iter = names.iterator();
+ while ( iter.hasNext() ) {
+ String name = (String) iter.next();
+ String propValue = props.getProperty(name);
+ if ( propValue != null ) {
+ newProps.setProperty(name, propValue);
+ }
+ }
+ return newProps;
+ }
+
+
+ /**
+ * Write the specified properties to the specified file,
+ * with the specified header.
+ * Results may not be sorted.
+ * @param fileName
+ * @param props
+ * @param header
+ * @throws IOException
+ * @since 4.3
+ */
+ public static void print(String fileName, Properties props, String header) throws IOException {
+ FileOutputStream stream = null;
+ try {
+ stream = new FileOutputStream(fileName);
+ props.store(stream, header);
+ stream.flush();
+ } finally {
+ try {
+ if (stream != null) {
+ stream.close();
+ }
+ } catch (Exception e) {
+ }
+ }
+ }
+
+
+
+ /**
+ * Write the specified properties to the specified file,
+ * with the specified header.
+ * Results are sorted by property name.
+ */
+ public static void print( String fileName, Properties props ) throws IOException {
+
+ FileOutputStream stream = null;
+ PrintStream writer = null;
+
+ try {
+
+ stream = new FileOutputStream(fileName);
+ writer = new PrintStream(stream);
+
+ List names = new ArrayList();
+ Enumeration enumeration = props.propertyNames();
+ while ( enumeration.hasMoreElements() ) {
+ String name = (String) enumeration.nextElement();
+ names.add(name);
+ }
+ Collections.sort(names);
+
+ StringBuffer sb;
+
+ for (Iterator nIt=names.iterator(); nIt.hasNext(); ) {
+ String name = (String) nIt.next();
+
+ String value = props.getProperty(name);
+
+ sb = new StringBuffer();
+
+ sb.append(name);
+ sb.append("="); //$NON-NLS-1$
+ sb.append(value);
+
+ writer.println(sb.toString());
+ }
+ writer.flush();
+ } finally {
+ try {
+ if (writer != null) {
+ writer.close();
+ }
+ } catch (Exception e){
+
+ }
+ try {
+ if (stream != null) {
+ stream.close();
+ }
+ } catch (Exception e){
+
+ }
+ }
+
+
+ }
+
+ public static void print( java.io.PrintStream stream, Properties props ) {
+ if (props != null) {
+ Collection sorted = sortPropertiesForPrinting(props);
+ for (Iterator it=sorted.iterator(); it.hasNext(); ) {
+ String value = (String) it.next();
+ stream.println(value);
+ }
+ }
+ }
+
+ private static final String NEWLINE = "\n"; //$NON-NLS-1$
+ public static String prettyPrint( Properties props ) {
+ if (props != null) {
+ Collection sorted = sortPropertiesForPrinting(props);
+
+ StringBuffer outBuf = new StringBuffer();
+
+ for (Iterator it=sorted.iterator(); it.hasNext(); ) {
+ String value = (String) it.next();
+ outBuf.append(value);
+ outBuf.append(NEWLINE);
+ }
+
+ return outBuf.toString();
+ }
+ return ""; //$NON-NLS-1$
+ }
+
+ /**
+ * Sorts the properties and returns a collection of entries
+ * where each entry can be printed. Each entry will print in the
+ * format of: Property: <code>name</code> = <code>value</code>
+ */
+
+ private static final String APREFIX = "Property '"; //$NON-NLS-1$
+ private static final String AEQUAL = "'='"; //$NON-NLS-1$
+ private static final String ASUFFIX = "'"; //$NON-NLS-1$
+ private static final String TAB = "\t"; //$NON-NLS-1$
+
+ public static Collection sortPropertiesForPrinting(Properties props) {
+
+ Collection sortedProps = new ArrayList(props.size());
+
+ List names = new ArrayList();
+ Enumeration enumeration = props.propertyNames();
+ while ( enumeration.hasMoreElements() ) {
+ String name = (String) enumeration.nextElement();
+ names.add(name);
+ }
+ Collections.sort(names);
+
+ StringBuffer sb;
+
+ for (Iterator nIt=names.iterator(); nIt.hasNext(); ) {
+ String name = (String) nIt.next();
+
+ String value = null;
+ if (PasswordMaskUtil.doesNameEndWithPasswordSuffix(name)){
+ value = PasswordMaskUtil.MASK_STRING;
+ } else {
+ value = props.getProperty(name);
+ value= saveConvert(value, false);
+ }
+
+ name = saveConvert(name, true);
+
+ sb = new StringBuffer(APREFIX);
+
+ sb.append(name);
+ sb.append(TAB);
+ sb.append(AEQUAL);
+ sb.append(value);
+ sb.append(ASUFFIX);
+
+// sortedProps.add(APREFIX + name + TAB + AEQUAL + value + ASUFFIX);
+ sortedProps.add(sb.toString());
+ }
+
+ return sortedProps;
+
+ }
+
+// private static final String keyValueSeparators = "=: \t\r\n\f";
+
+// private static final String strictKeyValueSeparators = "=:";
+
+ private static final String specialSaveChars = "=: \t\r\n\f#!"; //$NON-NLS-1$
+
+// private static final String whiteSpaceChars = " \t\r\n\f";
+
+
+ /*
+ * Converts unicodes to encoded \uxxxx
+ * and writes out any of the characters in specialSaveChars
+ * with a preceding slash
+ */
+ public static String saveConvert(String theString, boolean escapeSpace) {
+ if ( theString == null ) {
+ return ""; //$NON-NLS-1$
+ }
+ int len = theString.length();
+ StringBuffer outBuffer = new StringBuffer(len*2);
+
+ for(int x=0; x<len; x++) {
+ char aChar = theString.charAt(x);
+ switch(aChar) {
+ case ' ':
+ if (x == 0 || escapeSpace)
+ outBuffer.append('\\');
+
+ outBuffer.append(' ');
+ break;
+ case '\\':outBuffer.append('\\'); outBuffer.append('\\');
+ break;
+ case '\t':outBuffer.append('\\'); outBuffer.append('t');
+ break;
+ case '\n':outBuffer.append('\\'); outBuffer.append('n');
+ break;
+ case '\r':outBuffer.append('\\'); outBuffer.append('r');
+ break;
+ case '\f':outBuffer.append('\\'); outBuffer.append('f');
+ break;
+ default:
+ if ((aChar < 0x0020) || (aChar > 0x007e)) {
+ outBuffer.append('\\');
+ outBuffer.append('u');
+ outBuffer.append(toHex((aChar >> 12) & 0xF));
+ outBuffer.append(toHex((aChar >> 8) & 0xF));
+ outBuffer.append(toHex((aChar >> 4) & 0xF));
+ outBuffer.append(toHex( aChar & 0xF));
+ } else {
+ if (specialSaveChars.indexOf(aChar) != -1)
+ outBuffer.append('\\');
+ outBuffer.append(aChar);
+ }
+ }
+ }
+ return outBuffer.toString();
+ }
+
+ /**
+ * Convert a nibble to a hex character
+ * @param nibble the nibble to convert.
+ */
+ public static char toHex(int nibble) {
+ return hexDigit[(nibble & 0xF)];
+ }
+
+ /** A table of hex digits */
+ private static final char[] hexDigit = {
+ '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
+ };
+
+
+ public static final void copyProperty(Properties srcProperties, String srcPropName, Properties tgtProperties, String tgtPropName) {
+ if(srcProperties == null || srcPropName == null || tgtProperties == null || tgtPropName == null) {
+ return;
+ }
+
+ String value = srcProperties.getProperty(srcPropName);
+ if(value != null) {
+ tgtProperties.setProperty(tgtPropName, value);
+ }
+ }
+
+ /**
+ * The specialty of nested properties is, in a given property file
+ * there can be values with pattern like "${...}"
+ * <code>
+ * key1=value1
+ * key2=${key1}/value2
+ * </code>
+ * where the value of the <code>key2</code> should resolve to <code>value1/value2</code>
+ * also if the property in the pattern <code>${..}</code> is not found in the loaded
+ * properties, an exception is thrown. Multiple nesting is OK, however recursive nested is not supported.
+ * @param original - Original properties to be resolved
+ * @return resolved properties object.
+ * @since 4.4
+ */
+ public static Properties resolveNestedProperties(Properties original) {
+
+ for(Enumeration e = original.propertyNames(); e.hasMoreElements();) {
+ String key = (String)e.nextElement();
+ String value = original.getProperty(key);
+
+ // this will take care of the if there are any non-string properties,
+ // no nesting allowed on these.
+ if (value == null) {
+ continue;
+ }
+
+ boolean matched = true;
+ boolean modified = false;
+
+ while(matched) {
+ // now match the pattern, then extract and find the value
+ int start = value.indexOf("${"); //$NON-NLS-1$
+ int end = start;
+ if (start != -1) {
+ end = value.indexOf('}', start);
+ }
+ matched = ((start != -1) && (end != -1));
+ if (matched) {
+ String nestedkey = value.substring(start+2, end);
+ String nestedvalue = original.getProperty(nestedkey);
+
+ // in cases where the key and the nestedkey are the same, this has to be bypassed
+ // because it will cause an infinite loop, and because there will be no value
+ // for the nestedkey that doesnt contain ${..} in the value
+ if (key.equals(nestedkey)) {
+ matched = false;
+
+ } else {
+
+
+ // this will handle case where we did not resolve, mark it blank
+ if (nestedvalue == null) {
+ throw new TeiidRuntimeException(CorePlugin.Util.getString("PropertiesUtils.failed_to_resolve_property", nestedkey)); //$NON-NLS-1$
+ }
+ value = value.substring(0,start)+nestedvalue+value.substring(end+1);
+ modified = true;
+ }
+ }
+ }
+ if(modified) {
+ original.setProperty(key, value);
+ }
+ }
+ return original;
+ }
+
+ // ======================================================
+ /**
+ * Returns a boolean indicating whether the string matched the given pattern.
+ * A '*' may be
+ * given to match the pattern exactly up to the '*', then anything after.
+ * We will also support a leading star, and match on anything that ends with
+ * the string specified after the star.
+ * Note: Should also implement matching with '?' which means match any single
+ * char.
+ * @param pattern The property name to match which may include a '*'.
+ * @param props The properties to search.
+ * @return The boolean - passed or failed
+ * but never null.
+ */
+ public static boolean filterTest( String pattern, String sCandidate ) {
+
+ // Vars for match strategy
+ char chStar = '*';
+
+ // Match rule booleans. Please note that 'bLeading'
+ // and 'bTrailing' refer to the string we are searching for.
+ // For example, if the strategy is bLeading, and the Match frag
+ // is "wet", and the candidate string is "wetrust", it will pass.
+ // Likewise if the strategy is bTrailing and the Match frag is
+ // "rust" and the candidate string is "wetrust", it will pass.
+ boolean bLeading = false;
+ boolean bTrailing = false;
+ boolean bFullMatch = false;
+ boolean bAnywhere = false;
+ boolean bAllMatch = false;
+
+ boolean bPass = false;
+
+ String sMatchFrag = ""; //$NON-NLS-1$
+// List propNames = new ArrayList();
+
+
+ // 1. Analyze pattern to resolve match strategy
+
+ // First ensure the pattern is safe to work with.
+ // If the pattern is an empty string, set it to '*',
+ // which means anything passes.
+ pattern = pattern.trim();
+ if ( pattern.length() == 0 )
+ pattern = "*"; //$NON-NLS-1$
+
+ int iFirstStar = pattern.indexOf( chStar );
+ int iLastStar = pattern.lastIndexOf( chStar );
+
+ // If there are any stars:
+ if( (iFirstStar > -1) && ( iLastStar > -1 ) )
+ {
+ // and their positions are the same (same star, silly)
+ if( iFirstStar == iLastStar )
+ {
+ // and this star is at the front:
+ if( iFirstStar == 0 )
+ {
+ // and the pattern is only one byte long:
+ if( pattern.length() == 1 )
+ {
+ // Then the pattern is a single '*',
+ // and all will pass the match:
+ bAllMatch = true;
+ }
+ else
+ {
+ // Or the pattern is a leading star followed
+ // by a string:
+ bTrailing = true;
+ sMatchFrag = pattern.substring( 1 );
+ }
+ }
+ else
+ {
+ // OR the star is NOT at the front, so the
+ // pattern is a trailing star preceded by a string:
+ bLeading = true;
+ sMatchFrag = pattern.substring( 0, iLastStar );
+
+ }
+ }
+ else
+ {
+ // They are not equal
+ //sMatchStrategy = ANYWHERE;
+ bAnywhere = true;
+ sMatchFrag = pattern.substring( iFirstStar + 1, iLastStar );
+ }
+ }
+ else
+ {
+ // there are no stars at all
+ //sMatchStrategy = FULL_MATCH;
+ bFullMatch = true;
+ sMatchFrag = pattern;
+ }
+
+ // Now test the string
+ String name = sCandidate;
+ bPass = false;
+
+ // force the match fragment and the test string to UPPER case
+ String sMatchFragUpper = sMatchFrag.toUpperCase();
+ String sNameUpper = name.toUpperCase();
+
+ // Test all of the booleans. Only one should be true.
+ if( bAllMatch ) {
+ bPass = true;
+ }
+ else
+ if( bAnywhere ) {
+ if( sNameUpper.indexOf( sMatchFragUpper ) > -1 )
+ bPass = true;
+ }
+ else
+ if( bFullMatch ) {
+ if( sNameUpper.equals( sMatchFragUpper ) )
+ bPass = true;
+ }
+ else
+ if( bLeading ) {
+ if( sNameUpper.startsWith( sMatchFragUpper ) )
+ bPass = true;
+ }
+ else
+ if( bTrailing ) {
+ if( sNameUpper.endsWith( sMatchFragUpper ) )
+ bPass = true;
+ }
+
+ return bPass;
+ }
+
+ public static void setBeanProperties(Object bean, Properties props, String prefix) {
+ // Move all prop names to lower case so we can use reflection to get
+ // method names and look them up in the connection props.
+ final Properties connProps = lowerCaseAllPropNames(props);
+ final Method[] methods = bean.getClass().getMethods();
+ for (int i = 0; i < methods.length; i++) {
+ final Method method = methods[i];
+ final String methodName = method.getName();
+ // If setter ...
+ if ( methodName.startsWith("set") && method.getParameterTypes().length == 1 ) { //$NON-NLS-1$
+ // Get the property name
+ final String propertyName = methodName.substring(3); // remove the "set"
+ String shortName = propertyName.toLowerCase();
+ String propertyValue = null;
+ if (prefix != null) {
+ propertyValue = connProps.getProperty(prefix + "." + shortName); //$NON-NLS-1$
+ } else {
+ propertyValue = connProps.getProperty(shortName);
+ }
+ if (propertyValue == null) {
+ continue;
+ }
+ final Class<?> argType = method.getParameterTypes()[0];
+ try {
+ final Object[] params = new Object[] {StringUtil.valueOf(propertyValue, argType)};
+ method.invoke(bean, params);
+ } catch (Throwable e) {
+ throw new InvalidPropertyException(propertyName, propertyValue, argType, e);
+ }
+ }
+ }
+ }
+
+ public static void setBeanProperty(Object bean, String name, Object value) {
+ if (value == null) {
+ return;
+ }
+ name = name.toLowerCase();
+ final Method[] methods = bean.getClass().getMethods();
+ for (int i = 0; i < methods.length; i++) {
+ final Method method = methods[i];
+ final String methodName = method.getName();
+ // If setter ...
+ if ( methodName.startsWith("set") && method.getParameterTypes().length == 1 ) { //$NON-NLS-1$
+ // Get the property name
+ final String propertyName = methodName.substring(3); // remove the "set"
+ String shortName = propertyName.toLowerCase();
+ if (!shortName.equals(name)) {
+ continue;
+ }
+ final Class<?> argType = method.getParameterTypes()[0];
+ try {
+ Object[] params = new Object[] {value};
+ if (!argType.isAssignableFrom(value.getClass())) {
+ params = new Object[] {StringUtil.valueOf(value.toString(), argType)};
+ }
+ method.invoke(bean, params);
+ } catch (Throwable e) {
+ throw new InvalidPropertyException(propertyName, value.toString(), argType, e);
+ }
+ }
+ }
+ }
+
+ private static Properties lowerCaseAllPropNames(final Properties connectionProps) {
+ final Properties lcProps = new Properties();
+ final Enumeration<?> itr = connectionProps.propertyNames();
+ while ( itr.hasMoreElements() ) {
+ final String name = (String) itr.nextElement();
+ String propValue = connectionProps.getProperty(name);
+ if (propValue != null) {
+ lcProps.setProperty(name.toLowerCase(), propValue);
+ }
+ }
+ return lcProps;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/connector-file/pom.xml
===================================================================
--- trunk/connectors/connector-file/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/connector-file/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,58 +0,0 @@
-<?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>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>connector-file</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>File Connector</name>
- <packaging>rar</packaging>
- <description>This connector reads data from files.</description>
-
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <id>build_jar</id>
- <phase>process-classes</phase>
- <goals>
- <goal>jar</goal>
- </goals>
- </execution>
- <execution>
- <id>deploy_jar</id>
- <phase>package</phase>
- <goals>
- <goal>jar</goal>
- </goals>
- <configuration>
- <classifier>lib</classifier>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/connector-file/pom.xml (from rev 3220, trunk/connectors/connector-file/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/connector-file/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/connector-file/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,58 @@
+<?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>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>connector-file</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>File Connector</name>
+ <packaging>rar</packaging>
+ <description>This connector reads data from files.</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>build_jar</id>
+ <phase>process-classes</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>deploy_jar</id>
+ <phase>package</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ <configuration>
+ <classifier>lib</classifier>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ldap/pom.xml
===================================================================
--- trunk/connectors/connector-ldap/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ldap/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,57 +0,0 @@
-<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>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>connector-ldap</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>LDAP Connector</name>
- <description>LDAP Connector</description>
- <packaging>rar</packaging>
-
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <id>build_jar</id>
- <phase>process-classes</phase>
- <goals>
- <goal>jar</goal>
- </goals>
- </execution>
- <execution>
- <id>deploy_jar</id>
- <phase>package</phase>
- <goals>
- <goal>jar</goal>
- </goals>
- <configuration>
- <classifier>lib</classifier>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ldap/pom.xml (from rev 3220, trunk/connectors/connector-ldap/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ldap/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ldap/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,57 @@
+<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>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>connector-ldap</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>LDAP Connector</name>
+ <description>LDAP Connector</description>
+ <packaging>rar</packaging>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>build_jar</id>
+ <phase>process-classes</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>deploy_jar</id>
+ <phase>package</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ <configuration>
+ <classifier>lib</classifier>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/connector-salesforce/pom.xml
===================================================================
--- trunk/connectors/connector-salesforce/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/connector-salesforce/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,94 +0,0 @@
-<?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>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>connector-salesforce</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>Salesforce Connector</name>
- <packaging>rar</packaging>
- <description>Integrates the query engine with Salesforce.com.</description>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid.connectors</groupId>
- <artifactId>salesforce-api</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid.connectors</groupId>
- <artifactId>translator-salesforce</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-frontend-jaxws</artifactId>
- <version>2.2.2</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-transports-http</artifactId>
- <version>2.2.2</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-ws-security</artifactId>
- <version>2.2.2</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-ws-policy</artifactId>
- <version>2.2.2</version>
- <scope>provided</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <id>build_jar</id>
- <phase>process-classes</phase>
- <goals>
- <goal>jar</goal>
- </goals>
- </execution>
- <execution>
- <id>deploy_jar</id>
- <phase>package</phase>
- <goals>
- <goal>jar</goal>
- </goals>
- <configuration>
- <classifier>lib</classifier>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/connector-salesforce/pom.xml (from rev 3220, trunk/connectors/connector-salesforce/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/connector-salesforce/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/connector-salesforce/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,94 @@
+<?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>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>connector-salesforce</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>Salesforce Connector</name>
+ <packaging>rar</packaging>
+ <description>Integrates the query engine with Salesforce.com.</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <artifactId>salesforce-api</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <artifactId>translator-salesforce</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.cxf</groupId>
+ <artifactId>cxf-rt-frontend-jaxws</artifactId>
+ <version>2.2.2</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.cxf</groupId>
+ <artifactId>cxf-rt-transports-http</artifactId>
+ <version>2.2.2</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.cxf</groupId>
+ <artifactId>cxf-rt-ws-security</artifactId>
+ <version>2.2.2</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.cxf</groupId>
+ <artifactId>cxf-rt-ws-policy</artifactId>
+ <version>2.2.2</version>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>build_jar</id>
+ <phase>process-classes</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>deploy_jar</id>
+ <phase>package</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ <configuration>
+ <classifier>lib</classifier>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ws/pom.xml
===================================================================
--- trunk/connectors/connector-ws/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ws/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,82 +0,0 @@
-<?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>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>connector-ws</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>Web Service Connector</name>
- <packaging>rar</packaging>
- <description>This connector reads data from Web Services</description>
-
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-frontend-jaxws</artifactId>
- <version>2.2.2</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-transports-http</artifactId>
- <version>2.2.2</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-ws-security</artifactId>
- <version>2.2.2</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.cxf</groupId>
- <artifactId>cxf-rt-ws-policy</artifactId>
- <version>2.2.2</version>
- <scope>provided</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <id>build_jar</id>
- <phase>process-classes</phase>
- <goals>
- <goal>jar</goal>
- </goals>
- </execution>
- <execution>
- <id>deploy_jar</id>
- <phase>package</phase>
- <goals>
- <goal>jar</goal>
- </goals>
- <configuration>
- <classifier>lib</classifier>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ws/pom.xml (from rev 3220, trunk/connectors/connector-ws/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ws/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/connector-ws/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,82 @@
+<?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>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>connector-ws</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>Web Service Connector</name>
+ <packaging>rar</packaging>
+ <description>This connector reads data from Web Services</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.cxf</groupId>
+ <artifactId>cxf-rt-frontend-jaxws</artifactId>
+ <version>2.2.2</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.cxf</groupId>
+ <artifactId>cxf-rt-transports-http</artifactId>
+ <version>2.2.2</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.cxf</groupId>
+ <artifactId>cxf-rt-ws-security</artifactId>
+ <version>2.2.2</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.cxf</groupId>
+ <artifactId>cxf-rt-ws-policy</artifactId>
+ <version>2.2.2</version>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>build_jar</id>
+ <phase>process-classes</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>deploy_jar</id>
+ <phase>package</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ <configuration>
+ <classifier>lib</classifier>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/pom.xml
===================================================================
--- trunk/connectors/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,91 +0,0 @@
-<?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>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>connectors</artifactId>
- <packaging>pom</packaging>
- <name>Connectors</name>
- <description>This project is aggregator for all the supported connectors.</description>
- <dependencies>
-
- <!-- Internal Test Dependencies -->
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-engine</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-engine</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-metadata</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-metadata</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
-
- <!-- External dependencies -->
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jboss-vfs</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.man</groupId>
- <artifactId>jboss-managed</artifactId>
- <scope>test</scope>
- </dependency>
-
- </dependencies>
-
- <modules>
- <module>translator-jdbc</module>
- <module>translator-ldap</module>
- <module>translator-loopback</module>
- <module>translator-file</module>
- <module>translator-salesforce</module>
- <module>connector-file</module>
- <module>connector-salesforce</module>
- <module>connector-ldap</module>
- <module>salesforce-api</module>
- <module>connector-ws</module>
- <module>sandbox</module>
- <module>translator-ws</module>
- <module>translator-olap</module>
- </modules>
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/pom.xml (from rev 3220, trunk/connectors/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,91 @@
+<?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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>connectors</artifactId>
+ <packaging>pom</packaging>
+ <name>Connectors</name>
+ <description>This project is aggregator for all the supported connectors.</description>
+ <dependencies>
+
+ <!-- Internal Test Dependencies -->
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-engine</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-metadata</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-metadata</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+
+ <!-- External dependencies -->
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jboss-vfs</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.man</groupId>
+ <artifactId>jboss-managed</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+
+ <modules>
+ <module>translator-jdbc</module>
+ <module>translator-ldap</module>
+ <module>translator-loopback</module>
+ <module>translator-file</module>
+ <module>translator-salesforce</module>
+ <module>connector-file</module>
+ <module>connector-salesforce</module>
+ <module>connector-ldap</module>
+ <module>salesforce-api</module>
+ <module>connector-ws</module>
+ <module>sandbox</module>
+ <module>translator-ws</module>
+ <module>translator-olap</module>
+ </modules>
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/salesforce-api/pom.xml
===================================================================
--- trunk/connectors/salesforce-api/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/salesforce-api/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,14 +0,0 @@
-<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>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>salesforce-api</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>Salesforce API</name>
- <description>The java API for the Salesforce.com partner web service API</description>
- <dependencies>
- </dependencies>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/salesforce-api/pom.xml (from rev 3220, trunk/connectors/salesforce-api/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/salesforce-api/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/salesforce-api/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,14 @@
+<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>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>salesforce-api</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>Salesforce API</name>
+ <description>The java API for the Salesforce.com partner web service API</description>
+ <dependencies>
+ </dependencies>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/pom.xml
===================================================================
--- trunk/connectors/sandbox/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,17 +0,0 @@
-<?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>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.jboss.teiid.connectors</groupId>
- <artifactId>sandbox</artifactId>
- <packaging>pom</packaging>
- <name>Sandbox</name>
- <description>Experimental connectors in progress</description>
- <modules>
- <module>translator-yahoo</module>
- </modules>
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/pom.xml (from rev 3220, trunk/connectors/sandbox/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,17 @@
+<?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>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <artifactId>sandbox</artifactId>
+ <packaging>pom</packaging>
+ <name>Sandbox</name>
+ <description>Experimental connectors in progress</description>
+ <modules>
+ <module>translator-yahoo</module>
+ </modules>
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/translator-yahoo/pom.xml
===================================================================
--- trunk/connectors/sandbox/translator-yahoo/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/translator-yahoo/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,52 +0,0 @@
-<?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>sandbox</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>translator-yahoo</artifactId>
- <groupId>org.jboss.teiid.connectors.sandbox</groupId>
- <name>Yahoo Translator</name>
- <description>Test translator used to query ticker symbols from Yahoo website</description>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- </dependencies>
-
- <build>
- <outputDirectory>target/classes</outputDirectory>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- </resource>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>false</filtering>
- <excludes>
- <exclude>**/*.xml</exclude>
- <exclude>**/*.properties</exclude>
- </excludes>
- </resource>
- </resources>
- </build>
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/translator-yahoo/pom.xml (from rev 3220, trunk/connectors/sandbox/translator-yahoo/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/translator-yahoo/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/sandbox/translator-yahoo/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,52 @@
+<?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>sandbox</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>translator-yahoo</artifactId>
+ <groupId>org.jboss.teiid.connectors.sandbox</groupId>
+ <name>Yahoo Translator</name>
+ <description>Test translator used to query ticker symbols from Yahoo website</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <outputDirectory>target/classes</outputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.xml</include>
+ <include>**/*.properties</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>false</filtering>
+ <excludes>
+ <exclude>**/*.xml</exclude>
+ <exclude>**/*.properties</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ </build>
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-file/pom.xml
===================================================================
--- trunk/connectors/translator-file/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-file/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,53 +0,0 @@
-<?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>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>translator-file</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>File Translator</name>
- <description>This translator provides access to the file system.</description>
-
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- </dependencies>
-
- <build>
- <outputDirectory>target/classes</outputDirectory>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- </resource>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>false</filtering>
- <excludes>
- <exclude>**/*.xml</exclude>
- <exclude>**/*.properties</exclude>
- </excludes>
- </resource>
- </resources>
- </build>
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-file/pom.xml (from rev 3220, trunk/connectors/translator-file/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-file/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-file/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,53 @@
+<?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>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>translator-file</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>File Translator</name>
+ <description>This translator provides access to the file system.</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <outputDirectory>target/classes</outputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.xml</include>
+ <include>**/*.properties</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>false</filtering>
+ <excludes>
+ <exclude>**/*.xml</exclude>
+ <exclude>**/*.properties</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ </build>
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/pom.xml
===================================================================
--- trunk/connectors/translator-jdbc/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,54 +0,0 @@
-<?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>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>translator-jdbc</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>JDBC Translator</name>
-
- <description>This project contains translators for a JDBC source. Currently this is an aggregator for all the JDBC translators relational databases.</description>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- </dependencies>
-
- <build>
- <outputDirectory>target/classes</outputDirectory>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- </resource>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>false</filtering>
- <excludes>
- <exclude>**/*.xml</exclude>
- <exclude>**/*.properties</exclude>
- </excludes>
- </resource>
- </resources>
- </build>
-
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/pom.xml (from rev 3220, trunk/connectors/translator-jdbc/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,54 @@
+<?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>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>translator-jdbc</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>JDBC Translator</name>
+
+ <description>This project contains translators for a JDBC source. Currently this is an aggregator for all the JDBC translators relational databases.</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <outputDirectory>target/classes</outputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.xml</include>
+ <include>**/*.properties</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>false</filtering>
+ <excludes>
+ <exclude>**/*.xml</exclude>
+ <exclude>**/*.properties</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ </build>
+
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1141 +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;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.sql.CallableStatement;
-import java.sql.Connection;
-import java.sql.DatabaseMetaData;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.text.MessageFormat;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.TimeZone;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.sql.DataSource;
-
-import org.teiid.core.util.PropertiesUtils;
-import org.teiid.language.Argument;
-import org.teiid.language.Call;
-import org.teiid.language.ColumnReference;
-import org.teiid.language.Command;
-import org.teiid.language.Expression;
-import org.teiid.language.Function;
-import org.teiid.language.LanguageObject;
-import org.teiid.language.Limit;
-import org.teiid.language.Literal;
-import org.teiid.language.QueryExpression;
-import org.teiid.language.SetQuery;
-import org.teiid.language.Argument.Direction;
-import org.teiid.language.SetQuery.Operation;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.metadata.MetadataFactory;
-import org.teiid.metadata.RuntimeMetadata;
-import org.teiid.translator.ExecutionContext;
-import org.teiid.translator.ExecutionFactory;
-import org.teiid.translator.ProcedureExecution;
-import org.teiid.translator.ResultSetExecution;
-import org.teiid.translator.SourceSystemFunctions;
-import org.teiid.translator.Translator;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.TranslatorProperty;
-import org.teiid.translator.TypeFacility;
-import org.teiid.translator.UpdateExecution;
-
-
-/**
- * JDBC implementation of Connector interface.
- */
- at Translator(name="jdbc-ansi", description="JDBC ANSI translator, can used with any ANSI compatible JDBC Driver")
-public class JDBCExecutionFactory extends ExecutionFactory<DataSource, Connection> {
-
- public static final int DEFAULT_MAX_IN_CRITERIA = 1000;
- public static final int DEFAULT_MAX_DEPENDENT_PREDICATES = 50;
-
- // Because the retrieveValue() method will be hit for every value of
- // every JDBC result set returned, we do lots of weird special stuff here
- // to improve the performance (most importantly to remove big if/else checks
- // of every possible type.
-
- private static final Map<Class<?>, Integer> TYPE_CODE_MAP = new HashMap<Class<?>, Integer>();
-
- private static final int INTEGER_CODE = 0;
- private static final int LONG_CODE = 1;
- private static final int DOUBLE_CODE = 2;
- private static final int BIGDECIMAL_CODE = 3;
- private static final int SHORT_CODE = 4;
- private static final int FLOAT_CODE = 5;
- private static final int TIME_CODE = 6;
- private static final int DATE_CODE = 7;
- private static final int TIMESTAMP_CODE = 8;
- private static final int BLOB_CODE = 9;
- private static final int CLOB_CODE = 10;
- private static final int BOOLEAN_CODE = 11;
-
- static {
- TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.INTEGER, new Integer(INTEGER_CODE));
- TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.LONG, new Integer(LONG_CODE));
- TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.DOUBLE, new Integer(DOUBLE_CODE));
- TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.BIG_DECIMAL, new Integer(BIGDECIMAL_CODE));
- TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.SHORT, new Integer(SHORT_CODE));
- TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.FLOAT, new Integer(FLOAT_CODE));
- TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.TIME, new Integer(TIME_CODE));
- TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.DATE, new Integer(DATE_CODE));
- TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.TIMESTAMP, new Integer(TIMESTAMP_CODE));
- TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.BLOB, new Integer(BLOB_CODE));
- TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.CLOB, new Integer(CLOB_CODE));
- TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.BOOLEAN, new Integer(BOOLEAN_CODE));
- TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.BYTE, new Integer(SHORT_CODE));
- }
-
- private static final ThreadLocal<MessageFormat> COMMENT = new ThreadLocal<MessageFormat>() {
- protected MessageFormat initialValue() {
- return new MessageFormat("/*teiid sessionid:{0}, requestid:{1}.{2}*/ "); //$NON-NLS-1$
- }
- };
- public final static TimeZone DEFAULT_TIME_ZONE = TimeZone.getDefault();
-
- static class DatbaseCalender extends ThreadLocal<Calendar> {
- private String timeZone;
- public DatbaseCalender(String tz) {
- this.timeZone = tz;
- }
- @Override
- protected Calendar initialValue() {
- if(this.timeZone != null && this.timeZone.trim().length() > 0) {
- TimeZone tz = TimeZone.getTimeZone(this.timeZone);
- if(!DEFAULT_TIME_ZONE.hasSameRules(tz)) {
- return Calendar.getInstance(tz);
- }
- }
- return Calendar.getInstance();
- }
- };
-
- private Map<String, FunctionModifier> functionModifiers = new HashMap<String, FunctionModifier>();
-
- private boolean useBindVariables = true;
- private String databaseTimeZone;
- private boolean trimStrings;
- private boolean useCommentsInSourceQuery;
- private String version;
- private int maxInsertBatchSize = 2048;
- private DatbaseCalender databaseCalender;
-
- private AtomicBoolean initialConnection = new AtomicBoolean(true);
-
- public JDBCExecutionFactory() {
- setSupportsFullOuterJoins(true);
- setSupportsOrderBy(true);
- setSupportsOuterJoins(true);
- setSupportsSelectDistinct(true);
- setSupportsInnerJoins(true);
- setMaxInCriteriaSize(DEFAULT_MAX_IN_CRITERIA);
- setMaxDependentInPredicates(DEFAULT_MAX_DEPENDENT_PREDICATES);
- }
-
- @Override
- public void start() throws TranslatorException {
- super.start();
- this.databaseCalender = new DatbaseCalender(this.databaseTimeZone);
- }
-
- @TranslatorProperty(display="Database Version", description= "Database Version")
- public String getDatabaseVersion() {
- return this.version;
- }
-
- public void setDatabaseVersion(String version) {
- this.version = version;
- }
-
- @TranslatorProperty(display="Use Bind Variables", description="Use prepared statements and bind variables",advanced=true)
- public boolean useBindVariables() {
- return this.useBindVariables;
- }
-
- public void setUseBindVariables(boolean useBindVariables) {
- this.useBindVariables = useBindVariables;
- }
-
- @TranslatorProperty(display="Database time zone", description="Time zone of the database, if different than Integration Server", advanced=true)
- public String getDatabaseTimeZone() {
- return this.databaseTimeZone;
- }
-
- public void setDatabaseTimeZone(String databaseTimeZone) {
- this.databaseTimeZone = databaseTimeZone;
- }
-
- @TranslatorProperty(display="Trim string flag", description="Right Trim fixed character types returned as Strings - note that the native type must be char or nchar and the source must support the rtrim function.",advanced=true)
- public boolean isTrimStrings() {
- return this.trimStrings;
- }
-
- public void setTrimStrings(boolean trimStrings) {
- this.trimStrings = trimStrings;
- }
-
- @TranslatorProperty(display="Use informational comments in Source Queries", description="This will embed a /*comment*/ leading comment with session/request id in source SQL query for informational purposes", advanced=true)
- public boolean useCommentsInSourceQuery() {
- return this.useCommentsInSourceQuery;
- }
-
- public void setUseCommentsInSourceQuery(boolean useCommentsInSourceQuery) {
- this.useCommentsInSourceQuery = useCommentsInSourceQuery;
- }
-
- @Override
- public boolean isSourceRequired() {
- return true;
- }
-
- @Override
- public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, Connection conn)
- throws TranslatorException {
- //TODO: This is not correct; this should be only called once for connection creation
- obtainedConnection(conn);
- return new JDBCQueryExecution(command, conn, executionContext, this);
- }
-
- @Override
- public ProcedureExecution createProcedureExecution(Call command, ExecutionContext executionContext, RuntimeMetadata metadata, Connection conn)
- throws TranslatorException {
- //TODO: This is not correct; this should be only called once for connection creation
- obtainedConnection(conn);
- return new JDBCProcedureExecution(command, conn, executionContext, this);
- }
-
- @Override
- public UpdateExecution createUpdateExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, Connection conn)
- throws TranslatorException {
- //TODO: This is not correct; this should be only called once for connection creation
- obtainedConnection(conn);
- return new JDBCUpdateExecution(command, conn, executionContext, this);
- }
-
- @Override
- public Connection getConnection(DataSource ds)
- throws TranslatorException {
- try {
- return ds.getConnection();
- } catch (SQLException e) {
- throw new TranslatorException(e);
- }
- }
-
- @Override
- public void closeConnection(Connection connection, DataSource factory) {
- if (connection == null) {
- return;
- }
- try {
- connection.close();
- } catch (SQLException e) {
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, e, "Error closing"); //$NON-NLS-1$
- }
- }
-
- @Override
- public void getMetadata(MetadataFactory metadataFactory, Connection conn) throws TranslatorException {
- try {
- JDBCMetdataProcessor metadataProcessor = new JDBCMetdataProcessor();
- PropertiesUtils.setBeanProperties(metadataProcessor, metadataFactory.getImportProperties(), "importer"); //$NON-NLS-1$
- metadataProcessor.getConnectorMetadata(conn, metadataFactory);
- } catch (SQLException e) {
- throw new TranslatorException(e);
- }
- }
-
- @Override
- public List<String> getSupportedFunctions() {
- return getDefaultSupportedFunctions();
- }
-
- public List<String> getDefaultSupportedFunctions(){
- return Arrays.asList(new String[] { "+", "-", "*", "/" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Override
- public boolean supportsGroupBy() {
- return true;
- }
-
- @Override
- public boolean supportsAggregatesAvg() {
- return true;
- }
-
- @Override
- public boolean supportsAggregatesCount() {
- return true;
- }
-
- @Override
- public boolean supportsAggregatesCountStar() {
- return true;
- }
-
- @Override
- public boolean supportsAggregatesDistinct() {
- return true;
- }
-
- @Override
- public boolean supportsAggregatesMax() {
- return true;
- }
-
- @Override
- public boolean supportsAggregatesMin() {
- return true;
- }
-
- @Override
- public boolean supportsAggregatesSum() {
- return true;
- }
-
- @Override
- public boolean supportsAliasedTable() {
- return true;
- }
-
- @Override
- public boolean supportsBetweenCriteria() {
- return true;
- }
-
- @Override
- public boolean supportsCaseExpressions() {
- return true;
- }
-
- @Override
- public boolean supportsCompareCriteriaEquals() {
- return true;
- }
-
- @Override
- public boolean supportsCorrelatedSubqueries() {
- return true;
- }
-
- @Override
- public boolean supportsExistsCriteria() {
- return true;
- }
-
- @Override
- public boolean supportsInCriteria() {
- return true;
- }
-
- @Override
- public boolean supportsInCriteriaSubquery() {
- return true;
- }
-
- @Override
- public boolean supportsIsNullCriteria() {
- return true;
- }
-
- @Override
- public boolean supportsLikeCriteria() {
- return true;
- }
-
- @Override
- public boolean supportsLikeCriteriaEscapeCharacter() {
- return true;
- }
-
- @Override
- public boolean supportsNotCriteria() {
- return true;
- }
-
- @Override
- public boolean supportsOrCriteria() {
- return true;
- }
-
- @Override
- public boolean supportsOrderByUnrelated() {
- return true;
- }
-
- @Override
- public boolean supportsQuantifiedCompareCriteriaAll() {
- return true;
- }
-
- @Override
- public boolean supportsScalarSubqueries() {
- return true;
- }
-
- @Override
- public boolean supportsSearchedCaseExpressions() {
- return true;
- }
-
- @Override
- public boolean supportsSelfJoins() {
- return true;
- }
-
- @Override
- public boolean supportsInlineViews() {
- return false;
- }
-
- @Override
- public boolean supportsQuantifiedCompareCriteriaSome() {
- return true;
- }
-
- @Override
- public boolean supportsSetQueryOrderBy() {
- return true;
- }
-
- @Override
- public boolean supportsUnions() {
- return true;
- }
-
- @Override
- public boolean supportsBulkUpdate() {
- return true;
- }
-
- @Override
- public boolean supportsInsertWithIterator() {
- return super.supportsBulkUpdate();
- }
-
- @Override
- public boolean supportsBatchedUpdates() {
- return true;
- }
-
- @Override
- public boolean supportsCompareCriteriaOrdered() {
- return true;
- }
-
- @Override
- public boolean supportsHaving() {
- return true;
- }
-
- @Override
- public boolean supportsSelectExpression() {
- return true;
- }
-
- @Override
- public boolean supportsInsertWithQueryExpression() {
- return true;
- }
-
- /**
- * Get the max number of inserts to perform in one batch.
- * @return
- */
- @TranslatorProperty(display="Max Prepared Insert Batch Size", description="The max size of a prepared insert batch. Default 2048.", advanced=true)
- public int getMaxPreparedInsertBatchSize() {
- return maxInsertBatchSize;
- }
-
- public void setMaxPreparedInsertBatchSize(int maxInsertBatchSize) {
- if (maxInsertBatchSize < 1) {
- throw new AssertionError("Max prepared batch insert size must be greater than 0"); //$NON-NLS-1$
- }
- this.maxInsertBatchSize = maxInsertBatchSize;
- }
-
- /**
- * Gets the database calendar. This will be set to the time zone
- * specified by the property {@link JDBCPropertyNames#DATABASE_TIME_ZONE}, or
- * the local time zone if none is specified.
- * @return the database calendar
- */
- public Calendar getDatabaseCalendar() {
- return this.databaseCalender.get();
- }
-
- /**
- * Return a List of translated parts ({@link LanguageObject}s and Objects), or null
- * if to rely on the default translation. Override with care.
- * @param command
- * @param context
- * @return list of translated parts
- */
- public List<?> translate(LanguageObject obj, ExecutionContext context) {
- List<?> parts = null;
- 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);
- }
- }
- } else if (obj instanceof Command) {
- parts = translateCommand((Command)obj, context);
- } else if (obj instanceof Limit) {
- parts = translateLimit((Limit)obj, context);
- } else if (obj instanceof ColumnReference) {
- ColumnReference elem = (ColumnReference)obj;
- if (isTrimStrings() && elem.getType() == TypeFacility.RUNTIME_TYPES.STRING && elem.getMetadataObject() != null
- && ("char".equalsIgnoreCase(elem.getMetadataObject().getNativeType()) || "nchar".equalsIgnoreCase(elem.getMetadataObject().getNativeType()))) { //$NON-NLS-1$ //$NON-NLS-2$
- return Arrays.asList(getLanguageFactory().createFunction(SourceSystemFunctions.RTRIM, new Expression[] {elem}, TypeFacility.RUNTIME_TYPES.STRING));
- }
- }
- return parts;
- }
-
- /**
- * Return a List of translated parts ({@link LanguageObject}s and Objects), or null
- * if to rely on the default translation.
- * @param command
- * @param context
- * @return a list of translated parts
- */
- public List<?> translateCommand(Command command, ExecutionContext context) {
- return null;
- }
-
- /**
- * Return a List of translated parts ({@link LanguageObject}s and Objects), or null
- * if to rely on the default translation.
- * @param limit
- * @param context
- * @return a list of translated parts
- */
- public List<?> translateLimit(Limit limit, ExecutionContext context) {
- return null;
- }
-
- /**
- * Return a map of function name in lower case to FunctionModifier.
- * @return Map of function name to FunctionModifier.
- */
- public Map<String, FunctionModifier> getFunctionModifiers() {
- return functionModifiers;
- }
-
- /**
- * Add the {@link FunctionModifier} to the set of known modifiers.
- * @param name
- * @param modifier
- */
- public void registerFunctionModifier(String name, FunctionModifier modifier) {
- this.functionModifiers.put(name.toLowerCase(), modifier);
- }
-
- /**
- * Subclasses should override this method to provide a different sql translation
- * of the literal boolean value. By default, a boolean literal is represented as:
- * <code>'0'</code> or <code>'1'</code>.
- * @param booleanValue Boolean value, never null
- * @return Translated string
- */
- public String translateLiteralBoolean(Boolean booleanValue) {
- if(booleanValue.booleanValue()) {
- return "1"; //$NON-NLS-1$
- }
- return "0"; //$NON-NLS-1$
- }
-
- /**
- * Subclasses should override this method to provide a different sql translation
- * of the literal date value. By default, a date literal is represented as:
- * <code>{d '2002-12-31'}</code>
- * @param dateValue Date value, never null
- * @return Translated string
- */
- public String translateLiteralDate(java.sql.Date dateValue) {
- return "{d '" + formatDateValue(dateValue) + "'}"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Subclasses should override this method to provide a different sql translation
- * of the literal time value. By default, a time literal is represented as:
- * <code>{t '23:59:59'}</code>
- *
- * See {@link JDBCExecutionFactory#hasTimeType()} to represent literal times as timestamps.
- *
- * @param timeValue Time value, never null
- * @return Translated string
- */
- public String translateLiteralTime(Time timeValue) {
- if (!hasTimeType()) {
- return translateLiteralTimestamp(new Timestamp(timeValue.getTime()));
- }
- return "{t '" + formatDateValue(timeValue) + "'}"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Subclasses should override this method to provide a different sql translation
- * of the literal timestamp value. By default, a timestamp literal is
- * represented as: <code>{ts '2002-12-31 23:59:59'}</code>.
- *
- * See {@link JDBCExecutionFactory#getTimestampNanoPrecision()} to control the literal
- * precision.
- *
- * @param timestampValue Timestamp value, never null
- * @return Translated string
- */
- public String translateLiteralTimestamp(Timestamp timestampValue) {
- return "{ts '" + formatDateValue(timestampValue) + "'}"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Format the dateObject (of type date, time, or timestamp) into a string
- * using the DatabaseTimeZone format.
- * @param dateObject
- * @return Formatted string
- */
- public String formatDateValue(java.util.Date dateObject) {
- if (dateObject instanceof Timestamp && getTimestampNanoPrecision() < 9) {
- Timestamp ts = (Timestamp)dateObject;
- Timestamp newTs = new Timestamp(ts.getTime());
- if (getTimestampNanoPrecision() > 0) {
- int mask = (int)Math.pow(10, 9-getTimestampNanoPrecision());
- newTs.setNanos(ts.getNanos()/mask*mask);
- } else {
- newTs.setNanos(0);
- }
- dateObject = newTs;
- }
- return getTypeFacility().convertDate(dateObject, DEFAULT_TIME_ZONE, getDatabaseCalendar(), dateObject.getClass()).toString();
- }
-
- /**
- * Returns true to indicate that SQL should include a comment
- * indicating the session and request ids.
- */
- public boolean addSourceComment() {
- return useCommentsInSourceQuery();
- }
-
- /**
- * Indicates whether group alias should be of the form
- * "...FROM groupA AS X" or "...FROM groupA X". Certain
- * data sources (such as Oracle) may not support the first
- * form.
- * @return boolean
- */
- public boolean useAsInGroupAlias(){
- return true;
- }
-
- /**
- * Use PreparedStatements (or CallableStatements) as
- * appropriate for all commands. Bind values will be
- * determined by the {@link BindValueVisitor}. {@link Literal#setBindValue(boolean)}
- * can be used to force a literal to be a bind value.
- */
- public boolean usePreparedStatements() {
- return useBindVariables();
- }
-
- /**
- * Set to true to indicate that every branch of a set query
- * should have parenthesis, i.e. (query) union (query)
- * @return true if parenthesis should be used for each set branch
- */
- public boolean useParensForSetQueries() {
- return false;
- }
-
- /**
- * Return false to indicate that time support should be emulated
- * with timestamps.
- * @return true if database has a time type
- */
- public boolean hasTimeType() {
- return true;
- }
-
- /**
- * Returns the name for a given {@link Operation}
- * @param operation
- * @return the name for the set operation
- */
- public String getSetOperationString(SetQuery.Operation operation) {
- return operation.toString();
- }
-
- /**
- * Returns the source comment for the given command
- * @param context
- * @param command
- * @return the comment
- */
- public String getSourceComment(ExecutionContext context, Command command) {
- if (addSourceComment() && context != null) {
- return COMMENT.get().format(new Object[] {context.getConnectionIdentifier(), context.getRequestIdentifier(), context.getPartIdentifier()});
- }
- return ""; //$NON-NLS-1$
- }
-
- /**
- * Override to return a name other than the default [group.]element
- * @param group
- * @param element
- * @return thre replacement name
- */
- public String replaceElementName(String group, String element) {
- return null;
- }
-
- /**
- * Return the precision of timestamp literals. Defaults to 9.
- * @return digits of timestamp nano precision.
- */
- public int getTimestampNanoPrecision() {
- return 9;
- }
-
- /**
- * This is a generic implementation. Because different databases handle
- * stored procedures differently, subclasses should override this method
- * if necessary.
- */
- public ResultSet executeStoredProcedure(CallableStatement statement, TranslatedCommand command, Class<?> returnType) throws SQLException {
- List params = command.getPreparedValues();
- int index = 1;
-
- if(returnType != null){
- registerSpecificTypeOfOutParameter(statement, returnType, index++);
- }
-
- Iterator iter = params.iterator();
- while(iter.hasNext()){
- Argument param = (Argument)iter.next();
-
- if(param.getDirection() == Direction.INOUT){
- registerSpecificTypeOfOutParameter(statement,param.getType(), index);
- }else if(param.getDirection() == Direction.OUT){
- registerSpecificTypeOfOutParameter(statement,param.getType(), index++);
- }
-
- if(param.getDirection() == Direction.IN || param.getDirection() == Direction.INOUT){
- bindValue(statement, param.getArgumentValue().getValue(), param.getType(), index++);
- }
- }
- boolean resultSetNext = statement.execute();
-
- while (!resultSetNext) {
- int update_count = statement.getUpdateCount();
- if (update_count == -1) {
- break;
- }
- resultSetNext = statement.getMoreResults();
- }
- return statement.getResultSet();
- }
-
- /**
- * For registering specific output parameter types we need to translate these into the appropriate
- * java.sql.Types output parameters
- * We will need to match these up with the appropriate standard sql types
- * @param cstmt
- * @param parameter
- * @throws SQLException
- */
- protected void registerSpecificTypeOfOutParameter(CallableStatement statement, Class<?> runtimeType, int index) throws SQLException {
- int typeToSet = TypeFacility.getSQLTypeFromRuntimeType(runtimeType);
-
- statement.registerOutParameter(index,typeToSet);
- }
-
- /**
- * Sets prepared statement parameter i with param.
- *
- * Performs special handling to translate dates using the database time zone and to
- * translate biginteger, float, and char to JDBC safe objects.
- *
- * @param stmt
- * @param param
- * @param paramType
- * @param i
- * @param cal
- * @throws SQLException
- */
- public void bindValue(PreparedStatement stmt, Object param, Class<?> paramType, int i) throws SQLException {
- int type = TypeFacility.getSQLTypeFromRuntimeType(paramType);
-
- if (param == null) {
- stmt.setNull(i, type);
- return;
- }
- //if this is a Date object, then use the database calendar
- if (paramType.equals(TypeFacility.RUNTIME_TYPES.DATE)) {
- stmt.setDate(i,(java.sql.Date)param, getDatabaseCalendar());
- return;
- }
- if (paramType.equals(TypeFacility.RUNTIME_TYPES.TIME)) {
- stmt.setTime(i,(java.sql.Time)param, getDatabaseCalendar());
- return;
- }
- if (paramType.equals(TypeFacility.RUNTIME_TYPES.TIMESTAMP)) {
- stmt.setTimestamp(i,(java.sql.Timestamp)param, getDatabaseCalendar());
- return;
- }
- //not all drivers handle the setObject call with BigDecimal correctly (namely jConnect 6.05)
- if (TypeFacility.RUNTIME_TYPES.BIG_DECIMAL.equals(paramType)) {
- stmt.setBigDecimal(i, (BigDecimal)param);
- return;
- }
- //convert these the following to jdbc safe values
- if (TypeFacility.RUNTIME_TYPES.BIG_INTEGER.equals(paramType)) {
- param = new BigDecimal((BigInteger)param);
- } else if (TypeFacility.RUNTIME_TYPES.FLOAT.equals(paramType)) {
- param = new Double(((Float)param).doubleValue());
- } else if (TypeFacility.RUNTIME_TYPES.CHAR.equals(paramType)) {
- param = ((Character)param).toString();
- }
-
- stmt.setObject(i, param, type);
- }
-
- /**
- * Retrieve the value on the current resultset row for the given column index.
- * @param results
- * @param columnIndex
- * @param expectedType
- * @return the value
- * @throws SQLException
- */
- public Object retrieveValue(ResultSet results, int columnIndex, Class<?> expectedType) throws SQLException {
- Integer code = TYPE_CODE_MAP.get(expectedType);
- if(code != null) {
- // Calling the specific methods here is more likely to get uniform (and fast) results from different
- // data sources as the driver likely knows the best and fastest way to convert from the underlying
- // raw form of the data to the expected type. We use a switch with codes in order without gaps
- // as there is a special bytecode instruction that treats this case as a map such that not every value
- // needs to be tested, which means it is very fast.
- switch(code.intValue()) {
- case INTEGER_CODE: {
- int value = results.getInt(columnIndex);
- if(results.wasNull()) {
- return null;
- }
- return Integer.valueOf(value);
- }
- case LONG_CODE: {
- long value = results.getLong(columnIndex);
- if(results.wasNull()) {
- return null;
- }
- return Long.valueOf(value);
- }
- case DOUBLE_CODE: {
- double value = results.getDouble(columnIndex);
- if(results.wasNull()) {
- return null;
- }
- return Double.valueOf(value);
- }
- case BIGDECIMAL_CODE: {
- return results.getBigDecimal(columnIndex);
- }
- case SHORT_CODE: {
- short value = results.getShort(columnIndex);
- if(results.wasNull()) {
- return null;
- }
- return Short.valueOf(value);
- }
- case FLOAT_CODE: {
- float value = results.getFloat(columnIndex);
- if(results.wasNull()) {
- return null;
- }
- return Float.valueOf(value);
- }
- case TIME_CODE: {
- return results.getTime(columnIndex, getDatabaseCalendar());
- }
- case DATE_CODE: {
- return results.getDate(columnIndex, getDatabaseCalendar());
- }
- case TIMESTAMP_CODE: {
- return results.getTimestamp(columnIndex, getDatabaseCalendar());
- }
- case BLOB_CODE: {
- try {
- return results.getBlob(columnIndex);
- } catch (SQLException e) {
- // ignore
- }
- try {
- return results.getBytes(columnIndex);
- } catch (SQLException e) {
- // ignore
- }
- break;
- }
- case CLOB_CODE: {
- try {
- return results.getClob(columnIndex);
- } catch (SQLException e) {
- // ignore
- }
- break;
- }
- case BOOLEAN_CODE: {
- return results.getBoolean(columnIndex);
- }
- }
- }
-
- return results.getObject(columnIndex);
- }
-
- /**
- * Retrieve the value for the given parameter index
- * @param results
- * @param parameterIndex
- * @param expectedType
- * @return the value
- * @throws SQLException
- */
- public Object retrieveValue(CallableStatement results, int parameterIndex, Class<?> expectedType) throws SQLException{
- Integer code = TYPE_CODE_MAP.get(expectedType);
- if(code != null) {
- switch(code.intValue()) {
- case INTEGER_CODE: {
- int value = results.getInt(parameterIndex);
- if(results.wasNull()) {
- return null;
- }
- return Integer.valueOf(value);
- }
- case LONG_CODE: {
- long value = results.getLong(parameterIndex);
- if(results.wasNull()) {
- return null;
- }
- return Long.valueOf(value);
- }
- case DOUBLE_CODE: {
- double value = results.getDouble(parameterIndex);
- if(results.wasNull()) {
- return null;
- }
- return new Double(value);
- }
- case BIGDECIMAL_CODE: {
- return results.getBigDecimal(parameterIndex);
- }
- case SHORT_CODE: {
- short value = results.getShort(parameterIndex);
- if(results.wasNull()) {
- return null;
- }
- return Short.valueOf(value);
- }
- case FLOAT_CODE: {
- float value = results.getFloat(parameterIndex);
- if(results.wasNull()) {
- return null;
- }
- return new Float(value);
- }
- case TIME_CODE: {
- return results.getTime(parameterIndex, getDatabaseCalendar());
- }
- case DATE_CODE: {
- return results.getDate(parameterIndex, getDatabaseCalendar());
- }
- case TIMESTAMP_CODE: {
- return results.getTimestamp(parameterIndex, getDatabaseCalendar());
- }
- case BLOB_CODE: {
- try {
- return results.getBlob(parameterIndex);
- } catch (SQLException e) {
- // ignore
- }
- try {
- return results.getBytes(parameterIndex);
- } catch (SQLException e) {
- // ignore
- }
- }
- case CLOB_CODE: {
- try {
- return results.getClob(parameterIndex);
- } catch (SQLException e) {
- // ignore
- }
- }
- case BOOLEAN_CODE: {
- return results.getBoolean(parameterIndex);
- }
- }
- }
-
- // otherwise fall through and call getObject() and rely on the normal
- // translation routines
- return results.getObject(parameterIndex);
- }
-
- /**
- * Called exactly once for this source.
- * @param connection
- */
- protected void afterInitialConnectionObtained(Connection connection) {
- // now dig some details about this driver/database for log.
- try {
- StringBuffer sb = new StringBuffer(getClass().getSimpleName());
- DatabaseMetaData dbmd = connection.getMetaData();
- sb.append(" Commit=").append(connection.getAutoCommit()); //$NON-NLS-1$
- sb.append(";DatabaseProductName=").append(dbmd.getDatabaseProductName()); //$NON-NLS-1$
- sb.append(";DatabaseProductVersion=").append(dbmd.getDatabaseProductVersion()); //$NON-NLS-1$
- sb.append(";DriverMajorVersion=").append(dbmd.getDriverMajorVersion()); //$NON-NLS-1$
- sb.append(";DriverMajorVersion=").append(dbmd.getDriverMinorVersion()); //$NON-NLS-1$
- sb.append(";DriverName=").append(dbmd.getDriverName()); //$NON-NLS-1$
- sb.append(";DriverVersion=").append(dbmd.getDriverVersion()); //$NON-NLS-1$
- sb.append(";IsolationLevel=").append(dbmd.getDefaultTransactionIsolation()); //$NON-NLS-1$
-
- LogManager.logInfo(LogConstants.CTX_CONNECTOR, sb.toString());
- } catch (SQLException e) {
- String errorStr = JDBCPlugin.Util.getString("ConnectionListener.failed_to_report_jdbc_connection_details"); //$NON-NLS-1$
- LogManager.logInfo(LogConstants.CTX_CONNECTOR, errorStr);
- }
- }
-
- /**
- * Provides a hook to call source specific logic when
- * a connection is obtained.
- *
- * defect request 13979 & 13978
- */
- public void obtainedConnection(Connection connection) {
- if (initialConnection.compareAndSet(true, false)) {
- afterInitialConnectionObtained(connection);
- }
- }
-
-
-
- /**
- * Create the {@link SQLConversionVisitor} that will perform translation. Typical custom
- * JDBC connectors will not need to create custom conversion visitors, rather implementors
- * should override existing {@link JDBCExecutionFactory} methods.
- * @return the {@link SQLConversionVisitor}
- */
- public SQLConversionVisitor getSQLConversionVisitor() {
- return new SQLConversionVisitor(this);
- }
-
- /**
- * Set to true to indicate that every branch of a join
- * should have parenthesis.
- * @return true if every branch of a join should use parenthesis
- */
- public boolean useParensForJoins() {
- return false;
- }
-
- @Override
- public NullOrder getDefaultNullOrder() {
- return NullOrder.LOW;
- }
-
- /**
- * Returns whether the limit clause is applied to the select clause.
- * @return true if the limit clause is part of the select
- */
- public boolean useSelectLimit() {
- return false;
- }
-
- public static List<String> parseName(String tableName, char escape, char delim) {
- boolean quoted = false;
- boolean escaped = false;
- List<String> nameParts = new LinkedList<String>();
- StringBuilder current = new StringBuilder();
- for (int i = 0; i < tableName.length(); i++) {
- char c = tableName.charAt(i);
- if (quoted) {
- if (c == escape) {
- if (escaped) {
- current.append(c);
- }
- escaped = !escaped;
- } else if (c == delim) {
- if (escaped) {
- escaped = false;
- quoted = false;
- nameParts.add(current.toString());
- current = new StringBuilder();
- } else {
- current.append(c);
- }
- } else {
- current.append(c);
- }
- } else {
- if (c == escape) {
- if (current.length() == 0) {
- quoted = true;
- } else {
- current.append(c);
- }
- } else if (c == delim) {
- quoted = false;
- nameParts.add(current.toString());
- current = new StringBuilder();
- } else {
- current.append(c);
- }
- }
- }
- if (current.length() > 0) {
- nameParts.add(current.toString());
- }
- return nameParts;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java (from rev 3218, trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1151 @@
+/*
+ * 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;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.text.MessageFormat;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+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;
+
+import org.teiid.core.util.PropertiesUtils;
+import org.teiid.language.Argument;
+import org.teiid.language.Call;
+import org.teiid.language.ColumnReference;
+import org.teiid.language.Command;
+import org.teiid.language.Expression;
+import org.teiid.language.Function;
+import org.teiid.language.LanguageObject;
+import org.teiid.language.Limit;
+import org.teiid.language.Literal;
+import org.teiid.language.QueryExpression;
+import org.teiid.language.SetQuery;
+import org.teiid.language.Argument.Direction;
+import org.teiid.language.SetQuery.Operation;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.MetadataFactory;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.ExecutionFactory;
+import org.teiid.translator.ProcedureExecution;
+import org.teiid.translator.ResultSetExecution;
+import org.teiid.translator.SourceSystemFunctions;
+import org.teiid.translator.Translator;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.TranslatorProperty;
+import org.teiid.translator.TypeFacility;
+import org.teiid.translator.UpdateExecution;
+
+
+/**
+ * JDBC implementation of Connector interface.
+ */
+ at Translator(name="jdbc-ansi", description="JDBC ANSI translator, can used with any ANSI compatible JDBC Driver")
+public class JDBCExecutionFactory extends ExecutionFactory<DataSource, Connection> {
+
+ public static final int DEFAULT_MAX_IN_CRITERIA = 1000;
+ public static final int DEFAULT_MAX_DEPENDENT_PREDICATES = 50;
+
+ // Because the retrieveValue() method will be hit for every value of
+ // every JDBC result set returned, we do lots of weird special stuff here
+ // to improve the performance (most importantly to remove big if/else checks
+ // of every possible type.
+
+ private static final Map<Class<?>, Integer> TYPE_CODE_MAP = new HashMap<Class<?>, Integer>();
+
+ private static final int INTEGER_CODE = 0;
+ private static final int LONG_CODE = 1;
+ private static final int DOUBLE_CODE = 2;
+ private static final int BIGDECIMAL_CODE = 3;
+ private static final int SHORT_CODE = 4;
+ private static final int FLOAT_CODE = 5;
+ private static final int TIME_CODE = 6;
+ private static final int DATE_CODE = 7;
+ private static final int TIMESTAMP_CODE = 8;
+ private static final int BLOB_CODE = 9;
+ private static final int CLOB_CODE = 10;
+ private static final int BOOLEAN_CODE = 11;
+
+ static {
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.INTEGER, new Integer(INTEGER_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.LONG, new Integer(LONG_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.DOUBLE, new Integer(DOUBLE_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.BIG_DECIMAL, new Integer(BIGDECIMAL_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.SHORT, new Integer(SHORT_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.FLOAT, new Integer(FLOAT_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.TIME, new Integer(TIME_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.DATE, new Integer(DATE_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.TIMESTAMP, new Integer(TIMESTAMP_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.BLOB, new Integer(BLOB_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.CLOB, new Integer(CLOB_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.BOOLEAN, new Integer(BOOLEAN_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.BYTE, new Integer(SHORT_CODE));
+ }
+
+ private static final ThreadLocal<MessageFormat> COMMENT = new ThreadLocal<MessageFormat>() {
+ protected MessageFormat initialValue() {
+ return new MessageFormat("/*teiid sessionid:{0}, requestid:{1}.{2}*/ "); //$NON-NLS-1$
+ }
+ };
+ public final static TimeZone DEFAULT_TIME_ZONE = TimeZone.getDefault();
+
+ static class DatbaseCalender extends ThreadLocal<Calendar> {
+ private String timeZone;
+ public DatbaseCalender(String tz) {
+ this.timeZone = tz;
+ }
+ @Override
+ protected Calendar initialValue() {
+ if(this.timeZone != null && this.timeZone.trim().length() > 0) {
+ TimeZone tz = TimeZone.getTimeZone(this.timeZone);
+ if(!DEFAULT_TIME_ZONE.hasSameRules(tz)) {
+ return Calendar.getInstance(tz);
+ }
+ }
+ return Calendar.getInstance();
+ }
+ };
+
+ private Map<String, FunctionModifier> functionModifiers = new TreeMap<String, FunctionModifier>(String.CASE_INSENSITIVE_ORDER);
+
+ private boolean useBindVariables = true;
+ private String databaseTimeZone;
+ private boolean trimStrings;
+ private boolean useCommentsInSourceQuery;
+ private String version;
+ private int maxInsertBatchSize = 2048;
+ private DatbaseCalender databaseCalender;
+
+ private AtomicBoolean initialConnection = new AtomicBoolean(true);
+
+ public JDBCExecutionFactory() {
+ setSupportsFullOuterJoins(true);
+ setSupportsOrderBy(true);
+ setSupportsOuterJoins(true);
+ setSupportsSelectDistinct(true);
+ setSupportsInnerJoins(true);
+ setMaxInCriteriaSize(DEFAULT_MAX_IN_CRITERIA);
+ setMaxDependentInPredicates(DEFAULT_MAX_DEPENDENT_PREDICATES);
+ }
+
+ @Override
+ public void start() throws TranslatorException {
+ super.start();
+ this.databaseCalender = new DatbaseCalender(this.databaseTimeZone);
+ }
+
+ @TranslatorProperty(display="Database Version", description= "Database Version")
+ public String getDatabaseVersion() {
+ return this.version;
+ }
+
+ public void setDatabaseVersion(String version) {
+ this.version = version;
+ }
+
+ @TranslatorProperty(display="Use Bind Variables", description="Use prepared statements and bind variables",advanced=true)
+ public boolean useBindVariables() {
+ return this.useBindVariables;
+ }
+
+ public void setUseBindVariables(boolean useBindVariables) {
+ this.useBindVariables = useBindVariables;
+ }
+
+ @TranslatorProperty(display="Database time zone", description="Time zone of the database, if different than Integration Server", advanced=true)
+ public String getDatabaseTimeZone() {
+ return this.databaseTimeZone;
+ }
+
+ public void setDatabaseTimeZone(String databaseTimeZone) {
+ this.databaseTimeZone = databaseTimeZone;
+ }
+
+ @TranslatorProperty(display="Trim string flag", description="Right Trim fixed character types returned as Strings - note that the native type must be char or nchar and the source must support the rtrim function.",advanced=true)
+ public boolean isTrimStrings() {
+ return this.trimStrings;
+ }
+
+ public void setTrimStrings(boolean trimStrings) {
+ this.trimStrings = trimStrings;
+ }
+
+ @TranslatorProperty(display="Use informational comments in Source Queries", description="This will embed a /*comment*/ leading comment with session/request id in source SQL query for informational purposes", advanced=true)
+ public boolean useCommentsInSourceQuery() {
+ return this.useCommentsInSourceQuery;
+ }
+
+ public void setUseCommentsInSourceQuery(boolean useCommentsInSourceQuery) {
+ this.useCommentsInSourceQuery = useCommentsInSourceQuery;
+ }
+
+ @Override
+ public boolean isSourceRequired() {
+ return true;
+ }
+
+ @Override
+ public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, Connection conn)
+ throws TranslatorException {
+ //TODO: This is not correct; this should be only called once for connection creation
+ obtainedConnection(conn);
+ return new JDBCQueryExecution(command, conn, executionContext, this);
+ }
+
+ @Override
+ public ProcedureExecution createProcedureExecution(Call command, ExecutionContext executionContext, RuntimeMetadata metadata, Connection conn)
+ throws TranslatorException {
+ //TODO: This is not correct; this should be only called once for connection creation
+ obtainedConnection(conn);
+ return new JDBCProcedureExecution(command, conn, executionContext, this);
+ }
+
+ @Override
+ public UpdateExecution createUpdateExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, Connection conn)
+ throws TranslatorException {
+ //TODO: This is not correct; this should be only called once for connection creation
+ obtainedConnection(conn);
+ return new JDBCUpdateExecution(command, conn, executionContext, this);
+ }
+
+ @Override
+ public Connection getConnection(DataSource ds)
+ throws TranslatorException {
+ try {
+ return ds.getConnection();
+ } catch (SQLException e) {
+ throw new TranslatorException(e);
+ }
+ }
+
+ @Override
+ public void closeConnection(Connection connection, DataSource factory) {
+ if (connection == null) {
+ return;
+ }
+ try {
+ connection.close();
+ } catch (SQLException e) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, e, "Error closing"); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ public void getMetadata(MetadataFactory metadataFactory, Connection conn) throws TranslatorException {
+ try {
+ JDBCMetdataProcessor metadataProcessor = new JDBCMetdataProcessor();
+ PropertiesUtils.setBeanProperties(metadataProcessor, metadataFactory.getImportProperties(), "importer"); //$NON-NLS-1$
+ metadataProcessor.getConnectorMetadata(conn, metadataFactory);
+ } catch (SQLException e) {
+ throw new TranslatorException(e);
+ }
+ }
+
+ @Override
+ public List<String> getSupportedFunctions() {
+ return getDefaultSupportedFunctions();
+ }
+
+ public List<String> getDefaultSupportedFunctions(){
+ return Arrays.asList(new String[] { "+", "-", "*", "/" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Override
+ public boolean supportsGroupBy() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsAggregatesAvg() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsAggregatesCount() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsAggregatesCountStar() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsAggregatesDistinct() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsAggregatesMax() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsAggregatesMin() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsAggregatesSum() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsAliasedTable() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsBetweenCriteria() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsCaseExpressions() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsCompareCriteriaEquals() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsCorrelatedSubqueries() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsExistsCriteria() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsInCriteria() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsInCriteriaSubquery() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsIsNullCriteria() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsLikeCriteria() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsLikeCriteriaEscapeCharacter() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsNotCriteria() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsOrCriteria() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsOrderByUnrelated() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsQuantifiedCompareCriteriaAll() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsScalarSubqueries() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsSearchedCaseExpressions() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsSelfJoins() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsInlineViews() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsQuantifiedCompareCriteriaSome() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsSetQueryOrderBy() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsUnions() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsBulkUpdate() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsInsertWithIterator() {
+ return super.supportsBulkUpdate();
+ }
+
+ @Override
+ public boolean supportsBatchedUpdates() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsCompareCriteriaOrdered() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsHaving() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsSelectExpression() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsInsertWithQueryExpression() {
+ return true;
+ }
+
+ /**
+ * Get the max number of inserts to perform in one batch.
+ * @return
+ */
+ @TranslatorProperty(display="Max Prepared Insert Batch Size", description="The max size of a prepared insert batch. Default 2048.", advanced=true)
+ public int getMaxPreparedInsertBatchSize() {
+ return maxInsertBatchSize;
+ }
+
+ public void setMaxPreparedInsertBatchSize(int maxInsertBatchSize) {
+ if (maxInsertBatchSize < 1) {
+ throw new AssertionError("Max prepared batch insert size must be greater than 0"); //$NON-NLS-1$
+ }
+ this.maxInsertBatchSize = maxInsertBatchSize;
+ }
+
+ /**
+ * Gets the database calendar. This will be set to the time zone
+ * specified by the property {@link JDBCPropertyNames#DATABASE_TIME_ZONE}, or
+ * the local time zone if none is specified.
+ * @return the database calendar
+ */
+ public Calendar getDatabaseCalendar() {
+ return this.databaseCalender.get();
+ }
+
+ /**
+ * Return a List of translated parts ({@link LanguageObject}s and Objects), or null
+ * if to rely on the default translation. Override with care.
+ * @param command
+ * @param context
+ * @return list of translated parts
+ */
+ public List<?> translate(LanguageObject obj, ExecutionContext context) {
+ List<?> parts = null;
+ if (obj instanceof Function) {
+ Function function = (Function)obj;
+ if (functionModifiers != null) {
+ 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) {
+ parts = translateCommand((Command)obj, context);
+ } else if (obj instanceof Limit) {
+ parts = translateLimit((Limit)obj, context);
+ } else if (obj instanceof ColumnReference) {
+ ColumnReference elem = (ColumnReference)obj;
+ if (isTrimStrings() && elem.getType() == TypeFacility.RUNTIME_TYPES.STRING && elem.getMetadataObject() != null
+ && ("char".equalsIgnoreCase(elem.getMetadataObject().getNativeType()) || "nchar".equalsIgnoreCase(elem.getMetadataObject().getNativeType()))) { //$NON-NLS-1$ //$NON-NLS-2$
+ return Arrays.asList(getLanguageFactory().createFunction(SourceSystemFunctions.RTRIM, new Expression[] {elem}, TypeFacility.RUNTIME_TYPES.STRING));
+ }
+ }
+ return parts;
+ }
+
+ /**
+ * Return a List of translated parts ({@link LanguageObject}s and Objects), or null
+ * if to rely on the default translation.
+ * @param command
+ * @param context
+ * @return a list of translated parts
+ */
+ public List<?> translateCommand(Command command, ExecutionContext context) {
+ return null;
+ }
+
+ /**
+ * Return a List of translated parts ({@link LanguageObject}s and Objects), or null
+ * if to rely on the default translation.
+ * @param limit
+ * @param context
+ * @return a list of translated parts
+ */
+ public List<?> translateLimit(Limit limit, ExecutionContext context) {
+ return null;
+ }
+
+ /**
+ * Return a map of function name to FunctionModifier.
+ * @return Map of function name to FunctionModifier.
+ */
+ public Map<String, FunctionModifier> getFunctionModifiers() {
+ return functionModifiers;
+ }
+
+ /**
+ * Add the {@link FunctionModifier} to the set of known modifiers.
+ * @param name
+ * @param modifier
+ */
+ public void registerFunctionModifier(String name, FunctionModifier modifier) {
+ this.functionModifiers.put(name, modifier);
+ }
+
+ /**
+ * Subclasses should override this method to provide a different sql translation
+ * of the literal boolean value. By default, a boolean literal is represented as:
+ * <code>'0'</code> or <code>'1'</code>.
+ * @param booleanValue Boolean value, never null
+ * @return Translated string
+ */
+ public String translateLiteralBoolean(Boolean booleanValue) {
+ if(booleanValue.booleanValue()) {
+ return "1"; //$NON-NLS-1$
+ }
+ return "0"; //$NON-NLS-1$
+ }
+
+ /**
+ * Subclasses should override this method to provide a different sql translation
+ * of the literal date value. By default, a date literal is represented as:
+ * <code>{d '2002-12-31'}</code>
+ * @param dateValue Date value, never null
+ * @return Translated string
+ */
+ public String translateLiteralDate(java.sql.Date dateValue) {
+ return "{d '" + formatDateValue(dateValue) + "'}"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Subclasses should override this method to provide a different sql translation
+ * of the literal time value. By default, a time literal is represented as:
+ * <code>{t '23:59:59'}</code>
+ *
+ * See {@link JDBCExecutionFactory#hasTimeType()} to represent literal times as timestamps.
+ *
+ * @param timeValue Time value, never null
+ * @return Translated string
+ */
+ public String translateLiteralTime(Time timeValue) {
+ if (!hasTimeType()) {
+ return translateLiteralTimestamp(new Timestamp(timeValue.getTime()));
+ }
+ return "{t '" + formatDateValue(timeValue) + "'}"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Subclasses should override this method to provide a different sql translation
+ * of the literal timestamp value. By default, a timestamp literal is
+ * represented as: <code>{ts '2002-12-31 23:59:59'}</code>.
+ *
+ * See {@link JDBCExecutionFactory#getTimestampNanoPrecision()} to control the literal
+ * precision.
+ *
+ * @param timestampValue Timestamp value, never null
+ * @return Translated string
+ */
+ public String translateLiteralTimestamp(Timestamp timestampValue) {
+ return "{ts '" + formatDateValue(timestampValue) + "'}"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Format the dateObject (of type date, time, or timestamp) into a string
+ * using the DatabaseTimeZone format.
+ * @param dateObject
+ * @return Formatted string
+ */
+ public String formatDateValue(java.util.Date dateObject) {
+ if (dateObject instanceof Timestamp && getTimestampNanoPrecision() < 9) {
+ Timestamp ts = (Timestamp)dateObject;
+ Timestamp newTs = new Timestamp(ts.getTime());
+ if (getTimestampNanoPrecision() > 0) {
+ int mask = (int)Math.pow(10, 9-getTimestampNanoPrecision());
+ newTs.setNanos(ts.getNanos()/mask*mask);
+ } else {
+ newTs.setNanos(0);
+ }
+ dateObject = newTs;
+ }
+ return getTypeFacility().convertDate(dateObject, DEFAULT_TIME_ZONE, getDatabaseCalendar(), dateObject.getClass()).toString();
+ }
+
+ /**
+ * Returns true to indicate that SQL should include a comment
+ * indicating the session and request ids.
+ */
+ public boolean addSourceComment() {
+ return useCommentsInSourceQuery();
+ }
+
+ /**
+ * Indicates whether group alias should be of the form
+ * "...FROM groupA AS X" or "...FROM groupA X". Certain
+ * data sources (such as Oracle) may not support the first
+ * form.
+ * @return boolean
+ */
+ public boolean useAsInGroupAlias(){
+ return true;
+ }
+
+ /**
+ * Use PreparedStatements (or CallableStatements) as
+ * appropriate for all commands. Bind values will be
+ * determined by the {@link BindValueVisitor}. {@link Literal#setBindValue(boolean)}
+ * can be used to force a literal to be a bind value.
+ */
+ public boolean usePreparedStatements() {
+ return useBindVariables();
+ }
+
+ /**
+ * Set to true to indicate that every branch of a set query
+ * should have parenthesis, i.e. (query) union (query)
+ * @return true if parenthesis should be used for each set branch
+ */
+ public boolean useParensForSetQueries() {
+ return false;
+ }
+
+ /**
+ * Return false to indicate that time support should be emulated
+ * with timestamps.
+ * @return true if database has a time type
+ */
+ public boolean hasTimeType() {
+ return true;
+ }
+
+ /**
+ * Returns the name for a given {@link Operation}
+ * @param operation
+ * @return the name for the set operation
+ */
+ public String getSetOperationString(SetQuery.Operation operation) {
+ return operation.toString();
+ }
+
+ /**
+ * Returns the source comment for the given command
+ * @param context
+ * @param command
+ * @return the comment
+ */
+ public String getSourceComment(ExecutionContext context, Command command) {
+ if (addSourceComment() && context != null) {
+ return COMMENT.get().format(new Object[] {context.getConnectionIdentifier(), context.getRequestIdentifier(), context.getPartIdentifier()});
+ }
+ return ""; //$NON-NLS-1$
+ }
+
+ /**
+ * Override to return a name other than the default [group.]element
+ * @param group
+ * @param element
+ * @return thre replacement name
+ */
+ public String replaceElementName(String group, String element) {
+ return null;
+ }
+
+ /**
+ * Return the precision of timestamp literals. Defaults to 9.
+ * @return digits of timestamp nano precision.
+ */
+ public int getTimestampNanoPrecision() {
+ return 9;
+ }
+
+ /**
+ * This is a generic implementation. Because different databases handle
+ * stored procedures differently, subclasses should override this method
+ * if necessary.
+ */
+ public ResultSet executeStoredProcedure(CallableStatement statement, TranslatedCommand command, Class<?> returnType) throws SQLException {
+ List params = command.getPreparedValues();
+ int index = 1;
+
+ if(returnType != null){
+ registerSpecificTypeOfOutParameter(statement, returnType, index++);
+ }
+
+ Iterator iter = params.iterator();
+ while(iter.hasNext()){
+ Argument param = (Argument)iter.next();
+
+ if(param.getDirection() == Direction.INOUT){
+ registerSpecificTypeOfOutParameter(statement,param.getType(), index);
+ }else if(param.getDirection() == Direction.OUT){
+ registerSpecificTypeOfOutParameter(statement,param.getType(), index++);
+ }
+
+ if(param.getDirection() == Direction.IN || param.getDirection() == Direction.INOUT){
+ bindValue(statement, param.getArgumentValue().getValue(), param.getType(), index++);
+ }
+ }
+ boolean resultSetNext = statement.execute();
+
+ while (!resultSetNext) {
+ int update_count = statement.getUpdateCount();
+ if (update_count == -1) {
+ break;
+ }
+ resultSetNext = statement.getMoreResults();
+ }
+ return statement.getResultSet();
+ }
+
+ /**
+ * For registering specific output parameter types we need to translate these into the appropriate
+ * java.sql.Types output parameters
+ * We will need to match these up with the appropriate standard sql types
+ * @param cstmt
+ * @param parameter
+ * @throws SQLException
+ */
+ protected void registerSpecificTypeOfOutParameter(CallableStatement statement, Class<?> runtimeType, int index) throws SQLException {
+ int typeToSet = TypeFacility.getSQLTypeFromRuntimeType(runtimeType);
+
+ statement.registerOutParameter(index,typeToSet);
+ }
+
+ /**
+ * Sets prepared statement parameter i with param.
+ *
+ * Performs special handling to translate dates using the database time zone and to
+ * translate biginteger, float, and char to JDBC safe objects.
+ *
+ * @param stmt
+ * @param param
+ * @param paramType
+ * @param i
+ * @param cal
+ * @throws SQLException
+ */
+ public void bindValue(PreparedStatement stmt, Object param, Class<?> paramType, int i) throws SQLException {
+ int type = TypeFacility.getSQLTypeFromRuntimeType(paramType);
+
+ if (param == null) {
+ stmt.setNull(i, type);
+ return;
+ }
+ //if this is a Date object, then use the database calendar
+ if (paramType.equals(TypeFacility.RUNTIME_TYPES.DATE)) {
+ stmt.setDate(i,(java.sql.Date)param, getDatabaseCalendar());
+ return;
+ }
+ if (paramType.equals(TypeFacility.RUNTIME_TYPES.TIME)) {
+ stmt.setTime(i,(java.sql.Time)param, getDatabaseCalendar());
+ return;
+ }
+ if (paramType.equals(TypeFacility.RUNTIME_TYPES.TIMESTAMP)) {
+ stmt.setTimestamp(i,(java.sql.Timestamp)param, getDatabaseCalendar());
+ return;
+ }
+ //not all drivers handle the setObject call with BigDecimal correctly (namely jConnect 6.05)
+ if (TypeFacility.RUNTIME_TYPES.BIG_DECIMAL.equals(paramType)) {
+ stmt.setBigDecimal(i, (BigDecimal)param);
+ return;
+ }
+ //convert these the following to jdbc safe values
+ if (TypeFacility.RUNTIME_TYPES.BIG_INTEGER.equals(paramType)) {
+ param = new BigDecimal((BigInteger)param);
+ } else if (TypeFacility.RUNTIME_TYPES.FLOAT.equals(paramType)) {
+ param = new Double(((Float)param).doubleValue());
+ } else if (TypeFacility.RUNTIME_TYPES.CHAR.equals(paramType)) {
+ param = ((Character)param).toString();
+ }
+
+ stmt.setObject(i, param, type);
+ }
+
+ /**
+ * Retrieve the value on the current resultset row for the given column index.
+ * @param results
+ * @param columnIndex
+ * @param expectedType
+ * @return the value
+ * @throws SQLException
+ */
+ public Object retrieveValue(ResultSet results, int columnIndex, Class<?> expectedType) throws SQLException {
+ Integer code = TYPE_CODE_MAP.get(expectedType);
+ if(code != null) {
+ // Calling the specific methods here is more likely to get uniform (and fast) results from different
+ // data sources as the driver likely knows the best and fastest way to convert from the underlying
+ // raw form of the data to the expected type. We use a switch with codes in order without gaps
+ // as there is a special bytecode instruction that treats this case as a map such that not every value
+ // needs to be tested, which means it is very fast.
+ switch(code.intValue()) {
+ case INTEGER_CODE: {
+ int value = results.getInt(columnIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Integer.valueOf(value);
+ }
+ case LONG_CODE: {
+ long value = results.getLong(columnIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Long.valueOf(value);
+ }
+ case DOUBLE_CODE: {
+ double value = results.getDouble(columnIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Double.valueOf(value);
+ }
+ case BIGDECIMAL_CODE: {
+ return results.getBigDecimal(columnIndex);
+ }
+ case SHORT_CODE: {
+ short value = results.getShort(columnIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Short.valueOf(value);
+ }
+ case FLOAT_CODE: {
+ float value = results.getFloat(columnIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Float.valueOf(value);
+ }
+ case TIME_CODE: {
+ return results.getTime(columnIndex, getDatabaseCalendar());
+ }
+ case DATE_CODE: {
+ return results.getDate(columnIndex, getDatabaseCalendar());
+ }
+ case TIMESTAMP_CODE: {
+ return results.getTimestamp(columnIndex, getDatabaseCalendar());
+ }
+ case BLOB_CODE: {
+ try {
+ return results.getBlob(columnIndex);
+ } catch (SQLException e) {
+ // ignore
+ }
+ try {
+ return results.getBytes(columnIndex);
+ } catch (SQLException e) {
+ // ignore
+ }
+ break;
+ }
+ case CLOB_CODE: {
+ try {
+ return results.getClob(columnIndex);
+ } catch (SQLException e) {
+ // ignore
+ }
+ break;
+ }
+ case BOOLEAN_CODE: {
+ return results.getBoolean(columnIndex);
+ }
+ }
+ }
+
+ return results.getObject(columnIndex);
+ }
+
+ /**
+ * Retrieve the value for the given parameter index
+ * @param results
+ * @param parameterIndex
+ * @param expectedType
+ * @return the value
+ * @throws SQLException
+ */
+ public Object retrieveValue(CallableStatement results, int parameterIndex, Class<?> expectedType) throws SQLException{
+ Integer code = TYPE_CODE_MAP.get(expectedType);
+ if(code != null) {
+ switch(code.intValue()) {
+ case INTEGER_CODE: {
+ int value = results.getInt(parameterIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Integer.valueOf(value);
+ }
+ case LONG_CODE: {
+ long value = results.getLong(parameterIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Long.valueOf(value);
+ }
+ case DOUBLE_CODE: {
+ double value = results.getDouble(parameterIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return new Double(value);
+ }
+ case BIGDECIMAL_CODE: {
+ return results.getBigDecimal(parameterIndex);
+ }
+ case SHORT_CODE: {
+ short value = results.getShort(parameterIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Short.valueOf(value);
+ }
+ case FLOAT_CODE: {
+ float value = results.getFloat(parameterIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return new Float(value);
+ }
+ case TIME_CODE: {
+ return results.getTime(parameterIndex, getDatabaseCalendar());
+ }
+ case DATE_CODE: {
+ return results.getDate(parameterIndex, getDatabaseCalendar());
+ }
+ case TIMESTAMP_CODE: {
+ return results.getTimestamp(parameterIndex, getDatabaseCalendar());
+ }
+ case BLOB_CODE: {
+ try {
+ return results.getBlob(parameterIndex);
+ } catch (SQLException e) {
+ // ignore
+ }
+ try {
+ return results.getBytes(parameterIndex);
+ } catch (SQLException e) {
+ // ignore
+ }
+ }
+ case CLOB_CODE: {
+ try {
+ return results.getClob(parameterIndex);
+ } catch (SQLException e) {
+ // ignore
+ }
+ }
+ case BOOLEAN_CODE: {
+ return results.getBoolean(parameterIndex);
+ }
+ }
+ }
+
+ // otherwise fall through and call getObject() and rely on the normal
+ // translation routines
+ return results.getObject(parameterIndex);
+ }
+
+ /**
+ * Called exactly once for this source.
+ * @param connection
+ */
+ protected void afterInitialConnectionObtained(Connection connection) {
+ // now dig some details about this driver/database for log.
+ try {
+ StringBuffer sb = new StringBuffer(getClass().getSimpleName());
+ DatabaseMetaData dbmd = connection.getMetaData();
+ sb.append(" Commit=").append(connection.getAutoCommit()); //$NON-NLS-1$
+ sb.append(";DatabaseProductName=").append(dbmd.getDatabaseProductName()); //$NON-NLS-1$
+ sb.append(";DatabaseProductVersion=").append(dbmd.getDatabaseProductVersion()); //$NON-NLS-1$
+ sb.append(";DriverMajorVersion=").append(dbmd.getDriverMajorVersion()); //$NON-NLS-1$
+ sb.append(";DriverMajorVersion=").append(dbmd.getDriverMinorVersion()); //$NON-NLS-1$
+ sb.append(";DriverName=").append(dbmd.getDriverName()); //$NON-NLS-1$
+ sb.append(";DriverVersion=").append(dbmd.getDriverVersion()); //$NON-NLS-1$
+ sb.append(";IsolationLevel=").append(dbmd.getDefaultTransactionIsolation()); //$NON-NLS-1$
+
+ LogManager.logInfo(LogConstants.CTX_CONNECTOR, sb.toString());
+ } catch (SQLException e) {
+ String errorStr = JDBCPlugin.Util.getString("ConnectionListener.failed_to_report_jdbc_connection_details"); //$NON-NLS-1$
+ LogManager.logInfo(LogConstants.CTX_CONNECTOR, errorStr);
+ }
+ }
+
+ /**
+ * Provides a hook to call source specific logic when
+ * a connection is obtained.
+ *
+ * defect request 13979 & 13978
+ */
+ public void obtainedConnection(Connection connection) {
+ if (initialConnection.compareAndSet(true, false)) {
+ afterInitialConnectionObtained(connection);
+ }
+ }
+
+
+
+ /**
+ * Create the {@link SQLConversionVisitor} that will perform translation. Typical custom
+ * JDBC connectors will not need to create custom conversion visitors, rather implementors
+ * should override existing {@link JDBCExecutionFactory} methods.
+ * @return the {@link SQLConversionVisitor}
+ */
+ public SQLConversionVisitor getSQLConversionVisitor() {
+ return new SQLConversionVisitor(this);
+ }
+
+ /**
+ * Set to true to indicate that every branch of a join
+ * should have parenthesis.
+ * @return true if every branch of a join should use parenthesis
+ */
+ public boolean useParensForJoins() {
+ return false;
+ }
+
+ @Override
+ public NullOrder getDefaultNullOrder() {
+ return NullOrder.LOW;
+ }
+
+ /**
+ * Returns whether the limit clause is applied to the select clause.
+ * @return true if the limit clause is part of the select
+ */
+ public boolean useSelectLimit() {
+ return false;
+ }
+
+ public static List<String> parseName(String tableName, char escape, char delim) {
+ boolean quoted = false;
+ boolean escaped = false;
+ List<String> nameParts = new LinkedList<String>();
+ StringBuilder current = new StringBuilder();
+ for (int i = 0; i < tableName.length(); i++) {
+ char c = tableName.charAt(i);
+ if (quoted) {
+ if (c == escape) {
+ if (escaped) {
+ current.append(c);
+ }
+ escaped = !escaped;
+ } else if (c == delim) {
+ if (escaped) {
+ escaped = false;
+ quoted = false;
+ nameParts.add(current.toString());
+ current = new StringBuilder();
+ } else {
+ current.append(c);
+ }
+ } else {
+ current.append(c);
+ }
+ } else {
+ if (c == escape) {
+ if (current.length() == 0) {
+ quoted = true;
+ } else {
+ current.append(c);
+ }
+ } else if (c == delim) {
+ quoted = false;
+ nameParts.add(current.toString());
+ current = new StringBuilder();
+ } else {
+ current.append(c);
+ }
+ }
+ }
+ if (current.length() > 0) {
+ nameParts.add(current.toString());
+ }
+ return nameParts;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ingres/IngresExecutionFactory.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ingres/IngresExecutionFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ingres/IngresExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,277 +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.ingres;
-
-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.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;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.jdbc.AliasModifier;
-import org.teiid.translator.jdbc.ConvertModifier;
-import org.teiid.translator.jdbc.FunctionModifier;
-import org.teiid.translator.jdbc.JDBCExecutionFactory;
-
- at Translator(name="ingres", description="A translator for Ingres Databases")
-public class IngresExecutionFactory extends JDBCExecutionFactory {
-
- private static final String INGRES = "ingres"; //$NON-NLS-1$
- protected ConvertModifier convert = new ConvertModifier();
-
- @Override
- public void start() throws TranslatorException {
- super.start();
- convert.addTypeMapping("tinyint", FunctionModifier.BOOLEAN, FunctionModifier.BYTE); //$NON-NLS-1$
- convert.addTypeMapping("smallint", FunctionModifier.SHORT); //$NON-NLS-1$
- convert.addTypeMapping("integer", FunctionModifier.INTEGER); //$NON-NLS-1$
- convert.addTypeMapping("bigint", FunctionModifier.LONG); //$NON-NLS-1$
- convert.addTypeMapping("real", FunctionModifier.FLOAT); //$NON-NLS-1$
- convert.addTypeMapping("float", FunctionModifier.DOUBLE); //$NON-NLS-1$
- convert.addTypeMapping("decimal(38,19)", FunctionModifier.BIGDECIMAL); //$NON-NLS-1$
- convert.addTypeMapping("decimal(15,0)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$
- convert.addTypeMapping("date", FunctionModifier.DATE); //$NON-NLS-1$
- convert.addTypeMapping("time with time zone", FunctionModifier.TIME); //$NON-NLS-1$
- convert.addTypeMapping("timestamp with time zone", FunctionModifier.TIMESTAMP); //$NON-NLS-1$
- convert.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
- convert.addTypeMapping("varchar(4000)", FunctionModifier.STRING); //$NON-NLS-1$
- convert.addTypeMapping("blob", FunctionModifier.BLOB); //$NON-NLS-1$
- convert.addTypeMapping("clob", FunctionModifier.CLOB); //$NON-NLS-1$
- convert.addNumericBooleanConversions();
- registerFunctionModifier(SourceSystemFunctions.CONVERT, convert);
-
- registerFunctionModifier(SourceSystemFunctions.BITAND, new AliasModifier("bit_and")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.BITNOT, new AliasModifier("bit_not")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.BITOR, new AliasModifier("bit_or")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.BITXOR, new AliasModifier("bit_xor")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.CURTIME, new AliasModifier("current_time")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.CURDATE, new AliasModifier("current_date")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.LCASE, new AliasModifier("lowercase")); //$NON-NLS-1$
- 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()));
- }
-
- @Override
- public List<String> getSupportedFunctions() {
- List<String> supportedFunctions = new ArrayList<String>();
- supportedFunctions.addAll(super.getSupportedFunctions());
-
- supportedFunctions.add(SourceSystemFunctions.ABS);
- supportedFunctions.add(SourceSystemFunctions.ATAN);
- supportedFunctions.add(SourceSystemFunctions.BITAND);
- supportedFunctions.add(SourceSystemFunctions.BITNOT);
- supportedFunctions.add(SourceSystemFunctions.BITOR);
- supportedFunctions.add(SourceSystemFunctions.BITXOR);
- supportedFunctions.add(SourceSystemFunctions.CONCAT);
- supportedFunctions.add(SourceSystemFunctions.COS);
- supportedFunctions.add(SourceSystemFunctions.CONVERT);
- supportedFunctions.add(SourceSystemFunctions.CURTIME);
- supportedFunctions.add(SourceSystemFunctions.CURDATE);
- supportedFunctions.add(SourceSystemFunctions.DAYOFMONTH);
- supportedFunctions.add(SourceSystemFunctions.EXP);
- supportedFunctions.add(SourceSystemFunctions.HOUR);
- supportedFunctions.add(SourceSystemFunctions.LCASE);
- supportedFunctions.add(SourceSystemFunctions.LEFT);
- supportedFunctions.add(SourceSystemFunctions.LPAD);
- supportedFunctions.add(SourceSystemFunctions.LOCATE);
- supportedFunctions.add(SourceSystemFunctions.LENGTH);
- supportedFunctions.add(SourceSystemFunctions.LOG);
- supportedFunctions.add(SourceSystemFunctions.MINUTE);
- supportedFunctions.add(SourceSystemFunctions.MONTH);
- supportedFunctions.add(SourceSystemFunctions.POWER);
- supportedFunctions.add(SourceSystemFunctions.RAND);
- supportedFunctions.add(SourceSystemFunctions.RIGHT);
- supportedFunctions.add(SourceSystemFunctions.RPAD);
- supportedFunctions.add(SourceSystemFunctions.SECOND);
- supportedFunctions.add(SourceSystemFunctions.SIN);
- supportedFunctions.add(SourceSystemFunctions.SQRT);
- supportedFunctions.add(SourceSystemFunctions.SUBSTRING);
- supportedFunctions.add(SourceSystemFunctions.YEAR);
- supportedFunctions.add(SourceSystemFunctions.UCASE);
-
- return supportedFunctions;
- }
-
- @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;
- }
-
- @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 String translateLiteralDate(Date dateValue) {
- return "DATE '" + formatDateValue(dateValue) + "'"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- @Override
- public String translateLiteralTime(Time timeValue) {
- return "TIME '" + formatDateValue(timeValue) + "'"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- @Override
- public String translateLiteralTimestamp(Timestamp timestampValue) {
- return "TIMESTAMP '" + formatDateValue(timestampValue) + "'"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- @Override
- public NullOrder getDefaultNullOrder() {
- return NullOrder.LAST;
- }
-
- @Override
- public boolean supportsInlineViews() {
- return true;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ingres/IngresExecutionFactory.java (from rev 3218, trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ingres/IngresExecutionFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ingres/IngresExecutionFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ingres/IngresExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,197 @@
+/*
+ * 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.ingres;
+
+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.List;
+
+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.FunctionModifier;
+import org.teiid.translator.jdbc.JDBCExecutionFactory;
+ at Translator(name="ingres", description="A translator for Ingres Databases")
+public class IngresExecutionFactory extends JDBCExecutionFactory {
+
+ private static final String INGRES = "ingres"; //$NON-NLS-1$
+ protected ConvertModifier convert = new ConvertModifier();
+
+ @Override
+ public void start() throws TranslatorException {
+ super.start();
+ convert.addTypeMapping("tinyint", FunctionModifier.BOOLEAN, FunctionModifier.BYTE); //$NON-NLS-1$
+ convert.addTypeMapping("smallint", FunctionModifier.SHORT); //$NON-NLS-1$
+ convert.addTypeMapping("integer", FunctionModifier.INTEGER); //$NON-NLS-1$
+ convert.addTypeMapping("bigint", FunctionModifier.LONG); //$NON-NLS-1$
+ convert.addTypeMapping("real", FunctionModifier.FLOAT); //$NON-NLS-1$
+ convert.addTypeMapping("float", FunctionModifier.DOUBLE); //$NON-NLS-1$
+ convert.addTypeMapping("decimal(38,19)", FunctionModifier.BIGDECIMAL); //$NON-NLS-1$
+ convert.addTypeMapping("decimal(15,0)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$
+ convert.addTypeMapping("date", FunctionModifier.DATE); //$NON-NLS-1$
+ convert.addTypeMapping("time with time zone", FunctionModifier.TIME); //$NON-NLS-1$
+ convert.addTypeMapping("timestamp with time zone", FunctionModifier.TIMESTAMP); //$NON-NLS-1$
+ convert.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
+ convert.addTypeMapping("varchar(4000)", FunctionModifier.STRING); //$NON-NLS-1$
+ convert.addTypeMapping("blob", FunctionModifier.BLOB); //$NON-NLS-1$
+ convert.addTypeMapping("clob", FunctionModifier.CLOB); //$NON-NLS-1$
+ convert.addNumericBooleanConversions();
+ registerFunctionModifier(SourceSystemFunctions.CONVERT, convert);
+
+ registerFunctionModifier(SourceSystemFunctions.BITAND, new AliasModifier("bit_and")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.BITNOT, new AliasModifier("bit_not")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.BITOR, new AliasModifier("bit_or")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.BITXOR, new AliasModifier("bit_xor")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.CURTIME, new AliasModifier("current_time")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.CURDATE, new AliasModifier("current_date")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LCASE, new AliasModifier("lowercase")); //$NON-NLS-1$
+ 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()));
+
+ 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
+ public List<String> getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+
+ supportedFunctions.add(SourceSystemFunctions.ABS);
+ supportedFunctions.add(SourceSystemFunctions.ATAN);
+ supportedFunctions.add(SourceSystemFunctions.BITAND);
+ supportedFunctions.add(SourceSystemFunctions.BITNOT);
+ supportedFunctions.add(SourceSystemFunctions.BITOR);
+ supportedFunctions.add(SourceSystemFunctions.BITXOR);
+ supportedFunctions.add(SourceSystemFunctions.CONCAT);
+ supportedFunctions.add(SourceSystemFunctions.COS);
+ supportedFunctions.add(SourceSystemFunctions.CONVERT);
+ supportedFunctions.add(SourceSystemFunctions.CURTIME);
+ supportedFunctions.add(SourceSystemFunctions.CURDATE);
+ supportedFunctions.add(SourceSystemFunctions.DAYOFMONTH);
+ supportedFunctions.add(SourceSystemFunctions.EXP);
+ supportedFunctions.add(SourceSystemFunctions.HOUR);
+ supportedFunctions.add(SourceSystemFunctions.LCASE);
+ supportedFunctions.add(SourceSystemFunctions.LEFT);
+ supportedFunctions.add(SourceSystemFunctions.LPAD);
+ supportedFunctions.add(SourceSystemFunctions.LOCATE);
+ supportedFunctions.add(SourceSystemFunctions.LENGTH);
+ supportedFunctions.add(SourceSystemFunctions.LOG);
+ supportedFunctions.add(SourceSystemFunctions.MINUTE);
+ supportedFunctions.add(SourceSystemFunctions.MONTH);
+ supportedFunctions.add(SourceSystemFunctions.POWER);
+ supportedFunctions.add(SourceSystemFunctions.RAND);
+ supportedFunctions.add(SourceSystemFunctions.RIGHT);
+ supportedFunctions.add(SourceSystemFunctions.RPAD);
+ supportedFunctions.add(SourceSystemFunctions.SECOND);
+ supportedFunctions.add(SourceSystemFunctions.SIN);
+ supportedFunctions.add(SourceSystemFunctions.SQRT);
+ supportedFunctions.add(SourceSystemFunctions.SUBSTRING);
+ supportedFunctions.add(SourceSystemFunctions.YEAR);
+ supportedFunctions.add(SourceSystemFunctions.UCASE);
+
+ return supportedFunctions;
+ }
+
+ @Override
+ public boolean supportsRowLimit() {
+ return true;
+ }
+
+ @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 String translateLiteralDate(Date dateValue) {
+ return "DATE '" + formatDateValue(dateValue) + "'"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ @Override
+ public String translateLiteralTime(Time timeValue) {
+ return "TIME '" + formatDateValue(timeValue) + "'"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ @Override
+ public String translateLiteralTimestamp(Timestamp timestampValue) {
+ return "TIMESTAMP '" + formatDateValue(timestampValue) + "'"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ @Override
+ public NullOrder getDefaultNullOrder() {
+ return NullOrder.LAST;
+ }
+
+ @Override
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/intersyscache/InterSystemsCacheExecutionFactory.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/intersyscache/InterSystemsCacheExecutionFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/intersyscache/InterSystemsCacheExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,280 +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.intersyscache;
-
-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.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;
-import org.teiid.translator.TypeFacility;
-import org.teiid.translator.jdbc.AliasModifier;
-import org.teiid.translator.jdbc.ConvertModifier;
-import org.teiid.translator.jdbc.EscapeSyntaxModifier;
-import org.teiid.translator.jdbc.FunctionModifier;
-import org.teiid.translator.jdbc.JDBCExecutionFactory;
-
- at Translator(name="intersystems-cache", description="A translator for Intersystems Cache Database")
-public class InterSystemsCacheExecutionFactory extends JDBCExecutionFactory {
-
- private static final String INTER_CACHE = "intersystems-cache"; //$NON-NLS-1$
- protected ConvertModifier convert = new ConvertModifier();
-
- @Override
- public void start() throws TranslatorException {
- super.start();
- convert.addTypeMapping("tinyint", FunctionModifier.BYTE); //$NON-NLS-1$
- convert.addTypeMapping("smallint", FunctionModifier.SHORT); //$NON-NLS-1$
- convert.addTypeMapping("integer", FunctionModifier.INTEGER); //$NON-NLS-1$
- convert.addTypeMapping("bigint", FunctionModifier.LONG); //$NON-NLS-1$
- convert.addTypeMapping("decimal(38,19)", FunctionModifier.BIGDECIMAL); //$NON-NLS-1$
- convert.addTypeMapping("decimal(19,0)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$
- convert.addTypeMapping("character", FunctionModifier.CHAR); //$NON-NLS-1$
- convert.addTypeMapping("varchar(4000)", FunctionModifier.STRING); //$NON-NLS-1$
- convert.addTypeMapping("date", FunctionModifier.DATE); //$NON-NLS-1$
- convert.addTypeMapping("time", FunctionModifier.TIME); //$NON-NLS-1$
- convert.addTypeMapping("timestamp", FunctionModifier.TIMESTAMP); //$NON-NLS-1$
- convert.addNumericBooleanConversions();
- registerFunctionModifier(SourceSystemFunctions.CONVERT, convert);
-
- registerFunctionModifier(SourceSystemFunctions.IFNULL, new AliasModifier("nvl")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.CONCAT, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.ACOS, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.ASIN, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.ATAN, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.COS, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.COT, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.CURDATE, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.CURTIME, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.DAYNAME, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.DAYOFWEEK, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.DAYOFYEAR, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.EXP, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.HOUR, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.LOG,new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.LOG10, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.LEFT, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.MINUTE, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.MONTH, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.MONTHNAME, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.MOD, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.NOW, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.PI, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.QUARTER, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.RIGHT, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.SIN, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.SECOND, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.SQRT,new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.TAN, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.TIMESTAMPADD, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.TIMESTAMPDIFF, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.TRUNCATE, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.WEEK, new EscapeSyntaxModifier());
- registerFunctionModifier(SourceSystemFunctions.DIVIDE_OP, new FunctionModifier() {
-
- @Override
- public List<?> translate(Function function) {
- if (function.getType() == TypeFacility.RUNTIME_TYPES.INTEGER || function.getType() == TypeFacility.RUNTIME_TYPES.LONG) {
- Function result = ConvertModifier.createConvertFunction(getLanguageFactory(), function, TypeFacility.getDataTypeName(function.getType()));
- function.setType(TypeFacility.RUNTIME_TYPES.BIG_DECIMAL);
- return Arrays.asList(result);
- }
- return null;
- }
- });
- }
-
- @Override
- public List<String> getSupportedFunctions() {
- List<String> supportedFunctions = new ArrayList<String>();
- supportedFunctions.addAll(super.getSupportedFunctions());
-
- supportedFunctions.add(SourceSystemFunctions.ABS);
- supportedFunctions.add(SourceSystemFunctions.ACOS);
- supportedFunctions.add(SourceSystemFunctions.ASIN);
- supportedFunctions.add(SourceSystemFunctions.ATAN);
- supportedFunctions.add(SourceSystemFunctions.ASCII);
- supportedFunctions.add(SourceSystemFunctions.CEILING);
- supportedFunctions.add(SourceSystemFunctions.CHAR);
- supportedFunctions.add(SourceSystemFunctions.COALESCE);
- supportedFunctions.add(SourceSystemFunctions.CONCAT);
- supportedFunctions.add(SourceSystemFunctions.CONVERT);
- supportedFunctions.add(SourceSystemFunctions.COS);
- supportedFunctions.add(SourceSystemFunctions.COT);
- supportedFunctions.add(SourceSystemFunctions.CURDATE);
- supportedFunctions.add(SourceSystemFunctions.CURTIME);
- supportedFunctions.add(SourceSystemFunctions.DAYNAME);
- supportedFunctions.add(SourceSystemFunctions.DAYOFMONTH);
- supportedFunctions.add(SourceSystemFunctions.DAYOFWEEK);
- supportedFunctions.add(SourceSystemFunctions.DAYOFYEAR);
- supportedFunctions.add(SourceSystemFunctions.EXP);
- supportedFunctions.add(SourceSystemFunctions.FLOOR);
- supportedFunctions.add(SourceSystemFunctions.HOUR);
- supportedFunctions.add(SourceSystemFunctions.IFNULL);
- supportedFunctions.add(SourceSystemFunctions.LCASE);
- supportedFunctions.add(SourceSystemFunctions.LENGTH);
- supportedFunctions.add(SourceSystemFunctions.LPAD);
- supportedFunctions.add(SourceSystemFunctions.LTRIM);
- supportedFunctions.add(SourceSystemFunctions.LOG);
- supportedFunctions.add(SourceSystemFunctions.LOG10);
- supportedFunctions.add(SourceSystemFunctions.LEFT);
- supportedFunctions.add(SourceSystemFunctions.MINUTE);
- supportedFunctions.add(SourceSystemFunctions.MONTH);
- supportedFunctions.add(SourceSystemFunctions.MONTHNAME);
- supportedFunctions.add(SourceSystemFunctions.MOD);
- supportedFunctions.add(SourceSystemFunctions.NULLIF);
- supportedFunctions.add(SourceSystemFunctions.NOW);
- supportedFunctions.add(SourceSystemFunctions.PI);
- supportedFunctions.add(SourceSystemFunctions.POWER);
- supportedFunctions.add(SourceSystemFunctions.QUARTER);
- supportedFunctions.add(SourceSystemFunctions.RIGHT);
- supportedFunctions.add(SourceSystemFunctions.REPEAT);
- supportedFunctions.add(SourceSystemFunctions.REPLACE);
- supportedFunctions.add(SourceSystemFunctions.ROUND);
- supportedFunctions.add(SourceSystemFunctions.RPAD);
- supportedFunctions.add(SourceSystemFunctions.RTRIM);
- supportedFunctions.add(SourceSystemFunctions.SIGN);
- supportedFunctions.add(SourceSystemFunctions.SUBSTRING);
- supportedFunctions.add(SourceSystemFunctions.SIN);
- supportedFunctions.add(SourceSystemFunctions.SECOND);
- supportedFunctions.add(SourceSystemFunctions.SQRT);
- supportedFunctions.add(SourceSystemFunctions.TAN);
- supportedFunctions.add(SourceSystemFunctions.TIMESTAMPADD);
- supportedFunctions.add(SourceSystemFunctions.TIMESTAMPDIFF);
- supportedFunctions.add(SourceSystemFunctions.TRUNCATE);
- supportedFunctions.add(SourceSystemFunctions.UCASE);
- supportedFunctions.add(SourceSystemFunctions.XMLCONCAT);
- supportedFunctions.add(SourceSystemFunctions.WEEK);
-
- return supportedFunctions;
- }
-
- @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$
- }
-
- @Override
- public String translateLiteralTime(Time timeValue) {
- return "to_date('" + formatDateValue(timeValue) + "', 'hh:mi:ss')"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- @Override
- public String translateLiteralTimestamp(Timestamp timestampValue) {
- return "to_timestamp('" + formatDateValue(timestampValue) + "', 'yyyy-mm-dd hh:mi:ss.fffffffff')"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- @Override
- public NullOrder getDefaultNullOrder() {
- return NullOrder.LAST;
- }
-
- @Override
- public boolean supportsInlineViews() {
- return true;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/intersyscache/InterSystemsCacheExecutionFactory.java (from rev 3218, trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/intersyscache/InterSystemsCacheExecutionFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/intersyscache/InterSystemsCacheExecutionFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/intersyscache/InterSystemsCacheExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,217 @@
+/*
+ * 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.intersyscache;
+
+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.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.TypeFacility;
+import org.teiid.translator.jdbc.AliasModifier;
+import org.teiid.translator.jdbc.ConvertModifier;
+import org.teiid.translator.jdbc.EscapeSyntaxModifier;
+import org.teiid.translator.jdbc.FunctionModifier;
+import org.teiid.translator.jdbc.JDBCExecutionFactory;
+
+ at Translator(name="intersystems-cache", description="A translator for Intersystems Cache Database")
+public class InterSystemsCacheExecutionFactory extends JDBCExecutionFactory {
+
+ private static final String INTER_CACHE = "intersystems-cache"; //$NON-NLS-1$
+ protected ConvertModifier convert = new ConvertModifier();
+
+ @Override
+ public void start() throws TranslatorException {
+ super.start();
+ convert.addTypeMapping("tinyint", FunctionModifier.BYTE); //$NON-NLS-1$
+ convert.addTypeMapping("smallint", FunctionModifier.SHORT); //$NON-NLS-1$
+ convert.addTypeMapping("integer", FunctionModifier.INTEGER); //$NON-NLS-1$
+ convert.addTypeMapping("bigint", FunctionModifier.LONG); //$NON-NLS-1$
+ convert.addTypeMapping("decimal(38,19)", FunctionModifier.BIGDECIMAL); //$NON-NLS-1$
+ convert.addTypeMapping("decimal(19,0)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$
+ convert.addTypeMapping("character", FunctionModifier.CHAR); //$NON-NLS-1$
+ convert.addTypeMapping("varchar(4000)", FunctionModifier.STRING); //$NON-NLS-1$
+ convert.addTypeMapping("date", FunctionModifier.DATE); //$NON-NLS-1$
+ convert.addTypeMapping("time", FunctionModifier.TIME); //$NON-NLS-1$
+ convert.addTypeMapping("timestamp", FunctionModifier.TIMESTAMP); //$NON-NLS-1$
+ convert.addNumericBooleanConversions();
+ registerFunctionModifier(SourceSystemFunctions.CONVERT, convert);
+
+ registerFunctionModifier(SourceSystemFunctions.IFNULL, new AliasModifier("nvl")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.CONCAT, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.ACOS, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.ASIN, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.ATAN, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.COS, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.COT, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.CURDATE, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.CURTIME, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.DAYNAME, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.DAYOFWEEK, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.DAYOFYEAR, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.EXP, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.HOUR, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.LOG,new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.LOG10, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.LEFT, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.MINUTE, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.MONTH, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.MONTHNAME, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.MOD, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.NOW, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.PI, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.QUARTER, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.RIGHT, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.SIN, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.SECOND, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.SQRT,new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.TAN, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.TIMESTAMPADD, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.TIMESTAMPDIFF, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.TRUNCATE, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.WEEK, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.DIVIDE_OP, new FunctionModifier() {
+
+ @Override
+ public List<?> translate(Function function) {
+ if (function.getType() == TypeFacility.RUNTIME_TYPES.INTEGER || function.getType() == TypeFacility.RUNTIME_TYPES.LONG) {
+ Function result = ConvertModifier.createConvertFunction(getLanguageFactory(), function, TypeFacility.getDataTypeName(function.getType()));
+ function.setType(TypeFacility.RUNTIME_TYPES.BIG_DECIMAL);
+ return Arrays.asList(result);
+ }
+ 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
+ public List<String> getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+
+ supportedFunctions.add(SourceSystemFunctions.ABS);
+ supportedFunctions.add(SourceSystemFunctions.ACOS);
+ supportedFunctions.add(SourceSystemFunctions.ASIN);
+ supportedFunctions.add(SourceSystemFunctions.ATAN);
+ supportedFunctions.add(SourceSystemFunctions.ASCII);
+ supportedFunctions.add(SourceSystemFunctions.CEILING);
+ supportedFunctions.add(SourceSystemFunctions.CHAR);
+ supportedFunctions.add(SourceSystemFunctions.COALESCE);
+ supportedFunctions.add(SourceSystemFunctions.CONCAT);
+ supportedFunctions.add(SourceSystemFunctions.CONVERT);
+ supportedFunctions.add(SourceSystemFunctions.COS);
+ supportedFunctions.add(SourceSystemFunctions.COT);
+ supportedFunctions.add(SourceSystemFunctions.CURDATE);
+ supportedFunctions.add(SourceSystemFunctions.CURTIME);
+ supportedFunctions.add(SourceSystemFunctions.DAYNAME);
+ supportedFunctions.add(SourceSystemFunctions.DAYOFMONTH);
+ supportedFunctions.add(SourceSystemFunctions.DAYOFWEEK);
+ supportedFunctions.add(SourceSystemFunctions.DAYOFYEAR);
+ supportedFunctions.add(SourceSystemFunctions.EXP);
+ supportedFunctions.add(SourceSystemFunctions.FLOOR);
+ supportedFunctions.add(SourceSystemFunctions.HOUR);
+ supportedFunctions.add(SourceSystemFunctions.IFNULL);
+ supportedFunctions.add(SourceSystemFunctions.LCASE);
+ supportedFunctions.add(SourceSystemFunctions.LENGTH);
+ supportedFunctions.add(SourceSystemFunctions.LPAD);
+ supportedFunctions.add(SourceSystemFunctions.LTRIM);
+ supportedFunctions.add(SourceSystemFunctions.LOG);
+ supportedFunctions.add(SourceSystemFunctions.LOG10);
+ supportedFunctions.add(SourceSystemFunctions.LEFT);
+ supportedFunctions.add(SourceSystemFunctions.MINUTE);
+ supportedFunctions.add(SourceSystemFunctions.MONTH);
+ supportedFunctions.add(SourceSystemFunctions.MONTHNAME);
+ supportedFunctions.add(SourceSystemFunctions.MOD);
+ supportedFunctions.add(SourceSystemFunctions.NULLIF);
+ supportedFunctions.add(SourceSystemFunctions.NOW);
+ supportedFunctions.add(SourceSystemFunctions.PI);
+ supportedFunctions.add(SourceSystemFunctions.POWER);
+ supportedFunctions.add(SourceSystemFunctions.QUARTER);
+ supportedFunctions.add(SourceSystemFunctions.RIGHT);
+ supportedFunctions.add(SourceSystemFunctions.REPEAT);
+ supportedFunctions.add(SourceSystemFunctions.REPLACE);
+ supportedFunctions.add(SourceSystemFunctions.ROUND);
+ supportedFunctions.add(SourceSystemFunctions.RPAD);
+ supportedFunctions.add(SourceSystemFunctions.RTRIM);
+ supportedFunctions.add(SourceSystemFunctions.SIGN);
+ supportedFunctions.add(SourceSystemFunctions.SUBSTRING);
+ supportedFunctions.add(SourceSystemFunctions.SIN);
+ supportedFunctions.add(SourceSystemFunctions.SECOND);
+ supportedFunctions.add(SourceSystemFunctions.SQRT);
+ supportedFunctions.add(SourceSystemFunctions.TAN);
+ supportedFunctions.add(SourceSystemFunctions.TIMESTAMPADD);
+ supportedFunctions.add(SourceSystemFunctions.TIMESTAMPDIFF);
+ supportedFunctions.add(SourceSystemFunctions.TRUNCATE);
+ supportedFunctions.add(SourceSystemFunctions.UCASE);
+ supportedFunctions.add(SourceSystemFunctions.XMLCONCAT);
+ supportedFunctions.add(SourceSystemFunctions.WEEK);
+
+ return supportedFunctions;
+ }
+
+ @Override
+ public String translateLiteralDate(Date dateValue) {
+ return "to_date('" + formatDateValue(dateValue) + "', 'yyyy-mm-dd')"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ @Override
+ public String translateLiteralTime(Time timeValue) {
+ return "to_date('" + formatDateValue(timeValue) + "', 'hh:mi:ss')"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ @Override
+ public String translateLiteralTimestamp(Timestamp timestampValue) {
+ return "to_timestamp('" + formatDateValue(timestampValue) + "', 'yyyy-mm-dd hh:mi:ss.fffffffff')"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ @Override
+ public NullOrder getDefaultNullOrder() {
+ return NullOrder.LAST;
+ }
+
+ @Override
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/ModeShapeExecutionFactory.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/ModeShapeExecutionFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/ModeShapeExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,292 +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.modeshape;
-
-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.teiid.core.types.DataTypeManager;
-import org.teiid.language.Comparison;
-import org.teiid.language.Function;
-import org.teiid.language.LanguageObject;
-import org.teiid.language.Literal;
-import org.teiid.language.Not;
-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;
-import org.teiid.translator.TranslatorException;
-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.
- */
- at Translator(name="modeshape", description="A translator for the open source Modeshape JCR Repository")
-public class ModeShapeExecutionFactory extends JDBCExecutionFactory {
-
- private static final String JCR = "JCR"; //$NON-NLS-1$
- private static final String JCR_REFERENCE = "JCR_REFERENCE";//$NON-NLS-1$
- private static final String JCR_CONTAINS = "JCR_CONTAINS";//$NON-NLS-1$
- private static final String JCR_ISSAMENODE = "JCR_ISSAMENODE";//$NON-NLS-1$
- private static final String JCR_ISDESCENDANTNODE = "JCR_ISDESCENDANTNODE";//$NON-NLS-1$
- private static final String JCR_ISCHILDNODE = "JCR_ISCHILDNODE";//$NON-NLS-1$
-
- public ModeShapeExecutionFactory() {
- setDatabaseVersion("2.0"); //$NON-NLS-1$
- setUseBindVariables(false);
- }
-
- @Override
- public void start() throws TranslatorException {
- super.start();
-
- registerFunctionModifier(SourceSystemFunctions.UCASE, new AliasModifier("UpperCase")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.LCASE,new AliasModifier("LowerCase")); //$NON-NLS-1$
-
- registerFunctionModifier(JCR_ISCHILDNODE, new IdentifierFunctionModifier());
- registerFunctionModifier(JCR_ISDESCENDANTNODE, new IdentifierFunctionModifier());
- registerFunctionModifier(JCR_ISSAMENODE, new IdentifierFunctionModifier());
- registerFunctionModifier(JCR_REFERENCE, new IdentifierFunctionModifier());
- registerFunctionModifier(JCR_CONTAINS, new IdentifierFunctionModifier());
-
- LogManager.logTrace(LogConstants.CTX_CONNECTOR, "ModeShape Translator Started"); //$NON-NLS-1$
- }
-
- @Override
- public String translateLiteralDate(Date dateValue) {
- return "CAST('" + formatDateValue(dateValue) + "' AS DATE)"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- @Override
- public String translateLiteralTime(Time timeValue) {
- return "CAST('" + formatDateValue(timeValue) + "' AS DATE)"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- @Override
- public String translateLiteralTimestamp(Timestamp timestampValue) {
- return "CAST('" + formatDateValue(timestampValue) + "' AS DATE)"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- @Override
- public String translateLiteralBoolean(Boolean booleanValue) {
- return "CAST('" + booleanValue.toString() + "' AS BOOLEAN)"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- @Override
- public List<String> getSupportedFunctions() {
- List<String> supportedFunctions = new ArrayList<String>();
- supportedFunctions.addAll(super.getSupportedFunctions());
- supportedFunctions.add(SourceSystemFunctions.UCASE);
- supportedFunctions.add(SourceSystemFunctions.LCASE);
- supportedFunctions.add(SourceSystemFunctions.LENGTH);
- 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;
- if (compare.getLeftExpression().getType() == TypeFacility.RUNTIME_TYPES.BOOLEAN
- && compare.getLeftExpression() instanceof Function
- && compare.getRightExpression() instanceof Literal) {
- boolean isTrue = Boolean.TRUE.equals(((Literal)compare.getRightExpression()).getValue());
- if ((isTrue && compare.getOperator() == Operator.EQ) || (!isTrue && compare.getOperator() == Operator.NE)) {
- return Arrays.asList(compare.getLeftExpression());
- }
- if ((!isTrue && compare.getOperator() == Operator.EQ) || (isTrue && compare.getOperator() == Operator.NE)) {
- return Arrays.asList("NOT ", compare.getLeftExpression()); //$NON-NLS-1$
- }
- }
- } else if (obj instanceof Not) {
- Not not = (Not)obj;
- return Arrays.asList("NOT ", not.getCriteria()); //$NON-NLS-1$
- }
- return super.translate(obj, context);
- }
-
- @Override
- public boolean useBindVariables() {
- return false;
- }
-
- @Override
- public boolean supportsAggregatesAvg() {
- return false;
- }
-
- @Override
- public boolean supportsAggregatesCountStar() {
- return false;
- }
-
- @Override
- public boolean supportsAggregatesCount() {
- return false;
- }
-
- @Override
- public boolean supportsAggregatesEnhancedNumeric() {
- return false;
- }
-
- @Override
- public boolean supportsAggregatesMax() {
- return false;
- }
-
- @Override
- public boolean supportsAggregatesMin() {
- return false;
- }
-
- @Override
- public boolean supportsAggregatesSum() {
- return false;
- }
-
- @Override
- public boolean supportsGroupBy() {
- return false;
- }
-
- @Override
- public boolean supportsHaving() {
- return false;
- }
-
- @Override
- public boolean supportsSelectExpression() {
- return false;
- }
-
- @Override
- public boolean supportsCaseExpressions() {
- return false;
- }
-
- @Override
- public boolean supportsCorrelatedSubqueries() {
- return false;
- }
-
- @Override
- public boolean supportsExistsCriteria() {
- return false;
- }
-
- @Override
- public boolean supportsInCriteriaSubquery() {
- return false;
- }
-
- @Override
- public boolean supportsInlineViews() {
- return false;
- }
-
- @Override
- public boolean supportsOrderByNullOrdering() {
- return false;
- }
-
- @Override
- public boolean supportsQuantifiedCompareCriteriaAll() {
- return false;
- }
-
- @Override
- public boolean supportsQuantifiedCompareCriteriaSome() {
- return false;
- }
-
- @Override
- public boolean supportsScalarSubqueries() {
- return false;
- }
-
- @Override
- public boolean supportsSearchedCaseExpressions() {
- return false;
- }
-
- @Override
- public boolean supportsExcept() {
- return true;
- }
-
- @Override
- public boolean supportsIntersect() {
- return true;
- }
-
- @Override
- public boolean supportsSetQueryOrderBy() {
- return false;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/ModeShapeExecutionFactory.java (from rev 3218, trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/ModeShapeExecutionFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/ModeShapeExecutionFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/ModeShapeExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,261 @@
+/*
+ * 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.modeshape;
+
+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.List;
+
+import org.teiid.language.Comparison;
+import org.teiid.language.Function;
+import org.teiid.language.LanguageObject;
+import org.teiid.language.Literal;
+import org.teiid.language.Not;
+import org.teiid.language.Comparison.Operator;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+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.JDBCExecutionFactory;
+/**
+ * Translator class for accessing the ModeShape JCR repository.
+ */
+ at Translator(name="modeshape", description="A translator for the open source Modeshape JCR Repository")
+public class ModeShapeExecutionFactory extends JDBCExecutionFactory {
+
+ private static final String JCR = "JCR"; //$NON-NLS-1$
+ private static final String JCR_REFERENCE = "JCR_REFERENCE";//$NON-NLS-1$
+ private static final String JCR_CONTAINS = "JCR_CONTAINS";//$NON-NLS-1$
+ private static final String JCR_ISSAMENODE = "JCR_ISSAMENODE";//$NON-NLS-1$
+ private static final String JCR_ISDESCENDANTNODE = "JCR_ISDESCENDANTNODE";//$NON-NLS-1$
+ private static final String JCR_ISCHILDNODE = "JCR_ISCHILDNODE";//$NON-NLS-1$
+
+ public ModeShapeExecutionFactory() {
+ setDatabaseVersion("2.0"); //$NON-NLS-1$
+ setUseBindVariables(false);
+ }
+
+ @Override
+ public void start() throws TranslatorException {
+ super.start();
+
+ registerFunctionModifier(SourceSystemFunctions.UCASE, new AliasModifier("UpperCase")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LCASE,new AliasModifier("LowerCase")); //$NON-NLS-1$
+
+ registerFunctionModifier(JCR_ISCHILDNODE, new IdentifierFunctionModifier());
+ registerFunctionModifier(JCR_ISDESCENDANTNODE, new IdentifierFunctionModifier());
+ registerFunctionModifier(JCR_ISSAMENODE, new IdentifierFunctionModifier());
+ 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$
+ }
+
+ @Override
+ public String translateLiteralDate(Date dateValue) {
+ return "CAST('" + formatDateValue(dateValue) + "' AS DATE)"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ @Override
+ public String translateLiteralTime(Time timeValue) {
+ return "CAST('" + formatDateValue(timeValue) + "' AS DATE)"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ @Override
+ public String translateLiteralTimestamp(Timestamp timestampValue) {
+ return "CAST('" + formatDateValue(timestampValue) + "' AS DATE)"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ @Override
+ public String translateLiteralBoolean(Boolean booleanValue) {
+ return "CAST('" + booleanValue.toString() + "' AS BOOLEAN)"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ @Override
+ public List<String> getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+ supportedFunctions.add(SourceSystemFunctions.UCASE);
+ supportedFunctions.add(SourceSystemFunctions.LCASE);
+ supportedFunctions.add(SourceSystemFunctions.LENGTH);
+ return supportedFunctions;
+ }
+
+ @Override
+ public List<?> translate(LanguageObject obj, ExecutionContext context) {
+ if (obj instanceof Comparison) {
+ Comparison compare = (Comparison)obj;
+ if (compare.getLeftExpression().getType() == TypeFacility.RUNTIME_TYPES.BOOLEAN
+ && compare.getLeftExpression() instanceof Function
+ && compare.getRightExpression() instanceof Literal) {
+ boolean isTrue = Boolean.TRUE.equals(((Literal)compare.getRightExpression()).getValue());
+ if ((isTrue && compare.getOperator() == Operator.EQ) || (!isTrue && compare.getOperator() == Operator.NE)) {
+ return Arrays.asList(compare.getLeftExpression());
+ }
+ if ((!isTrue && compare.getOperator() == Operator.EQ) || (isTrue && compare.getOperator() == Operator.NE)) {
+ return Arrays.asList("NOT ", compare.getLeftExpression()); //$NON-NLS-1$
+ }
+ }
+ } else if (obj instanceof Not) {
+ Not not = (Not)obj;
+ return Arrays.asList("NOT ", not.getCriteria()); //$NON-NLS-1$
+ }
+ return super.translate(obj, context);
+ }
+
+ @Override
+ public boolean useBindVariables() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsAggregatesAvg() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsAggregatesCountStar() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsAggregatesCount() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsAggregatesEnhancedNumeric() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsAggregatesMax() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsAggregatesMin() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsAggregatesSum() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsGroupBy() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsHaving() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsSelectExpression() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsCaseExpressions() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsCorrelatedSubqueries() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsExistsCriteria() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsInCriteriaSubquery() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsInlineViews() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsOrderByNullOrdering() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsQuantifiedCompareCriteriaAll() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsQuantifiedCompareCriteriaSome() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsScalarSubqueries() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsSearchedCaseExpressions() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsExcept() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsIntersect() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsSetQueryOrderBy() {
+ return false;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,511 +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.sql.PreparedStatement;
-import java.sql.SQLException;
-import java.sql.Timestamp;
-import java.sql.Types;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-
-import org.teiid.language.ColumnReference;
-import org.teiid.language.Command;
-import org.teiid.language.DerivedColumn;
-import org.teiid.language.Expression;
-import org.teiid.language.ExpressionValueSource;
-import org.teiid.language.Function;
-import org.teiid.language.Insert;
-import org.teiid.language.Limit;
-import org.teiid.language.Literal;
-import org.teiid.language.NamedTable;
-import org.teiid.language.QueryExpression;
-import org.teiid.language.Select;
-import org.teiid.language.SQLConstants.Tokens;
-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;
-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.ExtractFunctionModifier;
-import org.teiid.translator.jdbc.FunctionModifier;
-import org.teiid.translator.jdbc.JDBCExecutionFactory;
-import org.teiid.translator.jdbc.LocateFunctionModifier;
-
-
- at Translator(name="oracle", description="A translator for Oracle 9i Database or later")
-public class OracleExecutionFactory extends JDBCExecutionFactory {
-
- private static final String TIME_FORMAT = "HH24:MI:SS"; //$NON-NLS-1$
- private static final String DATE_FORMAT = "YYYY-MM-DD"; //$NON-NLS-1$
- private static final String DATETIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT; //$NON-NLS-1$
- private static final String TIMESTAMP_FORMAT = DATETIME_FORMAT + ".FF"; //$NON-NLS-1$
-
- public final static String HINT_PREFIX = "/*+"; //$NON-NLS-1$
- 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$
-
- public void start() throws TranslatorException {
- super.start();
-
- registerFunctionModifier(SourceSystemFunctions.CHAR, new AliasModifier("chr")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.LCASE, new AliasModifier("lower")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.UCASE, new AliasModifier("upper")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.IFNULL, new AliasModifier("nvl")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.LOG, new AliasModifier("ln")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.CEILING, new AliasModifier("ceil")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.LOG10, new Log10FunctionModifier(getLanguageFactory()));
- registerFunctionModifier(SourceSystemFunctions.HOUR, new ExtractFunctionModifier());
- registerFunctionModifier(SourceSystemFunctions.YEAR, new ExtractFunctionModifier());
- registerFunctionModifier(SourceSystemFunctions.MINUTE, new ExtractFunctionModifier());
- registerFunctionModifier(SourceSystemFunctions.SECOND, new ExtractFunctionModifier());
- registerFunctionModifier(SourceSystemFunctions.MONTH, new ExtractFunctionModifier());
- registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new ExtractFunctionModifier());
- registerFunctionModifier(SourceSystemFunctions.MONTHNAME, new MonthOrDayNameFunctionModifier(getLanguageFactory(), "Month"));//$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.DAYNAME, new MonthOrDayNameFunctionModifier(getLanguageFactory(), "Day"));//$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.WEEK, new DayWeekQuarterFunctionModifier("WW"));//$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.QUARTER, new DayWeekQuarterFunctionModifier("Q"));//$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.DAYOFWEEK, new DayWeekQuarterFunctionModifier("D"));//$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.DAYOFYEAR, new DayWeekQuarterFunctionModifier("DDD"));//$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateFunctionModifier(getLanguageFactory(), "INSTR", true)); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.SUBSTRING, new AliasModifier("substr"));//$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.LEFT, new LeftOrRightFunctionModifier(getLanguageFactory()));
- registerFunctionModifier(SourceSystemFunctions.RIGHT, new LeftOrRightFunctionModifier(getLanguageFactory()));
- registerFunctionModifier(SourceSystemFunctions.CONCAT, new ConcatFunctionModifier(getLanguageFactory()));
- 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));
- }
- });
-
- //spatial functions
- registerFunctionModifier(OracleSpatialFunctions.RELATE, new OracleSpatialFunctionModifier());
- registerFunctionModifier(OracleSpatialFunctions.NEAREST_NEIGHBOR, new OracleSpatialFunctionModifier());
- registerFunctionModifier(OracleSpatialFunctions.FILTER, new OracleSpatialFunctionModifier());
- registerFunctionModifier(OracleSpatialFunctions.WITHIN_DISTANCE, new OracleSpatialFunctionModifier());
-
- //add in type conversion
- ConvertModifier convertModifier = new ConvertModifier();
- convertModifier.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
- convertModifier.addTypeMapping("date", FunctionModifier.DATE, FunctionModifier.TIME); //$NON-NLS-1$
- convertModifier.addTypeMapping("timestamp", FunctionModifier.TIMESTAMP); //$NON-NLS-1$
- convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.TIME, new FunctionModifier() {
- @Override
- public List<?> translate(Function function) {
- return Arrays.asList("case when ", function.getParameters().get(0), " is null then null else to_date('1970-01-01 ' || to_char(",function.getParameters().get(0),", 'HH24:MI:SS'), 'YYYY-MM-DD HH24:MI:SS') end"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- });
- convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.DATE, new FunctionModifier() {
- @Override
- public List<?> translate(Function function) {
- return Arrays.asList("trunc(cast(",function.getParameters().get(0)," AS date))"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- });
- convertModifier.addConvert(FunctionModifier.DATE, FunctionModifier.STRING, new ConvertModifier.FormatModifier("to_char", DATE_FORMAT)); //$NON-NLS-1$
- convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.STRING, new ConvertModifier.FormatModifier("to_char", TIME_FORMAT)); //$NON-NLS-1$
- convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.STRING, new FunctionModifier() {
- @Override
- public List<?> translate(Function function) {
- //if column and type is date, just use date format
- Expression ex = function.getParameters().get(0);
- String format = TIMESTAMP_FORMAT;
- if (ex instanceof ColumnReference && "date".equalsIgnoreCase(((ColumnReference)ex).getMetadataObject().getNativeType())) { //$NON-NLS-1$
- format = DATETIME_FORMAT;
- } else if (!(ex instanceof Literal) && !(ex instanceof Function)) {
- //this isn't needed in every case, but it's simpler than inspecting the expression more
- ex = ConvertModifier.createConvertFunction(getLanguageFactory(), function.getParameters().get(0), TypeFacility.RUNTIME_NAMES.TIMESTAMP);
- }
- return Arrays.asList("to_char(", ex, ", '", format, "')"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- });
- convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.DATE, new ConvertModifier.FormatModifier("to_date", DATE_FORMAT)); //$NON-NLS-1$
- convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIME, new ConvertModifier.FormatModifier("to_date", TIME_FORMAT)); //$NON-NLS-1$
- convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIMESTAMP, new ConvertModifier.FormatModifier("to_timestamp", TIMESTAMP_FORMAT)); //$NON-NLS-1$
- convertModifier.addTypeConversion(new ConvertModifier.FormatModifier("to_char"), FunctionModifier.STRING); //$NON-NLS-1$
- //NOTE: numeric handling in Oracle is split only between integral vs. floating/decimal types
- convertModifier.addTypeConversion(new ConvertModifier.FormatModifier("to_number"), //$NON-NLS-1$
- FunctionModifier.FLOAT, FunctionModifier.DOUBLE, FunctionModifier.BIGDECIMAL);
- convertModifier.addTypeConversion(new FunctionModifier() {
- @Override
- public List<?> translate(Function function) {
- if (Number.class.isAssignableFrom(function.getParameters().get(0).getType())) {
- return Arrays.asList("trunc(", function.getParameters().get(0), ")"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return Arrays.asList("trunc(to_number(", function.getParameters().get(0), "))"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- },
- FunctionModifier.BYTE, FunctionModifier.SHORT, FunctionModifier.INTEGER, FunctionModifier.LONG, FunctionModifier.BIGINTEGER);
- convertModifier.addNumericBooleanConversions();
- convertModifier.setWideningNumericImplicit(true);
- registerFunctionModifier(SourceSystemFunctions.CONVERT, convertModifier);
- }
-
- public void handleInsertSequences(Insert insert) throws TranslatorException {
- /*
- * If a missing auto_increment column is modeled with name in source indicating that an Oracle Sequence
- * then pull the Sequence name out of the name in source of the column.
- */
- if (!(insert.getValueSource() instanceof ExpressionValueSource)) {
- return;
- }
- ExpressionValueSource values = (ExpressionValueSource)insert.getValueSource();
- List<Column> allElements = insert.getTable().getMetadataObject().getColumns();
- if (allElements.size() == values.getValues().size()) {
- return;
- }
-
- int index = 0;
- List<ColumnReference> elements = insert.getColumns();
-
- for (Column element : allElements) {
- if (!element.isAutoIncremented()) {
- continue;
- }
- String name = element.getNameInSource();
- int seqIndex = name.indexOf(SEQUENCE);
- if (seqIndex == -1) {
- continue;
- }
- boolean found = false;
- while (index < elements.size()) {
- if (element.equals(elements.get(index).getMetadataObject())) {
- found = true;
- break;
- }
- index++;
- }
- if (found) {
- continue;
- }
-
- String sequence = name.substring(seqIndex + SEQUENCE.length());
-
- int delimiterIndex = sequence.indexOf(Tokens.DOT);
- if (delimiterIndex == -1) {
- throw new TranslatorException("Invalid name in source sequence format. Expected <element name>" + SEQUENCE + "<sequence name>.<sequence value>, but was " + name); //$NON-NLS-1$ //$NON-NLS-2$
- }
- String sequenceGroupName = sequence.substring(0, delimiterIndex);
- String sequenceElementName = sequence.substring(delimiterIndex + 1);
-
- NamedTable sequenceGroup = this.getLanguageFactory().createNamedTable(sequenceGroupName, null, null);
- ColumnReference sequenceElement = this.getLanguageFactory().createColumnReference(sequenceElementName, sequenceGroup, null, element.getJavaType());
- insert.getColumns().add(index, this.getLanguageFactory().createColumnReference(element.getName(), insert.getTable(), element, element.getJavaType()));
- values.getValues().add(index, sequenceElement);
- }
- }
-
- @Override
- public List<?> translateCommand(Command command, ExecutionContext context) {
- if (command instanceof Insert) {
- try {
- handleInsertSequences((Insert)command);
- } catch (TranslatorException e) {
- throw new RuntimeException(e);
- }
- }
-
- if (!(command instanceof QueryExpression)) {
- return null;
- }
- QueryExpression queryCommand = (QueryExpression)command;
- if (queryCommand.getLimit() == null) {
- return null;
- }
- Limit limit = queryCommand.getLimit();
- queryCommand.setLimit(null);
- List<Object> parts = new ArrayList<Object>();
- parts.add("SELECT "); //$NON-NLS-1$
- /*
- * if all of the columns are aliased, assume that names matter - it actually only seems to matter for
- * the first query of a set op when there is a order by. Rather than adding logic to traverse up,
- * we just use the projected names
- */
- boolean allAliased = true;
- for (DerivedColumn selectSymbol : queryCommand.getProjectedQuery().getDerivedColumns()) {
- if (selectSymbol.getAlias() == null) {
- allAliased = false;
- break;
- }
- }
- if (allAliased) {
- String[] columnNames = queryCommand.getColumnNames();
- for (int i = 0; i < columnNames.length; i++) {
- if (i > 0) {
- parts.add(", "); //$NON-NLS-1$
- }
- parts.add(columnNames[i]);
- }
- } else {
- parts.add("*"); //$NON-NLS-1$
- }
- if (limit.getRowOffset() > 0) {
- parts.add(" FROM (SELECT VIEW_FOR_LIMIT.*, ROWNUM ROWNUM_ FROM ("); //$NON-NLS-1$
- } else {
- parts.add(" FROM ("); //$NON-NLS-1$
- }
- parts.add(queryCommand);
- if (limit.getRowOffset() > 0) {
- parts.add(") VIEW_FOR_LIMIT WHERE ROWNUM <= "); //$NON-NLS-1$
- parts.add(limit.getRowLimit() + limit.getRowOffset());
- parts.add(") WHERE ROWNUM_ > "); //$NON-NLS-1$
- parts.add(limit.getRowOffset());
- } else {
- parts.add(") WHERE ROWNUM <= "); //$NON-NLS-1$
- parts.add(limit.getRowLimit());
- }
- return parts;
- }
-
- @Override
- public boolean useAsInGroupAlias(){
- return false;
- }
-
- @Override
- public String getSetOperationString(Operation operation) {
- if (operation == Operation.EXCEPT) {
- return "MINUS"; //$NON-NLS-1$
- }
- return super.getSetOperationString(operation);
- }
-
- @Override
- public String getSourceComment(ExecutionContext context, Command command) {
- String comment = super.getSourceComment(context, command);
-
- if (context != null) {
- // Check for db hints
- Object payload = context.getExecutionPayload();
- if (payload instanceof String) {
- String payloadString = (String)payload;
- if (payloadString.startsWith(HINT_PREFIX)) {
- comment += payloadString + " "; //$NON-NLS-1$
- }
- }
- }
-
- if (command instanceof Select) {
- //
- // This simple algorithm determines the hint which will be added to the
- // query.
- // Right now, we look through all functions passed in the query
- // (returned as a collection)
- // Then we check if any of those functions are sdo_relate
- // 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)) {
- return comment + "/*+ ORDERED */ "; //$NON-NLS-1$
- }
- }
- }
- return comment;
- }
-
- /**
- * Don't fully qualify elements if table = DUAL or element = ROWNUM or special stuff is packed into name in source value.
- *
- * @see org.teiid.language.visitor.SQLStringVisitor#skipGroupInElement(java.lang.String, java.lang.String)
- * @since 5.0
- */
- @Override
- public String replaceElementName(String group, String element) {
-
- // Check if the element was modeled as using a Sequence
- int useIndex = element.indexOf(SEQUENCE);
- if (useIndex >= 0) {
- String name = element.substring(0, useIndex);
- if (group != null) {
- return group + Tokens.DOT + name;
- }
- return name;
- }
-
- // Check if the group name should be discarded
- if((group != null && DUAL.equalsIgnoreCase(group)) || element.equalsIgnoreCase(ROWNUM)) {
- // Strip group if group or element are pseudo-columns
- return element;
- }
-
- return null;
- }
-
- @Override
- public boolean hasTimeType() {
- return false;
- }
-
- @Override
- public void bindValue(PreparedStatement stmt, Object param, Class<?> paramType, int i) throws SQLException {
- if(param == null && Object.class.equals(paramType)){
- //Oracle drive does not support JAVA_OBJECT type
- stmt.setNull(i, Types.LONGVARBINARY);
- return;
- }
- super.bindValue(stmt, param, paramType, i);
- }
-
- @Override
- public NullOrder getDefaultNullOrder() {
- return NullOrder.HIGH;
- }
-
- @Override
- public boolean supportsOrderByNullOrdering() {
- return true;
- }
-
- @Override
- public List<String> getSupportedFunctions() {
- List<String> supportedFunctions = new ArrayList<String>();
- supportedFunctions.addAll(super.getSupportedFunctions());
- supportedFunctions.add("ABS"); //$NON-NLS-1$
- supportedFunctions.add("ACOS"); //$NON-NLS-1$
- supportedFunctions.add("ASIN"); //$NON-NLS-1$
- supportedFunctions.add("ATAN"); //$NON-NLS-1$
- supportedFunctions.add("ATAN2"); //$NON-NLS-1$
- supportedFunctions.add("COS"); //$NON-NLS-1$
- supportedFunctions.add(SourceSystemFunctions.COT);
- supportedFunctions.add("EXP"); //$NON-NLS-1$
- supportedFunctions.add("FLOOR"); //$NON-NLS-1$
- supportedFunctions.add("CEILING"); //$NON-NLS-1$
- supportedFunctions.add("LOG"); //$NON-NLS-1$
- supportedFunctions.add("LOG10"); //$NON-NLS-1$
- supportedFunctions.add("MOD"); //$NON-NLS-1$
- supportedFunctions.add("POWER"); //$NON-NLS-1$
- supportedFunctions.add("SIGN"); //$NON-NLS-1$
- supportedFunctions.add("SIN"); //$NON-NLS-1$
- supportedFunctions.add("SQRT"); //$NON-NLS-1$
- supportedFunctions.add("TAN"); //$NON-NLS-1$
- supportedFunctions.add("ASCII"); //$NON-NLS-1$
- supportedFunctions.add("CHAR"); //$NON-NLS-1$
- supportedFunctions.add("CHR"); //$NON-NLS-1$
- supportedFunctions.add("CONCAT"); //$NON-NLS-1$
- supportedFunctions.add("||"); //$NON-NLS-1$
- supportedFunctions.add("INITCAP"); //$NON-NLS-1$
- supportedFunctions.add("LCASE"); //$NON-NLS-1$
- supportedFunctions.add("LENGTH"); //$NON-NLS-1$
- supportedFunctions.add("LEFT"); //$NON-NLS-1$
- supportedFunctions.add("LOCATE"); //$NON-NLS-1$
- supportedFunctions.add("LOWER"); //$NON-NLS-1$
- supportedFunctions.add("LPAD"); //$NON-NLS-1$
- supportedFunctions.add("LTRIM"); //$NON-NLS-1$
- supportedFunctions.add("REPLACE"); //$NON-NLS-1$
- supportedFunctions.add("RPAD"); //$NON-NLS-1$
- supportedFunctions.add("RIGHT"); //$NON-NLS-1$
- supportedFunctions.add("RTRIM"); //$NON-NLS-1$
- supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
- supportedFunctions.add("TRANSLATE"); //$NON-NLS-1$
- supportedFunctions.add("UCASE"); //$NON-NLS-1$
- supportedFunctions.add("UPPER"); //$NON-NLS-1$
- supportedFunctions.add("HOUR"); //$NON-NLS-1$
- supportedFunctions.add("MONTH"); //$NON-NLS-1$
- supportedFunctions.add("MONTHNAME"); //$NON-NLS-1$
- supportedFunctions.add("YEAR"); //$NON-NLS-1$
- supportedFunctions.add("DAY"); //$NON-NLS-1$
- supportedFunctions.add("DAYNAME"); //$NON-NLS-1$
- supportedFunctions.add("DAYOFMONTH"); //$NON-NLS-1$
- supportedFunctions.add("DAYOFWEEK"); //$NON-NLS-1$
- supportedFunctions.add("DAYOFYEAR"); //$NON-NLS-1$
- supportedFunctions.add("QUARTER"); //$NON-NLS-1$
- supportedFunctions.add("MINUTE"); //$NON-NLS-1$
- supportedFunctions.add("SECOND"); //$NON-NLS-1$
- supportedFunctions.add("QUARTER"); //$NON-NLS-1$
- supportedFunctions.add("WEEK"); //$NON-NLS-1$
- //supportedFunctions.add("FORMATDATE"); //$NON-NLS-1$
- //supportedFunctions.add("FORMATTIME"); //$NON-NLS-1$
- //supportedFunctions.add("FORMATTIMESTAMP"); //$NON-NLS-1$
- //supportedFunctions.add("PARSEDATE"); //$NON-NLS-1$
- //supportedFunctions.add("PARSETIME"); //$NON-NLS-1$
- //supportedFunctions.add("PARSETIMESTAMP"); //$NON-NLS-1$
- supportedFunctions.add("CAST"); //$NON-NLS-1$
- supportedFunctions.add("CONVERT"); //$NON-NLS-1$
- supportedFunctions.add("IFNULL"); //$NON-NLS-1$
- supportedFunctions.add("NVL"); //$NON-NLS-1$
- supportedFunctions.add("COALESCE"); //$NON-NLS-1$
-
- return supportedFunctions;
- }
-
- @Override
- public List<FunctionMethod> getPushDownFunctions(){
- return OracleSpatialFunctions.getOracleSpatialFunctions();
- }
-
- @Override
- public String translateLiteralTimestamp(Timestamp timestampValue) {
- if (timestampValue.getNanos() == 0) {
- String val = formatDateValue(timestampValue);
- val = val.substring(0, val.length() - 2);
- return "to_date('" + val + "', '" + DATETIME_FORMAT + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return super.translateLiteralTimestamp(timestampValue);
- }
-
- @Override
- public boolean supportsInlineViews() {
- return true;
- }
-
- @Override
- public boolean supportsFunctionsInGroupBy() {
- return true;
- }
- @Override
- public boolean supportsRowLimit() {
- return true;
- }
- @Override
- public boolean supportsRowOffset() {
- return true;
- }
-
- @Override
- public boolean supportsExcept() {
- return true;
- }
-
- @Override
- public boolean supportsIntersect() {
- return true;
- }
-
- @Override
- public boolean supportsAggregatesEnhancedNumeric() {
- return true;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java (from rev 3218, trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,535 @@
+/*
+ * 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 static org.teiid.translator.TypeFacility.RUNTIME_NAMES.*;
+
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import org.teiid.language.ColumnReference;
+import org.teiid.language.Command;
+import org.teiid.language.DerivedColumn;
+import org.teiid.language.Expression;
+import org.teiid.language.ExpressionValueSource;
+import org.teiid.language.Function;
+import org.teiid.language.Insert;
+import org.teiid.language.Limit;
+import org.teiid.language.Literal;
+import org.teiid.language.NamedTable;
+import org.teiid.language.QueryExpression;
+import org.teiid.language.Select;
+import org.teiid.language.SQLConstants.Tokens;
+import org.teiid.language.SetQuery.Operation;
+import org.teiid.language.visitor.CollectorVisitor;
+import org.teiid.metadata.Column;
+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.ExtractFunctionModifier;
+import org.teiid.translator.jdbc.FunctionModifier;
+import org.teiid.translator.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.LocateFunctionModifier;
+
+
+ at Translator(name="oracle", description="A translator for Oracle 9i Database or later")
+public class OracleExecutionFactory extends JDBCExecutionFactory {
+
+ private static final String TIME_FORMAT = "HH24:MI:SS"; //$NON-NLS-1$
+ private static final String DATE_FORMAT = "YYYY-MM-DD"; //$NON-NLS-1$
+ private static final String DATETIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT; //$NON-NLS-1$
+ private static final String TIMESTAMP_FORMAT = DATETIME_FORMAT + ".FF"; //$NON-NLS-1$
+
+ public final static String HINT_PREFIX = "/*+"; //$NON-NLS-1$
+ 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();
+
+ registerFunctionModifier(SourceSystemFunctions.CHAR, new AliasModifier("chr")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LCASE, new AliasModifier("lower")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.UCASE, new AliasModifier("upper")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.IFNULL, new AliasModifier("nvl")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LOG, new AliasModifier("ln")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.CEILING, new AliasModifier("ceil")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LOG10, new Log10FunctionModifier(getLanguageFactory()));
+ registerFunctionModifier(SourceSystemFunctions.HOUR, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.YEAR, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.MINUTE, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.SECOND, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.MONTH, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.MONTHNAME, new MonthOrDayNameFunctionModifier(getLanguageFactory(), "Month"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.DAYNAME, new MonthOrDayNameFunctionModifier(getLanguageFactory(), "Day"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.WEEK, new DayWeekQuarterFunctionModifier("WW"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.QUARTER, new DayWeekQuarterFunctionModifier("Q"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.DAYOFWEEK, new DayWeekQuarterFunctionModifier("D"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.DAYOFYEAR, new DayWeekQuarterFunctionModifier("DDD"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateFunctionModifier(getLanguageFactory(), "INSTR", true)); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.SUBSTRING, new AliasModifier("substr"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LEFT, new LeftOrRightFunctionModifier(getLanguageFactory()));
+ registerFunctionModifier(SourceSystemFunctions.RIGHT, new LeftOrRightFunctionModifier(getLanguageFactory()));
+ registerFunctionModifier(SourceSystemFunctions.CONCAT, new ConcatFunctionModifier(getLanguageFactory()));
+ 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));
+ }
+ });
+
+ //spatial functions
+ 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();
+ convertModifier.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
+ convertModifier.addTypeMapping("date", FunctionModifier.DATE, FunctionModifier.TIME); //$NON-NLS-1$
+ convertModifier.addTypeMapping("timestamp", FunctionModifier.TIMESTAMP); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.TIME, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ return Arrays.asList("case when ", function.getParameters().get(0), " is null then null else to_date('1970-01-01 ' || to_char(",function.getParameters().get(0),", 'HH24:MI:SS'), 'YYYY-MM-DD HH24:MI:SS') end"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ });
+ convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.DATE, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ return Arrays.asList("trunc(cast(",function.getParameters().get(0)," AS date))"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ });
+ convertModifier.addConvert(FunctionModifier.DATE, FunctionModifier.STRING, new ConvertModifier.FormatModifier("to_char", DATE_FORMAT)); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.STRING, new ConvertModifier.FormatModifier("to_char", TIME_FORMAT)); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.STRING, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ //if column and type is date, just use date format
+ Expression ex = function.getParameters().get(0);
+ String format = TIMESTAMP_FORMAT;
+ if (ex instanceof ColumnReference && "date".equalsIgnoreCase(((ColumnReference)ex).getMetadataObject().getNativeType())) { //$NON-NLS-1$
+ format = DATETIME_FORMAT;
+ } else if (!(ex instanceof Literal) && !(ex instanceof Function)) {
+ //this isn't needed in every case, but it's simpler than inspecting the expression more
+ ex = ConvertModifier.createConvertFunction(getLanguageFactory(), function.getParameters().get(0), TypeFacility.RUNTIME_NAMES.TIMESTAMP);
+ }
+ return Arrays.asList("to_char(", ex, ", '", format, "')"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ });
+ convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.DATE, new ConvertModifier.FormatModifier("to_date", DATE_FORMAT)); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIME, new ConvertModifier.FormatModifier("to_date", TIME_FORMAT)); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIMESTAMP, new ConvertModifier.FormatModifier("to_timestamp", TIMESTAMP_FORMAT)); //$NON-NLS-1$
+ convertModifier.addTypeConversion(new ConvertModifier.FormatModifier("to_char"), FunctionModifier.STRING); //$NON-NLS-1$
+ //NOTE: numeric handling in Oracle is split only between integral vs. floating/decimal types
+ convertModifier.addTypeConversion(new ConvertModifier.FormatModifier("to_number"), //$NON-NLS-1$
+ FunctionModifier.FLOAT, FunctionModifier.DOUBLE, FunctionModifier.BIGDECIMAL);
+ convertModifier.addTypeConversion(new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ if (Number.class.isAssignableFrom(function.getParameters().get(0).getType())) {
+ return Arrays.asList("trunc(", function.getParameters().get(0), ")"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return Arrays.asList("trunc(to_number(", function.getParameters().get(0), "))"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ },
+ FunctionModifier.BYTE, FunctionModifier.SHORT, FunctionModifier.INTEGER, FunctionModifier.LONG, FunctionModifier.BIGINTEGER);
+ 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 {
+ /*
+ * If a missing auto_increment column is modeled with name in source indicating that an Oracle Sequence
+ * then pull the Sequence name out of the name in source of the column.
+ */
+ if (!(insert.getValueSource() instanceof ExpressionValueSource)) {
+ return;
+ }
+ ExpressionValueSource values = (ExpressionValueSource)insert.getValueSource();
+ List<Column> allElements = insert.getTable().getMetadataObject().getColumns();
+ if (allElements.size() == values.getValues().size()) {
+ return;
+ }
+
+ int index = 0;
+ List<ColumnReference> elements = insert.getColumns();
+
+ for (Column element : allElements) {
+ if (!element.isAutoIncremented()) {
+ continue;
+ }
+ String name = element.getNameInSource();
+ int seqIndex = name.indexOf(SEQUENCE);
+ if (seqIndex == -1) {
+ continue;
+ }
+ boolean found = false;
+ while (index < elements.size()) {
+ if (element.equals(elements.get(index).getMetadataObject())) {
+ found = true;
+ break;
+ }
+ index++;
+ }
+ if (found) {
+ continue;
+ }
+
+ String sequence = name.substring(seqIndex + SEQUENCE.length());
+
+ int delimiterIndex = sequence.indexOf(Tokens.DOT);
+ if (delimiterIndex == -1) {
+ throw new TranslatorException("Invalid name in source sequence format. Expected <element name>" + SEQUENCE + "<sequence name>.<sequence value>, but was " + name); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ String sequenceGroupName = sequence.substring(0, delimiterIndex);
+ String sequenceElementName = sequence.substring(delimiterIndex + 1);
+
+ NamedTable sequenceGroup = this.getLanguageFactory().createNamedTable(sequenceGroupName, null, null);
+ ColumnReference sequenceElement = this.getLanguageFactory().createColumnReference(sequenceElementName, sequenceGroup, null, element.getJavaType());
+ insert.getColumns().add(index, this.getLanguageFactory().createColumnReference(element.getName(), insert.getTable(), element, element.getJavaType()));
+ values.getValues().add(index, sequenceElement);
+ }
+ }
+
+ @Override
+ public List<?> translateCommand(Command command, ExecutionContext context) {
+ if (command instanceof Insert) {
+ try {
+ handleInsertSequences((Insert)command);
+ } catch (TranslatorException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ if (!(command instanceof QueryExpression)) {
+ return null;
+ }
+ QueryExpression queryCommand = (QueryExpression)command;
+ if (queryCommand.getLimit() == null) {
+ return null;
+ }
+ Limit limit = queryCommand.getLimit();
+ queryCommand.setLimit(null);
+ List<Object> parts = new ArrayList<Object>();
+ parts.add("SELECT "); //$NON-NLS-1$
+ /*
+ * if all of the columns are aliased, assume that names matter - it actually only seems to matter for
+ * the first query of a set op when there is a order by. Rather than adding logic to traverse up,
+ * we just use the projected names
+ */
+ boolean allAliased = true;
+ for (DerivedColumn selectSymbol : queryCommand.getProjectedQuery().getDerivedColumns()) {
+ if (selectSymbol.getAlias() == null) {
+ allAliased = false;
+ break;
+ }
+ }
+ if (allAliased) {
+ String[] columnNames = queryCommand.getColumnNames();
+ for (int i = 0; i < columnNames.length; i++) {
+ if (i > 0) {
+ parts.add(", "); //$NON-NLS-1$
+ }
+ parts.add(columnNames[i]);
+ }
+ } else {
+ parts.add("*"); //$NON-NLS-1$
+ }
+ if (limit.getRowOffset() > 0) {
+ parts.add(" FROM (SELECT VIEW_FOR_LIMIT.*, ROWNUM ROWNUM_ FROM ("); //$NON-NLS-1$
+ } else {
+ parts.add(" FROM ("); //$NON-NLS-1$
+ }
+ parts.add(queryCommand);
+ if (limit.getRowOffset() > 0) {
+ parts.add(") VIEW_FOR_LIMIT WHERE ROWNUM <= "); //$NON-NLS-1$
+ parts.add(limit.getRowLimit() + limit.getRowOffset());
+ parts.add(") WHERE ROWNUM_ > "); //$NON-NLS-1$
+ parts.add(limit.getRowOffset());
+ } else {
+ parts.add(") WHERE ROWNUM <= "); //$NON-NLS-1$
+ parts.add(limit.getRowLimit());
+ }
+ return parts;
+ }
+
+ @Override
+ public boolean useAsInGroupAlias(){
+ return false;
+ }
+
+ @Override
+ public String getSetOperationString(Operation operation) {
+ if (operation == Operation.EXCEPT) {
+ return "MINUS"; //$NON-NLS-1$
+ }
+ return super.getSetOperationString(operation);
+ }
+
+ @Override
+ public String getSourceComment(ExecutionContext context, Command command) {
+ String comment = super.getSourceComment(context, command);
+
+ if (context != null) {
+ // Check for db hints
+ Object payload = context.getExecutionPayload();
+ if (payload instanceof String) {
+ String payloadString = (String)payload;
+ if (payloadString.startsWith(HINT_PREFIX)) {
+ comment += payloadString + " "; //$NON-NLS-1$
+ }
+ }
+ }
+
+ if (command instanceof Select) {
+ //
+ // This simple algorithm determines the hint which will be added to the
+ // query.
+ // Right now, we look through all functions passed in the query
+ // (returned as a collection)
+ // Then we check if any of those functions are sdo_relate
+ // 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(OracleExecutionFactory.RELATE)) {
+ return comment + "/*+ ORDERED */ "; //$NON-NLS-1$
+ }
+ }
+ }
+ return comment;
+ }
+
+ /**
+ * Don't fully qualify elements if table = DUAL or element = ROWNUM or special stuff is packed into name in source value.
+ *
+ * @see org.teiid.language.visitor.SQLStringVisitor#skipGroupInElement(java.lang.String, java.lang.String)
+ * @since 5.0
+ */
+ @Override
+ public String replaceElementName(String group, String element) {
+
+ // Check if the element was modeled as using a Sequence
+ int useIndex = element.indexOf(SEQUENCE);
+ if (useIndex >= 0) {
+ String name = element.substring(0, useIndex);
+ if (group != null) {
+ return group + Tokens.DOT + name;
+ }
+ return name;
+ }
+
+ // Check if the group name should be discarded
+ if((group != null && DUAL.equalsIgnoreCase(group)) || element.equalsIgnoreCase(ROWNUM)) {
+ // Strip group if group or element are pseudo-columns
+ return element;
+ }
+
+ return null;
+ }
+
+ @Override
+ public boolean hasTimeType() {
+ return false;
+ }
+
+ @Override
+ public void bindValue(PreparedStatement stmt, Object param, Class<?> paramType, int i) throws SQLException {
+ if(param == null && Object.class.equals(paramType)){
+ //Oracle drive does not support JAVA_OBJECT type
+ stmt.setNull(i, Types.LONGVARBINARY);
+ return;
+ }
+ super.bindValue(stmt, param, paramType, i);
+ }
+
+ @Override
+ public NullOrder getDefaultNullOrder() {
+ return NullOrder.HIGH;
+ }
+
+ @Override
+ public boolean supportsOrderByNullOrdering() {
+ return true;
+ }
+
+ @Override
+ public List<String> getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+ supportedFunctions.add("ABS"); //$NON-NLS-1$
+ supportedFunctions.add("ACOS"); //$NON-NLS-1$
+ supportedFunctions.add("ASIN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN2"); //$NON-NLS-1$
+ supportedFunctions.add("COS"); //$NON-NLS-1$
+ supportedFunctions.add(SourceSystemFunctions.COT);
+ supportedFunctions.add("EXP"); //$NON-NLS-1$
+ supportedFunctions.add("FLOOR"); //$NON-NLS-1$
+ supportedFunctions.add("CEILING"); //$NON-NLS-1$
+ supportedFunctions.add("LOG"); //$NON-NLS-1$
+ supportedFunctions.add("LOG10"); //$NON-NLS-1$
+ supportedFunctions.add("MOD"); //$NON-NLS-1$
+ supportedFunctions.add("POWER"); //$NON-NLS-1$
+ supportedFunctions.add("SIGN"); //$NON-NLS-1$
+ supportedFunctions.add("SIN"); //$NON-NLS-1$
+ supportedFunctions.add("SQRT"); //$NON-NLS-1$
+ supportedFunctions.add("TAN"); //$NON-NLS-1$
+ supportedFunctions.add("ASCII"); //$NON-NLS-1$
+ supportedFunctions.add("CHAR"); //$NON-NLS-1$
+ supportedFunctions.add("CHR"); //$NON-NLS-1$
+ supportedFunctions.add("CONCAT"); //$NON-NLS-1$
+ supportedFunctions.add("||"); //$NON-NLS-1$
+ supportedFunctions.add("INITCAP"); //$NON-NLS-1$
+ supportedFunctions.add("LCASE"); //$NON-NLS-1$
+ supportedFunctions.add("LENGTH"); //$NON-NLS-1$
+ supportedFunctions.add("LEFT"); //$NON-NLS-1$
+ supportedFunctions.add("LOCATE"); //$NON-NLS-1$
+ supportedFunctions.add("LOWER"); //$NON-NLS-1$
+ supportedFunctions.add("LPAD"); //$NON-NLS-1$
+ supportedFunctions.add("LTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("REPLACE"); //$NON-NLS-1$
+ supportedFunctions.add("RPAD"); //$NON-NLS-1$
+ supportedFunctions.add("RIGHT"); //$NON-NLS-1$
+ supportedFunctions.add("RTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
+ supportedFunctions.add("TRANSLATE"); //$NON-NLS-1$
+ supportedFunctions.add("UCASE"); //$NON-NLS-1$
+ supportedFunctions.add("UPPER"); //$NON-NLS-1$
+ supportedFunctions.add("HOUR"); //$NON-NLS-1$
+ supportedFunctions.add("MONTH"); //$NON-NLS-1$
+ supportedFunctions.add("MONTHNAME"); //$NON-NLS-1$
+ supportedFunctions.add("YEAR"); //$NON-NLS-1$
+ supportedFunctions.add("DAY"); //$NON-NLS-1$
+ supportedFunctions.add("DAYNAME"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFMONTH"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFWEEK"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFYEAR"); //$NON-NLS-1$
+ supportedFunctions.add("QUARTER"); //$NON-NLS-1$
+ supportedFunctions.add("MINUTE"); //$NON-NLS-1$
+ supportedFunctions.add("SECOND"); //$NON-NLS-1$
+ supportedFunctions.add("QUARTER"); //$NON-NLS-1$
+ supportedFunctions.add("WEEK"); //$NON-NLS-1$
+ //supportedFunctions.add("FORMATDATE"); //$NON-NLS-1$
+ //supportedFunctions.add("FORMATTIME"); //$NON-NLS-1$
+ //supportedFunctions.add("FORMATTIMESTAMP"); //$NON-NLS-1$
+ //supportedFunctions.add("PARSEDATE"); //$NON-NLS-1$
+ //supportedFunctions.add("PARSETIME"); //$NON-NLS-1$
+ //supportedFunctions.add("PARSETIMESTAMP"); //$NON-NLS-1$
+ supportedFunctions.add("CAST"); //$NON-NLS-1$
+ supportedFunctions.add("CONVERT"); //$NON-NLS-1$
+ 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 String translateLiteralTimestamp(Timestamp timestampValue) {
+ if (timestampValue.getNanos() == 0) {
+ String val = formatDateValue(timestampValue);
+ val = val.substring(0, val.length() - 2);
+ return "to_date('" + val + "', '" + DATETIME_FORMAT + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ return super.translateLiteralTimestamp(timestampValue);
+ }
+
+ @Override
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsFunctionsInGroupBy() {
+ return true;
+ }
+ @Override
+ public boolean supportsRowLimit() {
+ return true;
+ }
+ @Override
+ public boolean supportsRowOffset() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsExcept() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsIntersect() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsAggregatesEnhancedNumeric() {
+ return true;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSpatialFunctions.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSpatialFunctions.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSpatialFunctions.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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;
- }
-}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,474 +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.teradata;
-
-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.teiid.core.types.DataTypeManager;
-import org.teiid.language.ColumnReference;
-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.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.SQLConversionVisitor;
-
-
-
-/**
- * Teradata database Release 12
- */
- at Translator(name="teradata", description="A translator for Teradata Database")
-public class TeradataExecutionFactory extends JDBCExecutionFactory {
-
- public static String TERADATA = "teradata"; //$NON-NLS-1$
- protected ConvertModifier convert = new ConvertModifier();
-
- public TeradataExecutionFactory() {
- setSupportsOuterJoins(false);
- }
-
- @Override
- public void start() throws TranslatorException {
- super.start();
- convert.addTypeMapping("byteint", FunctionModifier.BYTE, FunctionModifier.SHORT, FunctionModifier.BOOLEAN); //$NON-NLS-1$
- 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.addTypeMapping("varchar(4000)", FunctionModifier.STRING); //$NON-NLS-1$
- convert.addNumericBooleanConversions();
-
- registerFunctionModifier(SourceSystemFunctions.CONVERT, convert);
-
- 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.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$
- registerFunctionModifier(SourceSystemFunctions.MONTH, new ExtractModifier("MONTH")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new ExtractModifier("DAY")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.HOUR, new ExtractModifier("HOUR")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.MINUTE, new ExtractModifier("MINUTE")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.SECOND, new ExtractModifier("SECOND")); //$NON-NLS-1$
- registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateModifier(this.convert));
- registerFunctionModifier(SourceSystemFunctions.LEFT, new LeftOrRightFunctionModifier(getLanguageFactory(), this.convert));
- registerFunctionModifier(SourceSystemFunctions.RIGHT, new LeftOrRightFunctionModifier(getLanguageFactory(), this.convert));
- 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 ", expressionToString(function.getParameters().get(0), convert), ")"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- });
- 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$
- }
- });
- 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
- public SQLConversionVisitor getSQLConversionVisitor() {
- return new TeradataSQLConversionVisitor(this);
- }
-
-
- @Override
- public List getSupportedFunctions() {
- List<String> supportedFunctions = new ArrayList<String>();
- supportedFunctions.addAll(super.getSupportedFunctions());
-
- supportedFunctions.add(SourceSystemFunctions.ABS);
- supportedFunctions.add(SourceSystemFunctions.ACOS);
- supportedFunctions.add(SourceSystemFunctions.ASIN);
- supportedFunctions.add(SourceSystemFunctions.ATAN);
- supportedFunctions.add(SourceSystemFunctions.ATAN2);
- supportedFunctions.add(SourceSystemFunctions.COALESCE);
- supportedFunctions.add(SourceSystemFunctions.COS);
- supportedFunctions.add(SourceSystemFunctions.COT);
- supportedFunctions.add(SourceSystemFunctions.CONVERT);
- supportedFunctions.add(SourceSystemFunctions.CURDATE);
- supportedFunctions.add(SourceSystemFunctions.CURTIME);
- supportedFunctions.add(SourceSystemFunctions.DAYOFMONTH);
- supportedFunctions.add(SourceSystemFunctions.EXP);
- supportedFunctions.add(SourceSystemFunctions.HOUR);
- supportedFunctions.add(SourceSystemFunctions.LEFT);
- 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);
- supportedFunctions.add(SourceSystemFunctions.MOD);
- supportedFunctions.add(SourceSystemFunctions.MONTH);
- supportedFunctions.add(SourceSystemFunctions.NULLIF);
- supportedFunctions.add(SourceSystemFunctions.RAND);
- supportedFunctions.add(SourceSystemFunctions.RIGHT);
- supportedFunctions.add(SourceSystemFunctions.RTRIM);
- supportedFunctions.add(SourceSystemFunctions.SECOND);
- supportedFunctions.add(SourceSystemFunctions.SIN);
- 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.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$
- }
-
- @Override
- public String translateLiteralTime(Time timeValue) {
- return "cast('" + formatDateValue(timeValue) + "' AS TIME(0) FORMAT 'hh:mi:ss')"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- @Override
- public String translateLiteralTimestamp(Timestamp timestampValue) {
- return "cast('" + formatDateValue(timestampValue) + "' AS TIMESTAMP(6))"; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- // Teradata also supports MINUS & ALL set operators
- // more aggregates available
-
- @Override
- public boolean supportsScalarSubqueries() {
- return false;
- }
-
- @Override
- public boolean supportsUnions() {
- return true;
- }
-
- @Override
- public boolean supportsIntersect() {
- return true;
- }
-
- @Override
- public boolean supportsExcept() {
- return true;
- }
-
- @Override
- public boolean supportsInlineViews() {
- return true;
- }
-
- @Override
- public boolean supportsAggregatesEnhancedNumeric() {
- return true;
- }
-
- @Override
- public boolean supportsCommonTableExpressions() {
- return false;
- }
-
- @Override
- public NullOrder getDefaultNullOrder() {
- return NullOrder.FIRST;
- }
-
- @Override
- public boolean supportsSetQueryOrderBy() {
- return false;
- }
-
- public static class LocateModifier extends FunctionModifier {
- ConvertModifier convertModifier;
-
- public LocateModifier(ConvertModifier convertModifier) {
- this.convertModifier = convertModifier;
- }
-
- @Override
- public List<?> translate(Function function) {
- 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$
- 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) {
- this.type = type;
- }
- @Override
- public List<?> translate(Function function) {
- return Arrays.asList("extract(",this.type," from ",function.getParameters().get(0) ,")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- }
-
- 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 {
- private String target;
- public TimeModifier(String target) {
- this.target = target;
- }
- @Override
- public List<?> translate(Function function) {
- return Arrays.asList("cast(", function.getParameters().get(0), " AS "+this.target+")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- }
-
- 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;
-
- public LeftOrRightFunctionModifier(LanguageFactory langFactory, ConvertModifier converModifier) {
- this.langFactory = langFactory;
- this.convertModifier = converModifier;
- }
-
- @Override
- public List<?> translate(Function function) {
- List<Expression> args = function.getParameters();
- ArrayList target = new ArrayList();
- 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(langFactory.createLiteral(Integer.valueOf(1), TypeFacility.RUNTIME_TYPES.INTEGER));
- 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(",(character_length("); //$NON-NLS-1$
- target.addAll(expressionToString(args.get(0), this.convertModifier));
- target.add(")-"); //$NON-NLS-1$
- target.add(args.get(1));
- target.add("))"); //$NON-NLS-1$
- }
- return target;
- }
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java (from rev 3218, trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,512 @@
+/*
+ * 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.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.List;
+
+import org.teiid.language.ColumnReference;
+import org.teiid.language.Expression;
+import org.teiid.language.Function;
+import org.teiid.language.LanguageFactory;
+import org.teiid.language.Literal;
+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.SQLConversionVisitor;
+
+
+
+/**
+ * Teradata database Release 12
+ */
+ at Translator(name="teradata", description="A translator for Teradata Database")
+public class TeradataExecutionFactory extends JDBCExecutionFactory {
+
+ public static String TERADATA = "teradata"; //$NON-NLS-1$
+ protected ConvertModifier convert = new ConvertModifier();
+
+ public TeradataExecutionFactory() {
+ setSupportsOuterJoins(false);
+ }
+
+ @Override
+ public void start() throws TranslatorException {
+ super.start();
+ convert.addTypeMapping("byteint", FunctionModifier.BYTE, FunctionModifier.SHORT, FunctionModifier.BOOLEAN); //$NON-NLS-1$
+ 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.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 SubstrModifier(this.convert));
+ registerFunctionModifier(SourceSystemFunctions.RAND, new AliasModifier("random")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LOG, new AliasModifier("LN")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LCASE, new StringOnlyModifier("LOWER", this.convert)); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.UCASE, new StringOnlyModifier("UPPER", this.convert)); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LENGTH, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ ArrayList target = new ArrayList();
+ target.add("character_length("); //$NON-NLS-1$
+ target.addAll(expressionToString(function.getParameters().get(0), convert));
+ target.add(")"); //$NON-NLS-1$
+ return target;
+ }
+ });
+ 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$
+ registerFunctionModifier(SourceSystemFunctions.MONTH, new ExtractModifier("MONTH")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new ExtractModifier("DAY")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.HOUR, new ExtractModifier("HOUR")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.MINUTE, new ExtractModifier("MINUTE")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.SECOND, new ExtractModifier("SECOND")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateModifier(this.convert));
+ registerFunctionModifier(SourceSystemFunctions.LEFT, new LeftOrRightFunctionModifier(getLanguageFactory(), this.convert));
+ registerFunctionModifier(SourceSystemFunctions.RIGHT, new LeftOrRightFunctionModifier(getLanguageFactory(), this.convert));
+ 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) {
+ ArrayList target = new ArrayList();
+ target.add("TRIM(LEADING FROM ");//$NON-NLS-1$
+ target.addAll(expressionToString(function.getParameters().get(0), convert));
+ target.add(")"); //$NON-NLS-1$
+ return target;
+ }
+ });
+ registerFunctionModifier(SourceSystemFunctions.RTRIM, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ ArrayList target = new ArrayList();
+ target.add("TRIM(TRAILING FROM ");//$NON-NLS-1$
+ target.addAll(expressionToString(function.getParameters().get(0), convert));
+ target.add(")"); //$NON-NLS-1$
+ return target;
+ }
+ });
+ 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$
+ }
+ });
+
+ 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
+ public SQLConversionVisitor getSQLConversionVisitor() {
+ return new TeradataSQLConversionVisitor(this);
+ }
+
+
+ @Override
+ public List getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+
+ supportedFunctions.add(SourceSystemFunctions.ABS);
+ supportedFunctions.add(SourceSystemFunctions.ACOS);
+ supportedFunctions.add(SourceSystemFunctions.ASIN);
+ supportedFunctions.add(SourceSystemFunctions.ATAN);
+ supportedFunctions.add(SourceSystemFunctions.ATAN2);
+ supportedFunctions.add(SourceSystemFunctions.COALESCE);
+ supportedFunctions.add(SourceSystemFunctions.COS);
+ supportedFunctions.add(SourceSystemFunctions.COT);
+ supportedFunctions.add(SourceSystemFunctions.CONVERT);
+ supportedFunctions.add(SourceSystemFunctions.CURDATE);
+ supportedFunctions.add(SourceSystemFunctions.CURTIME);
+ supportedFunctions.add(SourceSystemFunctions.DAYOFMONTH);
+ supportedFunctions.add(SourceSystemFunctions.EXP);
+ supportedFunctions.add(SourceSystemFunctions.HOUR);
+ supportedFunctions.add(SourceSystemFunctions.LEFT);
+ supportedFunctions.add(SourceSystemFunctions.LOCATE);
+ supportedFunctions.add(SourceSystemFunctions.LOG);
+ supportedFunctions.add(SourceSystemFunctions.LCASE);
+ supportedFunctions.add(SourceSystemFunctions.LTRIM);
+ supportedFunctions.add(SourceSystemFunctions.LENGTH);
+ supportedFunctions.add(SourceSystemFunctions.MINUTE);
+ supportedFunctions.add(SourceSystemFunctions.MOD);
+ supportedFunctions.add(SourceSystemFunctions.MONTH);
+ supportedFunctions.add(SourceSystemFunctions.NULLIF);
+ supportedFunctions.add(SourceSystemFunctions.RAND);
+ supportedFunctions.add(SourceSystemFunctions.RIGHT);
+ supportedFunctions.add(SourceSystemFunctions.RTRIM);
+ supportedFunctions.add(SourceSystemFunctions.SECOND);
+ supportedFunctions.add(SourceSystemFunctions.SIN);
+ supportedFunctions.add(SourceSystemFunctions.SQRT);
+ supportedFunctions.add(SourceSystemFunctions.SUBSTRING);
+ supportedFunctions.add(SourceSystemFunctions.TAN);
+ supportedFunctions.add(SourceSystemFunctions.UCASE);
+ supportedFunctions.add(SourceSystemFunctions.YEAR);
+
+ return supportedFunctions;
+ }
+
+ @Override
+ public String translateLiteralDate(Date dateValue) {
+ return "cast('" + formatDateValue(dateValue) + "' AS DATE FORMAT 'yyyy-mm-dd')"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ @Override
+ public String translateLiteralTime(Time timeValue) {
+ return "cast('" + formatDateValue(timeValue) + "' AS TIME(0) FORMAT 'hh:mi:ss')"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ @Override
+ public String translateLiteralTimestamp(Timestamp timestampValue) {
+ return "cast('" + formatDateValue(timestampValue) + "' AS TIMESTAMP(6))"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ // Teradata also supports MINUS & ALL set operators
+ // more aggregates available
+
+ @Override
+ public boolean supportsScalarSubqueries() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsUnions() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsIntersect() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsExcept() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsAggregatesEnhancedNumeric() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsCommonTableExpressions() {
+ return false;
+ }
+
+ @Override
+ public NullOrder getDefaultNullOrder() {
+ return NullOrder.FIRST;
+ }
+
+ @Override
+ public boolean supportsSetQueryOrderBy() {
+ return false;
+ }
+
+ public static class LocateModifier extends FunctionModifier {
+ ConvertModifier convertModifier;
+
+ public LocateModifier(ConvertModifier convertModifier) {
+ this.convertModifier = convertModifier;
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ ArrayList target = new ArrayList();
+ Expression expr1 = function.getParameters().get(0);
+ Expression expr2 = function.getParameters().get(1);
+ if (function.getParameters().size() > 2) {
+ Expression expr3 = function.getParameters().get(2);
+ target.add("position("); //$NON-NLS-1$
+ target.addAll(expressionToString(expr1, this.convertModifier));
+ target.add( " in "); //$NON-NLS-1$
+ target.add("substr("); //$NON-NLS-1$
+ target.addAll(expressionToString(expr2, this.convertModifier));
+ target.add(","); //$NON-NLS-1$
+ target.add(expr3);
+ target.add("))"); //$NON-NLS-1$
+ }
+ else {
+ 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$
+ }
+ return target;
+ }
+ }
+
+ private static List<?> expressionToString(Expression expr, ConvertModifier modifier) {
+ Class tgtType = expr.getType();
+ if (tgtType.equals(String.class) && ((expr instanceof Literal) || expr instanceof ColumnReference)) {
+ return Arrays.asList(expr);
+ }
+ else if (tgtType.equals(String.class) && (expr instanceof Function)) {
+
+ Function func = (Function)expr;
+ while(true) {
+ Expression arg1 = func.getParameters().get(0);
+ if ((arg1 instanceof Function) && ((Function)arg1).getName().equals("convert")) { //$NON-NLS-1$
+ func = (Function)arg1;
+ }
+ else {
+ break;
+ }
+ }
+ Expression arg1 = func.getParameters().get(0);
+ if (arg1 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$
+ return target;
+ }
+ else if (String.class.isAssignableFrom(ref.getType())) {
+ return Arrays.asList(ref);
+ }
+ }
+ 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) {
+ this.type = type;
+ }
+ @Override
+ public List<?> translate(Function function) {
+ return Arrays.asList("extract(",this.type," from ",function.getParameters().get(0) ,")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ }
+
+ 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+")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ }
+
+ public static class StringOnlyModifier extends FunctionModifier {
+ String funcName;
+ ConvertModifier convertModifier;
+ public StringOnlyModifier(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 SubstrModifier extends FunctionModifier {
+ ConvertModifier convertModifier;
+ public SubstrModifier(ConvertModifier converModifier) {
+ this.convertModifier = converModifier;
+ }
+ @Override
+ public List<?> translate(Function function) {
+ Expression expr = function.getParameters().get(0);
+ ArrayList target = new ArrayList();
+ target.add("substr("); //$NON-NLS-1$
+ target.addAll(expressionToString(expr, this.convertModifier));
+ target.add(","); //$NON-NLS-1$
+ target.add(function.getParameters().get(1));
+ if (function.getParameters().size() > 2 ) {
+ target.add(","); //$NON-NLS-1$
+ target.add(function.getParameters().get(2));
+ }
+ target.add(")"); //$NON-NLS-1$
+ return target;
+ }
+ }
+
+ public static class LeftOrRightFunctionModifier extends FunctionModifier {
+ private LanguageFactory langFactory;
+ ConvertModifier convertModifier;
+
+ public LeftOrRightFunctionModifier(LanguageFactory langFactory, ConvertModifier converModifier) {
+ this.langFactory = langFactory;
+ this.convertModifier = converModifier;
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ List<Expression> args = function.getParameters();
+ ArrayList target = new ArrayList();
+ 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(","); //$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(",(character_length("); //$NON-NLS-1$
+ target.addAll(expressionToString(args.get(0), this.convertModifier));
+ target.add(")-"); //$NON-NLS-1$
+ target.add(args.get(1));
+ target.add("+1))"); //$NON-NLS-1$ // offset for 1 based index
+ }
+ return target;
+ }
+ }
+
+ 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;
+ }
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.translator.jdbc;
-
-import static org.junit.Assert.assertEquals;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import javax.xml.bind.JAXBException;
-
-import junit.framework.Assert;
-
-import org.mockito.Mockito;
-import org.teiid.cdk.api.TranslationUtility;
-import org.teiid.cdk.unittest.FakeTranslationFactory;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.language.Command;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.query.function.metadata.FunctionMetadataReader;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.ExecutionContext;
-
-
-public class TranslationHelper {
-
- public static final String PARTS_VDB = "/PartsSupplier.vdb"; //$NON-NLS-1$
- public static final String BQT_VDB = "/bqt.vdb"; //$NON-NLS-1$
-
- public static Command helpTranslate(String vdbFileName, String sql) {
- return helpTranslate(vdbFileName, null, null, sql);
- }
-
- public static TranslationUtility getTranslationUtility(String vdbFileName, String udf) {
- TranslationUtility util = null;
- if (PARTS_VDB.equals(vdbFileName)) {
- util = new TranslationUtility(TranslationHelper.class.getResource(vdbFileName));
- } else if (BQT_VDB.equals(vdbFileName)){
- util = FakeTranslationFactory.getInstance().getBQTTranslationUtility();
- } else {
- Assert.fail("unknown vdb"); //$NON-NLS-1$
- }
-
- if (udf != null) {
- loadUDFs(udf, util);
- }
- return util;
- }
-
- public static void loadUDFs(String udf, TranslationUtility util) {
- try {
- Collection <FunctionMethod> methods = FunctionMetadataReader.loadFunctionMethods(TranslationHelper.class.getResource(udf).openStream());
- util.setUDF(methods);
- } catch (IOException e) {
- throw new TeiidRuntimeException("failed to load UDF"); //$NON-NLS-1$
- } catch (JAXBException e) {
- throw new TeiidRuntimeException("failed to load UDF"); //$NON-NLS-1$
- }
- }
-
- 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 (udf != null) {
- try {
- methods.addAll(FunctionMetadataReader.loadFunctionMethods(TranslationHelper.class.getResource(udf).openStream()));
- } catch (JAXBException e) {
- throw new TeiidRuntimeException("failed to load UDF"); //$NON-NLS-1$
- } catch (IOException e) {
- throw new TeiidRuntimeException("failed to load UDF"); //$NON-NLS-1$
- }
- }
- if (pushdowns != null) {
- methods.addAll(pushdowns);
- }
- util.setUDF(methods);
- return util.parseCommand(sql);
- }
-
- public static void helpTestVisitor(String vdb, String input, String expectedOutput, JDBCExecutionFactory translator) throws TranslatorException {
- helpTestVisitor(vdb,null,input, expectedOutput, translator);
- }
-
- public static void helpTestVisitor(String vdb, String udf, String input, String expectedOutput, JDBCExecutionFactory translator) throws TranslatorException {
- // Convert from sql to objects
- Command obj = helpTranslate(vdb, udf, translator.getPushDownFunctions(), input);
-
- helpTestVisitor(expectedOutput, translator, obj);
- }
-
- public static void helpTestVisitor(String expectedOutput, JDBCExecutionFactory translator, Command obj) throws TranslatorException {
- TranslatedCommand tc = new TranslatedCommand(Mockito.mock(ExecutionContext.class), translator);
- tc.translateCommand(obj);
- assertEquals("Did not get correct sql", expectedOutput, tc.getSql()); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java (from rev 3218, trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,121 @@
+/*
+ * 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;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import javax.xml.bind.JAXBException;
+
+import junit.framework.Assert;
+
+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;
+import org.teiid.query.function.metadata.FunctionMetadataReader;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.ExecutionContext;
+
+
+public class TranslationHelper {
+
+ public static final String PARTS_VDB = "/PartsSupplier.vdb"; //$NON-NLS-1$
+ public static final String BQT_VDB = "/bqt.vdb"; //$NON-NLS-1$
+
+ public static Command helpTranslate(String vdbFileName, String sql) {
+ return helpTranslate(vdbFileName, null, null, sql);
+ }
+
+ public static TranslationUtility getTranslationUtility(String vdbFileName, String udf) {
+ TranslationUtility util = null;
+ if (PARTS_VDB.equals(vdbFileName)) {
+ util = new TranslationUtility(TranslationHelper.class.getResource(vdbFileName));
+ } else if (BQT_VDB.equals(vdbFileName)){
+ util = FakeTranslationFactory.getInstance().getBQTTranslationUtility();
+ } else {
+ Assert.fail("unknown vdb"); //$NON-NLS-1$
+ }
+
+ if (udf != null) {
+ loadUDFs(udf, util);
+ }
+ return util;
+ }
+
+ public static void loadUDFs(String udf, TranslationUtility util) {
+ try {
+ Collection <FunctionMethod> methods = FunctionMetadataReader.loadFunctionMethods(TranslationHelper.class.getResource(udf).openStream());
+ util.addUDF("foo", methods); //$NON-NLS-1$
+ } catch (IOException e) {
+ throw new TeiidRuntimeException("failed to load UDF"); //$NON-NLS-1$
+ } catch (JAXBException e) {
+ throw new TeiidRuntimeException("failed to load UDF"); //$NON-NLS-1$
+ }
+ }
+
+ public static Command helpTranslate(String vdbFileName, String udf, List<FunctionMethod> pushdowns, String sql) {
+ TranslationUtility util = getTranslationUtility(vdbFileName, null);
+
+ 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) {
+ throw new TeiidRuntimeException("failed to load UDF"); //$NON-NLS-1$
+ } catch (IOException e) {
+ throw new TeiidRuntimeException("failed to load UDF"); //$NON-NLS-1$
+ }
+ util.addUDF("foo", methods); //$NON-NLS-1$
+ }
+ return util.parseCommand(sql);
+ }
+
+ public static void helpTestVisitor(String vdb, String input, String expectedOutput, JDBCExecutionFactory translator) throws TranslatorException {
+ helpTestVisitor(vdb,null,input, expectedOutput, translator);
+ }
+
+ public static void helpTestVisitor(String vdb, String udf, String input, String expectedOutput, JDBCExecutionFactory translator) throws TranslatorException {
+ // Convert from sql to objects
+ Command obj = helpTranslate(vdb, udf, translator.getPushDownFunctions(), input);
+
+ helpTestVisitor(expectedOutput, translator, obj);
+ }
+
+ public static void helpTestVisitor(String expectedOutput, JDBCExecutionFactory translator, Command obj) throws TranslatorException {
+ TranslatedCommand tc = new TranslatedCommand(Mockito.mock(ExecutionContext.class), translator);
+ tc.translateCommand(obj);
+ assertEquals("Did not get correct sql", expectedOutput, tc.getSql()); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,777 +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 static org.junit.Assert.assertEquals;
-
-import java.util.List;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.teiid.cdk.CommandBuilder;
-import org.teiid.cdk.api.TranslationUtility;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.UnitTestUtil;
-import org.teiid.dqp.internal.datamgr.ExecutionContextImpl;
-import org.teiid.dqp.internal.datamgr.FakeExecutionContextImpl;
-import org.teiid.language.Command;
-import org.teiid.metadata.Column;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.metadata.Schema;
-import org.teiid.metadata.Table;
-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.ExecutionContext;
-import org.teiid.translator.jdbc.TranslatedCommand;
-import org.teiid.translator.jdbc.TranslationHelper;
-
-
-public class TestOracleTranslator {
-
- private OracleExecutionFactory TRANSLATOR;
- private String UDF = "/OracleSpatialFunctions.xmi"; //$NON-NLS-1$;
- private static ExecutionContext EMPTY_CONTEXT = new FakeExecutionContextImpl();
-
- @Before
- public void setup() throws Exception {
- TRANSLATOR = new OracleExecutionFactory();
- TRANSLATOR.setUseBindVariables(false);
- TRANSLATOR.start();
- }
-
- private void helpTestVisitor(String input, String expectedOutput) throws TranslatorException {
- helpTestVisitor(getOracleSpecificMetadata(), input, EMPTY_CONTEXT, null, expectedOutput);
- }
-
- @Test public void testInsertWithSequnce() throws Exception {
- helpTestVisitor("insert into smalla (doublenum) values (1)", "INSERT INTO SmallishA (DoubleNum, ID) VALUES (1.0, MYSEQUENCE.nextVal)"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testInsertWithSequnce1() throws Exception {
- helpTestVisitor("insert into smalla (doublenum, id) values (1, 1)", "INSERT INTO SmallishA (DoubleNum, ID) VALUES (1.0, 1)"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testJoins() throws Exception {
- String input = "select smalla.intkey from bqt1.smalla inner join bqt1.smallb on smalla.stringkey=smallb.stringkey cross join bqt1.mediuma"; //$NON-NLS-1$
- String output = "SELECT SmallA.IntKey FROM SmallA INNER JOIN SmallB ON SmallA.StringKey = SmallB.StringKey CROSS JOIN MediumA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input,
- output, TRANSLATOR);
- }
-
- @Test public void testJoins2() throws Exception {
- String input = "select smalla.intkey from bqt1.smalla cross join (bqt1.smallb cross join bqt1.mediuma)"; //$NON-NLS-1$
- String output = "SELECT SmallA.IntKey FROM SmallA CROSS JOIN (SmallB CROSS JOIN MediumA)"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input,
- output, TRANSLATOR);
- }
-
- @Test public void testConversion1() throws Exception {
- String input = "SELECT char(convert(STRINGNUM, integer) + 100) FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT chr((trunc(to_number(SmallA.StringNum)) + 100)) FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- @Test public void testConversion2() throws Exception {
- String input = "SELECT convert(STRINGNUM, long) FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT trunc(to_number(SmallA.StringNum)) FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- @Test public void testConversion3() throws Exception {
- String input = "SELECT convert(convert(STRINGNUM, long), string) FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT to_char(trunc(to_number(SmallA.StringNum))) FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- @Test public void testConversion4() throws Exception {
- String input = "SELECT convert(convert(TIMESTAMPVALUE, date), string) FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT to_char(trunc(cast(SmallA.TimestampValue AS date)), 'YYYY-MM-DD') FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
- @Test public void testConversion6() throws Exception {
- String input = "SELECT convert(convert(TIMEVALUE, timestamp), string) FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT to_char(cast(SmallA.TimeValue AS timestamp), 'YYYY-MM-DD HH24:MI:SS.FF') FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * here we use the date form of the conversion
- */
- @Test public void testConversion6a() throws Exception {
- String input = "SELECT convert(timestampvalue, string) FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT to_char(SmallishA.timestampvalue, 'YYYY-MM-DD HH24:MI:SS') FROM SmallishA"; //$NON-NLS-1$
-
- helpTestVisitor(getOracleSpecificMetadata(), input, EMPTY_CONTEXT, null, output);
- }
-
- @Test public void testConversion8() throws Exception {
- String input = "SELECT nvl(INTNUM, 'otherString') FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT nvl(to_char(SmallA.IntNum), 'otherString') FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
- @Test public void testConversion7() throws Exception {
- String input = "SELECT convert(convert(STRINGNUM, integer), string) FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT to_char(trunc(to_number(SmallA.StringNum))) FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * Test the translator's ability to rewrite the LOCATE() function in a form
- * suitable for the data source.
- * <p>
- * <code>SELECT locate(INTNUM, 'chimp', 1) FROM BQT1.SMALLA</code>
- *
- * @throws Exception
- */
- @Test public void testLocate() throws Exception {
- String input = "SELECT locate(INTNUM, 'chimp', 1) FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT INSTR('chimp', to_char(SmallA.IntNum), 1) FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * Test the translator's ability to rewrite the LOCATE() function in a form
- * suitable for the data source.
- * <p>
- * <code>SELECT locate(STRINGNUM, 'chimp') FROM BQT1.SMALLA</code>
- *
- * @throws Exception
- */
- @Test public void testLocate2() throws Exception {
- String input = "SELECT locate(STRINGNUM, 'chimp') FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT INSTR('chimp', SmallA.StringNum) FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * Test the translator's ability to rewrite the LOCATE() function in a form
- * suitable for the data source.
- * <p>
- * <code>SELECT locate(INTNUM, '234567890', 1) FROM BQT1.SMALLA WHERE INTKEY = 26</code>
- *
- * @throws Exception
- */
- @Test public void testLocate3() throws Exception {
- String input = "SELECT locate(INTNUM, '234567890', 1) FROM BQT1.SMALLA WHERE INTKEY = 26"; //$NON-NLS-1$
- String output = "SELECT INSTR('234567890', to_char(SmallA.IntNum), 1) FROM SmallA WHERE SmallA.IntKey = 26"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * Test the translator's ability to rewrite the LOCATE() function in a form
- * suitable for the data source.
- * <p>
- * <code>SELECT locate('c', 'chimp', 1) FROM BQT1.SMALLA</code>
- *
- * @throws Exception
- */
- @Test public void testLocate4() throws Exception {
- String input = "SELECT locate('c', 'chimp', 1) FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT 1 FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * Test the translator's ability to rewrite the LOCATE() function in a form
- * suitable for the data source.
- * <p>
- * <code>SELECT locate(STRINGNUM, 'chimp', -5) FROM BQT1.SMALLA</code>
- *
- * @throws Exception
- */
- @Test public void testLocate5() throws Exception {
- String input = "SELECT locate(STRINGNUM, 'chimp', -5) FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT INSTR('chimp', SmallA.StringNum, 1) FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * Test the translator's ability to rewrite the LOCATE() function in a form
- * suitable for the data source.
- * <p>
- * <code>SELECT locate(STRINGNUM, 'chimp', INTNUM) FROM BQT1.SMALLA</code>
- *
- * @throws Exception
- */
- @Test public void testLocate6() throws Exception {
- String input = "SELECT locate(STRINGNUM, 'chimp', INTNUM) FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT INSTR('chimp', SmallA.StringNum, CASE WHEN SmallA.IntNum < 1 THEN 1 ELSE SmallA.IntNum END) FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * Test the translator's ability to rewrite the LOCATE() function in a form
- * suitable for the data source.
- * <p>
- * <code>SELECT locate(STRINGNUM, 'chimp', LOCATE(STRINGNUM, 'chimp') + 1) FROM BQT1.SMALLA</code>
- *
- * @throws Exception
- */
- @Test public void testLocate7() throws Exception {
- String input = "SELECT locate(STRINGNUM, 'chimp', LOCATE(STRINGNUM, 'chimp') + 1) FROM BQT1.SMALLA"; //$NON-NLS-1$
- 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"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- @Test public void testSubstring1() throws Exception {
- String input = "SELECT substring(StringNum, 1) FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT substr(SmallA.StringNum, 1) FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
- @Test public void testSubstring2() throws Exception {
- String input = "SELECT substring(StringNum, 1, 1) FROM BQT1.SMALLA"; //$NON-NLS-1$
- String output = "SELECT substr(SmallA.StringNum, 1, 1) FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
- @Test public void testUnionWithOrderBy() throws Exception {
- String input = "SELECT IntKey FROM BQT1.SMALLA UNION SELECT IntKey FROM BQT1.SMALLB ORDER BY IntKey"; //$NON-NLS-1$
- String output = "SELECT SmallA.IntKey FROM SmallA UNION SELECT SmallB.IntKey FROM SmallB ORDER BY IntKey"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
- @Test public void testRowLimit1() throws Exception {
- String input = "select intkey from bqt1.smalla limit 10, 0"; //$NON-NLS-1$
- String output = "SELECT * FROM (SELECT VIEW_FOR_LIMIT.*, ROWNUM ROWNUM_ FROM (SELECT SmallA.IntKey FROM SmallA) VIEW_FOR_LIMIT WHERE ROWNUM <= 10) WHERE ROWNUM_ > 10"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
- @Test public void testRowLimit2() throws Exception {
- String input = "select intkey from bqt1.smalla limit 0, 10"; //$NON-NLS-1$
- String output = "SELECT * FROM (SELECT SmallA.IntKey FROM SmallA) WHERE ROWNUM <= 10"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
- @Test public void testRowLimit3() throws Exception {
- String input = "select intkey from bqt1.smalla limit 1, 10"; //$NON-NLS-1$
- String output = "SELECT * FROM (SELECT VIEW_FOR_LIMIT.*, ROWNUM ROWNUM_ FROM (SELECT SmallA.IntKey FROM SmallA) VIEW_FOR_LIMIT WHERE ROWNUM <= 11) WHERE ROWNUM_ > 1"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
- @Test public void testRowLimit4() throws Exception {
- String input = "select intkey from bqt1.mediuma limit 100"; //$NON-NLS-1$
- String output = "SELECT * FROM (SELECT MediumA.IntKey FROM MediumA) WHERE ROWNUM <= 100"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
- @Test public void testRowLimit5() throws Exception {
- String input = "select intkey from bqt1.mediuma limit 50, 100"; //$NON-NLS-1$
- String output = "SELECT * FROM (SELECT VIEW_FOR_LIMIT.*, ROWNUM ROWNUM_ FROM (SELECT MediumA.IntKey FROM MediumA) VIEW_FOR_LIMIT WHERE ROWNUM <= 150) WHERE ROWNUM_ > 50"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- @Test public void testConcat2_useLiteral() throws Exception {
- String input = "select concat2(stringnum,'_xx') from bqt1.Smalla"; //$NON-NLS-1$
- String output = "SELECT concat(nvl(SmallA.StringNum, ''), '_xx') FROM SmallA"; //$NON-NLS-1$
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- @Test public void testConcat2() throws Exception {
- String input = "select concat2(stringnum, stringkey) from bqt1.Smalla"; //$NON-NLS-1$
- String output = "SELECT CASE WHEN SmallA.StringNum IS NULL AND SmallA.StringKey IS NULL THEN NULL ELSE concat(nvl(SmallA.StringNum, ''), nvl(SmallA.StringKey, '')) END FROM SmallA"; //$NON-NLS-1$
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * Test a query which uses
- * <code>sdo_relate(Object element, Object element, String literal) in its
- * criteria into a source specific command.
- *
- * @throws Exception
- */
- @Test public void test_sdo_relate() throws Exception {
- String input = "SELECT a.INTKEY FROM BQT1.SMALLA A, BQT1.SMALLB B WHERE sdo_relate(A.OBJECTVALUE, b.OBJECTVALUE, 'mask=ANYINTERACT') = true"; //$NON-NLS-1$
- String output = "SELECT /*+ ORDERED */ A.IntKey FROM SmallA A, SmallB B WHERE sdo_relate(A.ObjectValue, B.ObjectValue, 'mask=ANYINTERACT') = 'true'"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * Test a query which uses
- * <code>sdo_within_distance(Object element, String literal, String literal)
- * in its criteria into a source specific command.
- *
- * @throws Exception
- */
- @Test public void test_sdo_within_distance() 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, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * Test a query which uses
- * <code>sdo_within_distance(String literal, Object element, String literal)
- * in its criteria into a source specific command.
- *
- * @throws Exception
- */
- @Test public void test_sdo_within_distance2() throws Exception {
- String input = "SELECT INTKEY FROM BQT1.SMALLA WHERE sdo_within_distance('SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL)', OBJECTVALUE, 'DISTANCE=25.0 UNIT=NAUT_MILE') = true"; //$NON-NLS-1$
- String output = "SELECT SmallA.IntKey FROM SmallA WHERE sdo_within_distance(SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), SmallA.ObjectValue, 'DISTANCE=25.0 UNIT=NAUT_MILE') = 'true'"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * Test a query which uses
- * <code>sdo_within_distance(String element, String literal, String literal)
- * in its criteria into a source specific command.
- *
- * @throws Exception
- */
- @Test public void test_sdo_within_distance3() throws Exception {
- String input = "SELECT INTKEY FROM BQT1.SMALLA WHERE sdo_within_distance(STRINGKEY, '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.StringKey, 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, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * Test a query which uses
- * <code>sdo_within_distance(String literal, String literal, String literal)
- * in its criteria into a source specific command.
- *
- * @throws Exception
- */
- @Test public void test_sdo_within_distance4() throws Exception {
- String input = "SELECT INTKEY FROM BQT1.SMALLA WHERE sdo_within_distance('SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL)', '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(SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), 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, UDF,
- input, output,
- TRANSLATOR);
- }
-
- /**
- * Test a query which uses
- * <code>sdo_within_distance(Object element, Object element, String literal)
- * in its criteria into a source specific command.
- *
- * @throws Exception
- */
- @Test public void test_sdo_within_distance5() throws Exception {
- String input = "SELECT a.INTKEY FROM BQT1.SMALLA A, BQT1.SMALLB B WHERE sdo_within_distance(a.OBJECTVALUE, b.OBJECTVALUE, 'DISTANCE=25.0 UNIT=NAUT_MILE') = true"; //$NON-NLS-1$
- String output = "SELECT A.IntKey FROM SmallA A, SmallB B WHERE sdo_within_distance(A.ObjectValue, B.ObjectValue, 'DISTANCE=25.0 UNIT=NAUT_MILE') = 'true'"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- @Test public void testLogFunction() throws Exception {
- String input = "SELECT log(CONVERT(stringkey, INTEGER)) FROM bqt1.smalla"; //$NON-NLS-1$
- String output = "SELECT ln(trunc(to_number(SmallA.StringKey))) FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- @Test public void testLog10Function() throws Exception {
- String input = "SELECT log10(CONVERT(stringkey, INTEGER)) FROM bqt1.smalla"; //$NON-NLS-1$
- String output = "SELECT log(10, trunc(to_number(SmallA.StringKey))) FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- @Test public void testAliasedFunctions() throws Exception {
- String input = "SELECT char(CONVERT(stringkey, INTEGER)), lcase(stringkey), ucase(stringkey), ifnull(stringkey, 'x') FROM bqt1.smalla"; //$NON-NLS-1$
- String output = "SELECT chr(trunc(to_number(SmallA.StringKey))), lower(SmallA.StringKey), upper(SmallA.StringKey), nvl(SmallA.StringKey, 'x') FROM SmallA"; //$NON-NLS-1$
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
- input, output,
- TRANSLATOR);
- }
-
- private String getTestVDB() {
- return UnitTestUtil.getTestDataPath() + "/PartsSupplierOracle.vdb"; //$NON-NLS-1$
- }
-
- private void helpTestVisitor(String vdb, String input, String dbmsTimeZone, String expectedOutput) throws TranslatorException {
- helpTestVisitor(vdb, input, EMPTY_CONTEXT, dbmsTimeZone, expectedOutput, false);
- }
-
- private void helpTestVisitor(String vdb, String input, String dbmsTimeZone, String expectedOutput, boolean correctNaming) throws TranslatorException {
- helpTestVisitor(vdb, input, EMPTY_CONTEXT, dbmsTimeZone, expectedOutput, correctNaming);
- }
-
- private void helpTestVisitor(String vdb, String input, ExecutionContext context, String dbmsTimeZone, String expectedOutput, boolean correctNaming) throws TranslatorException {
- // Convert from sql to objects
- TranslationUtility util = new TranslationUtility(vdb);
- Command obj = util.parseCommand(input, correctNaming, true);
- this.helpTestVisitor(obj, context, dbmsTimeZone, expectedOutput);
- }
-
- /** Helper method takes a QueryMetadataInterface impl instead of a VDB filename
- * @throws TranslatorException
- */
- private void helpTestVisitor(QueryMetadataInterface metadata, String input, ExecutionContext context, String dbmsTimeZone, String expectedOutput) throws TranslatorException {
- // Convert from sql to objects
- CommandBuilder commandBuilder = new CommandBuilder(metadata);
- Command obj = commandBuilder.getCommand(input);
- this.helpTestVisitor(obj, context, dbmsTimeZone, expectedOutput);
- }
-
- private void helpTestVisitor(Command obj, ExecutionContext context, String dbmsTimeZone, String expectedOutput) throws TranslatorException {
- OracleExecutionFactory translator = new OracleExecutionFactory();
- if (dbmsTimeZone != null) {
- translator.setDatabaseTimeZone(dbmsTimeZone);
- }
- translator.setUseBindVariables(false);
- translator.start();
- // Convert back to SQL
- TranslatedCommand tc = new TranslatedCommand(context, translator);
- tc.translateCommand(obj);
-
- // Check stuff
- assertEquals("Did not get correct sql", expectedOutput, tc.getSql()); //$NON-NLS-1$
- }
-
- /** defect 21775 */
- @Test public void testDateStuff() throws Exception {
- 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(),
- input,
- EMPTY_CONTEXT, null, output);
- }
-
- @Test public void testAliasedGroup() throws Exception {
- helpTestVisitor(getTestVDB(),
- "select y.part_name from parts as y", //$NON-NLS-1$
- null,
- "SELECT y.PART_NAME FROM PARTS y"); //$NON-NLS-1$
- }
-
- @Test public void testDateLiteral() throws Exception {
- helpTestVisitor(getTestVDB(),
- "select {d '2002-12-31'} FROM parts", //$NON-NLS-1$
- null,
- "SELECT {d '2002-12-31'} FROM PARTS"); //$NON-NLS-1$
- }
-
- @Test public void testTimeLiteral() throws Exception {
- helpTestVisitor(getTestVDB(),
- "select {t '13:59:59'} FROM parts", //$NON-NLS-1$
- null,
- "SELECT to_date('1970-01-01 13:59:59', 'YYYY-MM-DD HH24:MI:SS') FROM PARTS"); //$NON-NLS-1$
- }
-
- @Test public void testTimestampLiteral() throws Exception {
- helpTestVisitor(getTestVDB(),
- "select {ts '2002-12-31 13:59:59.1'} FROM parts", //$NON-NLS-1$
- null,
- "SELECT {ts '2002-12-31 13:59:59.1'} FROM PARTS"); //$NON-NLS-1$
- }
-
- @Test public void testTimestampLiteral1() throws Exception {
- helpTestVisitor(getTestVDB(),
- "select {ts '2002-12-31 13:59:59'} FROM parts", //$NON-NLS-1$
- null,
- "SELECT to_date('2002-12-31 13:59:59', 'YYYY-MM-DD HH24:MI:SS') FROM PARTS"); //$NON-NLS-1$
- }
-
- @Test public void testUnionOrderByWithThreeBranches() throws Exception {
- helpTestVisitor(getTestVDB(),
- "select part_id id FROM parts UNION ALL select part_name FROM parts UNION ALL select part_id FROM parts ORDER BY id", //$NON-NLS-1$
- null,
- "SELECT g_2.PART_ID AS c_0 FROM PARTS g_2 UNION ALL SELECT g_1.PART_NAME AS c_0 FROM PARTS g_1 UNION ALL SELECT g_0.PART_ID AS c_0 FROM PARTS g_0 ORDER BY c_0", //$NON-NLS-1$
- true);
- }
-
- @Test public void testUnionOrderBy() throws Exception {
- helpTestVisitor(getTestVDB(),
- "select part_id FROM parts UNION ALL select part_name FROM parts ORDER BY part_id", //$NON-NLS-1$
- null,
- "SELECT g_1.PART_ID AS c_0 FROM PARTS g_1 UNION ALL SELECT g_0.PART_NAME AS c_0 FROM PARTS g_0 ORDER BY c_0", //$NON-NLS-1$
- true);
- }
-
- @Test public void testUnionOrderBy2() throws Exception {
- helpTestVisitor(getTestVDB(),
- "select part_id as p FROM parts UNION ALL select part_name FROM parts ORDER BY p", //$NON-NLS-1$
- null,
- "SELECT PARTS.PART_ID AS p FROM PARTS UNION ALL SELECT PARTS.PART_NAME FROM PARTS ORDER BY p"); //$NON-NLS-1$
- }
-
- @Test public void testUpdateWithFunction() throws Exception {
- 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(),
- input,
- EMPTY_CONTEXT, null, output);
- }
-
-
- /**
- * Oracle's DUAL table is a pseudo-table; element names cannot be
- * fully qualified since the table doesn't really exist nor contain
- * any columns. But this requires modeling the DUAL table in
- * MM as if it were a real physical table, and also modeling any
- * columns in the table. Case 3742
- *
- * @since 4.3
- */
- @Test public void testDUAL() throws Exception {
- String input = "SELECT something FROM DUAL"; //$NON-NLS-1$
- String output = "SELECT something FROM DUAL"; //$NON-NLS-1$
-
- helpTestVisitor(getOracleSpecificMetadata(),
- input,
- EMPTY_CONTEXT,
- null,
- output);
- }
-
- /**
- * Test Oracle's rownum pseudo-column. Not a real column, so it can't
- * be fully-qualified with a table name. MM requires this column to be
- * modeled in any table which the user wants to use rownum with.
- * Case 3739
- *
- * @since 4.3
- */
- @Test public void testROWNUM() throws Exception {
- String input = "SELECT part_name, rownum FROM parts"; //$NON-NLS-1$
- String output = "SELECT PARTS.PART_NAME, ROWNUM FROM PARTS"; //$NON-NLS-1$
-
- helpTestVisitor(getTestVDB(),
- input,
- null,
- output);
- }
-
- /**
- * Test Oracle's rownum pseudo-column. Not a real column, so it can't
- * be fully-qualified with a table name. MM requires this column to be
- * modeled in any table which the user wants to use rownum with. Case 3739
- *
- * @since 4.3
- */
- @Test public void testROWNUM2() throws Exception {
- String input = "SELECT part_name FROM parts where rownum < 100"; //$NON-NLS-1$
- String output = "SELECT PARTS.PART_NAME FROM PARTS WHERE ROWNUM < 100"; //$NON-NLS-1$
-
- helpTestVisitor(getTestVDB(),
- input,
- null,
- output); }
-
- /**
- * Case 3744. Test that an Oracle-specific db hint, delivered as a String via command
- * payload, is added to the translated SQL.
- *
- * @since 4.3
- */
- @Test public void testOracleCommentPayload() throws Exception {
- String input = "SELECT part_name, rownum FROM parts"; //$NON-NLS-1$
- String output = "SELECT /*+ ALL_ROWS */ PARTS.PART_NAME, ROWNUM FROM PARTS"; //$NON-NLS-1$
-
- String hint = "/*+ ALL_ROWS */"; //$NON-NLS-1$
- ExecutionContext context = new ExecutionContextImpl(null, 1, hint, null, "", null, null, null); //$NON-NLS-1$
-
- helpTestVisitor(getTestVDB(),
- input,
- context,
- null,
- output,
- false);
- }
-
- /**
- * reproducing this case relies on the name in source for the table being different from
- * the name
- */
- @Test public void testCase3845() throws Exception {
-
- String input = "SELECT (DoubleNum * 1.0) FROM BQT1.Smalla"; //$NON-NLS-1$
- String output = "SELECT (SmallishA.DoubleNum * 1.0) FROM SmallishA"; //$NON-NLS-1$
-
- QueryMetadataInterface metadata = getOracleSpecificMetadata();
-
- helpTestVisitor(metadata, input, EMPTY_CONTEXT, null, output);
- }
-
- /** create fake BQT metadata to test this case, name in source is important */
- private QueryMetadataInterface getOracleSpecificMetadata() {
- MetadataStore metadataStore = new MetadataStore();
- Schema foo = RealMetadataFactory.createPhysicalModel("BQT1", metadataStore); //$NON-NLS-1$
- Table table = RealMetadataFactory.createPhysicalGroup("SmallA", foo); //$NON-NLS-1$
- Table dual = RealMetadataFactory.createPhysicalGroup("DUAL", foo); //$NON-NLS-1$
- table.setNameInSource("SmallishA");//$NON-NLS-1$
- String[] elemNames = new String[] {
- "DoubleNum", //$NON-NLS-1$
- "ID", //$NON-NLS-1$
- "timestampvalue", //$NON-NLS-1$
- };
- String[] elemTypes = new String[] {
- DataTypeManager.DefaultDataTypes.DOUBLE,
- DataTypeManager.DefaultDataTypes.INTEGER,
- DataTypeManager.DefaultDataTypes.TIMESTAMP,
- };
- List<Column> cols = RealMetadataFactory.createElements(table, elemNames, elemTypes);
- cols.get(1).setAutoIncremented(true);
- cols.get(1).setNameInSource("ID:SEQUENCE=MYSEQUENCE.nextVal"); //$NON-NLS-1$
- cols.get(2).setNativeType("date"); //$NON-NLS-1$
- 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);
- }
-
- public void helpTestVisitor(String vdb, String input, String expectedOutput) throws TranslatorException {
- helpTestVisitor(vdb, input, null, expectedOutput);
- }
-
- @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"; //$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(),
- input,
- EMPTY_CONTEXT, null, output);
- }
-
- @Test public void testExceptAsMinus() throws Exception {
- 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(),
- input,
- EMPTY_CONTEXT, null, output);
- }
-
- @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);
- }
-
- @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);
- }
-
- @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());
- Command obj = commandBuilder.getCommand(input, true, true);
- this.helpTestVisitor(obj, EMPTY_CONTEXT, null, output);
- }
-
- @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);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java (from rev 3218, trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,784 @@
+/*
+ * 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 static org.junit.Assert.assertEquals;
+
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.teiid.cdk.CommandBuilder;
+import org.teiid.cdk.api.TranslationUtility;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.UnitTestUtil;
+import org.teiid.dqp.internal.datamgr.ExecutionContextImpl;
+import org.teiid.dqp.internal.datamgr.FakeExecutionContextImpl;
+import org.teiid.language.Command;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.query.metadata.CompositeMetadataStore;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.TranslationHelper;
+
+
+public class TestOracleTranslator {
+
+ private OracleExecutionFactory TRANSLATOR;
+ private String UDF = "/OracleSpatialFunctions.xmi"; //$NON-NLS-1$;
+ private static ExecutionContext EMPTY_CONTEXT = new FakeExecutionContextImpl();
+
+ @Before
+ public void setup() throws Exception {
+ TRANSLATOR = new OracleExecutionFactory();
+ TRANSLATOR.setUseBindVariables(false);
+ TRANSLATOR.start();
+ }
+
+ private void helpTestVisitor(String input, String expectedOutput) throws TranslatorException {
+ helpTestVisitor(getOracleSpecificMetadata(), input, EMPTY_CONTEXT, null, expectedOutput);
+ }
+
+ @Test public void testInsertWithSequnce() throws Exception {
+ helpTestVisitor("insert into smalla (doublenum) values (1)", "INSERT INTO SmallishA (DoubleNum, ID) VALUES (1.0, MYSEQUENCE.nextVal)"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInsertWithSequnce1() throws Exception {
+ helpTestVisitor("insert into smalla (doublenum, id) values (1, 1)", "INSERT INTO SmallishA (DoubleNum, ID) VALUES (1.0, 1)"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testJoins() throws Exception {
+ String input = "select smalla.intkey from bqt1.smalla inner join bqt1.smallb on smalla.stringkey=smallb.stringkey cross join bqt1.mediuma"; //$NON-NLS-1$
+ String output = "SELECT SmallA.IntKey FROM SmallA INNER JOIN SmallB ON SmallA.StringKey = SmallB.StringKey CROSS JOIN MediumA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input,
+ output, TRANSLATOR);
+ }
+
+ @Test public void testJoins2() throws Exception {
+ String input = "select smalla.intkey from bqt1.smalla cross join (bqt1.smallb cross join bqt1.mediuma)"; //$NON-NLS-1$
+ String output = "SELECT SmallA.IntKey FROM SmallA CROSS JOIN (SmallB CROSS JOIN MediumA)"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input,
+ output, TRANSLATOR);
+ }
+
+ @Test public void testConversion1() throws Exception {
+ String input = "SELECT char(convert(STRINGNUM, integer) + 100) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT chr((trunc(to_number(SmallA.StringNum)) + 100)) FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ @Test public void testConversion2() throws Exception {
+ String input = "SELECT convert(STRINGNUM, long) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT trunc(to_number(SmallA.StringNum)) FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ @Test public void testConversion3() throws Exception {
+ String input = "SELECT convert(convert(STRINGNUM, long), string) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT to_char(trunc(to_number(SmallA.StringNum))) FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ @Test public void testConversion4() throws Exception {
+ String input = "SELECT convert(convert(TIMESTAMPVALUE, date), string) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT to_char(trunc(cast(SmallA.TimestampValue AS date)), 'YYYY-MM-DD') FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+ @Test public void testConversion6() throws Exception {
+ String input = "SELECT convert(convert(TIMEVALUE, timestamp), string) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT to_char(cast(SmallA.TimeValue AS timestamp), 'YYYY-MM-DD HH24:MI:SS.FF') FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ /**
+ * here we use the date form of the conversion
+ */
+ @Test public void testConversion6a() throws Exception {
+ String input = "SELECT convert(timestampvalue, string) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT to_char(SmallishA.timestampvalue, 'YYYY-MM-DD HH24:MI:SS') FROM SmallishA"; //$NON-NLS-1$
+
+ helpTestVisitor(getOracleSpecificMetadata(), input, EMPTY_CONTEXT, null, output);
+ }
+
+ @Test public void testConversion8() throws Exception {
+ String input = "SELECT nvl(INTNUM, 'otherString') FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT nvl(to_char(SmallA.IntNum), 'otherString') FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+ @Test public void testConversion7() throws Exception {
+ String input = "SELECT convert(convert(STRINGNUM, integer), string) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT to_char(trunc(to_number(SmallA.StringNum))) FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ /**
+ * Test the translator's ability to rewrite the LOCATE() function in a form
+ * suitable for the data source.
+ * <p>
+ * <code>SELECT locate(INTNUM, 'chimp', 1) FROM BQT1.SMALLA</code>
+ *
+ * @throws Exception
+ */
+ @Test public void testLocate() throws Exception {
+ String input = "SELECT locate(INTNUM, 'chimp', 1) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT INSTR('chimp', to_char(SmallA.IntNum), 1) FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ /**
+ * Test the translator's ability to rewrite the LOCATE() function in a form
+ * suitable for the data source.
+ * <p>
+ * <code>SELECT locate(STRINGNUM, 'chimp') FROM BQT1.SMALLA</code>
+ *
+ * @throws Exception
+ */
+ @Test public void testLocate2() throws Exception {
+ String input = "SELECT locate(STRINGNUM, 'chimp') FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT INSTR('chimp', SmallA.StringNum) FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ /**
+ * Test the translator's ability to rewrite the LOCATE() function in a form
+ * suitable for the data source.
+ * <p>
+ * <code>SELECT locate(INTNUM, '234567890', 1) FROM BQT1.SMALLA WHERE INTKEY = 26</code>
+ *
+ * @throws Exception
+ */
+ @Test public void testLocate3() throws Exception {
+ String input = "SELECT locate(INTNUM, '234567890', 1) FROM BQT1.SMALLA WHERE INTKEY = 26"; //$NON-NLS-1$
+ String output = "SELECT INSTR('234567890', to_char(SmallA.IntNum), 1) FROM SmallA WHERE SmallA.IntKey = 26"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ /**
+ * Test the translator's ability to rewrite the LOCATE() function in a form
+ * suitable for the data source.
+ * <p>
+ * <code>SELECT locate('c', 'chimp', 1) FROM BQT1.SMALLA</code>
+ *
+ * @throws Exception
+ */
+ @Test public void testLocate4() throws Exception {
+ String input = "SELECT locate('c', 'chimp', 1) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT 1 FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ /**
+ * Test the translator's ability to rewrite the LOCATE() function in a form
+ * suitable for the data source.
+ * <p>
+ * <code>SELECT locate(STRINGNUM, 'chimp', -5) FROM BQT1.SMALLA</code>
+ *
+ * @throws Exception
+ */
+ @Test public void testLocate5() throws Exception {
+ String input = "SELECT locate(STRINGNUM, 'chimp', -5) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT INSTR('chimp', SmallA.StringNum, 1) FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ /**
+ * Test the translator's ability to rewrite the LOCATE() function in a form
+ * suitable for the data source.
+ * <p>
+ * <code>SELECT locate(STRINGNUM, 'chimp', INTNUM) FROM BQT1.SMALLA</code>
+ *
+ * @throws Exception
+ */
+ @Test public void testLocate6() throws Exception {
+ String input = "SELECT locate(STRINGNUM, 'chimp', INTNUM) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT INSTR('chimp', SmallA.StringNum, CASE WHEN SmallA.IntNum < 1 THEN 1 ELSE SmallA.IntNum END) FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ /**
+ * Test the translator's ability to rewrite the LOCATE() function in a form
+ * suitable for the data source.
+ * <p>
+ * <code>SELECT locate(STRINGNUM, 'chimp', LOCATE(STRINGNUM, 'chimp') + 1) FROM BQT1.SMALLA</code>
+ *
+ * @throws Exception
+ */
+ @Test public void testLocate7() throws Exception {
+ String input = "SELECT locate(STRINGNUM, 'chimp', LOCATE(STRINGNUM, 'chimp') + 1) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ 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"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ @Test public void testSubstring1() throws Exception {
+ String input = "SELECT substring(StringNum, 1) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT substr(SmallA.StringNum, 1) FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+ @Test public void testSubstring2() throws Exception {
+ String input = "SELECT substring(StringNum, 1, 1) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT substr(SmallA.StringNum, 1, 1) FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+ @Test public void testUnionWithOrderBy() throws Exception {
+ String input = "SELECT IntKey FROM BQT1.SMALLA UNION SELECT IntKey FROM BQT1.SMALLB ORDER BY IntKey"; //$NON-NLS-1$
+ String output = "SELECT SmallA.IntKey FROM SmallA UNION SELECT SmallB.IntKey FROM SmallB ORDER BY IntKey"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+ @Test public void testRowLimit1() throws Exception {
+ String input = "select intkey from bqt1.smalla limit 10, 0"; //$NON-NLS-1$
+ String output = "SELECT * FROM (SELECT VIEW_FOR_LIMIT.*, ROWNUM ROWNUM_ FROM (SELECT SmallA.IntKey FROM SmallA) VIEW_FOR_LIMIT WHERE ROWNUM <= 10) WHERE ROWNUM_ > 10"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+ @Test public void testRowLimit2() throws Exception {
+ String input = "select intkey from bqt1.smalla limit 0, 10"; //$NON-NLS-1$
+ String output = "SELECT * FROM (SELECT SmallA.IntKey FROM SmallA) WHERE ROWNUM <= 10"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+ @Test public void testRowLimit3() throws Exception {
+ String input = "select intkey from bqt1.smalla limit 1, 10"; //$NON-NLS-1$
+ String output = "SELECT * FROM (SELECT VIEW_FOR_LIMIT.*, ROWNUM ROWNUM_ FROM (SELECT SmallA.IntKey FROM SmallA) VIEW_FOR_LIMIT WHERE ROWNUM <= 11) WHERE ROWNUM_ > 1"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+ @Test public void testRowLimit4() throws Exception {
+ String input = "select intkey from bqt1.mediuma limit 100"; //$NON-NLS-1$
+ String output = "SELECT * FROM (SELECT MediumA.IntKey FROM MediumA) WHERE ROWNUM <= 100"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+ @Test public void testRowLimit5() throws Exception {
+ String input = "select intkey from bqt1.mediuma limit 50, 100"; //$NON-NLS-1$
+ String output = "SELECT * FROM (SELECT VIEW_FOR_LIMIT.*, ROWNUM ROWNUM_ FROM (SELECT MediumA.IntKey FROM MediumA) VIEW_FOR_LIMIT WHERE ROWNUM <= 150) WHERE ROWNUM_ > 50"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ @Test public void testConcat2_useLiteral() throws Exception {
+ String input = "select concat2(stringnum,'_xx') from bqt1.Smalla"; //$NON-NLS-1$
+ String output = "SELECT concat(nvl(SmallA.StringNum, ''), '_xx') FROM SmallA"; //$NON-NLS-1$
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ @Test public void testConcat2() throws Exception {
+ String input = "select concat2(stringnum, stringkey) from bqt1.Smalla"; //$NON-NLS-1$
+ String output = "SELECT CASE WHEN SmallA.StringNum IS NULL AND SmallA.StringKey IS NULL THEN NULL ELSE concat(nvl(SmallA.StringNum, ''), nvl(SmallA.StringKey, '')) END FROM SmallA"; //$NON-NLS-1$
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ /**
+ * Test a query which uses
+ * <code>sdo_relate(Object element, Object element, String literal) in its
+ * criteria into a source specific command.
+ *
+ * @throws Exception
+ */
+ @Test public void test_sdo_relate() throws Exception {
+ String input = "SELECT a.INTKEY FROM BQT1.SMALLA A, BQT1.SMALLB B WHERE sdo_relate(A.OBJECTVALUE, b.OBJECTVALUE, 'mask=ANYINTERACT') = true"; //$NON-NLS-1$
+ String output = "SELECT /*+ ORDERED */ A.IntKey FROM SmallA A, SmallB B WHERE sdo_relate(A.ObjectValue, B.ObjectValue, 'mask=ANYINTERACT') = 'true'"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ /**
+ * Test a query which uses
+ * <code>sdo_within_distance(Object element, String literal, String literal)
+ * in its criteria into a source specific command.
+ *
+ * @throws Exception
+ */
+ @Test public void test_sdo_within_distance() 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, UDF,
+ 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)
+ * in its criteria into a source specific command.
+ *
+ * @throws Exception
+ */
+ @Test public void test_sdo_within_distance2() throws Exception {
+ String input = "SELECT INTKEY FROM BQT1.SMALLA WHERE sdo_within_distance('SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL)', OBJECTVALUE, 'DISTANCE=25.0 UNIT=NAUT_MILE') = true"; //$NON-NLS-1$
+ String output = "SELECT SmallA.IntKey FROM SmallA WHERE sdo_within_distance(SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), SmallA.ObjectValue, 'DISTANCE=25.0 UNIT=NAUT_MILE') = 'true'"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ /**
+ * Test a query which uses
+ * <code>sdo_within_distance(String element, String literal, String literal)
+ * in its criteria into a source specific command.
+ *
+ * @throws Exception
+ */
+ @Test public void test_sdo_within_distance3() throws Exception {
+ String input = "SELECT INTKEY FROM BQT1.SMALLA WHERE sdo_within_distance(STRINGKEY, '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.StringKey, 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, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ /**
+ * Test a query which uses
+ * <code>sdo_within_distance(String literal, String literal, String literal)
+ * in its criteria into a source specific command.
+ *
+ * @throws Exception
+ */
+ @Test public void test_sdo_within_distance4() throws Exception {
+ String input = "SELECT INTKEY FROM BQT1.SMALLA WHERE sdo_within_distance('SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL)', '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(SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), 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, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ /**
+ * Test a query which uses
+ * <code>sdo_within_distance(Object element, Object element, String literal)
+ * in its criteria into a source specific command.
+ *
+ * @throws Exception
+ */
+ @Test public void test_sdo_within_distance5() throws Exception {
+ String input = "SELECT a.INTKEY FROM BQT1.SMALLA A, BQT1.SMALLB B WHERE sdo_within_distance(a.OBJECTVALUE, b.OBJECTVALUE, 'DISTANCE=25.0 UNIT=NAUT_MILE') = true"; //$NON-NLS-1$
+ String output = "SELECT A.IntKey FROM SmallA A, SmallB B WHERE sdo_within_distance(A.ObjectValue, B.ObjectValue, 'DISTANCE=25.0 UNIT=NAUT_MILE') = 'true'"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ @Test public void testLogFunction() throws Exception {
+ String input = "SELECT log(CONVERT(stringkey, INTEGER)) FROM bqt1.smalla"; //$NON-NLS-1$
+ String output = "SELECT ln(trunc(to_number(SmallA.StringKey))) FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ @Test public void testLog10Function() throws Exception {
+ String input = "SELECT log10(CONVERT(stringkey, INTEGER)) FROM bqt1.smalla"; //$NON-NLS-1$
+ String output = "SELECT log(10, trunc(to_number(SmallA.StringKey))) FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ @Test public void testAliasedFunctions() throws Exception {
+ String input = "SELECT char(CONVERT(stringkey, INTEGER)), lcase(stringkey), ucase(stringkey), ifnull(stringkey, 'x') FROM bqt1.smalla"; //$NON-NLS-1$
+ String output = "SELECT chr(trunc(to_number(SmallA.StringKey))), lower(SmallA.StringKey), upper(SmallA.StringKey), nvl(SmallA.StringKey, 'x') FROM SmallA"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
+ input, output,
+ TRANSLATOR);
+ }
+
+ private String getTestVDB() {
+ return UnitTestUtil.getTestDataPath() + "/PartsSupplierOracle.vdb"; //$NON-NLS-1$
+ }
+
+ private void helpTestVisitor(String vdb, String input, String dbmsTimeZone, String expectedOutput) throws TranslatorException {
+ helpTestVisitor(vdb, input, EMPTY_CONTEXT, dbmsTimeZone, expectedOutput, false);
+ }
+
+ private void helpTestVisitor(String vdb, String input, String dbmsTimeZone, String expectedOutput, boolean correctNaming) throws TranslatorException {
+ helpTestVisitor(vdb, input, EMPTY_CONTEXT, dbmsTimeZone, expectedOutput, correctNaming);
+ }
+
+ private void helpTestVisitor(String vdb, String input, ExecutionContext context, String dbmsTimeZone, String expectedOutput, boolean correctNaming) throws TranslatorException {
+ // Convert from sql to objects
+ TranslationUtility util = new TranslationUtility(vdb);
+ Command obj = util.parseCommand(input, correctNaming, true);
+ this.helpTestVisitor(obj, context, dbmsTimeZone, expectedOutput);
+ }
+
+ /** Helper method takes a QueryMetadataInterface impl instead of a VDB filename
+ * @throws TranslatorException
+ */
+ private void helpTestVisitor(QueryMetadataInterface metadata, String input, ExecutionContext context, String dbmsTimeZone, String expectedOutput) throws TranslatorException {
+ // Convert from sql to objects
+ CommandBuilder commandBuilder = new CommandBuilder(metadata);
+ Command obj = commandBuilder.getCommand(input);
+ this.helpTestVisitor(obj, context, dbmsTimeZone, expectedOutput);
+ }
+
+ private void helpTestVisitor(Command obj, ExecutionContext context, String dbmsTimeZone, String expectedOutput) throws TranslatorException {
+ OracleExecutionFactory translator = new OracleExecutionFactory();
+ if (dbmsTimeZone != null) {
+ translator.setDatabaseTimeZone(dbmsTimeZone);
+ }
+ translator.setUseBindVariables(false);
+ translator.start();
+ // Convert back to SQL
+ TranslatedCommand tc = new TranslatedCommand(context, translator);
+ tc.translateCommand(obj);
+
+ // Check stuff
+ assertEquals("Did not get correct sql", expectedOutput, tc.getSql()); //$NON-NLS-1$
+ }
+
+ /** defect 21775 */
+ @Test public void testDateStuff() throws Exception {
+ 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(RealMetadataFactory.exampleBQTCached(),
+ input,
+ EMPTY_CONTEXT, null, output);
+ }
+
+ @Test public void testAliasedGroup() throws Exception {
+ helpTestVisitor(getTestVDB(),
+ "select y.part_name from parts as y", //$NON-NLS-1$
+ null,
+ "SELECT y.PART_NAME FROM PARTS y"); //$NON-NLS-1$
+ }
+
+ @Test public void testDateLiteral() throws Exception {
+ helpTestVisitor(getTestVDB(),
+ "select {d '2002-12-31'} FROM parts", //$NON-NLS-1$
+ null,
+ "SELECT {d '2002-12-31'} FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testTimeLiteral() throws Exception {
+ helpTestVisitor(getTestVDB(),
+ "select {t '13:59:59'} FROM parts", //$NON-NLS-1$
+ null,
+ "SELECT to_date('1970-01-01 13:59:59', 'YYYY-MM-DD HH24:MI:SS') FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testTimestampLiteral() throws Exception {
+ helpTestVisitor(getTestVDB(),
+ "select {ts '2002-12-31 13:59:59.1'} FROM parts", //$NON-NLS-1$
+ null,
+ "SELECT {ts '2002-12-31 13:59:59.1'} FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testTimestampLiteral1() throws Exception {
+ helpTestVisitor(getTestVDB(),
+ "select {ts '2002-12-31 13:59:59'} FROM parts", //$NON-NLS-1$
+ null,
+ "SELECT to_date('2002-12-31 13:59:59', 'YYYY-MM-DD HH24:MI:SS') FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testUnionOrderByWithThreeBranches() throws Exception {
+ helpTestVisitor(getTestVDB(),
+ "select part_id id FROM parts UNION ALL select part_name FROM parts UNION ALL select part_id FROM parts ORDER BY id", //$NON-NLS-1$
+ null,
+ "SELECT g_2.PART_ID AS c_0 FROM PARTS g_2 UNION ALL SELECT g_1.PART_NAME AS c_0 FROM PARTS g_1 UNION ALL SELECT g_0.PART_ID AS c_0 FROM PARTS g_0 ORDER BY c_0", //$NON-NLS-1$
+ true);
+ }
+
+ @Test public void testUnionOrderBy() throws Exception {
+ helpTestVisitor(getTestVDB(),
+ "select part_id FROM parts UNION ALL select part_name FROM parts ORDER BY part_id", //$NON-NLS-1$
+ null,
+ "SELECT g_1.PART_ID AS c_0 FROM PARTS g_1 UNION ALL SELECT g_0.PART_NAME AS c_0 FROM PARTS g_0 ORDER BY c_0", //$NON-NLS-1$
+ true);
+ }
+
+ @Test public void testUnionOrderBy2() throws Exception {
+ helpTestVisitor(getTestVDB(),
+ "select part_id as p FROM parts UNION ALL select part_name FROM parts ORDER BY p", //$NON-NLS-1$
+ null,
+ "SELECT PARTS.PART_ID AS p FROM PARTS UNION ALL SELECT PARTS.PART_NAME FROM PARTS ORDER BY p"); //$NON-NLS-1$
+ }
+
+ @Test public void testUpdateWithFunction() throws Exception {
+ 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(RealMetadataFactory.exampleBQTCached(),
+ input,
+ EMPTY_CONTEXT, null, output);
+ }
+
+
+ /**
+ * Oracle's DUAL table is a pseudo-table; element names cannot be
+ * fully qualified since the table doesn't really exist nor contain
+ * any columns. But this requires modeling the DUAL table in
+ * MM as if it were a real physical table, and also modeling any
+ * columns in the table. Case 3742
+ *
+ * @since 4.3
+ */
+ @Test public void testDUAL() throws Exception {
+ String input = "SELECT something FROM DUAL"; //$NON-NLS-1$
+ String output = "SELECT something FROM DUAL"; //$NON-NLS-1$
+
+ helpTestVisitor(getOracleSpecificMetadata(),
+ input,
+ EMPTY_CONTEXT,
+ null,
+ output);
+ }
+
+ /**
+ * Test Oracle's rownum pseudo-column. Not a real column, so it can't
+ * be fully-qualified with a table name. MM requires this column to be
+ * modeled in any table which the user wants to use rownum with.
+ * Case 3739
+ *
+ * @since 4.3
+ */
+ @Test public void testROWNUM() throws Exception {
+ String input = "SELECT part_name, rownum FROM parts"; //$NON-NLS-1$
+ String output = "SELECT PARTS.PART_NAME, ROWNUM FROM PARTS"; //$NON-NLS-1$
+
+ helpTestVisitor(getTestVDB(),
+ input,
+ null,
+ output);
+ }
+
+ /**
+ * Test Oracle's rownum pseudo-column. Not a real column, so it can't
+ * be fully-qualified with a table name. MM requires this column to be
+ * modeled in any table which the user wants to use rownum with. Case 3739
+ *
+ * @since 4.3
+ */
+ @Test public void testROWNUM2() throws Exception {
+ String input = "SELECT part_name FROM parts where rownum < 100"; //$NON-NLS-1$
+ String output = "SELECT PARTS.PART_NAME FROM PARTS WHERE ROWNUM < 100"; //$NON-NLS-1$
+
+ helpTestVisitor(getTestVDB(),
+ input,
+ null,
+ output); }
+
+ /**
+ * Case 3744. Test that an Oracle-specific db hint, delivered as a String via command
+ * payload, is added to the translated SQL.
+ *
+ * @since 4.3
+ */
+ @Test public void testOracleCommentPayload() throws Exception {
+ String input = "SELECT part_name, rownum FROM parts"; //$NON-NLS-1$
+ String output = "SELECT /*+ ALL_ROWS */ PARTS.PART_NAME, ROWNUM FROM PARTS"; //$NON-NLS-1$
+
+ String hint = "/*+ ALL_ROWS */"; //$NON-NLS-1$
+ ExecutionContext context = new ExecutionContextImpl(null, 1, hint, null, "", null, null, null); //$NON-NLS-1$
+
+ helpTestVisitor(getTestVDB(),
+ input,
+ context,
+ null,
+ output,
+ false);
+ }
+
+ /**
+ * reproducing this case relies on the name in source for the table being different from
+ * the name
+ */
+ @Test public void testCase3845() throws Exception {
+
+ String input = "SELECT (DoubleNum * 1.0) FROM BQT1.Smalla"; //$NON-NLS-1$
+ String output = "SELECT (SmallishA.DoubleNum * 1.0) FROM SmallishA"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = getOracleSpecificMetadata();
+
+ helpTestVisitor(metadata, input, EMPTY_CONTEXT, null, output);
+ }
+
+ /** create fake BQT metadata to test this case, name in source is important */
+ private QueryMetadataInterface getOracleSpecificMetadata() {
+ MetadataStore metadataStore = new MetadataStore();
+ Schema foo = RealMetadataFactory.createPhysicalModel("BQT1", metadataStore); //$NON-NLS-1$
+ Table table = RealMetadataFactory.createPhysicalGroup("SmallA", foo); //$NON-NLS-1$
+ Table dual = RealMetadataFactory.createPhysicalGroup("DUAL", foo); //$NON-NLS-1$
+ table.setNameInSource("SmallishA");//$NON-NLS-1$
+ String[] elemNames = new String[] {
+ "DoubleNum", //$NON-NLS-1$
+ "ID", //$NON-NLS-1$
+ "timestampvalue", //$NON-NLS-1$
+ };
+ String[] elemTypes = new String[] {
+ DataTypeManager.DefaultDataTypes.DOUBLE,
+ DataTypeManager.DefaultDataTypes.INTEGER,
+ DataTypeManager.DefaultDataTypes.TIMESTAMP,
+ };
+ List<Column> cols = RealMetadataFactory.createElements(table, elemNames, elemTypes);
+ cols.get(1).setAutoIncremented(true);
+ cols.get(1).setNameInSource("ID:SEQUENCE=MYSEQUENCE.nextVal"); //$NON-NLS-1$
+ cols.get(2).setNativeType("date"); //$NON-NLS-1$
+ 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, RealMetadataFactory.SFM.getSystemFunctions(), null);
+ }
+
+ public void helpTestVisitor(String vdb, String input, String expectedOutput) throws TranslatorException {
+ helpTestVisitor(vdb, input, null, expectedOutput);
+ }
+
+ @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"; //$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(RealMetadataFactory.exampleBQTCached(),
+ input,
+ EMPTY_CONTEXT, null, output);
+ }
+
+ @Test public void testExceptAsMinus() throws Exception {
+ 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(RealMetadataFactory.exampleBQTCached(),
+ input,
+ EMPTY_CONTEXT, null, output);
+ }
+
+ @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(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(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(RealMetadataFactory.exampleBQTCached());
+ Command obj = commandBuilder.getCommand(input, true, true);
+ this.helpTestVisitor(obj, EMPTY_CONTEXT, null, output);
+ }
+
+ @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(RealMetadataFactory.exampleBQTCached(), sql, EMPTY_CONTEXT, null, expected);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,182 +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.sqlserver;
-
-import java.util.List;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.teiid.cdk.CommandBuilder;
-import org.teiid.cdk.api.TranslationUtility;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.language.Command;
-import org.teiid.metadata.Column;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.metadata.Schema;
-import org.teiid.metadata.Table;
-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;
-
-
-/**
- */
-public class TestSqlServerConversionVisitor {
-
- private static SQLServerExecutionFactory trans = new SQLServerExecutionFactory();
-
- @BeforeClass
- public static void setup() throws TranslatorException {
- trans.start();
- }
-
- public String getTestVDB() {
- return TranslationHelper.PARTS_VDB;
- }
-
- public String getBQTVDB() {
- return TranslationHelper.BQT_VDB;
- }
-
- public void helpTestVisitor(String vdb, String input, String expectedOutput) throws TranslatorException {
- TranslationHelper.helpTestVisitor(vdb, input, expectedOutput, trans);
- }
-
- @Test
- public void testModFunction() throws Exception {
- String input = "SELECT mod(CONVERT(PART_ID, INTEGER), 13) FROM parts"; //$NON-NLS-1$
- String output = "SELECT (cast(PARTS.PART_ID AS int) % 13) FROM PARTS"; //$NON-NLS-1$
-
- helpTestVisitor(getTestVDB(),
- input,
- output);
- }
-
- @Test
- public void testConcatFunction() throws Exception {
- String input = "SELECT concat(part_name, 'b') FROM PARTS"; //$NON-NLS-1$
- String output = "SELECT (PARTS.PART_NAME + 'b') FROM PARTS"; //$NON-NLS-1$
-
- helpTestVisitor(getTestVDB(),
- input,
- output);
- }
-
- @Test
- public void testDayOfMonthFunction() throws Exception {
- String input = "SELECT dayofmonth(convert(PARTS.PART_ID, date)) FROM PARTS"; //$NON-NLS-1$
- String output = "SELECT {fn dayofmonth(cast(PARTS.PART_ID AS datetime))} FROM PARTS"; //$NON-NLS-1$
-
- helpTestVisitor(getTestVDB(),
- input,
- output);
- }
-
- @Test
- public void testRowLimit() throws Exception {
- String input = "select intkey from bqt1.smalla limit 100"; //$NON-NLS-1$
- String output = "SELECT TOP 100 SmallA.IntKey FROM SmallA"; //$NON-NLS-1$
-
- helpTestVisitor(getBQTVDB(),
- input,
- output);
- }
-
- @Test
- public void testUnionLimitWithOrderBy() throws Exception {
- String input = "select intkey from bqt1.smalla union select intnum from bqt1.smalla order by intkey limit 100"; //$NON-NLS-1$
- String output = "SELECT TOP 100 * FROM (SELECT SmallA.IntKey FROM SmallA UNION SELECT SmallA.IntNum FROM SmallA) AS X ORDER BY intkey"; //$NON-NLS-1$
-
- helpTestVisitor(getBQTVDB(),
- input,
- output);
- }
-
- @Test public void testLimitWithOrderByUnrelated() throws Exception {
- String input = "select intkey from bqt1.smalla order by intnum limit 100"; //$NON-NLS-1$
- String output = "SELECT TOP 100 SmallA.IntKey FROM SmallA ORDER BY SmallA.IntNum"; //$NON-NLS-1$
-
- helpTestVisitor(getBQTVDB(),
- input,
- output);
- }
-
- @Test
- public void testDateFunctions() throws Exception {
- String input = "select dayName(timestampValue), dayOfWeek(timestampValue), quarter(timestampValue) from bqt1.smalla"; //$NON-NLS-1$
- String output = "SELECT {fn dayname(SmallA.TimestampValue)}, {fn dayofweek(SmallA.TimestampValue)}, {fn quarter(SmallA.TimestampValue)} FROM SmallA"; //$NON-NLS-1$
-
- helpTestVisitor(getBQTVDB(),
- input,
- output);
- }
-
- @Test public void testConvert() throws Exception {
- String input = "select convert(timestampvalue, date), convert(timestampvalue, string), convert(datevalue, string) from bqt1.smalla"; //$NON-NLS-1$
- String output = "SELECT cast(replace(convert(varchar, SmallA.TimestampValue, 102), '.', '-') AS datetime), convert(varchar, SmallA.TimestampValue, 21), replace(convert(varchar, SmallA.DateValue, 102), '.', '-') FROM SmallA"; //$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$
- Table table = RealMetadataFactory.createPhysicalGroup("bar", foo); //$NON-NLS-1$
- String[] elemNames = new String[] {
- "x" //$NON-NLS-1$
- };
- String[] elemTypes = new String[] {
- DataTypeManager.DefaultDataTypes.STRING
- };
- List<Column> cols =RealMetadataFactory.createElements(table, elemNames, elemTypes);
-
- Column obj = cols.get(0);
- obj.setNativeType("uniqueidentifier"); //$NON-NLS-1$
-
- CompositeMetadataStore store = new CompositeMetadataStore(metadataStore);
- QueryMetadataInterface metadata = new TransformationMetadata(null, store, null, FakeMetadataFactory.SFM.getSystemFunctions(), null);
-
- TranslationUtility tu = new TranslationUtility(metadata);
- Command command = tu.parseCommand("select max(x) from bar"); //$NON-NLS-1$
- TranslationHelper.helpTestVisitor("SELECT MAX(cast(bar.x as char(36))) FROM bar", trans, command); //$NON-NLS-1$
-
- command = tu.parseCommand("select * from (select max(x) as max from bar) x"); //$NON-NLS-1$
- TranslationHelper.helpTestVisitor("SELECT x.max FROM (SELECT MAX(cast(bar.x as char(36))) AS max FROM bar) x", trans, command); //$NON-NLS-1$
- }
-
- @Test public void testRowLimitWithInlineViewOrderBy() throws Exception {
- 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());
- Command obj = commandBuilder.getCommand(input, true, true);
- TranslationHelper.helpTestVisitor(output, trans, obj);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java (from rev 3218, trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,181 @@
+/*
+ * 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.sqlserver;
+
+import java.util.List;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.teiid.cdk.CommandBuilder;
+import org.teiid.cdk.api.TranslationUtility;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.language.Command;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.query.metadata.CompositeMetadataStore;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.jdbc.TranslationHelper;
+
+
+/**
+ */
+public class TestSqlServerConversionVisitor {
+
+ private static SQLServerExecutionFactory trans = new SQLServerExecutionFactory();
+
+ @BeforeClass
+ public static void setup() throws TranslatorException {
+ trans.start();
+ }
+
+ public String getTestVDB() {
+ return TranslationHelper.PARTS_VDB;
+ }
+
+ public String getBQTVDB() {
+ return TranslationHelper.BQT_VDB;
+ }
+
+ public void helpTestVisitor(String vdb, String input, String expectedOutput) throws TranslatorException {
+ TranslationHelper.helpTestVisitor(vdb, input, expectedOutput, trans);
+ }
+
+ @Test
+ public void testModFunction() throws Exception {
+ String input = "SELECT mod(CONVERT(PART_ID, INTEGER), 13) FROM parts"; //$NON-NLS-1$
+ String output = "SELECT (cast(PARTS.PART_ID AS int) % 13) FROM PARTS"; //$NON-NLS-1$
+
+ helpTestVisitor(getTestVDB(),
+ input,
+ output);
+ }
+
+ @Test
+ public void testConcatFunction() throws Exception {
+ String input = "SELECT concat(part_name, 'b') FROM PARTS"; //$NON-NLS-1$
+ String output = "SELECT (PARTS.PART_NAME + 'b') FROM PARTS"; //$NON-NLS-1$
+
+ helpTestVisitor(getTestVDB(),
+ input,
+ output);
+ }
+
+ @Test
+ public void testDayOfMonthFunction() throws Exception {
+ String input = "SELECT dayofmonth(convert(PARTS.PART_ID, date)) FROM PARTS"; //$NON-NLS-1$
+ String output = "SELECT {fn dayofmonth(cast(PARTS.PART_ID AS datetime))} FROM PARTS"; //$NON-NLS-1$
+
+ helpTestVisitor(getTestVDB(),
+ input,
+ output);
+ }
+
+ @Test
+ public void testRowLimit() throws Exception {
+ String input = "select intkey from bqt1.smalla limit 100"; //$NON-NLS-1$
+ String output = "SELECT TOP 100 SmallA.IntKey FROM SmallA"; //$NON-NLS-1$
+
+ helpTestVisitor(getBQTVDB(),
+ input,
+ output);
+ }
+
+ @Test
+ public void testUnionLimitWithOrderBy() throws Exception {
+ String input = "select intkey from bqt1.smalla union select intnum from bqt1.smalla order by intkey limit 100"; //$NON-NLS-1$
+ String output = "SELECT TOP 100 * FROM (SELECT SmallA.IntKey FROM SmallA UNION SELECT SmallA.IntNum FROM SmallA) AS X ORDER BY intkey"; //$NON-NLS-1$
+
+ helpTestVisitor(getBQTVDB(),
+ input,
+ output);
+ }
+
+ @Test public void testLimitWithOrderByUnrelated() throws Exception {
+ String input = "select intkey from bqt1.smalla order by intnum limit 100"; //$NON-NLS-1$
+ String output = "SELECT TOP 100 SmallA.IntKey FROM SmallA ORDER BY SmallA.IntNum"; //$NON-NLS-1$
+
+ helpTestVisitor(getBQTVDB(),
+ input,
+ output);
+ }
+
+ @Test
+ public void testDateFunctions() throws Exception {
+ String input = "select dayName(timestampValue), dayOfWeek(timestampValue), quarter(timestampValue) from bqt1.smalla"; //$NON-NLS-1$
+ String output = "SELECT {fn dayname(SmallA.TimestampValue)}, {fn dayofweek(SmallA.TimestampValue)}, {fn quarter(SmallA.TimestampValue)} FROM SmallA"; //$NON-NLS-1$
+
+ helpTestVisitor(getBQTVDB(),
+ input,
+ output);
+ }
+
+ @Test public void testConvert() throws Exception {
+ String input = "select convert(timestampvalue, date), convert(timestampvalue, string), convert(datevalue, string) from bqt1.smalla"; //$NON-NLS-1$
+ String output = "SELECT cast(replace(convert(varchar, SmallA.TimestampValue, 102), '.', '-') AS datetime), convert(varchar, SmallA.TimestampValue, 21), replace(convert(varchar, SmallA.DateValue, 102), '.', '-') FROM SmallA"; //$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$
+ Table table = RealMetadataFactory.createPhysicalGroup("bar", foo); //$NON-NLS-1$
+ String[] elemNames = new String[] {
+ "x" //$NON-NLS-1$
+ };
+ String[] elemTypes = new String[] {
+ DataTypeManager.DefaultDataTypes.STRING
+ };
+ List<Column> cols =RealMetadataFactory.createElements(table, elemNames, elemTypes);
+
+ Column obj = cols.get(0);
+ obj.setNativeType("uniqueidentifier"); //$NON-NLS-1$
+
+ CompositeMetadataStore store = new CompositeMetadataStore(metadataStore);
+ 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$
+ TranslationHelper.helpTestVisitor("SELECT MAX(cast(bar.x as char(36))) FROM bar", trans, command); //$NON-NLS-1$
+
+ command = tu.parseCommand("select * from (select max(x) as max from bar) x"); //$NON-NLS-1$
+ TranslationHelper.helpTestVisitor("SELECT x.max FROM (SELECT MAX(cast(bar.x as char(36))) AS max FROM bar) x", trans, command); //$NON-NLS-1$
+ }
+
+ @Test public void testRowLimitWithInlineViewOrderBy() throws Exception {
+ 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(RealMetadataFactory.exampleBQTCached());
+ Command obj = commandBuilder.getCommand(input, true, true);
+ TranslationHelper.helpTestVisitor(output, trans, obj);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/teradata/TestTeradataTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/teradata/TestTeradataTranslator.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/teradata/TestTeradataTranslator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,184 +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.teradata;
-
-import static org.junit.Assert.*;
-
-import java.sql.Date;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.teiid.language.Expression;
-import org.teiid.language.Function;
-import org.teiid.language.In;
-import org.teiid.language.LanguageFactory;
-import org.teiid.query.unittest.TimestampUtil;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.TypeFacility;
-import org.teiid.translator.jdbc.SQLConversionVisitor;
-import org.teiid.translator.jdbc.TranslationHelper;
-
- at SuppressWarnings("nls")
-public class TestTeradataTranslator {
-
- private static TeradataExecutionFactory TRANSLATOR;
- private static final LanguageFactory LANG_FACTORY = new LanguageFactory();
-
- @BeforeClass
- public static void setUp() throws TranslatorException {
- TRANSLATOR = new TeradataExecutionFactory();
- TRANSLATOR.setUseBindVariables(false);
- TRANSLATOR.start();
- }
-
- 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();
- }
-
- @Test public void testSubstring1() throws Exception {
- String input = "SELECT dayofmonth(datevalue) FROM BQT1.SMALLA";
- String output = "SELECT extract(DAY from SmallA.DateValue) FROM SmallA";
-
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);
- }
-
- @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)");
- }
-
- @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";
- 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";
- 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";
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);
- }
-
-
- @Test public void testByteToString() throws Exception {
- helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "string", "1");
- }
-
- @Test public void testByte2ToString() throws Exception {
- helpTest(LANG_FACTORY.createLiteral(new Byte((byte)-1), Byte.class), "string", "-1");
- }
-
- @Test public void testDoubleToString() throws Exception {
- helpTest(LANG_FACTORY.createLiteral(new Double(1.0), Double.class), "string", "1.0");
- }
-
- @Test public void testInDecompose() throws Exception {
- Expression left = LANG_FACTORY.createLiteral("1", String.class);
- List<Expression> right = new ArrayList<Expression>();
- right.add(LANG_FACTORY.createLiteral("2", String.class));
- right.add(LANG_FACTORY.createLiteral("3", String.class));
-
- In expr = LANG_FACTORY.createIn(left,right, false);
-
- assertEquals("'1' IN ('2', '3')", helpGetString(expr));
- }
-
- @Test public void testSingleInDecompose() throws Exception {
- Expression left = LANG_FACTORY.createLiteral("1", String.class);
- List<Expression> right = new ArrayList<Expression>();
- right.add(LANG_FACTORY.createLiteral("2", String.class));
-
- In expr = LANG_FACTORY.createIn(left,right, false);
-
- assertEquals("'1' IN ('2')", helpGetString(expr));
- }
-
- @Test public void testInDecomposeNonLiterals() throws Exception {
- Expression left = LANG_FACTORY.createLiteral("1", String.class);
- List<Expression> right = new ArrayList<Expression>();
- right.add(LANG_FACTORY.createFunction("func", new Expression[] {}, Date.class));
- right.add(LANG_FACTORY.createLiteral("3", String.class));
-
- In expr = LANG_FACTORY.createIn(left,right, false);
-
- assertEquals("'1' = func() OR '1' = '3'", helpGetString(expr));
- }
-
- @Test public void testNegatedInDecomposeNonLiterals() throws Exception {
- Expression left = LANG_FACTORY.createLiteral("1", String.class);
- List<Expression> right = new ArrayList<Expression>();
- right.add(LANG_FACTORY.createFunction("func", new Expression[] {}, Date.class));
- right.add(LANG_FACTORY.createLiteral("3", String.class));
-
- In expr = LANG_FACTORY.createIn(left,right, true);
-
- assertEquals("'1' <> func() AND '1' <> '3'", helpGetString(expr));
- }
-
- @Test public void testsingleInDecomposeNonLiterals() throws Exception {
- Expression left = LANG_FACTORY.createLiteral("1", String.class);
- List<Expression> right = new ArrayList<Expression>();
- right.add(LANG_FACTORY.createFunction("func", new Expression[] {}, Date.class));
-
- In expr = LANG_FACTORY.createIn(left,right, false);
-
- assertEquals("'1' = func()", helpGetString(expr));
- }
-
- @Test public void testNullComapreNull() throws Exception {
- String input = "SELECT INTKEY, STRINGKEY, DOUBLENUM FROM bqt1.smalla WHERE NULL <> NULL";
- String out = "SELECT SmallA.IntKey, SmallA.StringKey, SmallA.DoubleNum FROM SmallA WHERE 1 = 0";
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, null, input, out, TRANSLATOR);
- }
-
- @Test public void testPushDownFunction() throws Exception {
- String input = "SELECT teradata.HASHBAKAMP(STRINGKEY) DOUBLENUM FROM bqt1.smalla";
- String out = "SELECT HASHBAKAMP(SmallA.StringKey) AS DOUBLENUM FROM SmallA";
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, null, input, out, TRANSLATOR);
- }
-
- @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";
- TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, null, input, out, TRANSLATOR);
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/teradata/TestTeradataTranslator.java (from rev 3218, trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/teradata/TestTeradataTranslator.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/teradata/TestTeradataTranslator.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/teradata/TestTeradataTranslator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,206 @@
+/*
+ * 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.teradata;
+
+import static org.junit.Assert.*;
+
+import java.sql.Date;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.teiid.language.Expression;
+import org.teiid.language.Function;
+import org.teiid.language.In;
+import org.teiid.language.LanguageFactory;
+import org.teiid.query.unittest.TimestampUtil;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.TypeFacility;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.TranslationHelper;
+
+ at SuppressWarnings("nls")
+public class TestTeradataTranslator {
+
+ private static TeradataExecutionFactory TRANSLATOR;
+ private static final LanguageFactory LANG_FACTORY = new LanguageFactory();
+
+ @BeforeClass
+ public static void setUp() throws TranslatorException {
+ TRANSLATOR = new TeradataExecutionFactory();
+ TRANSLATOR.setUseBindVariables(false);
+ TRANSLATOR.start();
+ }
+
+ 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();
+ }
+
+ @Test public void testSubstring1() throws Exception {
+ String input = "SELECT dayofmonth(datevalue) FROM BQT1.SMALLA";
+ String output = "SELECT extract(DAY from SmallA.DateValue) FROM SmallA";
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);
+ }
+
+ @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)");
+ }
+
+ @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";
+ 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(100)),1) = '1' ORDER BY SmallA.IntKey";
+ 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(100)),1,2) = '1' ORDER BY SmallA.IntKey";
+ 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(cast(SmallA.TimeValue AS FORMAT 'HH:MI:SS') AS VARCHAR(9))) AS UPPER FROM SmallA ORDER BY SmallA.IntKey";
+ 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";
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);
+ }
+
+
+ @Test public void testByteToString() throws Exception {
+ 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", "cast(-1 AS varchar(4000))");
+ }
+
+ @Test public void testDoubleToString() throws Exception {
+ 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>();
+ right.add(LANG_FACTORY.createLiteral("2", String.class));
+ right.add(LANG_FACTORY.createLiteral("3", String.class));
+
+ In expr = LANG_FACTORY.createIn(left,right, false);
+
+ assertEquals("'1' IN ('2', '3')", helpGetString(expr));
+ }
+
+ @Test public void testSingleInDecompose() throws Exception {
+ Expression left = LANG_FACTORY.createLiteral("1", String.class);
+ List<Expression> right = new ArrayList<Expression>();
+ right.add(LANG_FACTORY.createLiteral("2", String.class));
+
+ In expr = LANG_FACTORY.createIn(left,right, false);
+
+ assertEquals("'1' IN ('2')", helpGetString(expr));
+ }
+
+ @Test public void testInDecomposeNonLiterals() throws Exception {
+ Expression left = LANG_FACTORY.createLiteral("1", String.class);
+ List<Expression> right = new ArrayList<Expression>();
+ right.add(LANG_FACTORY.createFunction("func", new Expression[] {}, Date.class));
+ right.add(LANG_FACTORY.createLiteral("3", String.class));
+
+ In expr = LANG_FACTORY.createIn(left,right, false);
+
+ assertEquals("'1' = func() OR '1' = '3'", helpGetString(expr));
+ }
+
+ @Test public void testNegatedInDecomposeNonLiterals() throws Exception {
+ Expression left = LANG_FACTORY.createLiteral("1", String.class);
+ List<Expression> right = new ArrayList<Expression>();
+ right.add(LANG_FACTORY.createFunction("func", new Expression[] {}, Date.class));
+ right.add(LANG_FACTORY.createLiteral("3", String.class));
+
+ In expr = LANG_FACTORY.createIn(left,right, true);
+
+ assertEquals("'1' <> func() AND '1' <> '3'", helpGetString(expr));
+ }
+
+ @Test public void testsingleInDecomposeNonLiterals() throws Exception {
+ Expression left = LANG_FACTORY.createLiteral("1", String.class);
+ List<Expression> right = new ArrayList<Expression>();
+ right.add(LANG_FACTORY.createFunction("func", new Expression[] {}, Date.class));
+
+ In expr = LANG_FACTORY.createIn(left,right, false);
+
+ assertEquals("'1' = func()", helpGetString(expr));
+ }
+
+ @Test public void testNullComapreNull() throws Exception {
+ String input = "SELECT INTKEY, STRINGKEY, DOUBLENUM FROM bqt1.smalla WHERE NULL <> NULL";
+ String out = "SELECT SmallA.IntKey, SmallA.StringKey, SmallA.DoubleNum FROM SmallA WHERE 1 = 0";
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, null, input, out, TRANSLATOR);
+ }
+
+ @Test public void testPushDownFunction() throws Exception {
+ String input = "SELECT teradata.HASHBAKAMP(STRINGKEY) DOUBLENUM FROM bqt1.smalla";
+ String out = "SELECT HASHBAKAMP(SmallA.StringKey) AS DOUBLENUM FROM SmallA";
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, null, input, out, TRANSLATOR);
+ }
+
+ @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+1)) <> '0' ORDER BY SmallA.IntKey";
+ 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(100)),4)) = 6 ORDER BY SmallA.IntKey";
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, null, input, out, TRANSLATOR);
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/pom.xml
===================================================================
--- trunk/connectors/translator-ldap/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,52 +0,0 @@
-<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>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>translator-ldap</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>LDAP Translator</name>
- <description>LDAP Translator</description>
-
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- </dependencies>
-
- <build>
- <outputDirectory>target/classes</outputDirectory>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- </resource>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>false</filtering>
- <excludes>
- <exclude>**/*.xml</exclude>
- <exclude>**/*.properties</exclude>
- </excludes>
- </resource>
- </resources>
- </build>
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/pom.xml (from rev 3220, trunk/connectors/translator-ldap/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,52 @@
+<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>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>translator-ldap</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>LDAP Translator</name>
+ <description>LDAP Translator</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <outputDirectory>target/classes</outputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.xml</include>
+ <include>**/*.properties</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>false</filtering>
+ <excludes>
+ <exclude>**/*.xml</exclude>
+ <exclude>**/*.properties</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ </build>
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/src/test/java/org/teiid/translator/ldap/TestIQueryToLdapSearchParser.java
===================================================================
--- trunk/connectors/translator-ldap/src/test/java/org/teiid/translator/ldap/TestIQueryToLdapSearchParser.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/src/test/java/org/teiid/translator/ldap/TestIQueryToLdapSearchParser.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,310 +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.ldap;
-
-import static org.mockito.Mockito.mock;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.naming.directory.Attribute;
-import javax.naming.directory.SearchControls;
-import javax.naming.ldap.SortKey;
-
-import junit.framework.TestCase;
-
-import org.teiid.cdk.CommandBuilder;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.dqp.internal.datamgr.RuntimeMetadataImpl;
-import org.teiid.language.Command;
-import org.teiid.language.Select;
-import org.teiid.metadata.Column;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.metadata.RuntimeMetadata;
-import org.teiid.metadata.Schema;
-import org.teiid.metadata.Table;
-import org.teiid.metadata.Column.SearchType;
-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;
-import org.teiid.translator.ldap.LDAPExecutionFactory;
-import org.teiid.translator.ldap.LDAPSearchDetails;
-
-
-/**
- * Test IQueryToLdapSearchParser.
- */
-/**
- * @author mdrilling
- *
- */
-public class TestIQueryToLdapSearchParser extends TestCase {
-
- public TestIQueryToLdapSearchParser(String name) {
- super(name);
- }
-
- /**
- * Get Resolved Command using SQL String and metadata.
- */
- public Command getCommand(String sql, QueryMetadataInterface metadata) {
- CommandBuilder builder = new CommandBuilder(metadata);
- return builder.getCommand(sql);
- }
-
- /**
- * Helper method for testing the provided LDAPSearchDetails against expected values
- * @param searchDetails the LDAPSearchDetails object
- * @param expectedContextName the expected context name
- * @param expectedContextFilter the expected context filter string
- * @param expectedAttrNameList list of expected attribute names
- * @param expectedCountLimit the expected count limit
- * @param expectedSearchScope the expected search scope
- * @param expectedSortKeys the expected sortKeys list.
- */
- public void helpTestSearchDetails(final LDAPSearchDetails searchDetails, final String expectedContextName,
- final String expectedContextFilter, final List expectedAttrNameList, final long expectedCountLimit,
- final int expectedSearchScope, final SortKey[] expectedSortKeys) {
-
- // Get all of the actual values
- String contextName = searchDetails.getContextName();
- String contextFilter = searchDetails.getContextFilter();
- List attrList = searchDetails.getAttributeList();
- long countLimit = searchDetails.getCountLimit();
- int searchScope = searchDetails.getSearchScope();
- SortKey[] sortKeys = searchDetails.getSortKeys();
-
- // Compare actual with Expected
- assertEquals(expectedContextName, contextName);
- assertEquals(expectedContextFilter, contextFilter);
-
- assertEquals(attrList.size(),expectedAttrNameList.size());
- Iterator iter = attrList.iterator();
- Iterator eIter = expectedAttrNameList.iterator();
- while(iter.hasNext()&&eIter.hasNext()) {
- String actualName = ((Attribute)iter.next()).getID();
- String expectedName = (String)eIter.next();
- assertEquals(actualName, expectedName);
- }
-
- assertEquals(expectedCountLimit, countLimit);
- assertEquals(expectedSearchScope, searchScope);
- assertEquals(expectedSortKeys, sortKeys);
- }
-
- /**
- * Test a Query without criteria
- */
- public void testSelectFrom1() throws Exception {
- LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People"); //$NON-NLS-1$
-
- //-----------------------------------
- // Set Expected SearchDetails Values
- //-----------------------------------
- String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
- String expectedContextFilter = "(objectClass=*)"; //$NON-NLS-1$
-
- List expectedAttrNameList = new ArrayList();
- expectedAttrNameList.add("uid"); //$NON-NLS-1$
- expectedAttrNameList.add("cn"); //$NON-NLS-1$
-
- long expectedCountLimit = -1;
- int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
- SortKey[] expectedSortKeys = null;
-
- helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
- expectedCountLimit, expectedSearchScope, expectedSortKeys);
-
- }
-
- /**
- * Test a Query with a criteria
- */
- public void testSelectFromWhere1() throws Exception {
- LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name = 'R%'"); //$NON-NLS-1$
-
- //-----------------------------------
- // Set Expected SearchDetails Values
- //-----------------------------------
- String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
- String expectedContextFilter = "(cn=R%)"; //$NON-NLS-1$
-
- List expectedAttrNameList = new ArrayList();
- expectedAttrNameList.add("uid"); //$NON-NLS-1$
- expectedAttrNameList.add("cn"); //$NON-NLS-1$
-
- long expectedCountLimit = -1;
- int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
- SortKey[] expectedSortKeys = null;
-
- helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
- expectedCountLimit, expectedSearchScope, expectedSortKeys);
-
- }
-
- /**
- * Test a Query with a criteria
- */
- public void testEscaping() throws Exception {
- LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name = 'R*'"); //$NON-NLS-1$
-
- //-----------------------------------
- // Set Expected SearchDetails Values
- //-----------------------------------
- String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
- String expectedContextFilter = "(cn=R\\2a)"; //$NON-NLS-1$
-
- List expectedAttrNameList = new ArrayList();
- expectedAttrNameList.add("uid"); //$NON-NLS-1$
- expectedAttrNameList.add("cn"); //$NON-NLS-1$
-
- long expectedCountLimit = -1;
- int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
- SortKey[] expectedSortKeys = null;
-
- helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
- expectedCountLimit, expectedSearchScope, expectedSortKeys);
-
- }
-
- public void testNot() throws Exception {
- LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE not (Name like 'R%' or Name like 'S%')"); //$NON-NLS-1$
-
- //-----------------------------------
- // Set Expected SearchDetails Values
- //-----------------------------------
- String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
- String expectedContextFilter = "(&(!(cn=R*))(!(cn=S*)))"; //$NON-NLS-1$
-
- List expectedAttrNameList = new ArrayList();
- expectedAttrNameList.add("uid"); //$NON-NLS-1$
- expectedAttrNameList.add("cn"); //$NON-NLS-1$
-
- long expectedCountLimit = -1;
- int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
- SortKey[] expectedSortKeys = null;
-
- helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
- expectedCountLimit, expectedSearchScope, expectedSortKeys);
-
- }
-
- public void testGT() throws Exception {
- LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name > 'R'"); //$NON-NLS-1$
-
- //-----------------------------------
- // Set Expected SearchDetails Values
- //-----------------------------------
- String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
- String expectedContextFilter = "(!(cn<=R))"; //$NON-NLS-1$
-
- List expectedAttrNameList = new ArrayList();
- expectedAttrNameList.add("uid"); //$NON-NLS-1$
- expectedAttrNameList.add("cn"); //$NON-NLS-1$
-
- long expectedCountLimit = -1;
- int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
- SortKey[] expectedSortKeys = null;
-
- helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
- expectedCountLimit, expectedSearchScope, expectedSortKeys);
- }
-
- public void testLT() throws Exception {
- LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name < 'R'"); //$NON-NLS-1$
-
- //-----------------------------------
- // Set Expected SearchDetails Values
- //-----------------------------------
- String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
- String expectedContextFilter = "(!(cn>=R))"; //$NON-NLS-1$
-
- List expectedAttrNameList = new ArrayList();
- expectedAttrNameList.add("uid"); //$NON-NLS-1$
- expectedAttrNameList.add("cn"); //$NON-NLS-1$
-
- long expectedCountLimit = -1;
- int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
- SortKey[] expectedSortKeys = null;
-
- helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
- expectedCountLimit, expectedSearchScope, expectedSortKeys);
- }
-
- private LDAPSearchDetails helpGetSearchDetails(String queryString) throws TranslatorException {
- QueryMetadataInterface metadata = exampleLdap();
- RuntimeMetadata rm = new RuntimeMetadataImpl(metadata);
-
- LDAPExecutionFactory config = mock(LDAPExecutionFactory.class);
-
- IQueryToLdapSearchParser searchParser = new IQueryToLdapSearchParser(config);
-
- Select query = (Select)getCommand(queryString, metadata);
-
- LDAPSearchDetails searchDetails = searchParser.translateSQLQueryToLDAPSearch(query);
- return searchDetails;
- }
-
- public static QueryMetadataInterface exampleLdap() {
- MetadataStore metadataStore = new MetadataStore();
-
- // Create models
- Schema ldapModel = RealMetadataFactory.createPhysicalModel("LdapModel", metadataStore); //$NON-NLS-1$
-
- // Create physical groups
- Table table = RealMetadataFactory.createPhysicalGroup("People", ldapModel); //$NON-NLS-1$
- table.setNameInSource("ou=people,dc=metamatrix,dc=com"); //$NON-NLS-1$
-
- // Create physical elements
- String[] elemNames = new String[] {
- "UserID", "Name" //$NON-NLS-1$ //$NON-NLS-2$
- };
- String[] elemTypes = new String[] {
- DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING
- };
-
- List<Column> cols = RealMetadataFactory.createElements(table, elemNames, elemTypes);
-
- // Set name in source on each column
- String[] nameInSource = new String[] {
- "uid", "cn" //$NON-NLS-1$ //$NON-NLS-2$
- };
- for(int i=0; i<2; i++) {
- Column obj = cols.get(i);
- obj.setNameInSource(nameInSource[i]);
- }
-
- // Set column-specific properties
- for(int i=1; i<2; i++) {
- cols.get(i).setSearchType(SearchType.Unsearchable);
- }
-
- // Create the facade from the store
- return new TransformationMetadata(null, new CompositeMetadataStore(metadataStore), null, FakeMetadataFactory.SFM.getSystemFunctions(), null);
- }
-}
-
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/src/test/java/org/teiid/translator/ldap/TestIQueryToLdapSearchParser.java (from rev 3218, trunk/connectors/translator-ldap/src/test/java/org/teiid/translator/ldap/TestIQueryToLdapSearchParser.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/src/test/java/org/teiid/translator/ldap/TestIQueryToLdapSearchParser.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ldap/src/test/java/org/teiid/translator/ldap/TestIQueryToLdapSearchParser.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,309 @@
+/*
+ * 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.ldap;
+
+import static org.mockito.Mockito.mock;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.naming.directory.Attribute;
+import javax.naming.directory.SearchControls;
+import javax.naming.ldap.SortKey;
+
+import junit.framework.TestCase;
+
+import org.teiid.cdk.CommandBuilder;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.dqp.internal.datamgr.RuntimeMetadataImpl;
+import org.teiid.language.Command;
+import org.teiid.language.Select;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.metadata.Column.SearchType;
+import org.teiid.query.metadata.CompositeMetadataStore;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.ldap.IQueryToLdapSearchParser;
+import org.teiid.translator.ldap.LDAPExecutionFactory;
+import org.teiid.translator.ldap.LDAPSearchDetails;
+
+
+/**
+ * Test IQueryToLdapSearchParser.
+ */
+/**
+ * @author mdrilling
+ *
+ */
+public class TestIQueryToLdapSearchParser extends TestCase {
+
+ public TestIQueryToLdapSearchParser(String name) {
+ super(name);
+ }
+
+ /**
+ * Get Resolved Command using SQL String and metadata.
+ */
+ public Command getCommand(String sql, QueryMetadataInterface metadata) {
+ CommandBuilder builder = new CommandBuilder(metadata);
+ return builder.getCommand(sql);
+ }
+
+ /**
+ * Helper method for testing the provided LDAPSearchDetails against expected values
+ * @param searchDetails the LDAPSearchDetails object
+ * @param expectedContextName the expected context name
+ * @param expectedContextFilter the expected context filter string
+ * @param expectedAttrNameList list of expected attribute names
+ * @param expectedCountLimit the expected count limit
+ * @param expectedSearchScope the expected search scope
+ * @param expectedSortKeys the expected sortKeys list.
+ */
+ public void helpTestSearchDetails(final LDAPSearchDetails searchDetails, final String expectedContextName,
+ final String expectedContextFilter, final List expectedAttrNameList, final long expectedCountLimit,
+ final int expectedSearchScope, final SortKey[] expectedSortKeys) {
+
+ // Get all of the actual values
+ String contextName = searchDetails.getContextName();
+ String contextFilter = searchDetails.getContextFilter();
+ List attrList = searchDetails.getAttributeList();
+ long countLimit = searchDetails.getCountLimit();
+ int searchScope = searchDetails.getSearchScope();
+ SortKey[] sortKeys = searchDetails.getSortKeys();
+
+ // Compare actual with Expected
+ assertEquals(expectedContextName, contextName);
+ assertEquals(expectedContextFilter, contextFilter);
+
+ assertEquals(attrList.size(),expectedAttrNameList.size());
+ Iterator iter = attrList.iterator();
+ Iterator eIter = expectedAttrNameList.iterator();
+ while(iter.hasNext()&&eIter.hasNext()) {
+ String actualName = ((Attribute)iter.next()).getID();
+ String expectedName = (String)eIter.next();
+ assertEquals(actualName, expectedName);
+ }
+
+ assertEquals(expectedCountLimit, countLimit);
+ assertEquals(expectedSearchScope, searchScope);
+ assertEquals(expectedSortKeys, sortKeys);
+ }
+
+ /**
+ * Test a Query without criteria
+ */
+ public void testSelectFrom1() throws Exception {
+ LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People"); //$NON-NLS-1$
+
+ //-----------------------------------
+ // Set Expected SearchDetails Values
+ //-----------------------------------
+ String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
+ String expectedContextFilter = "(objectClass=*)"; //$NON-NLS-1$
+
+ List expectedAttrNameList = new ArrayList();
+ expectedAttrNameList.add("uid"); //$NON-NLS-1$
+ expectedAttrNameList.add("cn"); //$NON-NLS-1$
+
+ long expectedCountLimit = -1;
+ int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
+ SortKey[] expectedSortKeys = null;
+
+ helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
+ expectedCountLimit, expectedSearchScope, expectedSortKeys);
+
+ }
+
+ /**
+ * Test a Query with a criteria
+ */
+ public void testSelectFromWhere1() throws Exception {
+ LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name = 'R%'"); //$NON-NLS-1$
+
+ //-----------------------------------
+ // Set Expected SearchDetails Values
+ //-----------------------------------
+ String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
+ String expectedContextFilter = "(cn=R%)"; //$NON-NLS-1$
+
+ List expectedAttrNameList = new ArrayList();
+ expectedAttrNameList.add("uid"); //$NON-NLS-1$
+ expectedAttrNameList.add("cn"); //$NON-NLS-1$
+
+ long expectedCountLimit = -1;
+ int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
+ SortKey[] expectedSortKeys = null;
+
+ helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
+ expectedCountLimit, expectedSearchScope, expectedSortKeys);
+
+ }
+
+ /**
+ * Test a Query with a criteria
+ */
+ public void testEscaping() throws Exception {
+ LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name = 'R*'"); //$NON-NLS-1$
+
+ //-----------------------------------
+ // Set Expected SearchDetails Values
+ //-----------------------------------
+ String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
+ String expectedContextFilter = "(cn=R\\2a)"; //$NON-NLS-1$
+
+ List expectedAttrNameList = new ArrayList();
+ expectedAttrNameList.add("uid"); //$NON-NLS-1$
+ expectedAttrNameList.add("cn"); //$NON-NLS-1$
+
+ long expectedCountLimit = -1;
+ int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
+ SortKey[] expectedSortKeys = null;
+
+ helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
+ expectedCountLimit, expectedSearchScope, expectedSortKeys);
+
+ }
+
+ public void testNot() throws Exception {
+ LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE not (Name like 'R%' or Name like 'S%')"); //$NON-NLS-1$
+
+ //-----------------------------------
+ // Set Expected SearchDetails Values
+ //-----------------------------------
+ String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
+ String expectedContextFilter = "(&(!(cn=R*))(!(cn=S*)))"; //$NON-NLS-1$
+
+ List expectedAttrNameList = new ArrayList();
+ expectedAttrNameList.add("uid"); //$NON-NLS-1$
+ expectedAttrNameList.add("cn"); //$NON-NLS-1$
+
+ long expectedCountLimit = -1;
+ int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
+ SortKey[] expectedSortKeys = null;
+
+ helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
+ expectedCountLimit, expectedSearchScope, expectedSortKeys);
+
+ }
+
+ public void testGT() throws Exception {
+ LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name > 'R'"); //$NON-NLS-1$
+
+ //-----------------------------------
+ // Set Expected SearchDetails Values
+ //-----------------------------------
+ String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
+ String expectedContextFilter = "(!(cn<=R))"; //$NON-NLS-1$
+
+ List expectedAttrNameList = new ArrayList();
+ expectedAttrNameList.add("uid"); //$NON-NLS-1$
+ expectedAttrNameList.add("cn"); //$NON-NLS-1$
+
+ long expectedCountLimit = -1;
+ int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
+ SortKey[] expectedSortKeys = null;
+
+ helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
+ expectedCountLimit, expectedSearchScope, expectedSortKeys);
+ }
+
+ public void testLT() throws Exception {
+ LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name < 'R'"); //$NON-NLS-1$
+
+ //-----------------------------------
+ // Set Expected SearchDetails Values
+ //-----------------------------------
+ String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
+ String expectedContextFilter = "(!(cn>=R))"; //$NON-NLS-1$
+
+ List expectedAttrNameList = new ArrayList();
+ expectedAttrNameList.add("uid"); //$NON-NLS-1$
+ expectedAttrNameList.add("cn"); //$NON-NLS-1$
+
+ long expectedCountLimit = -1;
+ int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
+ SortKey[] expectedSortKeys = null;
+
+ helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
+ expectedCountLimit, expectedSearchScope, expectedSortKeys);
+ }
+
+ private LDAPSearchDetails helpGetSearchDetails(String queryString) throws TranslatorException {
+ QueryMetadataInterface metadata = exampleLdap();
+ RuntimeMetadata rm = new RuntimeMetadataImpl(metadata);
+
+ LDAPExecutionFactory config = mock(LDAPExecutionFactory.class);
+
+ IQueryToLdapSearchParser searchParser = new IQueryToLdapSearchParser(config);
+
+ Select query = (Select)getCommand(queryString, metadata);
+
+ LDAPSearchDetails searchDetails = searchParser.translateSQLQueryToLDAPSearch(query);
+ return searchDetails;
+ }
+
+ public static QueryMetadataInterface exampleLdap() {
+ MetadataStore metadataStore = new MetadataStore();
+
+ // Create models
+ Schema ldapModel = RealMetadataFactory.createPhysicalModel("LdapModel", metadataStore); //$NON-NLS-1$
+
+ // Create physical groups
+ Table table = RealMetadataFactory.createPhysicalGroup("People", ldapModel); //$NON-NLS-1$
+ table.setNameInSource("ou=people,dc=metamatrix,dc=com"); //$NON-NLS-1$
+
+ // Create physical elements
+ String[] elemNames = new String[] {
+ "UserID", "Name" //$NON-NLS-1$ //$NON-NLS-2$
+ };
+ String[] elemTypes = new String[] {
+ DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING
+ };
+
+ List<Column> cols = RealMetadataFactory.createElements(table, elemNames, elemTypes);
+
+ // Set name in source on each column
+ String[] nameInSource = new String[] {
+ "uid", "cn" //$NON-NLS-1$ //$NON-NLS-2$
+ };
+ for(int i=0; i<2; i++) {
+ Column obj = cols.get(i);
+ obj.setNameInSource(nameInSource[i]);
+ }
+
+ // Set column-specific properties
+ for(int i=1; i<2; i++) {
+ cols.get(i).setSearchType(SearchType.Unsearchable);
+ }
+
+ // Create the facade from the store
+ return new TransformationMetadata(null, new CompositeMetadataStore(metadataStore), null, RealMetadataFactory.SFM.getSystemFunctions(), null);
+ }
+}
+
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-loopback/pom.xml
===================================================================
--- trunk/connectors/translator-loopback/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-loopback/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,53 +0,0 @@
-<?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>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>translator-loopback</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>Loopback Translator</name>
- <description>Loopback Translator</description>
-
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- </dependencies>
-
- <build>
- <outputDirectory>target/classes</outputDirectory>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- </resource>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>false</filtering>
- <excludes>
- <exclude>**/*.xml</exclude>
- <exclude>**/*.properties</exclude>
- </excludes>
- </resource>
- </resources>
- </build>
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-loopback/pom.xml (from rev 3220, trunk/connectors/translator-loopback/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-loopback/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-loopback/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,53 @@
+<?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>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>translator-loopback</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>Loopback Translator</name>
+ <description>Loopback Translator</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <outputDirectory>target/classes</outputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.xml</include>
+ <include>**/*.properties</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>false</filtering>
+ <excludes>
+ <exclude>**/*.xml</exclude>
+ <exclude>**/*.properties</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ </build>
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-olap/pom.xml
===================================================================
--- trunk/connectors/translator-olap/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-olap/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,59 +0,0 @@
-<?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>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>translator-olap</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>OLAP Translator</name>
- <description>This translator provides access to Query Analysis Cubes</description>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.olap4j</groupId>
- <artifactId>olap4j</artifactId>
- <version>0.9.8.343</version>
- <scope>provided</scope>
- </dependency>
- </dependencies>
-
- <build>
- <outputDirectory>target/classes</outputDirectory>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- </resource>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>false</filtering>
- <excludes>
- <exclude>**/*.xml</exclude>
- <exclude>**/*.properties</exclude>
- </excludes>
- </resource>
- </resources>
- </build>
-
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-olap/pom.xml (from rev 3220, trunk/connectors/translator-olap/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-olap/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-olap/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,59 @@
+<?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>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>translator-olap</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>OLAP Translator</name>
+ <description>This translator provides access to Query Analysis Cubes</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.olap4j</groupId>
+ <artifactId>olap4j</artifactId>
+ <version>0.9.8.343</version>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <outputDirectory>target/classes</outputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.xml</include>
+ <include>**/*.properties</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>false</filtering>
+ <excludes>
+ <exclude>**/*.xml</exclude>
+ <exclude>**/*.properties</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ </build>
+
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/pom.xml
===================================================================
--- trunk/connectors/translator-salesforce/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,57 +0,0 @@
-<?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>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>translator-salesforce</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>Salesforce Translator</name>
- <description>Integrates the query engine with Salesforce.com.</description>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid.connectors</groupId>
- <artifactId>salesforce-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- </dependencies>
-
- <build>
- <outputDirectory>target/classes</outputDirectory>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- </resource>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>false</filtering>
- <excludes>
- <exclude>**/*.xml</exclude>
- <exclude>**/*.properties</exclude>
- </excludes>
- </resource>
- </resources>
- </build>
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/pom.xml (from rev 3220, trunk/connectors/translator-salesforce/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,57 @@
+<?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>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>translator-salesforce</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>Salesforce Translator</name>
+ <description>Integrates the query engine with Salesforce.com.</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <artifactId>salesforce-api</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <outputDirectory>target/classes</outputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.xml</include>
+ <include>**/*.properties</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>false</filtering>
+ <excludes>
+ <exclude>**/*.xml</exclude>
+ <exclude>**/*.properties</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ </build>
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/SalesForceExecutionFactory.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/SalesForceExecutionFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/SalesForceExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,188 +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.salesforce;
-
-import java.util.ArrayList;
-import java.util.Collections;
-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;
-import org.teiid.translator.ExecutionFactory;
-import org.teiid.translator.ProcedureExecution;
-import org.teiid.translator.ResultSetExecution;
-import org.teiid.translator.Translator;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.TranslatorProperty;
-import org.teiid.translator.UpdateExecution;
-import org.teiid.translator.salesforce.execution.DeleteExecutionImpl;
-import org.teiid.translator.salesforce.execution.InsertExecutionImpl;
-import org.teiid.translator.salesforce.execution.ProcedureExecutionParentImpl;
-import org.teiid.translator.salesforce.execution.QueryExecutionImpl;
-import org.teiid.translator.salesforce.execution.UpdateExecutionImpl;
-
- at Translator(name="salesforce", description="A translator for Salesforce")
-public class SalesForceExecutionFactory extends ExecutionFactory<ConnectionFactory, SalesforceConnection> {
-
- private static final String SALESFORCE = "salesforce"; //$NON-NLS-1$
- private static final String EXCLUDES = "excludes";//$NON-NLS-1$
- private static final String INCLUDES = "includes";//$NON-NLS-1$
- private String connectorStateClass;
- private boolean auditModelFields = false;
-
- public SalesForceExecutionFactory() {
- // http://jira.jboss.org/jira/browse/JBEDSP-306
- // Salesforce supports ORDER BY, but not on all column types
- setSupportsOrderBy(false);
- setSupportsOuterJoins(true);
- setSupportedJoinCriteria(SupportedJoinCriteria.KEY);
- }
-
- public String getConnectorStateClass() {
- return this.connectorStateClass;
- }
- public void setConnectorStateClass(String connectorStateClass) {
- this.connectorStateClass = connectorStateClass;
- }
-
- @TranslatorProperty(display="Audit Model Fields", advanced=true)
- public boolean isModelAuditFields() {
- return this.auditModelFields;
- }
-
- public void setModelAuditFields(boolean modelAuditFields) {
- this.auditModelFields = modelAuditFields;
- }
-
- @Override
- public void start() throws TranslatorException {
- super.start();
- LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Started"); //$NON-NLS-1$
- }
-
-
- @Override
- public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, SalesforceConnection connection)
- throws TranslatorException {
- return new QueryExecutionImpl(command, connection, metadata, executionContext);
- }
-
- @Override
- public UpdateExecution createUpdateExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, SalesforceConnection connection) throws TranslatorException {
- UpdateExecution result = null;
- if(command instanceof org.teiid.language.Delete) {
- result = new DeleteExecutionImpl(command, connection, metadata, executionContext);
- } else if (command instanceof org.teiid.language.Insert) {
- result = new InsertExecutionImpl(command, connection, metadata, executionContext);
- } else if (command instanceof org.teiid.language.Update) {
- result = new UpdateExecutionImpl(command, connection, metadata, executionContext);
- }
- return result;
-
- }
-
- @Override
- public ProcedureExecution createProcedureExecution(Call command,ExecutionContext executionContext, RuntimeMetadata metadata, SalesforceConnection connection)
- throws TranslatorException {
- return new ProcedureExecutionParentImpl(command, connection, metadata, executionContext);
- }
- @Override
- public void getMetadata(MetadataFactory metadataFactory, SalesforceConnection connection) throws TranslatorException {
- MetadataProcessor processor = new MetadataProcessor(connection,metadataFactory, this);
- processor.processMetadata();
- }
-
- @Override
- public List getSupportedFunctions() {
- return Collections.EMPTY_LIST;
- }
-
- @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;
- }
-
- @Override
- public boolean supportsInCriteria() {
- return true;
- }
-
- @Override
- public boolean supportsLikeCriteria() {
- return true;
- }
-
- @Override
- public boolean supportsRowLimit() {
- return true;
- }
-
- @Override
- public boolean supportsAggregatesCountStar() {
- return true;
- }
-
- @Override
- public boolean supportsNotCriteria() {
- return true;
- }
-
- @Override
- public boolean supportsOrCriteria() {
- return true;
- }
-
- @Override
- public boolean supportsCompareCriteriaOrdered() {
- return true;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/SalesForceExecutionFactory.java (from rev 3218, trunk/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/SalesForceExecutionFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/SalesForceExecutionFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/SalesForceExecutionFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,175 @@
+/*
+ * 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.salesforce;
+
+import static org.teiid.translator.TypeFacility.RUNTIME_NAMES.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+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;
+import org.teiid.translator.ExecutionFactory;
+import org.teiid.translator.ProcedureExecution;
+import org.teiid.translator.ResultSetExecution;
+import org.teiid.translator.Translator;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.TranslatorProperty;
+import org.teiid.translator.UpdateExecution;
+import org.teiid.translator.salesforce.execution.DeleteExecutionImpl;
+import org.teiid.translator.salesforce.execution.InsertExecutionImpl;
+import org.teiid.translator.salesforce.execution.ProcedureExecutionParentImpl;
+import org.teiid.translator.salesforce.execution.QueryExecutionImpl;
+import org.teiid.translator.salesforce.execution.UpdateExecutionImpl;
+
+ at Translator(name="salesforce", description="A translator for Salesforce")
+public class SalesForceExecutionFactory extends ExecutionFactory<ConnectionFactory, SalesforceConnection> {
+
+ private static final String SALESFORCE = "salesforce"; //$NON-NLS-1$
+ private static final String EXCLUDES = "excludes";//$NON-NLS-1$
+ private static final String INCLUDES = "includes";//$NON-NLS-1$
+ private String connectorStateClass;
+ private boolean auditModelFields = false;
+
+ public SalesForceExecutionFactory() {
+ // http://jira.jboss.org/jira/browse/JBEDSP-306
+ // Salesforce supports ORDER BY, but not on all column types
+ setSupportsOrderBy(false);
+ setSupportsOuterJoins(true);
+ setSupportedJoinCriteria(SupportedJoinCriteria.KEY);
+ }
+
+ public String getConnectorStateClass() {
+ return this.connectorStateClass;
+ }
+ public void setConnectorStateClass(String connectorStateClass) {
+ this.connectorStateClass = connectorStateClass;
+ }
+
+ @TranslatorProperty(display="Audit Model Fields", advanced=true)
+ public boolean isModelAuditFields() {
+ return this.auditModelFields;
+ }
+
+ public void setModelAuditFields(boolean modelAuditFields) {
+ this.auditModelFields = modelAuditFields;
+ }
+
+ @Override
+ public void start() throws TranslatorException {
+ super.start();
+ addPushDownFunction(SALESFORCE, INCLUDES, BOOLEAN, STRING, STRING);
+ addPushDownFunction(SALESFORCE, EXCLUDES, BOOLEAN, STRING, STRING);
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Salesforce ExecutionFactory Started"); //$NON-NLS-1$
+ }
+
+
+ @Override
+ public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, SalesforceConnection connection)
+ throws TranslatorException {
+ return new QueryExecutionImpl(command, connection, metadata, executionContext);
+ }
+
+ @Override
+ public UpdateExecution createUpdateExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, SalesforceConnection connection) throws TranslatorException {
+ UpdateExecution result = null;
+ if(command instanceof org.teiid.language.Delete) {
+ result = new DeleteExecutionImpl(command, connection, metadata, executionContext);
+ } else if (command instanceof org.teiid.language.Insert) {
+ result = new InsertExecutionImpl(command, connection, metadata, executionContext);
+ } else if (command instanceof org.teiid.language.Update) {
+ result = new UpdateExecutionImpl(command, connection, metadata, executionContext);
+ }
+ return result;
+
+ }
+
+ @Override
+ public ProcedureExecution createProcedureExecution(Call command,ExecutionContext executionContext, RuntimeMetadata metadata, SalesforceConnection connection)
+ throws TranslatorException {
+ return new ProcedureExecutionParentImpl(command, connection, metadata, executionContext);
+ }
+ @Override
+ public void getMetadata(MetadataFactory metadataFactory, SalesforceConnection connection) throws TranslatorException {
+ MetadataProcessor processor = new MetadataProcessor(connection,metadataFactory, this);
+ processor.processMetadata();
+ }
+
+ @Override
+ public List<String> getSupportedFunctions() {
+ return Arrays.asList(INCLUDES, EXCLUDES);
+ }
+
+ @Override
+ public boolean supportsCompareCriteriaEquals() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsInCriteria() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsLikeCriteria() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsRowLimit() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsAggregatesCountStar() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsNotCriteria() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsOrCriteria() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsCompareCriteriaOrdered() {
+ return true;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java
===================================================================
--- trunk/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,221 +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.salesforce.execution.visitors;
-
-import static org.junit.Assert.*;
-
-import java.util.Arrays;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.TimeZone;
-
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.cdk.api.TranslationUtility;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.language.Select;
-import org.teiid.metadata.Column;
-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.Column.SearchType;
-import org.teiid.query.metadata.CompositeMetadataStore;
-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;
-import org.teiid.translator.salesforce.Constants;
-import org.teiid.translator.salesforce.SalesforceConnection;
-import org.teiid.translator.salesforce.execution.QueryExecutionImpl;
-
- at SuppressWarnings("nls")
-public class TestVisitors {
-
- public static QueryMetadataInterface exampleSalesforce() {
- MetadataStore store = new MetadataStore();
- // Create models
- Schema salesforceModel = RealMetadataFactory.createPhysicalModel("SalesforceModel", store); //$NON-NLS-1$
-
- // Create Account group
- Table accountTable = RealMetadataFactory.createPhysicalGroup("Account", salesforceModel); //$NON-NLS-1$
- accountTable.setNameInSource("Account"); //$NON-NLS-1$
- accountTable.setProperty("Supports Query", Boolean.TRUE.toString()); //$NON-NLS-1$
- accountTable.setProperty(Constants.SUPPORTS_RETRIEVE, Boolean.TRUE.toString());
- // Create Account Columns
- String[] acctNames = new String[] {
- "ID", "Name", "Stuff", "Industry" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- };
- String[] acctTypes = new String[] {
- DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING
- };
-
- List<Column> acctCols = RealMetadataFactory.createElements(accountTable, acctNames, acctTypes);
- acctCols.get(2).setNativeType("multipicklist"); //$NON-NLS-1$
- acctCols.get(2).setSearchType(SearchType.Like_Only);
- // Set name in source on each column
- String[] accountNameInSource = new String[] {
- "id", "AccountName", "Stuff", "Industry" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- };
- for(int i=0; i<2; i++) {
- Column obj = acctCols.get(i);
- obj.setNameInSource(accountNameInSource[i]);
- }
-
- // Create Contact group
- Table contactTable = RealMetadataFactory.createPhysicalGroup("Contacts", salesforceModel); //$NON-NLS-1$
- contactTable.setNameInSource("Contact"); //$NON-NLS-1$
- contactTable.setProperty("Supports Query", Boolean.TRUE.toString()); //$NON-NLS-1$
- // Create Contact Columns
- String[] elemNames = new String[] {
- "ContactID", "Name", "AccountId", "InitialContact" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- };
- String[] elemTypes = new String[] {
- DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.TIMESTAMP
- };
-
- List<Column> contactCols = RealMetadataFactory.createElements(contactTable, elemNames, elemTypes);
- // Set name in source on each column
- String[] contactNameInSource = new String[] {
- "id", "ContactName", "accountid", "InitialContact" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- };
- for(int i=0; i<2; i++) {
- Column obj = contactCols.get(i);
- obj.setNameInSource(contactNameInSource[i]);
- }
-
-
- List<ProcedureParameter> params = new LinkedList<ProcedureParameter>();
- params.add(RealMetadataFactory.createParameter("type", SPParameter.IN, TypeFacility.RUNTIME_NAMES.STRING));
- 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");
- 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);
- }
-
- private static TranslationUtility translationUtility = new TranslationUtility(exampleSalesforce());
-
- @Test public void testOr() throws Exception {
- Select command = (Select)translationUtility.parseCommand("select * from Account where Name = 'foo' or Stuff = 'bar'"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (Account.AccountName = 'foo') OR (Account.Stuff = 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
- @Test public void testNot() throws Exception {
- Select command = (Select)translationUtility.parseCommand("select * from Account where not (Name = 'foo' and Stuff = 'bar')"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (Account.AccountName != 'foo') OR (Account.Stuff != 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
- @Test public void testCountStart() throws Exception {
- Select command = (Select)translationUtility.parseCommand("select count(*) from Account"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT count() FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
- @Test public void testNotLike() throws Exception {
- Select command = (Select)translationUtility.parseCommand("select * from Account where Name not like '%foo' or Stuff = 'bar'"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (NOT (Account.AccountName LIKE '%foo')) OR (Account.Stuff = 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
-
- @Test public void testIN() throws Exception {
- Select command = (Select)translationUtility.parseCommand("select * from Account where Industry IN (1,2,3)"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertFalse(visitor.hasOnlyIDCriteria());
- assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE Industry IN('1','2','3')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
-
- }
-
- @Test public void testOnlyIDsIN() throws Exception {
- // this can resolve to a better performing retrieve call
- Select command = (Select)translationUtility.parseCommand("select * from Account where ID IN (1,2,3)"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertTrue(visitor.hasOnlyIdInCriteria());
- assertEquals("Account", visitor.getTableName());
- assertEquals("Account.id, Account.AccountName, Account.Stuff, Account.Industry", visitor.getRetrieveFieldList());
- assertEquals(Arrays.asList(new String[]{"1", "2", "3"}), visitor.getIdInCriteria());
- }
-
- @Test public void testJoin() throws Exception {
- Select command = (Select)translationUtility.parseCommand("SELECT Account.Name, Contacts.Name FROM Contacts LEFT OUTER JOIN Account ON Account.Id = Contacts.AccountId"); //$NON-NLS-1$
- SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT Account.AccountName, Contact.ContactName FROM Contact", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
- @Test public void testJoin2() throws Exception {
- Select command = (Select)translationUtility.parseCommand("SELECT Account.Name, Contacts.Name FROM Account LEFT OUTER JOIN Contacts ON Account.Id = Contacts.AccountId"); //$NON-NLS-1$
- SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT Account.AccountName, (SELECT Contact.ContactName FROM Contacts) FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
- @Test public void testJoin3() throws Exception {
- Select command = (Select)translationUtility.parseCommand("SELECT Contacts.Name FROM Account LEFT OUTER JOIN Contacts ON Account.Id = Contacts.AccountId"); //$NON-NLS-1$
- SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT (SELECT Contact.ContactName FROM Contacts) FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
- @Test public void testInWithNameInSourceDifferent() throws Exception {
- Select command = (Select)translationUtility.parseCommand("SELECT Contacts.Name FROM Contacts WHERE Contacts.Name in ('x', 'y')"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT Contact.ContactName FROM Contact WHERE ContactName IN('x','y')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
- @Test public void testIDCriteria() throws Exception {
- Select command = (Select)translationUtility.parseCommand("select id, name from Account where id = 'bar'"); //$NON-NLS-1$
- SalesforceConnection sfc = Mockito.mock(SalesforceConnection.class);
- QueryExecutionImpl qei = new QueryExecutionImpl(command, sfc, translationUtility.createRuntimeMetadata(), Mockito.mock(ExecutionContext.class));
- qei.execute();
- Mockito.verify(sfc).retrieve("Account.id, Account.AccountName", "Account", Arrays.asList("bar"));
- }
-
- @Test public void testDateTimeFormating() throws Exception {
- TimeZone.setDefault(TimeZone.getTimeZone("GMT-06:00"));
- try {
- Select command = (Select)translationUtility.parseCommand("select name from contacts where initialcontact = {ts'2003-03-11 11:42:10.5'}"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT Contact.ContactName FROM Contact WHERE Contact.InitialContact = 2003-03-11T11:42:10.500-06:00", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- } finally {
- TimeZone.setDefault(null);
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java (from rev 3218, trunk/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,220 @@
+/*
+ * 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.salesforce.execution.visitors;
+
+import static org.junit.Assert.*;
+
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.TimeZone;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.cdk.api.TranslationUtility;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.language.Select;
+import org.teiid.metadata.Column;
+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.Column.SearchType;
+import org.teiid.query.metadata.CompositeMetadataStore;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.TypeFacility;
+import org.teiid.translator.salesforce.Constants;
+import org.teiid.translator.salesforce.SalesforceConnection;
+import org.teiid.translator.salesforce.execution.QueryExecutionImpl;
+
+ at SuppressWarnings("nls")
+public class TestVisitors {
+
+ public static QueryMetadataInterface exampleSalesforce() {
+ MetadataStore store = new MetadataStore();
+ // Create models
+ Schema salesforceModel = RealMetadataFactory.createPhysicalModel("SalesforceModel", store); //$NON-NLS-1$
+
+ // Create Account group
+ Table accountTable = RealMetadataFactory.createPhysicalGroup("Account", salesforceModel); //$NON-NLS-1$
+ accountTable.setNameInSource("Account"); //$NON-NLS-1$
+ accountTable.setProperty("Supports Query", Boolean.TRUE.toString()); //$NON-NLS-1$
+ accountTable.setProperty(Constants.SUPPORTS_RETRIEVE, Boolean.TRUE.toString());
+ // Create Account Columns
+ String[] acctNames = new String[] {
+ "ID", "Name", "Stuff", "Industry" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ };
+ String[] acctTypes = new String[] {
+ DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING
+ };
+
+ List<Column> acctCols = RealMetadataFactory.createElements(accountTable, acctNames, acctTypes);
+ acctCols.get(2).setNativeType("multipicklist"); //$NON-NLS-1$
+ acctCols.get(2).setSearchType(SearchType.Like_Only);
+ // Set name in source on each column
+ String[] accountNameInSource = new String[] {
+ "id", "AccountName", "Stuff", "Industry" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ };
+ for(int i=0; i<2; i++) {
+ Column obj = acctCols.get(i);
+ obj.setNameInSource(accountNameInSource[i]);
+ }
+
+ // Create Contact group
+ Table contactTable = RealMetadataFactory.createPhysicalGroup("Contacts", salesforceModel); //$NON-NLS-1$
+ contactTable.setNameInSource("Contact"); //$NON-NLS-1$
+ contactTable.setProperty("Supports Query", Boolean.TRUE.toString()); //$NON-NLS-1$
+ // Create Contact Columns
+ String[] elemNames = new String[] {
+ "ContactID", "Name", "AccountId", "InitialContact" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ };
+ String[] elemTypes = new String[] {
+ DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.TIMESTAMP
+ };
+
+ List<Column> contactCols = RealMetadataFactory.createElements(contactTable, elemNames, elemTypes);
+ // Set name in source on each column
+ String[] contactNameInSource = new String[] {
+ "id", "ContactName", "accountid", "InitialContact" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ };
+ for(int i=0; i<2; i++) {
+ Column obj = contactCols.get(i);
+ obj.setNameInSource(contactNameInSource[i]);
+ }
+
+
+ List<ProcedureParameter> params = new LinkedList<ProcedureParameter>();
+ params.add(RealMetadataFactory.createParameter("type", SPParameter.IN, TypeFacility.RUNTIME_NAMES.STRING));
+ 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.setResultSet(RealMetadataFactory.createResultSet("rs", new String[] {"updated"}, new String[] {TypeFacility.RUNTIME_NAMES.STRING}));
+
+ return new TransformationMetadata(null, new CompositeMetadataStore(store), null, RealMetadataFactory.SFM.getSystemFunctions(), null);
+ }
+
+ private static TranslationUtility translationUtility = new TranslationUtility(exampleSalesforce());
+
+ @Test public void testOr() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("select * from Account where Name = 'foo' or Stuff = 'bar'"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (Account.AccountName = 'foo') OR (Account.Stuff = 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+ @Test public void testNot() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("select * from Account where not (Name = 'foo' and Stuff = 'bar')"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (Account.AccountName != 'foo') OR (Account.Stuff != 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+ @Test public void testCountStart() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("select count(*) from Account"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT count() FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+ @Test public void testNotLike() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("select * from Account where Name not like '%foo' or Stuff = 'bar'"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (NOT (Account.AccountName LIKE '%foo')) OR (Account.Stuff = 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+
+ @Test public void testIN() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("select * from Account where Industry IN (1,2,3)"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertFalse(visitor.hasOnlyIDCriteria());
+ assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE Industry IN('1','2','3')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+
+ }
+
+ @Test public void testOnlyIDsIN() throws Exception {
+ // this can resolve to a better performing retrieve call
+ Select command = (Select)translationUtility.parseCommand("select * from Account where ID IN (1,2,3)"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertTrue(visitor.hasOnlyIdInCriteria());
+ assertEquals("Account", visitor.getTableName());
+ assertEquals("Account.id, Account.AccountName, Account.Stuff, Account.Industry", visitor.getRetrieveFieldList());
+ assertEquals(Arrays.asList(new String[]{"1", "2", "3"}), visitor.getIdInCriteria());
+ }
+
+ @Test public void testJoin() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("SELECT Account.Name, Contacts.Name FROM Contacts LEFT OUTER JOIN Account ON Account.Id = Contacts.AccountId"); //$NON-NLS-1$
+ SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT Account.AccountName, Contact.ContactName FROM Contact", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+ @Test public void testJoin2() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("SELECT Account.Name, Contacts.Name FROM Account LEFT OUTER JOIN Contacts ON Account.Id = Contacts.AccountId"); //$NON-NLS-1$
+ SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT Account.AccountName, (SELECT Contact.ContactName FROM Contacts) FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+ @Test public void testJoin3() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("SELECT Contacts.Name FROM Account LEFT OUTER JOIN Contacts ON Account.Id = Contacts.AccountId"); //$NON-NLS-1$
+ SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT (SELECT Contact.ContactName FROM Contacts) FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+ @Test public void testInWithNameInSourceDifferent() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("SELECT Contacts.Name FROM Contacts WHERE Contacts.Name in ('x', 'y')"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT Contact.ContactName FROM Contact WHERE ContactName IN('x','y')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+ @Test public void testIDCriteria() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("select id, name from Account where id = 'bar'"); //$NON-NLS-1$
+ SalesforceConnection sfc = Mockito.mock(SalesforceConnection.class);
+ QueryExecutionImpl qei = new QueryExecutionImpl(command, sfc, translationUtility.createRuntimeMetadata(), Mockito.mock(ExecutionContext.class));
+ qei.execute();
+ Mockito.verify(sfc).retrieve("Account.id, Account.AccountName", "Account", Arrays.asList("bar"));
+ }
+
+ @Test public void testDateTimeFormating() throws Exception {
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT-06:00"));
+ try {
+ Select command = (Select)translationUtility.parseCommand("select name from contacts where initialcontact = {ts'2003-03-11 11:42:10.5'}"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT Contact.ContactName FROM Contact WHERE Contact.InitialContact = 2003-03-11T11:42:10.500-06:00", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ } finally {
+ TimeZone.setDefault(null);
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ws/pom.xml
===================================================================
--- trunk/connectors/translator-ws/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ws/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,63 +0,0 @@
-<?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>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>translator-ws</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>Web service Translator</name>
- <description>This translator provides access to Web Services.</description>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- </dependencies>
-
- <build>
- <outputDirectory>target/classes</outputDirectory>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- </resource>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>false</filtering>
- <excludes>
- <exclude>**/*.xml</exclude>
- <exclude>**/*.properties</exclude>
- </excludes>
- </resource>
- </resources>
- </build>
-
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ws/pom.xml (from rev 3220, trunk/connectors/translator-ws/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ws/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/connectors/translator-ws/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,63 @@
+<?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>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>translator-ws</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>Web service Translator</name>
+ <description>This translator provides access to Web Services.</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <outputDirectory>target/classes</outputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.xml</include>
+ <include>**/*.properties</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>false</filtering>
+ <excludes>
+ <exclude>**/*.xml</exclude>
+ <exclude>**/*.properties</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ </build>
+
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/console/pom.xml
===================================================================
--- trunk/console/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/console/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,175 +0,0 @@
-<?xml version="1.0"?>
-<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-console</artifactId>
- <name>Console</name>
- <description>This project is for the RHQ plugin that supports the TEIID Console </description>
-
- <properties>
- <!--
- <org.jboss.jopr.as4.version>1.2.0.GA</org.jboss.jopr.as4.version>
- -->
- <org.jboss.jopr.as5.version>1.2.0.GA</org.jboss.jopr.as5.version>
- <jopr.jboss.as5.plugin.version>1.4.0.B01</jopr.jboss.as5.plugin.version>
- <org.rhq.version>1.3.0.GA</org.rhq.version>
- <apache.ant.version>1.7.0</apache.ant.version>
- <teiid.version>${project.version}</teiid.version>
-
-
- </properties>
-
- <dependencies>
- <!--
- Below are the core modules that are required dependencies of all
- plugins
- -->
- <dependency>
- <groupId>org.rhq</groupId>
- <artifactId>rhq-core-domain</artifactId>
- <version>${org.rhq.version}</version>
- <scope>provided</scope>
- <!--
- provided by the agent/plugin-container
- -->
- </dependency>
-
-
- <dependency>
- <groupId>org.rhq</groupId>
- <artifactId>rhq-core-plugin-api</artifactId>
- <version>${org.rhq.version}</version>
- <scope>provided</scope> <!-- provided by the agent/plugin-container -->
- </dependency>
-
- <dependency>
- <groupId>org.rhq</groupId>
- <artifactId>rhq-core-native-system</artifactId>
- <version>${org.rhq.version}</version>
- <scope>provided</scope> <!-- provided by the agent/plugin-container -->
- </dependency>
-
- <dependency>
- <groupId>org.rhq</groupId>
- <artifactId>rhq-jmx-plugin</artifactId>
- <version>${org.rhq.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.rhq</groupId>
- <artifactId>rhq-core-util</artifactId>
- <version>${org.rhq.version}</version>
- </dependency>
-
- <dependency>
- <groupId>mc4j</groupId>
- <artifactId>org-mc4j-ems</artifactId>
- <version>1.2.6</version>
- </dependency>
-
- <!--
- TODO: This is a fix for the Javac bug requiring annotations to be
- available when compiling dependent classes. It is fixed in JDK 6.
- -->
- <dependency>
- <groupId>javax.persistence</groupId>
- <artifactId>persistence-api</artifactId>
- <version>1.0</version>
- <scope>provided</scope> <!-- provided by the agent/plugin-container -->
- </dependency>
-
-
- <!--
- TODO: This is a fix for the Javac bug requiring annotations to be
- available when compiling dependent classes; it is fixed in JDK 6.
- -->
- <dependency>
- <groupId>jboss.jboss-embeddable-ejb3</groupId>
- <artifactId>hibernate-all</artifactId>
- <version>1.0.0.Alpha9</version>
- <scope>provided</scope> <!-- provided by the agent/plugin-container -->
- </dependency>
-
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.1</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- <type>test-jar</type>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <type>test-jar</type>
- </dependency>
- <dependency>
- <groupId>org.jboss.jopr</groupId>
- <artifactId>jopr-embedded-jbas5</artifactId>
- <type>war</type>
- <version>${org.jboss.jopr.as5.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.integration</groupId>
- <artifactId>jboss-profileservice-spi</artifactId>
- <version>5.1.0.CR2</version>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.on</groupId>
- <artifactId>jopr-jboss-as-5-plugin</artifactId>
- <version>${jopr.jboss.as5.plugin.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.ant</groupId>
- <artifactId>ant</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-io</artifactId>
- <version>1.3.2</version>
- </dependency>
-
-
- </dependencies>
-
-
-
- <build>
- <outputDirectory>target/classes</outputDirectory>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- <includes>
- <include>**/*.xml</include>
- <include>**/*.properties</include>
- </includes>
- </resource>
- </resources>
- </build>
-
-
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/console/pom.xml (from rev 3220, trunk/console/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/console/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/console/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,175 @@
+<?xml version="1.0"?>
+<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</version>
+ </parent>
+
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>teiid-console</artifactId>
+ <name>Console</name>
+ <description>This project is for the RHQ plugin that supports the TEIID Console </description>
+
+ <properties>
+ <!--
+ <org.jboss.jopr.as4.version>1.2.0.GA</org.jboss.jopr.as4.version>
+ -->
+ <org.jboss.jopr.as5.version>1.2.0.GA</org.jboss.jopr.as5.version>
+ <jopr.jboss.as5.plugin.version>1.4.0.B01</jopr.jboss.as5.plugin.version>
+ <org.rhq.version>1.3.0.GA</org.rhq.version>
+ <apache.ant.version>1.7.0</apache.ant.version>
+ <teiid.version>${project.version}</teiid.version>
+
+
+ </properties>
+
+ <dependencies>
+ <!--
+ Below are the core modules that are required dependencies of all
+ plugins
+ -->
+ <dependency>
+ <groupId>org.rhq</groupId>
+ <artifactId>rhq-core-domain</artifactId>
+ <version>${org.rhq.version}</version>
+ <scope>provided</scope>
+ <!--
+ provided by the agent/plugin-container
+ -->
+ </dependency>
+
+
+ <dependency>
+ <groupId>org.rhq</groupId>
+ <artifactId>rhq-core-plugin-api</artifactId>
+ <version>${org.rhq.version}</version>
+ <scope>provided</scope> <!-- provided by the agent/plugin-container -->
+ </dependency>
+
+ <dependency>
+ <groupId>org.rhq</groupId>
+ <artifactId>rhq-core-native-system</artifactId>
+ <version>${org.rhq.version}</version>
+ <scope>provided</scope> <!-- provided by the agent/plugin-container -->
+ </dependency>
+
+ <dependency>
+ <groupId>org.rhq</groupId>
+ <artifactId>rhq-jmx-plugin</artifactId>
+ <version>${org.rhq.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.rhq</groupId>
+ <artifactId>rhq-core-util</artifactId>
+ <version>${org.rhq.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>mc4j</groupId>
+ <artifactId>org-mc4j-ems</artifactId>
+ <version>1.2.6</version>
+ </dependency>
+
+ <!--
+ TODO: This is a fix for the Javac bug requiring annotations to be
+ available when compiling dependent classes. It is fixed in JDK 6.
+ -->
+ <dependency>
+ <groupId>javax.persistence</groupId>
+ <artifactId>persistence-api</artifactId>
+ <version>1.0</version>
+ <scope>provided</scope> <!-- provided by the agent/plugin-container -->
+ </dependency>
+
+
+ <!--
+ TODO: This is a fix for the Javac bug requiring annotations to be
+ available when compiling dependent classes; it is fixed in JDK 6.
+ -->
+ <dependency>
+ <groupId>jboss.jboss-embeddable-ejb3</groupId>
+ <artifactId>hibernate-all</artifactId>
+ <version>1.0.0.Alpha9</version>
+ <scope>provided</scope> <!-- provided by the agent/plugin-container -->
+ </dependency>
+
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ <version>1.1</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ <type>test-jar</type>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.jopr</groupId>
+ <artifactId>jopr-embedded-jbas5</artifactId>
+ <type>war</type>
+ <version>${org.jboss.jopr.as5.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.integration</groupId>
+ <artifactId>jboss-profileservice-spi</artifactId>
+ <version>5.1.0.CR2</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.on</groupId>
+ <artifactId>jopr-jboss-as-5-plugin</artifactId>
+ <version>${jopr.jboss.as5.plugin.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.ant</groupId>
+ <artifactId>ant</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-io</artifactId>
+ <version>1.3.2</version>
+ </dependency>
+
+
+ </dependencies>
+
+
+
+ <build>
+ <outputDirectory>target/classes</outputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.xml</include>
+ <include>**/*.properties</include>
+ </includes>
+ </resource>
+ </resources>
+ </build>
+
+
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/admin-guide/pom.xml
===================================================================
--- trunk/documentation/admin-guide/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/admin-guide/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,77 +0,0 @@
-<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/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>documentation</artifactId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>admin-guide</artifactId>
- <groupId>org.jboss.teiid.documentation</groupId>
- <packaging>jdocbook</packaging>
- <name>Admin Guide</name>
- <description>The Teiid Admin manual</description>
- <build>
- <plugins>
- <plugin>
- <groupId>org.jboss.maven.plugins</groupId>
- <artifactId>maven-jdocbook-plugin</artifactId>
- <version>2.1.2</version>
- <extensions>true</extensions>
- <dependencies>
- <dependency>
- <groupId>net.sf.docbook</groupId>
- <artifactId>docbook</artifactId>
- <version>1.74.0</version>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jbossorg-docbook-xslt</artifactId>
- <version>1.1.0</version>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jbossorg-jdocbook-style</artifactId>
- <version>1.1.0</version>
- <type>jdocbook-style</type>
- </dependency>
- </dependencies>
- <configuration>
- <sourceDocumentName>admin_guide.xml</sourceDocumentName>
- <imageResource>
- <directory>${basedir}/src/main/docbook/en-US</directory>
- <excludes>
- <exclude>*.xml</exclude>
- <exclude>**/*.xml</exclude>
- <exclude>*.zargo</exclude>
- <exclude>**/*.zargo</exclude>
- </excludes>
- </imageResource>
- <formats>
- <format>
- <formatName>pdf</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
- <finalName>teiid_admin_guide.pdf</finalName>
- </format>
- <format>
- <formatName>html_single</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
- <finalName>index.html</finalName>
- </format>
- <format>
- <formatName>html</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
- <finalName>index.html</finalName>
- </format>
- </formats>
- <options>
- <xincludeSupported>true</xincludeSupported>
- <xmlTransformerType>saxon</xmlTransformerType>
- <docbookVersion>1.72.0</docbookVersion>
- <localeSeparator>-</localeSeparator>
- <useRelativeImageUris>false</useRelativeImageUris>
- </options>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/admin-guide/pom.xml (from rev 3220, trunk/documentation/admin-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/admin-guide/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/admin-guide/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,77 @@
+<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/xsd/maven-4.0.0.xsd">
+ <parent>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>documentation</artifactId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>admin-guide</artifactId>
+ <groupId>org.jboss.teiid.documentation</groupId>
+ <packaging>jdocbook</packaging>
+ <name>Admin Guide</name>
+ <description>The Teiid Admin manual</description>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.jboss.maven.plugins</groupId>
+ <artifactId>maven-jdocbook-plugin</artifactId>
+ <version>2.1.2</version>
+ <extensions>true</extensions>
+ <dependencies>
+ <dependency>
+ <groupId>net.sf.docbook</groupId>
+ <artifactId>docbook</artifactId>
+ <version>1.74.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jbossorg-docbook-xslt</artifactId>
+ <version>1.1.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jbossorg-jdocbook-style</artifactId>
+ <version>1.1.0</version>
+ <type>jdocbook-style</type>
+ </dependency>
+ </dependencies>
+ <configuration>
+ <sourceDocumentName>admin_guide.xml</sourceDocumentName>
+ <imageResource>
+ <directory>${basedir}/src/main/docbook/en-US</directory>
+ <excludes>
+ <exclude>*.xml</exclude>
+ <exclude>**/*.xml</exclude>
+ <exclude>*.zargo</exclude>
+ <exclude>**/*.zargo</exclude>
+ </excludes>
+ </imageResource>
+ <formats>
+ <format>
+ <formatName>pdf</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
+ <finalName>teiid_admin_guide.pdf</finalName>
+ </format>
+ <format>
+ <formatName>html_single</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ <format>
+ <formatName>html</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ </formats>
+ <options>
+ <xincludeSupported>true</xincludeSupported>
+ <xmlTransformerType>saxon</xmlTransformerType>
+ <docbookVersion>1.72.0</docbookVersion>
+ <localeSeparator>-</localeSeparator>
+ <useRelativeImageUris>false</useRelativeImageUris>
+ </options>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/caching-guide/pom.xml
===================================================================
--- trunk/documentation/caching-guide/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/caching-guide/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,77 +0,0 @@
-<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/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>documentation</artifactId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>caching-guide</artifactId>
- <groupId>org.jboss.teiid.documentation</groupId>
- <packaging>jdocbook</packaging>
- <name>Teiid Caching Guide</name>
- <description>The Teiid Caching Guide</description>
- <build>
- <plugins>
- <plugin>
- <groupId>org.jboss.maven.plugins</groupId>
- <artifactId>maven-jdocbook-plugin</artifactId>
- <version>2.1.2</version>
- <extensions>true</extensions>
- <dependencies>
- <dependency>
- <groupId>net.sf.docbook</groupId>
- <artifactId>docbook</artifactId>
- <version>1.74.0</version>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jbossorg-docbook-xslt</artifactId>
- <version>1.1.0</version>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jbossorg-jdocbook-style</artifactId>
- <version>1.1.0</version>
- <type>jdocbook-style</type>
- </dependency>
- </dependencies>
- <configuration>
- <sourceDocumentName>main.xml</sourceDocumentName>
- <imageResource>
- <directory>${basedir}/src/main/docbook/en-US</directory>
- <excludes>
- <exclude>*.xml</exclude>
- <exclude>**/*.xml</exclude>
- <exclude>*.zargo</exclude>
- <exclude>**/*.zargo</exclude>
- </excludes>
- </imageResource>
- <formats>
- <format>
- <formatName>pdf</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
- <finalName>teiid_caching_guide.pdf</finalName>
- </format>
- <format>
- <formatName>html_single</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
- <finalName>index.html</finalName>
- </format>
- <format>
- <formatName>html</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
- <finalName>index.html</finalName>
- </format>
- </formats>
- <options>
- <xincludeSupported>true</xincludeSupported>
- <xmlTransformerType>saxon</xmlTransformerType>
- <docbookVersion>1.72.0</docbookVersion>
- <localeSeparator>-</localeSeparator>
- <useRelativeImageUris>false</useRelativeImageUris>
- </options>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/caching-guide/pom.xml (from rev 3220, trunk/documentation/caching-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/caching-guide/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/caching-guide/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,77 @@
+<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/xsd/maven-4.0.0.xsd">
+ <parent>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>documentation</artifactId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>caching-guide</artifactId>
+ <groupId>org.jboss.teiid.documentation</groupId>
+ <packaging>jdocbook</packaging>
+ <name>Teiid Caching Guide</name>
+ <description>The Teiid Caching Guide</description>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.jboss.maven.plugins</groupId>
+ <artifactId>maven-jdocbook-plugin</artifactId>
+ <version>2.1.2</version>
+ <extensions>true</extensions>
+ <dependencies>
+ <dependency>
+ <groupId>net.sf.docbook</groupId>
+ <artifactId>docbook</artifactId>
+ <version>1.74.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jbossorg-docbook-xslt</artifactId>
+ <version>1.1.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jbossorg-jdocbook-style</artifactId>
+ <version>1.1.0</version>
+ <type>jdocbook-style</type>
+ </dependency>
+ </dependencies>
+ <configuration>
+ <sourceDocumentName>main.xml</sourceDocumentName>
+ <imageResource>
+ <directory>${basedir}/src/main/docbook/en-US</directory>
+ <excludes>
+ <exclude>*.xml</exclude>
+ <exclude>**/*.xml</exclude>
+ <exclude>*.zargo</exclude>
+ <exclude>**/*.zargo</exclude>
+ </excludes>
+ </imageResource>
+ <formats>
+ <format>
+ <formatName>pdf</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
+ <finalName>teiid_caching_guide.pdf</finalName>
+ </format>
+ <format>
+ <formatName>html_single</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ <format>
+ <formatName>html</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ </formats>
+ <options>
+ <xincludeSupported>true</xincludeSupported>
+ <xmlTransformerType>saxon</xmlTransformerType>
+ <docbookVersion>1.72.0</docbookVersion>
+ <localeSeparator>-</localeSeparator>
+ <useRelativeImageUris>false</useRelativeImageUris>
+ </options>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/pom.xml
===================================================================
--- trunk/documentation/client-developers-guide/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,77 +0,0 @@
-<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/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>documentation</artifactId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>client-developers-guide</artifactId>
- <groupId>org.jboss.teiid.documentation</groupId>
- <packaging>jdocbook</packaging>
- <name>Teiid Client Developers Guide</name>
- <description>The Client Developers Guide</description>
- <build>
- <plugins>
- <plugin>
- <groupId>org.jboss.maven.plugins</groupId>
- <artifactId>maven-jdocbook-plugin</artifactId>
- <version>2.1.2</version>
- <extensions>true</extensions>
- <dependencies>
- <dependency>
- <groupId>net.sf.docbook</groupId>
- <artifactId>docbook</artifactId>
- <version>1.74.0</version>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jbossorg-docbook-xslt</artifactId>
- <version>1.1.0</version>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jbossorg-jdocbook-style</artifactId>
- <version>1.1.0</version>
- <type>jdocbook-style</type>
- </dependency>
- </dependencies>
- <configuration>
- <sourceDocumentName>main.xml</sourceDocumentName>
- <imageResource>
- <directory>${basedir}/src/main/docbook/en-US</directory>
- <excludes>
- <exclude>*.xml</exclude>
- <exclude>**/*.xml</exclude>
- <exclude>*.zargo</exclude>
- <exclude>**/*.zargo</exclude>
- </excludes>
- </imageResource>
- <formats>
- <format>
- <formatName>pdf</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
- <finalName>teiid_client_developers_guide.pdf</finalName>
- </format>
- <format>
- <formatName>html_single</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
- <finalName>index.html</finalName>
- </format>
- <format>
- <formatName>html</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
- <finalName>index.html</finalName>
- </format>
- </formats>
- <options>
- <xincludeSupported>true</xincludeSupported>
- <xmlTransformerType>saxon</xmlTransformerType>
- <docbookVersion>1.72.0</docbookVersion>
- <localeSeparator>-</localeSeparator>
- <useRelativeImageUris>false</useRelativeImageUris>
- </options>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/pom.xml (from rev 3220, trunk/documentation/client-developers-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,77 @@
+<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/xsd/maven-4.0.0.xsd">
+ <parent>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>documentation</artifactId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>client-developers-guide</artifactId>
+ <groupId>org.jboss.teiid.documentation</groupId>
+ <packaging>jdocbook</packaging>
+ <name>Teiid Client Developers Guide</name>
+ <description>The Client Developers Guide</description>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.jboss.maven.plugins</groupId>
+ <artifactId>maven-jdocbook-plugin</artifactId>
+ <version>2.1.2</version>
+ <extensions>true</extensions>
+ <dependencies>
+ <dependency>
+ <groupId>net.sf.docbook</groupId>
+ <artifactId>docbook</artifactId>
+ <version>1.74.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jbossorg-docbook-xslt</artifactId>
+ <version>1.1.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jbossorg-jdocbook-style</artifactId>
+ <version>1.1.0</version>
+ <type>jdocbook-style</type>
+ </dependency>
+ </dependencies>
+ <configuration>
+ <sourceDocumentName>main.xml</sourceDocumentName>
+ <imageResource>
+ <directory>${basedir}/src/main/docbook/en-US</directory>
+ <excludes>
+ <exclude>*.xml</exclude>
+ <exclude>**/*.xml</exclude>
+ <exclude>*.zargo</exclude>
+ <exclude>**/*.zargo</exclude>
+ </excludes>
+ </imageResource>
+ <formats>
+ <format>
+ <formatName>pdf</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
+ <finalName>teiid_client_developers_guide.pdf</finalName>
+ </format>
+ <format>
+ <formatName>html_single</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ <format>
+ <formatName>html</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ </formats>
+ <options>
+ <xincludeSupported>true</xincludeSupported>
+ <xmlTransformerType>saxon</xmlTransformerType>
+ <docbookVersion>1.72.0</docbookVersion>
+ <localeSeparator>-</localeSeparator>
+ <useRelativeImageUris>false</useRelativeImageUris>
+ </options>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-connection.xml
===================================================================
--- trunk/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-connection.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-connection.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,550 +0,0 @@
-<?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" [
-<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
-%CustomDTD;
-]>
-<chapter id="teiid_connection">
- <title>Connecting to Teiid Server</title>
-
- <para>The Teiid JDBC API provides Java Database Connectivity (JDBC) access to any Virtual Database (VDB) deployed on a Teiid Server.
- The Teiid JDBC API is compatible with the JDBC 4.0 specification; however, it does not fully support all <link linkend="unsupported_jdbc">methods</link>.
- Advanced features, such as updatable result sets or SQL3 data types, are not supported. </para>
-
- <para>Java client applications connecting to a Teiid Server will need to use Java 1.6 JDK. Previous versions of Java are not supported.</para>
-
- <para>Before you can connect to the Teiid Server using the Teiid JDBC API, please do following tasks first.</para>
- <orderedlist>
- <listitem> <para>Install the Teiid Server. See the "Admin Guide" for instructions. </para> </listitem>
- <listitem> <para>Build a Virtual Database (VDB). You can either build a "Dynamic VDB" (Designer not required),
- or you can use the Eclipse based GUI tool <ulink url="http://www.jboss.org/teiiddesigner.html">Designer</ulink>.
- Check the "Reference Guide" for instructions on how to build a VDB. If you do not know what VDB is, then start with this
- <ulink url="http://www.jboss.org/teiid/basics/virtualdatabases.html">document</ulink>.</para> </listitem>
- <listitem> <para>Deploy the VDB into Teiid Server. Check "Admin Guide" for instructions. </para> </listitem>
- <listitem> <para>Start the Teiid Server (JBoss AS), if it is not already running.</para> </listitem>
- </orderedlist>
-
- <para>Now that you have the VDB deployed in the Teiid Server, client applications
- can connect to the Teiid Server and issue SQL queries against deployed VDB using Teiid's JDBC API. If you are new to JDBC, see Java's documentation about
- <ulink url="http://java.sun.com/docs/books/tutorial/jdbc/index.html">JDBC</ulink>. Teiid ships with
- <code>teiid-&versionNumber;-client.jar</code> in the <code>"jboss-install/server/<profile>/lib"</code> directory.
-
- <itemizedlist>
- <para>Main classes in the client JAR:</para>
- <listitem> <para><code>org.teiid.jdbc.TeiidDriver</code> - allows JDBC connections using the
- <ulink url="http://java.sun.com/javase/6/docs/api/java/sql/DriverManager.html">DriverManager</ulink> class.</para> </listitem>
- <listitem> <para><code>org.teiid.jdbc.TeiidDatasource</code> - allows JDBC connections using the
- <ulink url="http://java.sun.com/javase/6/docs/api/javax/sql/DataSource.html">DataSource</ulink> or <ulink url="http://java.sun.com/javase/6/docs/api/javax/sql/XADataSource.html">XADataSource</ulink> class. You should use this class to create managed or XA connections.</para> </listitem>
- </itemizedlist>
- </para>
-
- <para>Once you have established a connection with the Teiid Server, you can use standard JDBC API classes to interrogate metadata and execute queries.</para>
-
- <section id="driver_connection">
- <title>Driver Connection</title>
- <para>Use <code>org.teiid.jdbc.TeiidDriver</code> as the driver class.</para>
-
- <para>Use the following URL format for JDBC connections:<synopsis>jdbc:teiid:<vdb-name>@mm[s]://<host>:<port>;[prop-name=prop-value;]*</synopsis></para>
-
- <para>URL Components</para>
- <orderedlist>
- <listitem><para><vdb-name> - Name of the VDB you are connecting to. Optionally VDB
- name can also contain version information inside it. For example: "myvdb.2", this is equivalent to supplying the
- "version=2" connection property defined below. However, use of vdb name in this format and
- the "version" property at the same time is not allowed.
- </para></listitem>
- <listitem><para>mm - defines Teiid JDBC protocol, mms defines a secure channel (see the <link linkend="ssl">SSL chapter</link> for more)</para></listitem>
- <listitem><para><host> - defines the server where the Teiid Server is installed. If you are using IPv6 binding address as the host name, place it in square brackets. ex:[::1]</para></listitem>
- <listitem><para><port> - defines the port on which the Teiid Server is listening for incoming JDBC connections.</para></listitem>
- <listitem><para>[prop-name=prop-value] - additionally you can supply any number of name value pairs separated by semi-colon
- [;]. All supported URL properties are defined in the <link linkend="connection_properties">connection properties section</link>. Property values should be URL encoded if they contain reserved characters, e.g. ('?', '=', ';', etc.)</para></listitem>
- </orderedlist>
-
- <section id="connection_properties">
- <title>URL Connection Properties</title>
- <para>The following table shows all the supported connection properties that can used with Teiid
- JDBC Driver URL connection string, or on the Teiid JDBC Data Source class.</para>
-
- <table frame='all'>
- <title>Connection Properties</title>
- <tgroup cols='3' align='left' colsep='1' rowsep='1'>
- <colspec colname='c1' colwidth=".75*" />
- <colspec colname='c2' colwidth=".5*" />
- <colspec colname='c3' colwidth="2*" />
- <thead>
- <row>
- <entry>Property Name</entry>
- <entry>Type</entry>
- <entry>Description</entry>
- </row>
- </thead>
- <tbody>
- <row>
- <entry>
- <code>ApplicationName</code>
- </entry>
- <entry>
- <code>String</code>
- </entry>
- <entry>Name of the client application; allows the administrator to identify the connections</entry>
- </row>
- <row>
- <entry>
- <code>FetchSize</code>
- </entry>
- <entry>
- <code>int</code>
- </entry>
- <entry>Size of the resultset; The default size if 500. <=0 indicates that the default should be used.</entry>
- </row>
- <row>
- <entry>
- <code>partialResultsMode</code>
- </entry>
- <entry>
- <code>boolean</code>
- </entry>
- <entry>Enable/disable support partial results mode. Default false. See the <link linkend="partial_results">partial results</link> section.</entry>
- </row>
- <row id="auto_commit_txn">
- <entry>
- <code>autoCommitTxn</code>
- </entry>
- <entry>
- <code>String</code>
- </entry>
- <entry>Only applies only when "autoCommit" is set to "true".
-
- This determines how a executed command needs to be transactionally wrapped inside the
- Teiid engine to maintain the data integrity.
- <itemizedlist>
- <listitem><para>ON - Always wrap command in distributed transaction</para></listitem>
- <listitem><para>OFF - Never wrap command in distributed transaction</para></listitem>
- <listitem><para>DETECT (default)- If the executed command is spanning more than one source it automatically uses distributed transaction.</para></listitem>
- </itemizedlist>
- <link linkend="jdbc_transactions">Transactions with JDBC</link> for more information.
- </entry>
- </row>
- <row>
- <entry>
- <code>disableLocalTxn</code>
- </entry>
- <entry>
- <code>boolean</code>
- </entry>
- <entry>If "true", the autoCommit setting, commit and rollback will be ignored for local transactions. Default false.</entry>
- </row>
- <row>
- <entry>
- <code>user</code>
- </entry>
- <entry>
- <code>String</code>
- </entry>
- <entry>User name</entry>
- </row>
- <row>
- <entry>
- <code>Password</code>
- </entry>
- <entry>
- <code>String</code>
- </entry>
- <entry>Credential for user</entry>
- </row>
- <row>
- <entry>
- <code>ansiQuotedIdentifiers</code>
- </entry>
- <entry>
- <code>boolean</code>
- </entry>
- <entry>Sets the parsing behavior for double quoted entries in SQL. The default, true, parses dobuled
- quoted entries as identifiers. If set to false, then double quoted values that
- are valid string literals will be parsed as string literals.</entry>
- </row>
- <row>
- <entry>
- <code>version</code>
- </entry>
- <entry>
- <code>integer</code>
- </entry>
- <entry>Version number of the VDB</entry>
- </row>
- <row>
- <entry>
- <code>resultSetCacheMode</code>
- </entry>
- <entry>
- <code>boolean</code>
- </entry>
- <entry>ResultSet caching is turned on/off. Default false.</entry>
- </row>
-
- <row>
- <entry>
- <code>autoFailover</code>
- </entry>
- <entry>
- <code>boolean</code>
- </entry>
- <entry>If true, will automatically select a new server instance after a communication exception. Default false.
- This is typically not needed when connections are managed, as the connection can be purged from the pool.</entry>
- </row>
-
- <row>
- <entry>
- <code>SHOWPLAN</code>
- </entry>
- <entry>
- <code>String</code>
- </entry>
- <entry>(typically not set as a connection property) Can be ON|OFF|DEBUG; ON returns the query plan along with the results and DEBUG additionally prints the query planner debug information in the log and returns it with the results. Both the plan and the log are available through JDBC API extensions. Default OFF.</entry>
- </row>
-
- <row>
- <entry>
- <code>NoExec</code>
- </entry>
- <entry>
- <code>String</code>
- </entry>
- <entry>(typically not set as a connection property) Can be ON|OFF; ON prevents query execution, but parsing and planning will still occur. Default OFF.</entry>
- </row>
- <row id="PassthroughAuthentication">
- <entry>
- <code>PassthroughAuthentication</code>
- </entry>
- <entry>
- <code>boolean</code>
- </entry>
- <entry>Only applies to "local" connections. When this option is set to "true", then Teiid looks for
- already authenticated security context on the calling thread. If one found it uses that users credentials
- 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>
- <entry>
- <code>QueryTimeout</code>
- </entry>
- <entry>
- <code>integer</code>
- </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>
- </tbody>
- </tgroup>
- </table>
- </section>
-
- </section>
-
- <section id="datasource_connection">
- <title>Datasource Connection</title>
- <para>To use a data source based connection, use <code>org.teiid.jdbc.TeiidDataSource</code> as the data source class.
- The <code>TeiidDataSource</code> is also an XADatasource. Teiid DataSource class is also Serializable, so it possible for it to be used with
- JNDI naming services.</para>
-
- <note><para>Teiid supports the XA protocol, XA transactions will be extended to Teiid sources that also support XA.</para></note>
-
- <para>All the properties (except for version, which is known on TeiidDataSource as DatabaseVersion) defined in the <link linkend="connection_properties">connection properties</link>have corresponding "set" methods on the <code>org.teiid.jdbc.TeiidDataSource</code>.
- Properties that are assumed from the URL string have addtional "set" methods, which are described in the following table.</para>
-
- <table id="ds_methods" frame='all'>
- <title>Datasource Properties</title>
- <tgroup cols='3' align='left' colsep='1' rowsep='1'>
- <colspec colname='c1' colwidth="1.25*" />
- <colspec colname='c2' colwidth=".7*" />
- <colspec colname='c3' colwidth="2*" />
- <thead>
- <row>
- <entry>Property Name</entry>
- <entry>Type</entry>
- <entry>Description</entry>
- </row>
- </thead>
- <tbody>
- <row>
- <entry>
- <code>DatabaseName</code>
- </entry>
- <entry>
- <code>String</code>
- </entry>
- <entry>The name of a virtual database (VDB) deployed to Teiid. Optionally Database
- name can also contain "DatabaseVersion" information inside it. For example: "myvdb.2", this is equivalent to supplying the
- "DatabaseVersion" property set to value of 2. However, use of Database name in this format and use of
- DatabaseVersion property at the same time is not allowed.</entry>
- </row>
- <row>
- <entry>
- <code>ServerName</code>
- </entry>
- <entry>
- <code>String</code>
- </entry>
- <entry>Server hostname where the Teiid runtime installed. If you are using IPv6 binding address as the host name,
- place it in square brackets. ex:[::1]</entry>
- </row>
- <row>
- <entry>
- <code>AlternateServers</code>
- </entry>
- <entry>
- <code>String</code>
- </entry>
- <entry>Optional delimited list of host:port entries. See the <link linkend="multiple_hosts">multiple hosts</link>
- section for more information. If you are using IPv6 binding address as the host name,
- place them in square brackets. ex:[::1]</entry>
- </row>
- <row>
- <entry>
- <code>AdditionalProperties</code>
- </entry>
- <entry>
- <code>String</code>
- </entry>
- <entry>Optional setting of properties that has the same format as the property string in a connection URL.</entry>
- </row>
- <row>
- <entry>
- <code>PortNumber</code>
- </entry>
- <entry>
- <code>integer</code>
- </entry>
- <entry>Port number on which the Server process is listening on.</entry>
- </row>
- <row>
- <entry>
- <code>secure</code>
- </entry>
- <entry>
- <code>boolean</code>
- </entry>
- <entry>Secure connection. Flag to indicate to use SSL (mms) based connection between client and server</entry>
- </row>
- <row>
- <entry>
- <code>DatabaseVersion</code>
- </entry>
- <entry>
- <code>integer</code>
- </entry>
- <entry>VDB version</entry>
- </row>
- <row>
- <entry>
- <code>DataSourceName</code>
- </entry>
- <entry>
- <code>String</code>
- </entry>
- <entry>Name given to this data source</entry>
- </row>
-
- </tbody>
- </tgroup>
- </table>
- </section>
-
- <section>
- <title>Standalone Application</title>
- <para>To use either Driver or DataSource based connections, add the client JAR to your Java client application's classpath. See the simple client example in the kit for a full Java sample of the following.</para>
-
- <section id="sa_driver_connection">
- <title>Driver Connection</title>
-
- <para>Sample Code:</para>
- <programlisting><![CDATA[public class TeiidClient {
- public Connection getConnection(String user, String password) throws Exception {
- String url = "jdbc:teiid:myVDB at mm://localhost:31000;ApplicationName=myApp";
- return DriverManager.getConnection(url, user, password);
- }
-}]]></programlisting>
-
- </section>
-
- <section id="sa_datasource_connection">
- <title>Datasource Connection</title>
-
- <para>Sample Code:</para>
- <programlisting><![CDATA[public class TeiidClient {
- public Connection getConnection(String user, String password) throws Exception {
- TeiidDataSource ds = new TeiidDataSource();
- ds.setUser(user);
- ds.setPassword(password);
- ds.setServerName("localhost");
- ds.setPortNumber(31000);
- ds.setDatabaseName("myVDB");
- return ds.getConnection();
- }
-}]]></programlisting>
-
- </section>
-
- </section>
-
- <section id="ds_in_jbossas">
- <title>JBoss AS Data Source</title>
- <para>Teiid can be configured as a JDBC data source in the JBoss Application Server to be accessed
- from JNDI or injected into your JEE applications. Deploying Teiid as data source in JBoss AS is exactly same as
- deploying any other RDBMS resources like Oracle or DB2.</para>
-
- <para>Defining as data source is not limited to
- JBoss AS, you can also deploy as data source in Glassfish, Tomcat, Websphere, Weblogic etc servers, however their
- configuration files are different than JBoss AS. Consult the respective documentation of the environment
- in which you are deploying.</para>
-
- <para>A special case is if the Teiid instance you are connecting to is in the same VM as the JBoss AS instance. If that matches you deployment, then follow the <xref linkend="local_connection"/> instructions</para>
-
- <orderedlist numeration="arabic">
- <para>Installation Steps</para>
- <listitem><para>If Teiid is not installed in the AS instance, copy the <code>teiid-&versionNumber;-client.jar</code> into
- <code><jboss-install>/server/<profile>/lib</code> directory.</para></listitem>
- <listitem><para>Create a "<datasource name>-ds.xml" file in <code><jboss-install>/server/<profile>/deploy</code>
- directory. Based on the type of deployment (XA, driver, or local), the contents of the file will be different. See the following sections for more.</para></listitem>
- </orderedlist>
-
- <para>The data source will then be accessable through the JNDI name specified in the -ds.xml file.</para>
-
- <section id="as_xa_connection">
- <title>DataSource Connection</title>
- <para>Make sure you know the correct DatabaseName, ServerName, Port number and credentials that are specific
- to your deployment environment. </para>
- <example>
- <title>Sample XADataSource in the JBoss AS using the
- Teiid DataSource class <code>org.teiid.jdbc.TeiidDataSource</code></title>
-
- <programlisting><![CDATA[<datasources>
- <xa-datasource>
- <jndi-name>TEIID-DS</jndi-name>
- <xa-datasource-class>org.teiid.jdbc.TeiidDataSource</xa-datasource-class>
- <xa-datasource-property name="DatabaseName">myVDB</xa-datasource-property>
- <xa-datasource-property name="serverName">localhost</xa-datasource-property>
- <xa-datasource-property name="portNumber">31000</xa-datasource-property>
- <xa-datasource-property name="user">admin</xa-datasource-property>
- <xa-datasource-property name="password">password</xa-datasource-property>
-
- <!-- pool and other JBoss datasource properties -->
- <check-valid-connection-sql>SELECT 1</check-valid-connection-sql>
- <min-pool-size>5</min-pool-size>
- <max-pool-size>10</max-pool-size>
- </xa-datasource>
-</datasources>]]></programlisting> </example>
- </section>
- <section id="as_driver_connection">
- <title>Driver based connection</title>
- <para>You can also use Teiid's JDBC driver class <code>org.teiid.jdbc.TeiidDriver</code> to create a data source</para>
- <programlisting><![CDATA[<datasources>
- <local-tx-datasource>
- <jndi-name>TEIID-DS</jndi-name>
- <connection-url>jdbc:teiid:myVDB at mm://localhost:31000</connection-url>
- <driver-class>org.teiid.jdbc.TeiidDriver</driver-class>
- <user-name>admin</user-name>
- <password>teiid</password>
-
- <!-- pool and other JBoss datasource properties -->
- <check-valid-connection-sql>SELECT 1</check-valid-connection-sql>
- <min-pool-size>5</min-pool-size>
- <max-pool-size>10</max-pool-size>
- </local-tx-datasource>
-</datasources>]]></programlisting>
- </section>
- <section id="local_connection">
- <title>Local JDBC Connection</title>
- <para>If you are deploying your client application on the same JBoss AS instance as the Teiid runtime is installed, then
- 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>
- <example>
- <title>Local data source</title>
- <programlisting><![CDATA[<datasources>
- <xa-datasource>
- <jndi-name>TEIID-DS</jndi-name>
- <xa-datasource-class>org.teiid.jdbc.TeiidDataSource</xa-datasource-class>
- <xa-datasource-property name="DatabaseName">myVDB</xa-datasource-property>
- <xa-datasource-property name="user">admin</xa-datasource-property>
- <xa-datasource-property name="password">password</xa-datasource-property>
-
- <!-- pool and other JBoss datasource properties -->
- <max-pool-size>10</max-pool-size>
- </xa-datasource>
-</datasources>]]></programlisting>
-</example>
- <para>This is essentially the same as the XA configuration, but "ServerName" and "PortNumber" are not specified. Local connections have additional features such as using <xref linkend="PassthroughAuthentication"/> </para>
- </section>
-
- </section>
-
- <section id="multiple_hosts">
- <title>Using Multiple Hosts</title>
- <para>A group of Teiid Servers in the same JBoss AS cluster may be connected using failover and load-balancing features.
- To enable theses features in their simplest form, the client needs to specify multiple host name and port number combinations on the URL connection string.
- <example><title>Example URL connection string</title><programlisting><![CDATA[jdbc:teiid:<vdb-name>@mm://host1:31000,host1:31001,host2:31000;version=2]]></programlisting></example>
- </para>
- <para>If you are using a DataSource to connect to Teiid Server, use the "AlternateServers" property/method to define the failover servers. The format is also a comma separated list of host:port combinations.</para>
- <para>The client will randomly pick one the Teiid server from the list and establish a session with that server.
- If that server cannot be contacted, then a connection will be attempted to each of the remaining servers in random order.
- This allows for both connection time fail-over and random server selection load balancing.
- </para>
- <section id="failover">
- <title>Fail Over</title>
- <para>Post connection fail over will be used, if you're using an admin connection (such as what is used by AdminShell) or if the <emphasis>autoFailover</emphasis> connection property on JDBC URL is set to true.
- Post connection failover works by sending a ping, at most every second, to test the connection prior to use. If the ping fails, a new instance will be selected prior to the operation being attempted.
- This is not true "transparent application failover" as the client will not restart the transaction/query/recreate session scoped temp tables, etc. So this feature should be used with caution by non-admin connections.</para>
- </section>
- <section id="loadbalancing">
- <title>Load Balancing</title>
- <para>Post connection load balancing can be utilized in one of two ways. First if you are using <code>TeiidDataSource</code> and the Connections returned by
- Teiid <code>PooledConnections</code> have their <code>close</code> method called, then a new server instance will be selected automatically.
- However when using driver based connections or even when using <code>TeiidDataSource</code> in a connection pool (such as JBoss AS), the automatic load balancing will not happen.
- Second you can explicitly trigger load balancing through the use of the set statement: <programlisting>SET NEWINSTANCE TRUE</programlisting>
- Typically you will not need want to issue this statement manually, but instead use it as the connection test query on your DataSource configuration.
- <example>
- <title>JBoss AS DataSource With Post Connection Load Balancing</title>
- <programlisting><![CDATA[<datasources>
- <local-tx-datasource>
- <jndi-name>TEIID-DS</jndi-name>
- <connection-url>jdbc:teiid:myVDB at mm://localhost:31000,mm://localhost:32000</connection-url>
- <driver-class>org.teiid.jdbc.TeiidDriver</driver-class>
- <user-name>admin</user-name>
- <password>teiid</password>
-
- <!-- pool and other JBoss datasource properties -->
- <check-valid-connection-sql>SET NEWINSTANCE TRUE</check-valid-connection-sql>
- <min-pool-size>5</min-pool-size>
- <max-pool-size>10</max-pool-size>
- </local-tx-datasource>
-</datasources>]]></programlisting>
-</example>
- </para>
- <para>Teiid by default maintians a pool of extra socket connections that are reused. For load balancing, this reduces the potential cost of switching a connection to another server instance.
- The default setting is to maintain 16 connections (see <code>org.teiid.sockets.maxCachedInstances</code> in the client jar's teiid-client-settings.properties file.
- If you're client is connecting to large numbers of Teiid instances and you're using post connection time load balancing, then consider increasing the number of cached instances.
- You may either set an analogous system property or create another version of teiid-client-settings.properties file and place it into the classpath ahead of the client jar.</para>
- <note><para>Session level temporary tables, currently running transactions, session level cache entries, and PreparedPlans for a given session will not be available on other cluster members.
- Therefore, it is recommended that post connection time load balancing is only used when the logical connection could have been closed, but the actual connection is reused (the typical connection pool pattern).</para></note>
- </section>
- <section id="advancedconfig">
- <title>Advanced Configuration</title>
- <para>Server discovery, load balancing, fail over, retry, retry delay, etc. may be customize if the default policy is not sufficient.
- See the <code>org.teiid.net.socket.ServerDiscovery</code> interface and default implementaion <code>org.teiid.net.socket.UrlServerDiscovery</code> for how to start with your customization.
- The <code>UrlServerDiscovery</code> implemenation provides the following: discovery of servers from the URL hosts (DataSource server/alternativeServers), random selection for load balancing and failover, 1 connection attempt per host, no biasing, black listing, or other advanced features.
- Typically you'll want to extend the <code>UrlServerDiscovery</code> so that it can be used as the fallback strategy and to only implement the necessary changed methods.
- It's important to consider that 1 <code>ServerDiscovery</code> instance will be created for each connection. Any sharing of information between instances should be done through static state or some other shared lookup.
- </para>
- <para>Your customized server discovery class will then need to be referenced by the discoveryStategy connection/DataSource property by its full class name.</para>
- <para>You may also choose to use an external tcp load balancer, such as <ulink url="http://haproxy.1wt.eu/">haproxy</ulink>.
- The Teiid driver/DataSource should then typically be configured to just use the single host/port of your load balancer.</para>
- </section>
- </section>
- <section>
- <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.
- Existing statements/result sets are still available for use under the old identity. See the JBossAS issue <ulink url="https://issues.jboss.org/browse/JBAS-1429">JBAS-1429</ulink> for more on using reauthentication support with JCA.</para>
- </section>
-</chapter>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-connection.xml (from rev 3218, trunk/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-connection.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-connection.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-connection.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,560 @@
+<?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" [
+<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
+%CustomDTD;
+]>
+<chapter id="teiid_connection">
+ <title>Connecting to Teiid Server</title>
+
+ <para>The Teiid JDBC API provides Java Database Connectivity (JDBC) access to any Virtual Database (VDB) deployed on a Teiid Server.
+ The Teiid JDBC API is compatible with the JDBC 4.0 specification; however, it does not fully support all <link linkend="unsupported_jdbc">methods</link>.
+ Advanced features, such as updatable result sets or SQL3 data types, are not supported. </para>
+
+ <para>Java client applications connecting to a Teiid Server will need to use Java 1.6 JDK. Previous versions of Java are not supported.</para>
+
+ <para>Before you can connect to the Teiid Server using the Teiid JDBC API, please do following tasks first.</para>
+ <orderedlist>
+ <listitem> <para>Install the Teiid Server. See the "Admin Guide" for instructions. </para> </listitem>
+ <listitem> <para>Build a Virtual Database (VDB). You can either build a "Dynamic VDB" (Designer not required),
+ or you can use the Eclipse based GUI tool <ulink url="http://www.jboss.org/teiiddesigner.html">Designer</ulink>.
+ Check the "Reference Guide" for instructions on how to build a VDB. If you do not know what VDB is, then start with this
+ <ulink url="http://www.jboss.org/teiid/basics/virtualdatabases.html">document</ulink>.</para> </listitem>
+ <listitem> <para>Deploy the VDB into Teiid Server. Check "Admin Guide" for instructions. </para> </listitem>
+ <listitem> <para>Start the Teiid Server (JBoss AS), if it is not already running.</para> </listitem>
+ </orderedlist>
+
+ <para>Now that you have the VDB deployed in the Teiid Server, client applications
+ can connect to the Teiid Server and issue SQL queries against deployed VDB using Teiid's JDBC API. If you are new to JDBC, see Java's documentation about
+ <ulink url="http://java.sun.com/docs/books/tutorial/jdbc/index.html">JDBC</ulink>. Teiid ships with
+ <code>teiid-&versionNumber;-client.jar</code> in the <code>"jboss-install/server/<profile>/lib"</code> directory.
+
+ <itemizedlist>
+ <para>Main classes in the client JAR:</para>
+ <listitem> <para><code>org.teiid.jdbc.TeiidDriver</code> - allows JDBC connections using the
+ <ulink url="http://java.sun.com/javase/6/docs/api/java/sql/DriverManager.html">DriverManager</ulink> class.</para> </listitem>
+ <listitem> <para><code>org.teiid.jdbc.TeiidDatasource</code> - allows JDBC connections using the
+ <ulink url="http://java.sun.com/javase/6/docs/api/javax/sql/DataSource.html">DataSource</ulink> or <ulink url="http://java.sun.com/javase/6/docs/api/javax/sql/XADataSource.html">XADataSource</ulink> class. You should use this class to create managed or XA connections.</para> </listitem>
+ </itemizedlist>
+ </para>
+
+ <para>Once you have established a connection with the Teiid Server, you can use standard JDBC API classes to interrogate metadata and execute queries.</para>
+
+ <section id="driver_connection">
+ <title>Driver Connection</title>
+ <para>Use <code>org.teiid.jdbc.TeiidDriver</code> as the driver class.</para>
+
+ <para>Use the following URL format for JDBC connections:<synopsis>jdbc:teiid:<vdb-name>@mm[s]://<host>:<port>;[prop-name=prop-value;]*</synopsis></para>
+
+ <para>URL Components</para>
+ <orderedlist>
+ <listitem><para><vdb-name> - Name of the VDB you are connecting to. Optionally VDB
+ name can also contain version information inside it. For example: "myvdb.2", this is equivalent to supplying the
+ "version=2" connection property defined below. However, use of vdb name in this format and
+ the "version" property at the same time is not allowed.
+ </para></listitem>
+ <listitem><para>mm - defines Teiid JDBC protocol, mms defines a secure channel (see the <link linkend="ssl">SSL chapter</link> for more)</para></listitem>
+ <listitem><para><host> - defines the server where the Teiid Server is installed. If you are using IPv6 binding address as the host name, place it in square brackets. ex:[::1]</para></listitem>
+ <listitem><para><port> - defines the port on which the Teiid Server is listening for incoming JDBC connections.</para></listitem>
+ <listitem><para>[prop-name=prop-value] - additionally you can supply any number of name value pairs separated by semi-colon
+ [;]. All supported URL properties are defined in the <link linkend="connection_properties">connection properties section</link>. Property values should be URL encoded if they contain reserved characters, e.g. ('?', '=', ';', etc.)</para></listitem>
+ </orderedlist>
+
+ <section id="connection_properties">
+ <title>URL Connection Properties</title>
+ <para>The following table shows all the supported connection properties that can used with Teiid
+ JDBC Driver URL connection string, or on the Teiid JDBC Data Source class.</para>
+
+ <table frame='all'>
+ <title>Connection Properties</title>
+ <tgroup cols='3' align='left' colsep='1' rowsep='1'>
+ <colspec colname='c1' colwidth=".75*" />
+ <colspec colname='c2' colwidth=".5*" />
+ <colspec colname='c3' colwidth="2*" />
+ <thead>
+ <row>
+ <entry>Property Name</entry>
+ <entry>Type</entry>
+ <entry>Description</entry>
+ </row>
+ </thead>
+ <tbody>
+ <row>
+ <entry>
+ <code>ApplicationName</code>
+ </entry>
+ <entry>
+ <code>String</code>
+ </entry>
+ <entry>Name of the client application; allows the administrator to identify the connections</entry>
+ </row>
+ <row>
+ <entry>
+ <code>FetchSize</code>
+ </entry>
+ <entry>
+ <code>int</code>
+ </entry>
+ <entry>Size of the resultset; The default size if 500. <=0 indicates that the default should be used.</entry>
+ </row>
+ <row>
+ <entry>
+ <code>partialResultsMode</code>
+ </entry>
+ <entry>
+ <code>boolean</code>
+ </entry>
+ <entry>Enable/disable support partial results mode. Default false. See the <link linkend="partial_results">partial results</link> section.</entry>
+ </row>
+ <row id="auto_commit_txn">
+ <entry>
+ <code>autoCommitTxn</code>
+ </entry>
+ <entry>
+ <code>String</code>
+ </entry>
+ <entry>Only applies only when "autoCommit" is set to "true".
+
+ This determines how a executed command needs to be transactionally wrapped inside the
+ Teiid engine to maintain the data integrity.
+ <itemizedlist>
+ <listitem><para>ON - Always wrap command in distributed transaction</para></listitem>
+ <listitem><para>OFF - Never wrap command in distributed transaction</para></listitem>
+ <listitem><para>DETECT (default)- If the executed command is spanning more than one source it automatically uses distributed transaction.</para></listitem>
+ </itemizedlist>
+ <link linkend="jdbc_transactions">Transactions with JDBC</link> for more information.
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <code>disableLocalTxn</code>
+ </entry>
+ <entry>
+ <code>boolean</code>
+ </entry>
+ <entry>If "true", the autoCommit setting, commit and rollback will be ignored for local transactions. Default false.</entry>
+ </row>
+ <row>
+ <entry>
+ <code>user</code>
+ </entry>
+ <entry>
+ <code>String</code>
+ </entry>
+ <entry>User name</entry>
+ </row>
+ <row>
+ <entry>
+ <code>Password</code>
+ </entry>
+ <entry>
+ <code>String</code>
+ </entry>
+ <entry>Credential for user</entry>
+ </row>
+ <row>
+ <entry>
+ <code>ansiQuotedIdentifiers</code>
+ </entry>
+ <entry>
+ <code>boolean</code>
+ </entry>
+ <entry>Sets the parsing behavior for double quoted entries in SQL. The default, true, parses dobuled
+ quoted entries as identifiers. If set to false, then double quoted values that
+ are valid string literals will be parsed as string literals.</entry>
+ </row>
+ <row>
+ <entry>
+ <code>version</code>
+ </entry>
+ <entry>
+ <code>integer</code>
+ </entry>
+ <entry>Version number of the VDB</entry>
+ </row>
+ <row>
+ <entry>
+ <code>resultSetCacheMode</code>
+ </entry>
+ <entry>
+ <code>boolean</code>
+ </entry>
+ <entry>ResultSet caching is turned on/off. Default false.</entry>
+ </row>
+
+ <row>
+ <entry>
+ <code>autoFailover</code>
+ </entry>
+ <entry>
+ <code>boolean</code>
+ </entry>
+ <entry>If true, will automatically select a new server instance after a communication exception. Default false.
+ This is typically not needed when connections are managed, as the connection can be purged from the pool.</entry>
+ </row>
+
+ <row>
+ <entry>
+ <code>SHOWPLAN</code>
+ </entry>
+ <entry>
+ <code>String</code>
+ </entry>
+ <entry>(typically not set as a connection property) Can be ON|OFF|DEBUG; ON returns the query plan along with the results and DEBUG additionally prints the query planner debug information in the log and returns it with the results. Both the plan and the log are available through JDBC API extensions. Default OFF.</entry>
+ </row>
+
+ <row>
+ <entry>
+ <code>NoExec</code>
+ </entry>
+ <entry>
+ <code>String</code>
+ </entry>
+ <entry>(typically not set as a connection property) Can be ON|OFF; ON prevents query execution, but parsing and planning will still occur. Default OFF.</entry>
+ </row>
+ <row id="PassthroughAuthentication">
+ <entry>
+ <code>PassthroughAuthentication</code>
+ </entry>
+ <entry>
+ <code>boolean</code>
+ </entry>
+ <entry>Only applies to "local" connections. When this option is set to "true", then Teiid looks for
+ already authenticated security context on the calling thread. If one found it uses that users credentials
+ 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 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>
+ </entry>
+ <entry>
+ <code>integer</code>
+ </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>
+ </tbody>
+ </tgroup>
+ </table>
+ </section>
+
+ </section>
+
+ <section id="datasource_connection">
+ <title>Datasource Connection</title>
+ <para>To use a data source based connection, use <code>org.teiid.jdbc.TeiidDataSource</code> as the data source class.
+ The <code>TeiidDataSource</code> is also an XADatasource. Teiid DataSource class is also Serializable, so it possible for it to be used with
+ JNDI naming services.</para>
+
+ <note><para>Teiid supports the XA protocol, XA transactions will be extended to Teiid sources that also support XA.</para></note>
+
+ <para>All the properties (except for version, which is known on TeiidDataSource as DatabaseVersion) defined in the <link linkend="connection_properties">connection properties</link>have corresponding "set" methods on the <code>org.teiid.jdbc.TeiidDataSource</code>.
+ Properties that are assumed from the URL string have addtional "set" methods, which are described in the following table.</para>
+
+ <table id="ds_methods" frame='all'>
+ <title>Datasource Properties</title>
+ <tgroup cols='3' align='left' colsep='1' rowsep='1'>
+ <colspec colname='c1' colwidth="1.25*" />
+ <colspec colname='c2' colwidth=".7*" />
+ <colspec colname='c3' colwidth="2*" />
+ <thead>
+ <row>
+ <entry>Property Name</entry>
+ <entry>Type</entry>
+ <entry>Description</entry>
+ </row>
+ </thead>
+ <tbody>
+ <row>
+ <entry>
+ <code>DatabaseName</code>
+ </entry>
+ <entry>
+ <code>String</code>
+ </entry>
+ <entry>The name of a virtual database (VDB) deployed to Teiid. Optionally Database
+ name can also contain "DatabaseVersion" information inside it. For example: "myvdb.2", this is equivalent to supplying the
+ "DatabaseVersion" property set to value of 2. However, use of Database name in this format and use of
+ DatabaseVersion property at the same time is not allowed.</entry>
+ </row>
+ <row>
+ <entry>
+ <code>ServerName</code>
+ </entry>
+ <entry>
+ <code>String</code>
+ </entry>
+ <entry>Server hostname where the Teiid runtime installed. If you are using IPv6 binding address as the host name,
+ place it in square brackets. ex:[::1]</entry>
+ </row>
+ <row>
+ <entry>
+ <code>AlternateServers</code>
+ </entry>
+ <entry>
+ <code>String</code>
+ </entry>
+ <entry>Optional delimited list of host:port entries. See the <link linkend="multiple_hosts">multiple hosts</link>
+ section for more information. If you are using IPv6 binding address as the host name,
+ place them in square brackets. ex:[::1]</entry>
+ </row>
+ <row>
+ <entry>
+ <code>AdditionalProperties</code>
+ </entry>
+ <entry>
+ <code>String</code>
+ </entry>
+ <entry>Optional setting of properties that has the same format as the property string in a connection URL.</entry>
+ </row>
+ <row>
+ <entry>
+ <code>PortNumber</code>
+ </entry>
+ <entry>
+ <code>integer</code>
+ </entry>
+ <entry>Port number on which the Server process is listening on.</entry>
+ </row>
+ <row>
+ <entry>
+ <code>secure</code>
+ </entry>
+ <entry>
+ <code>boolean</code>
+ </entry>
+ <entry>Secure connection. Flag to indicate to use SSL (mms) based connection between client and server</entry>
+ </row>
+ <row>
+ <entry>
+ <code>DatabaseVersion</code>
+ </entry>
+ <entry>
+ <code>integer</code>
+ </entry>
+ <entry>VDB version</entry>
+ </row>
+ <row>
+ <entry>
+ <code>DataSourceName</code>
+ </entry>
+ <entry>
+ <code>String</code>
+ </entry>
+ <entry>Name given to this data source</entry>
+ </row>
+
+ </tbody>
+ </tgroup>
+ </table>
+ </section>
+
+ <section>
+ <title>Standalone Application</title>
+ <para>To use either Driver or DataSource based connections, add the client JAR to your Java client application's classpath. See the simple client example in the kit for a full Java sample of the following.</para>
+
+ <section id="sa_driver_connection">
+ <title>Driver Connection</title>
+
+ <para>Sample Code:</para>
+ <programlisting><![CDATA[public class TeiidClient {
+ public Connection getConnection(String user, String password) throws Exception {
+ String url = "jdbc:teiid:myVDB at mm://localhost:31000;ApplicationName=myApp";
+ return DriverManager.getConnection(url, user, password);
+ }
+}]]></programlisting>
+
+ </section>
+
+ <section id="sa_datasource_connection">
+ <title>Datasource Connection</title>
+
+ <para>Sample Code:</para>
+ <programlisting><![CDATA[public class TeiidClient {
+ public Connection getConnection(String user, String password) throws Exception {
+ TeiidDataSource ds = new TeiidDataSource();
+ ds.setUser(user);
+ ds.setPassword(password);
+ ds.setServerName("localhost");
+ ds.setPortNumber(31000);
+ ds.setDatabaseName("myVDB");
+ return ds.getConnection();
+ }
+}]]></programlisting>
+
+ </section>
+
+ </section>
+
+ <section id="ds_in_jbossas">
+ <title>JBoss AS Data Source</title>
+ <para>Teiid can be configured as a JDBC data source in the JBoss Application Server to be accessed
+ from JNDI or injected into your JEE applications. Deploying Teiid as data source in JBoss AS is exactly same as
+ deploying any other RDBMS resources like Oracle or DB2.</para>
+
+ <para>Defining as data source is not limited to
+ JBoss AS, you can also deploy as data source in Glassfish, Tomcat, Websphere, Weblogic etc servers, however their
+ configuration files are different than JBoss AS. Consult the respective documentation of the environment
+ in which you are deploying.</para>
+
+ <para>A special case is if the Teiid instance you are connecting to is in the same VM as the JBoss AS instance. If that matches you deployment, then follow the <xref linkend="local_connection"/> instructions</para>
+
+ <orderedlist numeration="arabic">
+ <para>Installation Steps</para>
+ <listitem><para>If Teiid is not installed in the AS instance, copy the <code>teiid-&versionNumber;-client.jar</code> into
+ <code><jboss-install>/server/<profile>/lib</code> directory.</para></listitem>
+ <listitem><para>Create a "<datasource name>-ds.xml" file in <code><jboss-install>/server/<profile>/deploy</code>
+ directory. Based on the type of deployment (XA, driver, or local), the contents of the file will be different. See the following sections for more.</para></listitem>
+ </orderedlist>
+
+ <para>The data source will then be accessable through the JNDI name specified in the -ds.xml file.</para>
+
+ <section id="as_xa_connection">
+ <title>DataSource Connection</title>
+ <para>Make sure you know the correct DatabaseName, ServerName, Port number and credentials that are specific
+ to your deployment environment. </para>
+ <example>
+ <title>Sample XADataSource in the JBoss AS using the
+ Teiid DataSource class <code>org.teiid.jdbc.TeiidDataSource</code></title>
+
+ <programlisting><![CDATA[<datasources>
+ <xa-datasource>
+ <jndi-name>TEIID-DS</jndi-name>
+ <xa-datasource-class>org.teiid.jdbc.TeiidDataSource</xa-datasource-class>
+ <xa-datasource-property name="DatabaseName">myVDB</xa-datasource-property>
+ <xa-datasource-property name="serverName">localhost</xa-datasource-property>
+ <xa-datasource-property name="portNumber">31000</xa-datasource-property>
+ <xa-datasource-property name="user">admin</xa-datasource-property>
+ <xa-datasource-property name="password">password</xa-datasource-property>
+
+ <!-- pool and other JBoss datasource properties -->
+ <check-valid-connection-sql>SELECT 1</check-valid-connection-sql>
+ <min-pool-size>5</min-pool-size>
+ <max-pool-size>10</max-pool-size>
+ </xa-datasource>
+</datasources>]]></programlisting> </example>
+ </section>
+ <section id="as_driver_connection">
+ <title>Driver based connection</title>
+ <para>You can also use Teiid's JDBC driver class <code>org.teiid.jdbc.TeiidDriver</code> to create a data source</para>
+ <programlisting><![CDATA[<datasources>
+ <local-tx-datasource>
+ <jndi-name>TEIID-DS</jndi-name>
+ <connection-url>jdbc:teiid:myVDB at mm://localhost:31000</connection-url>
+ <driver-class>org.teiid.jdbc.TeiidDriver</driver-class>
+ <user-name>admin</user-name>
+ <password>teiid</password>
+
+ <!-- pool and other JBoss datasource properties -->
+ <check-valid-connection-sql>SELECT 1</check-valid-connection-sql>
+ <min-pool-size>5</min-pool-size>
+ <max-pool-size>10</max-pool-size>
+ </local-tx-datasource>
+</datasources>]]></programlisting>
+ </section>
+ <section id="local_connection">
+ <title>Local JDBC Connection</title>
+ <para>If you are deploying your client application on the same JBoss AS instance as the Teiid runtime is installed, then
+ 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>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>
+ <xa-datasource>
+ <jndi-name>TEIID-DS</jndi-name>
+ <xa-datasource-class>org.teiid.jdbc.TeiidDataSource</xa-datasource-class>
+ <xa-datasource-property name="DatabaseName">myVDB</xa-datasource-property>
+ <xa-datasource-property name="user">admin</xa-datasource-property>
+ <xa-datasource-property name="password">password</xa-datasource-property>
+
+ <!-- pool and other JBoss datasource properties -->
+ <max-pool-size>10</max-pool-size>
+ </xa-datasource>
+</datasources>]]></programlisting>
+</example>
+ <para>This is essentially the same as the XA configuration, but "ServerName" and "PortNumber" are not specified. Local connections have additional features such as using <xref linkend="PassthroughAuthentication"/> </para>
+ </section>
+
+ </section>
+
+ <section id="multiple_hosts">
+ <title>Using Multiple Hosts</title>
+ <para>A group of Teiid Servers in the same JBoss AS cluster may be connected using failover and load-balancing features.
+ To enable theses features in their simplest form, the client needs to specify multiple host name and port number combinations on the URL connection string.
+ <example><title>Example URL connection string</title><programlisting><![CDATA[jdbc:teiid:<vdb-name>@mm://host1:31000,host1:31001,host2:31000;version=2]]></programlisting></example>
+ </para>
+ <para>If you are using a DataSource to connect to Teiid Server, use the "AlternateServers" property/method to define the failover servers. The format is also a comma separated list of host:port combinations.</para>
+ <para>The client will randomly pick one the Teiid server from the list and establish a session with that server.
+ If that server cannot be contacted, then a connection will be attempted to each of the remaining servers in random order.
+ This allows for both connection time fail-over and random server selection load balancing.
+ </para>
+ <section id="failover">
+ <title>Fail Over</title>
+ <para>Post connection fail over will be used, if you're using an admin connection (such as what is used by AdminShell) or if the <emphasis>autoFailover</emphasis> connection property on JDBC URL is set to true.
+ Post connection failover works by sending a ping, at most every second, to test the connection prior to use. If the ping fails, a new instance will be selected prior to the operation being attempted.
+ This is not true "transparent application failover" as the client will not restart the transaction/query/recreate session scoped temp tables, etc. So this feature should be used with caution by non-admin connections.</para>
+ </section>
+ <section id="loadbalancing">
+ <title>Load Balancing</title>
+ <para>Post connection load balancing can be utilized in one of two ways. First if you are using <code>TeiidDataSource</code> and the Connections returned by
+ Teiid <code>PooledConnections</code> have their <code>close</code> method called, then a new server instance will be selected automatically.
+ However when using driver based connections or even when using <code>TeiidDataSource</code> in a connection pool (such as JBoss AS), the automatic load balancing will not happen.
+ Second you can explicitly trigger load balancing through the use of the set statement: <programlisting>SET NEWINSTANCE TRUE</programlisting>
+ Typically you will not need want to issue this statement manually, but instead use it as the connection test query on your DataSource configuration.
+ <example>
+ <title>JBoss AS DataSource With Post Connection Load Balancing</title>
+ <programlisting><![CDATA[<datasources>
+ <local-tx-datasource>
+ <jndi-name>TEIID-DS</jndi-name>
+ <connection-url>jdbc:teiid:myVDB at mm://localhost:31000,mm://localhost:32000</connection-url>
+ <driver-class>org.teiid.jdbc.TeiidDriver</driver-class>
+ <user-name>admin</user-name>
+ <password>teiid</password>
+
+ <!-- pool and other JBoss datasource properties -->
+ <check-valid-connection-sql>SET NEWINSTANCE TRUE</check-valid-connection-sql>
+ <min-pool-size>5</min-pool-size>
+ <max-pool-size>10</max-pool-size>
+ </local-tx-datasource>
+</datasources>]]></programlisting>
+</example>
+ </para>
+ <para>Teiid by default maintians a pool of extra socket connections that are reused. For load balancing, this reduces the potential cost of switching a connection to another server instance.
+ The default setting is to maintain 16 connections (see <code>org.teiid.sockets.maxCachedInstances</code> in the client jar's teiid-client-settings.properties file.
+ If you're client is connecting to large numbers of Teiid instances and you're using post connection time load balancing, then consider increasing the number of cached instances.
+ You may either set an analogous system property or create another version of teiid-client-settings.properties file and place it into the classpath ahead of the client jar.</para>
+ <note><para>Session level temporary tables, currently running transactions, session level cache entries, and PreparedPlans for a given session will not be available on other cluster members.
+ Therefore, it is recommended that post connection time load balancing is only used when the logical connection could have been closed, but the actual connection is reused (the typical connection pool pattern).</para></note>
+ </section>
+ <section id="advancedconfig">
+ <title>Advanced Configuration</title>
+ <para>Server discovery, load balancing, fail over, retry, retry delay, etc. may be customize if the default policy is not sufficient.
+ See the <code>org.teiid.net.socket.ServerDiscovery</code> interface and default implementaion <code>org.teiid.net.socket.UrlServerDiscovery</code> for how to start with your customization.
+ The <code>UrlServerDiscovery</code> implemenation provides the following: discovery of servers from the URL hosts (DataSource server/alternativeServers), random selection for load balancing and failover, 1 connection attempt per host, no biasing, black listing, or other advanced features.
+ Typically you'll want to extend the <code>UrlServerDiscovery</code> so that it can be used as the fallback strategy and to only implement the necessary changed methods.
+ It's important to consider that 1 <code>ServerDiscovery</code> instance will be created for each connection. Any sharing of information between instances should be done through static state or some other shared lookup.
+ </para>
+ <para>Your customized server discovery class will then need to be referenced by the discoveryStategy connection/DataSource property by its full class name.</para>
+ <para>You may also choose to use an external tcp load balancer, such as <ulink url="http://haproxy.1wt.eu/">haproxy</ulink>.
+ The Teiid driver/DataSource should then typically be configured to just use the single host/port of your load balancer.</para>
+ </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.
+ Existing statements/result sets are still available for use under the old identity. See the JBossAS issue <ulink url="https://issues.jboss.org/browse/JBAS-1429">JBAS-1429</ulink> for more on using reauthentication support with JCA.</para>
+ </section>
+</chapter>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-extensions.xml
===================================================================
--- trunk/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-extensions.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-extensions.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,375 +0,0 @@
-<?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" [
-<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
-%CustomDTD;
-]>
-<chapter id="jdbc_extensions">
- <title>Teiid extensions to the JDBC API</title>
-
- <section id="statement_extensions">
- <title>Statement Extensions</title>
- <para>The Teiid statement extension interface,
- <code>org.teiid.jdbc.TeiidStatement</code>, provides functionality beyond the JDBC standard. To use the extension interface, simply
- cast or unwap the statement returned by the Connection. The following methods are provided on the extension interface:</para>
-
- <table frame='all'>
- <title>Connection Properties</title>
- <tgroup cols='2' align='left' colsep='1' rowsep='1'>
- <colspec colname='c1' colwidth="1*" />
- <colspec colname='c2' colwidth="2*" />
- <thead>
- <row>
- <entry>Method Name</entry>
- <entry>Description</entry>
- </row>
- </thead>
- <tbody>
- <row>
- <entry>
- <code>getAnnotations</code>
- </entry>
- <entry>
- <para>Get the query engine annotations if the statement was last executed with SHOWPLAN ON|DEBUG. Each <code>org.teiid.client.plan.Annotation</code> contains a description,
- a category, a severity, and possibly a resolution of notes recorded during query planning that can be used to understand choices made by the query planner.</para>
- </entry>
- </row>
-
- <row>
- <entry>
- <code>getDebugLog</code>
- </entry>
- <entry>
- <para>Get the debug log if the statement was last executed with SHOWPLAN DEBUG.</para>
- </entry>
- </row>
-
- <row>
- <entry>
- <code>getExecutionProperty</code>
- </entry>
- <entry>
- <para>Get the current value of an execution property on this statement object.</para>
- </entry>
- </row>
-
- <row>
- <entry>
- <code>getPlanDescription</code>
- </entry>
- <entry>
- <para>Get the query plan description if the statement was last executed with SHOWPLAN ON|DEBUG. The plan is a tree made up of <code>org.teiid.client.plan.PlanNode</code> objects.
- Typically <code>PlanNode.toString()</code> or <code>PlanNode.toXml()</code></para> will be used to convert the plan into a textual form.
- </entry>
- </row>
- <row>
- <entry>
- <code>getRequestIdentifier</code>
- </entry>
- <entry>
- <para>Get an identifier for the last command executed on this statement. If no command has been executed yet, null is returned.</para>
- </entry>
- </row>
-
- <row>
- <entry>
- <code>setExecutionProperty</code>
- </entry>
- <entry>
- <para>Set the execution property on this statement. See the <link linkend="execution_properties">execution properties</link> section for more information.
- It is generally preferable to use the <link linkend="set_statement">SET statement</link> unless the execution property applies only to the statement being executed.</para>
- </entry>
- </row>
-
- <row>
- <entry>
- <code>setPayload</code>
- </entry>
- <entry>
- <para>Set a per-command payload to pass to translators. Currently
- the only built-in use is for sending hints for Oracle
- data source.</para>
- </entry>
- </row>
- </tbody>
- </tgroup>
- </table>
- </section>
-
- <section id="execution_properties">
- <title>Execution Properties</title>
- <para>Execution properties may be set on a per statement basis through the <link linkend="statement_extensions"><code>TeiidStatement</code></link> interface or on the connection via the <link linkend="set_statement">SET statement</link>.
- For convenience, the property keys are defined by constants on the <code>org.teiid.jdbc.ExecutionProperties</code> interface.</para>
-
- <table frame='all'>
- <title>Execution Properties</title>
- <tgroup cols='2' align='left' colsep='1' rowsep='1'>
- <colspec colname='c1' colwidth="1*" />
- <colspec colname='c2' colwidth="2*" />
- <thead>
- <row>
- <entry>Property Name/String Constant</entry>
- <entry>Description</entry>
- </row>
- </thead>
- <tbody>
- <row>
- <entry>
- <code>PROP_TXN_AUTO_WRAP / autoCommitTxn</code>
- </entry>
- <entry>
- <para>Same as the connection property.</para>
- </entry>
- </row>
- <row>
- <entry>
- <code>PROP_PARTIAL_RESULTS_MODE / partialResultsMode</code>
- </entry>
- <entry>
- <para>See the <link linkend="partial_results">partial results</link> section.</para>
- </entry>
- </row>
- <row>
- <entry>
- <code>PROP_XML_FORMAT / XMLFormat</code>
- </entry>
- <entry>
- <para>Determines the formatting of XML documents returned by XML document models. See the <link linkend="document_formatting">document formatting</link> section.</para>
- </entry>
- </row>
- <row>
- <entry>
- <code>PROP_XML_VALIDATION / XMLValidation</code>
- </entry>
- <entry>
- <para>Determines whether XML documents returned by XML document models will be validated
- against their schema after processing. See the Reference Guide's "XML SELECT Command" chapter and
- "document validation" section.</para>
- </entry>
- </row>
- <row>
- <entry>
- <code>RESULT_SET_CACHE_MODE / resultSetCacheMode</code>
- </entry>
- <entry>
- <para>Same as the connection property.</para>
- </entry>
- </row>
- <row>
- <entry>
- <code>SQL_OPTION_SHOWPLAN / SHOWPLAN</code>
- </entry>
- <entry>
- <para>Same as the connection property.</para>
- </entry>
- </row>
- <row>
- <entry>
- <code>NOEXEC / NOEXEC</code>
- </entry>
- <entry>
- <para>Same as the connection property.</para>
- </entry>
- </row>
- </tbody>
- </tgroup>
- </table>
- </section>
-
- <section id="set_statement">
- <title>SET Statement</title>
-
- <para>Execution properties may also be set on the connection by using the SET statement.
- The SET statement is not yet a language feature of Teiid and is handled only in the JDBC client.</para>
-
- <itemizedlist>
- <para>SET Syntax:
- </para>
- <listitem>
- <para>SET parameter value
- </para>
- </listitem>
- </itemizedlist>
- <itemizedlist>
- <para>Syntax Rules:
- </para>
- <listitem>
- <para>Both parameter and value must be simple literals - they 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>
- </listitem>
- </itemizedlist>
- <para>The SET statement is most commonly used to control planning and execution.</para>
- <itemizedlist>
- <listitem>
- <para>SET SHOWPLAN (ON|DEBUG|OFF)</para>
- </listitem>
- <listitem>
- <para>SET NOEXEC (ON|OFF)</para>
- </listitem>
- </itemizedlist>
-
- <example id="plan_debug">
- <title>Enabling Plan Debug</title>
- <programlisting>Statement s = connection.createStatement();
-s.execute("SET SHOWPLAN DEBUG");
-...
-Statement s1 = connection.createStatement();
-ResultSet rs = s1.executeQuery("select col from table");
-
-ResultSet planRs = s1.exeuteQuery("SHOW PLAN");
-planRs.next();
-String debugLog = planRs.getString("DEBUG_LOG");
- </programlisting>
- </example>
- </section>
-
- <section id="show_statement">
- <title>SHOW Statement</title>
-
- <para>The SHOW statement can be used to see a varitey of information.
- The SHOW statement is not yet a language feature of Teiid and is handled only in the JDBC client.</para>
-
- <itemizedlist>
- <para>SHOW Usage:
- </para>
- <listitem>
- <para>SHOW <emphasis>PLAN</emphasis> - returns a resultset with a clob column PLAN_TEXT, an xml column PLAN_XML, and a clob column DEBUG_LOG with a row containing the values from the previously executed query.
- If SHOWPLAN is OFF or no plan is available, no rows are returned. If SHOWPLAN is not set to DEBUG, then DEBUG_LOG will return a null value.
- </para>
- </listitem>
- <listitem>
- <para>SHOW <emphasis>ANNOTATIONS</emphasis> - returns a resultset with string columns CATEGORY, PRIORITY, ANNOTATION, RESOLUTION and a row for each annotation on the previously executed query.
- If SHOWPLAN is OFF or no plan is available, no rows are returned.
- </para>
- </listitem>
- <listitem>
- <para>SHOW property - the inverse of SET, shows the property value for the given property, returns a resultset with a single string column with a name matching the property key.
- </para>
- </listitem>
- <listitem>
- <para>SHOW <emphasis>ALL</emphasis> - returns a resultset with a NAME string column and a VALUE string column with a row entry for every property value.
- </para>
- </listitem>
- </itemizedlist>
- <para>The SHOW statement is most commonly used to retrieve the query plan, see the plan <link linkend="plan_debug">debug example</link>.</para>
- </section>
-
- <section id="transaction_statement">
- <title>Transaction Statements</title>
- <para>In situations where the direct use of the JDBC connection is not possible, transaction statements can be used to control a local transaction.</para>
- <itemizedlist>
- <listitem><para><emphasis>START TRANSACTION</emphasis> - synonym for <code>connection.setAutoCommit(false)</code></para>
- </listitem>
- <listitem><para><emphasis>COMMIT</emphasis> - synonym for <code>connection.setAutoCommit(true)</code></para>
- </listitem>
- <listitem><para><emphasis>ROLLBACK</emphasis> - synonym for <code>connection.rollback()</code> and returning to auto commit mode.</para>
- </listitem>
- </itemizedlist>
- </section>
-
- <section id="partial_results">
- <title>Partial Results Mode</title>
- <para>The Teiid Server supports a "partial results" query mode. This mode changes the behavior of the
- query processor so the server returns results even when some data sources are unavailable.</para>
-
- <para>For example, suppose that two data sources exist for different suppliers and your
- data Designers have created a virtual group that creates a union between the information
- from the two suppliers. If your application submits a query without using partial
- results query mode and one of the suppliers’ databases is down, the query
- against the virtual group returns an exception. However, if your application runs
- the same query in “partial results” query mode, the server returns data from the
- running data source and no data from the data source that is down.</para>
-
- <para>When using "partial results" mode, if a source throws an exception during
- processing it does not cause the user’s query to fail. Rather, that source is treated
- as returning no more rows after the failure point.
- Most commonly, that source will return 0 rows. </para>
-
- <para>This behavior is most useful when using <code>UNION</code> or <code>OUTER JOIN</code> queries
- as these operations handle missing information in a useful way. Most
- other kinds of queries will simply return 0 rows to the user
- when used in partial results mode and the source is unavailable. </para>
-
- <para>For each source that is excluded from the query, a warning will be generated
- describing the source and the failure. These warnings can be obtained from the
- <code>Statement.getWarnings()</code> method. This method returns a <code>SQLWarning</code> object but
- in the case of "partial results" warnings, this will be an object of
- type <code>org.teiid.jdbc.PartialResultsWarning</code> class. This class can be
- used to obtain a list of all the failed sources by name and to obtain
- the specific exception thrown by each resource adaptor. </para>
-
- <note>
- <para> Since Teiid supports cursoring before the entire result is formed, it is
- possible that a data source failure will not
- be determined until after the first batch of results have
- been returned to the client. This can happen in the case of
- unions, but not joins. To ensure that all warnings have been accumulated, the
- statement should be checked after the entire result set has been read.</para>
- </note>
-
- <para>
- Partial results mode is off by default but can be turned on for all queries in a Connection with either
- setPartialResultsMode("true") on a DataSource or
- partialResultsMode=true on a JDBC URL. In either case, partial
- results mode may be toggled later with a <link linkend="set_statement">set statement</link>.
- </para>
- <example>
- <title>Setting Partial Results Mode</title>
- <programlisting>Statement statement = ...obtain statement from Connection...
-statement.execute("set partialResultsMode true");</programlisting>
- </example>
-
- <example>
- <title>Getting Partial Results Warnings
- </title>
- <programlisting>statement.execute("set partialResultsMode true");
-ResultSet results = statement.executeQuery("SELECT Name FROM Accounts");
-while (results.next()) {
- ... //process the result set
-}
-SQLWarning warning = statement.getWarnings();
-if(warning instanceof PartialResultsWarning) {
- PartialResultsWarning partialWarning = (PartialResultsWarning)warning;
- Collection failedConnectors = partialWarning.getFailedConnectors();
- Iterator iter = failedConnectors.iterator();
- while(iter.hasNext()) {
- String connectorName = (String) iter.next();
- SQLException connectorException = partialWarning.getConnectorException(connectorName);
- System.out.println(connectorName + ": " + ConnectorException.getMessage();
- }
-}</programlisting>
- </example>
- </section>
-
- <section>
- <title>XML extensions</title>
- <para>The XML extensions apply on to XML resutls from queries to XML document models, and not to XML produced by SQL/XML or read from some other source.</para>
- <section id="document_formatting">
- <title>Document formatting</title>
- <para>The PROP_XML_FORMAT execution property can be set to modify the way that
- XML documents are formatted from XML document models. Valid values for the constant
- are defined in the same ExecutionProperties interface:</para>
- <orderedlist>
- <listitem><para><code>XML_TREE_FORMAT</code> - Returns a version of the XML formatted for display.
- The XML will use line breaks and tabs as appropriate to format the XML as a tree.
- This format is slower due to the formatting time and the larger document size.</para></listitem>
- <listitem><para><code>XML_COMPACT_FORMAT</code> - Returns a version of the XML formatted for
- optimal performance. The XML is a single long string without any
- unnecessary white space. </para></listitem>
- <listitem><para>Not Set - If no format is set, the formatting flag on the
- XML document in the original model is honored. This may produce either the “tree” or “compact”
- form of the document depending on the document setting.</para></listitem>
- </orderedlist>
- </section>
-
- <section id="schema_validation">
- <title>Schema validation</title>
- <para>The <code>PROP_XML_VALIDATION</code> execution property can be set to indicate that
- the server should validate XML document model documents against their schema before returning them
- to the client. If schema validation is on, then the server send a SQLWarning if the document does not conform to the schema it is associated with.
- Using schema validation will reduce the performance of your XML queries. </para>
- </section>
- </section>
-
-</chapter>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-extensions.xml (from rev 3218, trunk/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-extensions.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-extensions.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-extensions.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,384 @@
+<?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" [
+<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
+%CustomDTD;
+]>
+<chapter id="jdbc_extensions">
+ <title>Teiid extensions to the JDBC API</title>
+
+ <section id="statement_extensions">
+ <title>Statement Extensions</title>
+ <para>The Teiid statement extension interface,
+ <code>org.teiid.jdbc.TeiidStatement</code>, provides functionality beyond the JDBC standard. To use the extension interface, simply
+ cast or unwap the statement returned by the Connection. The following methods are provided on the extension interface:</para>
+
+ <table frame='all'>
+ <title>Connection Properties</title>
+ <tgroup cols='2' align='left' colsep='1' rowsep='1'>
+ <colspec colname='c1' colwidth="1*" />
+ <colspec colname='c2' colwidth="2*" />
+ <thead>
+ <row>
+ <entry>Method Name</entry>
+ <entry>Description</entry>
+ </row>
+ </thead>
+ <tbody>
+ <row>
+ <entry>
+ <code>getAnnotations</code>
+ </entry>
+ <entry>
+ <para>Get the query engine annotations if the statement was last executed with SHOWPLAN ON|DEBUG. Each <code>org.teiid.client.plan.Annotation</code> contains a description,
+ a category, a severity, and possibly a resolution of notes recorded during query planning that can be used to understand choices made by the query planner.</para>
+ </entry>
+ </row>
+
+ <row>
+ <entry>
+ <code>getDebugLog</code>
+ </entry>
+ <entry>
+ <para>Get the debug log if the statement was last executed with SHOWPLAN DEBUG.</para>
+ </entry>
+ </row>
+
+ <row>
+ <entry>
+ <code>getExecutionProperty</code>
+ </entry>
+ <entry>
+ <para>Get the current value of an execution property on this statement object.</para>
+ </entry>
+ </row>
+
+ <row>
+ <entry>
+ <code>getPlanDescription</code>
+ </entry>
+ <entry>
+ <para>Get the query plan description if the statement was last executed with SHOWPLAN ON|DEBUG. The plan is a tree made up of <code>org.teiid.client.plan.PlanNode</code> objects.
+ Typically <code>PlanNode.toString()</code> or <code>PlanNode.toXml()</code></para> will be used to convert the plan into a textual form.
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <code>getRequestIdentifier</code>
+ </entry>
+ <entry>
+ <para>Get an identifier for the last command executed on this statement. If no command has been executed yet, null is returned.</para>
+ </entry>
+ </row>
+
+ <row>
+ <entry>
+ <code>setExecutionProperty</code>
+ </entry>
+ <entry>
+ <para>Set the execution property on this statement. See the <link linkend="execution_properties">execution properties</link> section for more information.
+ It is generally preferable to use the <link linkend="set_statement">SET statement</link> unless the execution property applies only to the statement being executed.</para>
+ </entry>
+ </row>
+
+ <row>
+ <entry>
+ <code>setPayload</code>
+ </entry>
+ <entry>
+ <para>Set a per-command payload to pass to translators. Currently
+ the only built-in use is for sending hints for Oracle
+ data source.</para>
+ </entry>
+ </row>
+ </tbody>
+ </tgroup>
+ </table>
+ </section>
+
+ <section id="execution_properties">
+ <title>Execution Properties</title>
+ <para>Execution properties may be set on a per statement basis through the <link linkend="statement_extensions"><code>TeiidStatement</code></link> interface or on the connection via the <link linkend="set_statement">SET statement</link>.
+ For convenience, the property keys are defined by constants on the <code>org.teiid.jdbc.ExecutionProperties</code> interface.</para>
+
+ <table frame='all'>
+ <title>Execution Properties</title>
+ <tgroup cols='2' align='left' colsep='1' rowsep='1'>
+ <colspec colname='c1' colwidth="1*" />
+ <colspec colname='c2' colwidth="2*" />
+ <thead>
+ <row>
+ <entry>Property Name/String Constant</entry>
+ <entry>Description</entry>
+ </row>
+ </thead>
+ <tbody>
+ <row>
+ <entry>
+ <code>PROP_TXN_AUTO_WRAP / autoCommitTxn</code>
+ </entry>
+ <entry>
+ <para>Same as the connection property.</para>
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <code>PROP_PARTIAL_RESULTS_MODE / partialResultsMode</code>
+ </entry>
+ <entry>
+ <para>See the <link linkend="partial_results">partial results</link> section.</para>
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <code>PROP_XML_FORMAT / XMLFormat</code>
+ </entry>
+ <entry>
+ <para>Determines the formatting of XML documents returned by XML document models. See the <link linkend="document_formatting">document formatting</link> section.</para>
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <code>PROP_XML_VALIDATION / XMLValidation</code>
+ </entry>
+ <entry>
+ <para>Determines whether XML documents returned by XML document models will be validated
+ against their schema after processing. See the Reference Guide's "XML SELECT Command" chapter and
+ "document validation" section.</para>
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <code>RESULT_SET_CACHE_MODE / resultSetCacheMode</code>
+ </entry>
+ <entry>
+ <para>Same as the connection property.</para>
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <code>SQL_OPTION_SHOWPLAN / SHOWPLAN</code>
+ </entry>
+ <entry>
+ <para>Same as the connection property.</para>
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <code>NOEXEC / NOEXEC</code>
+ </entry>
+ <entry>
+ <para>Same as the connection property.</para>
+ </entry>
+ </row>
+ </tbody>
+ </tgroup>
+ </table>
+ </section>
+
+ <section id="set_statement">
+ <title>SET Statement</title>
+
+ <para>Execution properties may also be set on the connection by using the SET statement.
+ The SET statement is not yet a language feature of Teiid and is handled only in the JDBC client.</para>
+
+ <itemizedlist>
+ <para>SET Syntax:
+ </para>
+ <listitem>
+ <para>SET (parameter|SESSION AUTHORIZATION) value
+ </para>
+ </listitem>
+ </itemizedlist>
+ <itemizedlist>
+ <para>Syntax Rules:
+ </para>
+ <listitem>
+ <para>The parameter must be a non-quoted identifier - it cannot contain spaces.</para>
+ </listitem>
+ <listitem>
+ <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>
+ <itemizedlist>
+ <listitem>
+ <para>SET SHOWPLAN (ON|DEBUG|OFF)</para>
+ </listitem>
+ <listitem>
+ <para>SET NOEXEC (ON|OFF)</para>
+ </listitem>
+ </itemizedlist>
+ <example id="plan_debug">
+ <title>Enabling Plan Debug</title>
+ <programlisting>Statement s = connection.createStatement();
+s.execute("SET SHOWPLAN DEBUG");
+...
+Statement s1 = connection.createStatement();
+ResultSet rs = s1.executeQuery("select col from table");
+
+ResultSet planRs = s1.exeuteQuery("SHOW PLAN");
+planRs.next();
+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">
+ <title>SHOW Statement</title>
+
+ <para>The SHOW statement can be used to see a varitey of information.
+ The SHOW statement is not yet a language feature of Teiid and is handled only in the JDBC client.</para>
+
+ <itemizedlist>
+ <para>SHOW Usage:
+ </para>
+ <listitem>
+ <para>SHOW <emphasis>PLAN</emphasis> - returns a resultset with a clob column PLAN_TEXT, an xml column PLAN_XML, and a clob column DEBUG_LOG with a row containing the values from the previously executed query.
+ If SHOWPLAN is OFF or no plan is available, no rows are returned. If SHOWPLAN is not set to DEBUG, then DEBUG_LOG will return a null value.
+ </para>
+ </listitem>
+ <listitem>
+ <para>SHOW <emphasis>ANNOTATIONS</emphasis> - returns a resultset with string columns CATEGORY, PRIORITY, ANNOTATION, RESOLUTION and a row for each annotation on the previously executed query.
+ If SHOWPLAN is OFF or no plan is available, no rows are returned.
+ </para>
+ </listitem>
+ <listitem>
+ <para>SHOW property - the inverse of SET, shows the property value for the given property, returns a resultset with a single string column with a name matching the property key.
+ </para>
+ </listitem>
+ <listitem>
+ <para>SHOW <emphasis>ALL</emphasis> - returns a resultset with a NAME string column and a VALUE string column with a row entry for every property value.
+ </para>
+ </listitem>
+ </itemizedlist>
+ <para>The SHOW statement is most commonly used to retrieve the query plan, see the plan <link linkend="plan_debug">debug example</link>.</para>
+ </section>
+
+ <section id="transaction_statement">
+ <title>Transaction Statements</title>
+ <para>In situations where the direct use of the JDBC connection is not possible, transaction statements can be used to control a local transaction.</para>
+ <itemizedlist>
+ <listitem><para><emphasis>START TRANSACTION</emphasis> - synonym for <code>connection.setAutoCommit(false)</code></para>
+ </listitem>
+ <listitem><para><emphasis>COMMIT</emphasis> - synonym for <code>connection.setAutoCommit(true)</code></para>
+ </listitem>
+ <listitem><para><emphasis>ROLLBACK</emphasis> - synonym for <code>connection.rollback()</code> and returning to auto commit mode.</para>
+ </listitem>
+ </itemizedlist>
+ </section>
+
+ <section id="partial_results">
+ <title>Partial Results Mode</title>
+ <para>The Teiid Server supports a "partial results" query mode. This mode changes the behavior of the
+ query processor so the server returns results even when some data sources are unavailable.</para>
+
+ <para>For example, suppose that two data sources exist for different suppliers and your
+ data Designers have created a virtual group that creates a union between the information
+ from the two suppliers. If your application submits a query without using partial
+ results query mode and one of the suppliers’ databases is down, the query
+ against the virtual group returns an exception. However, if your application runs
+ the same query in “partial results” query mode, the server returns data from the
+ running data source and no data from the data source that is down.</para>
+
+ <para>When using "partial results" mode, if a source throws an exception during
+ processing it does not cause the user’s query to fail. Rather, that source is treated
+ as returning no more rows after the failure point.
+ Most commonly, that source will return 0 rows. </para>
+
+ <para>This behavior is most useful when using <code>UNION</code> or <code>OUTER JOIN</code> queries
+ as these operations handle missing information in a useful way. Most
+ other kinds of queries will simply return 0 rows to the user
+ when used in partial results mode and the source is unavailable. </para>
+
+ <para>For each source that is excluded from the query, a warning will be generated
+ describing the source and the failure. These warnings can be obtained from the
+ <code>Statement.getWarnings()</code> method. This method returns a <code>SQLWarning</code> object but
+ in the case of "partial results" warnings, this will be an object of
+ type <code>org.teiid.jdbc.PartialResultsWarning</code> class. This class can be
+ used to obtain a list of all the failed sources by name and to obtain
+ the specific exception thrown by each resource adaptor. </para>
+
+ <note>
+ <para> Since Teiid supports cursoring before the entire result is formed, it is
+ possible that a data source failure will not
+ be determined until after the first batch of results have
+ been returned to the client. This can happen in the case of
+ unions, but not joins. To ensure that all warnings have been accumulated, the
+ statement should be checked after the entire result set has been read.</para>
+ </note>
+
+ <para>
+ Partial results mode is off by default but can be turned on for all queries in a Connection with either
+ setPartialResultsMode("true") on a DataSource or
+ partialResultsMode=true on a JDBC URL. In either case, partial
+ results mode may be toggled later with a <link linkend="set_statement">set statement</link>.
+ </para>
+ <example>
+ <title>Setting Partial Results Mode</title>
+ <programlisting>Statement statement = ...obtain statement from Connection...
+statement.execute("set partialResultsMode true");</programlisting>
+ </example>
+
+ <example>
+ <title>Getting Partial Results Warnings
+ </title>
+ <programlisting>statement.execute("set partialResultsMode true");
+ResultSet results = statement.executeQuery("SELECT Name FROM Accounts");
+while (results.next()) {
+ ... //process the result set
+}
+SQLWarning warning = statement.getWarnings();
+if(warning instanceof PartialResultsWarning) {
+ PartialResultsWarning partialWarning = (PartialResultsWarning)warning;
+ Collection failedConnectors = partialWarning.getFailedConnectors();
+ Iterator iter = failedConnectors.iterator();
+ while(iter.hasNext()) {
+ String connectorName = (String) iter.next();
+ SQLException connectorException = partialWarning.getConnectorException(connectorName);
+ System.out.println(connectorName + ": " + ConnectorException.getMessage();
+ }
+}</programlisting>
+ </example>
+ </section>
+
+ <section>
+ <title>XML extensions</title>
+ <para>The XML extensions apply on to XML resutls from queries to XML document models, and not to XML produced by SQL/XML or read from some other source.</para>
+ <section id="document_formatting">
+ <title>Document formatting</title>
+ <para>The PROP_XML_FORMAT execution property can be set to modify the way that
+ XML documents are formatted from XML document models. Valid values for the constant
+ are defined in the same ExecutionProperties interface:</para>
+ <orderedlist>
+ <listitem><para><code>XML_TREE_FORMAT</code> - Returns a version of the XML formatted for display.
+ The XML will use line breaks and tabs as appropriate to format the XML as a tree.
+ This format is slower due to the formatting time and the larger document size.</para></listitem>
+ <listitem><para><code>XML_COMPACT_FORMAT</code> - Returns a version of the XML formatted for
+ optimal performance. The XML is a single long string without any
+ unnecessary white space. </para></listitem>
+ <listitem><para>Not Set - If no format is set, the formatting flag on the
+ XML document in the original model is honored. This may produce either the “tree” or “compact”
+ form of the document depending on the document setting.</para></listitem>
+ </orderedlist>
+ </section>
+
+ <section id="schema_validation">
+ <title>Schema validation</title>
+ <para>The <code>PROP_XML_VALIDATION</code> execution property can be set to indicate that
+ the server should validate XML document model documents against their schema before returning them
+ to the client. If schema validation is on, then the server send a SQLWarning if the document does not conform to the schema it is associated with.
+ Using schema validation will reduce the performance of your XML queries. </para>
+ </section>
+ </section>
+
+</chapter>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/odbc.xml
===================================================================
--- trunk/documentation/client-developers-guide/src/main/docbook/en-US/content/odbc.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/odbc.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,250 +0,0 @@
-<?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" [
-<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
-%CustomDTD;
-]>
-<chapter id="ODBC">
- <title>ODBC Support</title>
-
- <para>Open DataBase Connectivity (ODBC) is a standard database access method developed by the SQL Access group in 1992.
- ODBC, just like JDBC in Java, allows consistent client access regardless of which database management
- system (DBMS) is handling the data. ODBC uses a driver to translate the application's data queries
- into commands that the DBMS understands. For this to work, both the application and the DBMS must be ODBC-compliant
- -- that is, the application must be capable of issuing ODBC commands and the
- DBMS must be capable of responding to them.</para>
-
- <para>Teiid can provide ODBC access to deployed VDBs in the Teiid runtime through
- <ulink url="http://www.postgresql.org/">PostgreSQL</ulink>'s ODBC driver.
- This is possible because Teiid has specialized handling that allows it emulate a PostgreSQL server and respond appropriate to expected
- metadata queries.</para>
-
- <note><para>By default, ODBC on the Teiid is enabled and running on on port <emphasis>35432</emphasis>.</para></note>
-
- <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>
-
- <section id="install">
- <title>Installing the ODBC Driver Client</title>
- <para>A PostgreSQL ODBC driver needed to make the ODBC connection to Teiid is <emphasis>not</emphasis>
- bundled with the Teiid distribution. The appropriate driver needs be <ulink url="http://www.postgresql.org/ftp/odbc/versions/">downloaded</ulink>
- directly from the PostgreSQL web site. We have tested with <emphasis>8.04.200</emphasis> version of the ODBC driver.</para>
-
- <section>
- <title>Microsoft Windows</title>
- <orderedlist>
- <listitem><para>Download the ODBC driver from <ulink url="http://wwwmaster.postgresql.org/download/mirrors-ftp/odbc/versions/msi/psqlodbc_08_04_0200.zip">
- PostgreSQL download site</ulink>. If you are looking for 64-bit Windows driver download the driver from <ulink url="http://code.google.com/p/visionmap/wiki/psqlODBC">here</ulink>. </para></listitem>
- <listitem><para>Extract the contents of the ZIP file into a temporary location on your system. For example: "c:\temp\pgodbc"</para></listitem>
- <listitem><para>Double click on "psqlodbc.msi" file or (.exe file in the case of 64 bit) to start installation of the driver.</para></listitem>
- <listitem>
- <para>The Wizard appears as</para>
- <figure id="step1">
- <title>Welcome Screen </title>
- <graphic align="center" scale="100" fileref="../images/winsetup1.png" />
- </figure>
- <para>Click "Next".</para>
- </listitem>
- <listitem>
- <para>The next step of the wizard displays.</para>
- <figure id="step2">
- <title>End-User License Agreement </title>
- <graphic align="center" scale="100" fileref="../images/winsetup2.png" />
- </figure>
- <para>Carefully read it, and check the "I accept the terms in the License Agreement",
- if you are agreeing to the licensing terms. Then click "Next".</para>
- </listitem>
- <listitem>
- <para>The next step of the wizard displays.</para>
- <figure id="step3">
- <title>Setup</title>
- <graphic align="center" scale="100" fileref="../images/winsetup3.png" />
- </figure>
- <para>If you want to install in a different directory than the default that is already selected,
- click the "Browse" button and select a directory.
- Click "Next" to start installing in the selected directory.</para>
- </listitem>
- <listitem>
- <para>The next step of the wizard displays.</para>
- <figure id="step4">
- <title>Confirm the Install</title>
- <graphic align="center" scale="100" fileref="../images/winsetup4.png" />
- </figure>
- <para>This step summarizes the choices you have made in the wizard. Review this information.
- If you need to change anything, you can use the Back button to return to previous steps.
- Click "Install" to proceed.</para>
- </listitem>
- <listitem>
- <para>1.The installation wizard copies the necessary files to the location
- you specified. When it finishes, the following screen displays.</para>
- <figure id="step5">
- <title>Finish</title>
- <graphic align="center" scale="100" fileref="../images/winsetup5.png" />
- </figure>
- <para>Click "Finish" to complete.</para>
- </listitem>
- </orderedlist>
- </section>
- <section>
- <title>Other *nix Platform Installations</title>
- <para>For all other platforms other than Microsoft Windows, the ODBC driver needs built from the
- source files provided. Download the ODBC driver source files from
- <ulink url="http://wwwmaster.postgresql.org/download/mirrors-ftp/odbc/versions/src/psqlodbc-08.04.0200.tar.gz">
- the PostgreSQL download site</ulink>. Untar the files to a temporary location. For example: "~/tmp/pgodbc".
- Build and install the driver by running the commands below.</para>
- <note><para>You should use super user account or use "sudo" command for running the "make install" command. </para></note>
- <programlisting><![CDATA[
- % tar -zxvf psqlodbc-xx.xx.xxxx.tar.gz
- % cd psqlodbc-xx.xx.xxxx
- % ./configure
- % make
- % make install
- ]]></programlisting>
- <para>Some *nix distributions may already provide binary forms of the appropriate driver, which can be used as an alternative to
- building from source.</para>
- </section>
- </section>
-
- <section>
- <title>Configuring the Data Source Name (DSN)</title>
- <section>
- <title>Windows Installation</title>
- <para>Once you have installed the ODBC Driver Client software on your workstation, you have to
- configure it to connect to a Teiid Runtime. Note that the following instructions are specific
- to the Microsoft Windows Platform.</para>
-
- <para>To do this, you must have logged into the workstation with administrative rights, and you
- need to use the Control Panel’s <emphasis>Data Sources (ODBC)</emphasis> applet to add a new data source name.
- </para>
-
- <para>Each data source name you configure can only access one VDB within a Teiid System. To make more than
- one VDB available, you need to configure more than one data source name.</para>
-
- <para>Follow the below steps in creating a data source name (DSN)</para>
- <orderedlist numeration="arabic">
- <listitem><para>From the Start menu, select Settings > Control Panel.</para></listitem>
- <listitem><para>The Control Panel displays. Double click <emphasis>Administrative Tools</emphasis>.</para></listitem>
- <listitem><para>Then Double-click <emphasis>Data Sources (ODBC)</emphasis>.</para></listitem>
- <listitem><para>The ODBC Data Source Administrator applet displays. Click the tab
- associated with the type of DSN you want to add.</para></listitem>
- <listitem><para>The Create New Data Source dialog box displays. In the Select a driver for which you
- want to set up a data source table, select <emphasis>PostgreSQL Unicode</emphasis>.</para></listitem>
- <listitem><para>Click Finish</para></listitem>
- <listitem><para>The PostgreSQL ODBC DSN Setup dialog box displays.</para></listitem>
-
- <listitem>
- <figure id="dsn1">
- <title>Main Screen</title>
- <graphic align="center" scale="100" fileref="../images/dsnsetup1.png" />
- </figure>
- <para>In the <emphasis>Data Source</emphasis> Name edit box, type the name you want to assign to this data source.</para>
- <para>In the <emphasis>Database</emphasis> edit box, type the name of the virtual database you want to access through this data source.</para>
- <para>In the <emphasis>Server</emphasis> edit box, type the host name or IP address of your Teiid runtime. If connecting
- via a firewall or NAT address, the firewall address or NAT address should be entered. </para>
- <para>In the Port edit box, type the port number to which the Teiid System listens for ODBC requests. By default, Teiid
- 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>
-
- <listitem>
- <para>Click on the <emphasis>Datasource</emphasis> button, you will see this below figure. Configure options as shown.</para>
- <figure id="dsn2">
- <title>DSN Options Page-1</title>
- <graphic align="center" scale="100" fileref="../images/dsnsetup2.png" />
- </figure>
-
- <para>Click on "page2" and make sure the options are selected as shown</para>
- <figure id="dsn3">
- <title>DSN Options Page-2</title>
- <graphic align="center" scale="100" fileref="../images/dsnsetup3.png" />
- </figure>
- </listitem>
-
- <listitem><para> Click "save" and you can optionally click "test" to validate your
- connection if the Teiid is running.</para></listitem>
- </orderedlist>
- <para>You have configured a Teiid's virtual database as a data source for your ODBC applications. Now you can
- use applications such as Excel, Access to query the data in the VDB</para>
- </section>
-
- <section>
- <title>Other *nix Platform Installations</title>
- <para>Before you can access Teiid using ODBC on any *nix platforms, you need to either install a ODBC driver manager or verify
- that one already exists. As the ODBC Driver manager Teiid recommends <ulink url="http://www.unixodbc.org/">unixODBC</ulink>.
- If you are working with RedHat Linux or Fedora you can check the graphical "yum" installer to search, find and install unixODBC.
- Otherwise you can <ulink url="http://www.unixodbc.org/unixODBC-2.3.0.tar.gz">download</ulink> the unixODBC manager here.
- To install, simply untar the contents of the file to a temporary location and execute the following commands as super user.</para>
- <programlisting><![CDATA[
- ./configure
- make
- make install
- ]]></programlisting>
- <para>Check <ulink url="http://www.unixodbc.org/">unixODBC</ulink> website site for more information, if you
- run into any issues during the installation.</para>
-
- <para>Now, to o verify that PostgreSQL driver installed correctly from earlier step, execute the following command</para>
- <programlisting><![CDATA[
- odbcinst -q -d
- ]]></programlisting>
-
- <para>That should show you all the ODBC drivers installed in your system. Now it is time to create a DSN.
- Edit "/etc/odbc.ini" file and add the following </para>
-
- <programlisting><![CDATA[
- [<DSN name>]
- Driver = /usr/lib/psqlodbc.so
- Description = PostgreSQL Data Source
- Servername = <Teiid Host name or ip>
- Port = 35432
- Protocol = 7.4
- UserName = <user-name>
- Password = <password>
- Database = <vdb-name>
- ReadOnly = no
- ServerType = Postgres
- ConnSettings =
- UseServerSidePrepare=0
- ByteaAsLongVarBinary=1
- Optimizer=0
- Ksqo=0
- Trace = No
- TraceFile = /var/log/trace.log
- Debug = No
- DebugFile = /var/log/debug.log
- ]]></programlisting>
-
- <para>Note that you need "sudo" permissions to edit the "/etc/odbc.ini" file.
- For all the available configurable options that you can use in defining a DSN can be found <ulink url="http://psqlodbc.projects.postgresql.org/config.html">
- here</ulink> on postgreSQL ODBC page.</para>
-
- <para>Once you are done with defining the DSN, you can verify your DSN using the following command
- </para>
- <programlisting><![CDATA[
- isql <DSN-name> [<user-name> <password>] < commands.sql
- ]]></programlisting>
-
- <para>where "commands.sql" file contains the SQL commands you would like to execute.</para>
- </section>
-
- </section>
-
- <section>
- <title>DSN Less Connection</title>
- <para>You can also connect to Teiid VDB using ODBC with out explicitly creating a DSN. However, in these scenarios your
- application needs, what is called as "DSN less connection string". The below is a sample connection string </para>
-
- <para>For Windows:</para>
- <programlisting><![CDATA[
- ODBC;DRIVER={PostgreSQL Unicode};DATABASE=<vdb-name>;SERVER=<host-name>;PORT=<port>;Uid=<username>;Pwd=<password>
- ]]></programlisting>
-
- <para>>For *nix:</para>
- <programlisting><![CDATA[
- ODBC;DRIVER={PostgreSQL};DATABASE=<vdb-name>;SERVER=<host-name>;PORT=<port>;Uid=<username>;Pwd=<password>
- ]]></programlisting>
-
- </section>
-</chapter>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/odbc.xml (from rev 3218, trunk/documentation/client-developers-guide/src/main/docbook/en-US/content/odbc.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/odbc.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/odbc.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,254 @@
+<?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" [
+<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
+%CustomDTD;
+]>
+<chapter id="ODBC">
+ <title>ODBC Support</title>
+
+ <para>Open DataBase Connectivity (ODBC) is a standard database access method developed by the SQL Access group in 1992.
+ ODBC, just like JDBC in Java, allows consistent client access regardless of which database management
+ system (DBMS) is handling the data. ODBC uses a driver to translate the application's data queries
+ into commands that the DBMS understands. For this to work, both the application and the DBMS must be ODBC-compliant
+ -- that is, the application must be capable of issuing ODBC commands and the
+ DBMS must be capable of responding to them.</para>
+
+ <para>Teiid can provide ODBC access to deployed VDBs in the Teiid runtime through
+ <ulink url="http://www.postgresql.org/">PostgreSQL</ulink>'s ODBC driver.
+ This is possible because Teiid has specialized handling that allows it emulate a PostgreSQL server and respond appropriate to expected
+ metadata queries.</para>
+
+ <note><para>By default, ODBC on the Teiid is enabled and running on on port <emphasis>35432</emphasis>.</para></note>
+
+ <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>
+ <para>A PostgreSQL ODBC driver needed to make the ODBC connection to Teiid is <emphasis>not</emphasis>
+ bundled with the Teiid distribution. The appropriate driver needs be <ulink url="http://www.postgresql.org/ftp/odbc/versions/">downloaded</ulink>
+ directly from the PostgreSQL web site. We have tested with <emphasis>8.04.200</emphasis> version of the ODBC driver.</para>
+
+ <section>
+ <title>Microsoft Windows</title>
+ <orderedlist>
+ <listitem><para>Download the ODBC driver from <ulink url="http://wwwmaster.postgresql.org/download/mirrors-ftp/odbc/versions/msi/psqlodbc_08_04_0200.zip">
+ PostgreSQL download site</ulink>. If you are looking for 64-bit Windows driver download the driver from <ulink url="http://code.google.com/p/visionmap/wiki/psqlODBC">here</ulink>. </para></listitem>
+ <listitem><para>Extract the contents of the ZIP file into a temporary location on your system. For example: "c:\temp\pgodbc"</para></listitem>
+ <listitem><para>Double click on "psqlodbc.msi" file or (.exe file in the case of 64 bit) to start installation of the driver.</para></listitem>
+ <listitem>
+ <para>The Wizard appears as</para>
+ <figure id="step1">
+ <title>Welcome Screen </title>
+ <graphic align="center" scale="100" fileref="../images/winsetup1.png" />
+ </figure>
+ <para>Click "Next".</para>
+ </listitem>
+ <listitem>
+ <para>The next step of the wizard displays.</para>
+ <figure id="step2">
+ <title>End-User License Agreement </title>
+ <graphic align="center" scale="100" fileref="../images/winsetup2.png" />
+ </figure>
+ <para>Carefully read it, and check the "I accept the terms in the License Agreement",
+ if you are agreeing to the licensing terms. Then click "Next".</para>
+ </listitem>
+ <listitem>
+ <para>The next step of the wizard displays.</para>
+ <figure id="step3">
+ <title>Setup</title>
+ <graphic align="center" scale="100" fileref="../images/winsetup3.png" />
+ </figure>
+ <para>If you want to install in a different directory than the default that is already selected,
+ click the "Browse" button and select a directory.
+ Click "Next" to start installing in the selected directory.</para>
+ </listitem>
+ <listitem>
+ <para>The next step of the wizard displays.</para>
+ <figure id="step4">
+ <title>Confirm the Install</title>
+ <graphic align="center" scale="100" fileref="../images/winsetup4.png" />
+ </figure>
+ <para>This step summarizes the choices you have made in the wizard. Review this information.
+ If you need to change anything, you can use the Back button to return to previous steps.
+ Click "Install" to proceed.</para>
+ </listitem>
+ <listitem>
+ <para>1.The installation wizard copies the necessary files to the location
+ you specified. When it finishes, the following screen displays.</para>
+ <figure id="step5">
+ <title>Finish</title>
+ <graphic align="center" scale="100" fileref="../images/winsetup5.png" />
+ </figure>
+ <para>Click "Finish" to complete.</para>
+ </listitem>
+ </orderedlist>
+ </section>
+ <section>
+ <title>Other *nix Platform Installations</title>
+ <para>For all other platforms other than Microsoft Windows, the ODBC driver needs built from the
+ source files provided. Download the ODBC driver source files from
+ <ulink url="http://wwwmaster.postgresql.org/download/mirrors-ftp/odbc/versions/src/psqlodbc-08.04.0200.tar.gz">
+ the PostgreSQL download site</ulink>. Untar the files to a temporary location. For example: "~/tmp/pgodbc".
+ Build and install the driver by running the commands below.</para>
+ <note><para>You should use super user account or use "sudo" command for running the "make install" command. </para></note>
+ <programlisting><![CDATA[
+ % tar -zxvf psqlodbc-xx.xx.xxxx.tar.gz
+ % cd psqlodbc-xx.xx.xxxx
+ % ./configure
+ % make
+ % make install
+ ]]></programlisting>
+ <para>Some *nix distributions may already provide binary forms of the appropriate driver, which can be used as an alternative to
+ building from source.</para>
+ </section>
+ </section>
+
+ <section>
+ <title>Configuring the Data Source Name (DSN)</title>
+ <section>
+ <title>Windows Installation</title>
+ <para>Once you have installed the ODBC Driver Client software on your workstation, you have to
+ configure it to connect to a Teiid Runtime. Note that the following instructions are specific
+ to the Microsoft Windows Platform.</para>
+
+ <para>To do this, you must have logged into the workstation with administrative rights, and you
+ need to use the Control Panel’s <emphasis>Data Sources (ODBC)</emphasis> applet to add a new data source name.
+ </para>
+
+ <para>Each data source name you configure can only access one VDB within a Teiid System. To make more than
+ one VDB available, you need to configure more than one data source name.</para>
+
+ <para>Follow the below steps in creating a data source name (DSN)</para>
+ <orderedlist numeration="arabic">
+ <listitem><para>From the Start menu, select Settings > Control Panel.</para></listitem>
+ <listitem><para>The Control Panel displays. Double click <emphasis>Administrative Tools</emphasis>.</para></listitem>
+ <listitem><para>Then Double-click <emphasis>Data Sources (ODBC)</emphasis>.</para></listitem>
+ <listitem><para>The ODBC Data Source Administrator applet displays. Click the tab
+ associated with the type of DSN you want to add.</para></listitem>
+ <listitem><para>The Create New Data Source dialog box displays. In the Select a driver for which you
+ want to set up a data source table, select <emphasis>PostgreSQL Unicode</emphasis>.</para></listitem>
+ <listitem><para>Click Finish</para></listitem>
+ <listitem><para>The PostgreSQL ODBC DSN Setup dialog box displays.</para></listitem>
+
+ <listitem>
+ <figure id="dsn1">
+ <title>Main Screen</title>
+ <graphic align="center" scale="100" fileref="../images/dsnsetup1.png" />
+ </figure>
+ <para>In the <emphasis>Data Source</emphasis> Name edit box, type the name you want to assign to this data source.</para>
+ <para>In the <emphasis>Database</emphasis> edit box, type the name of the virtual database you want to access through this data source.</para>
+ <para>In the <emphasis>Server</emphasis> edit box, type the host name or IP address of your Teiid runtime. If connecting
+ via a firewall or NAT address, the firewall address or NAT address should be entered. </para>
+ <para>In the Port edit box, type the port number to which the Teiid System listens for ODBC requests. By default, Teiid
+ 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>Provide any description about the data source in the <emphasis>Description</emphasis> field.</para>
+ </listitem>
+
+ <listitem>
+ <para>Click on the <emphasis>Datasource</emphasis> button, you will see this below figure. Configure options as shown.</para>
+ <figure id="dsn2">
+ <title>DSN Options Page-1</title>
+ <graphic align="center" scale="100" fileref="../images/dsnsetup2.png" />
+ </figure>
+
+ <para>Click on "page2" and make sure the options are selected as shown</para>
+ <figure id="dsn3">
+ <title>DSN Options Page-2</title>
+ <graphic align="center" scale="100" fileref="../images/dsnsetup3.png" />
+ </figure>
+ </listitem>
+
+ <listitem><para> Click "save" and you can optionally click "test" to validate your
+ connection if the Teiid is running.</para></listitem>
+ </orderedlist>
+ <para>You have configured a Teiid's virtual database as a data source for your ODBC applications. Now you can
+ use applications such as Excel, Access to query the data in the VDB</para>
+ </section>
+
+ <section>
+ <title>Other *nix Platform Installations</title>
+ <para>Before you can access Teiid using ODBC on any *nix platforms, you need to either install a ODBC driver manager or verify
+ that one already exists. As the ODBC Driver manager Teiid recommends <ulink url="http://www.unixodbc.org/">unixODBC</ulink>.
+ If you are working with RedHat Linux or Fedora you can check the graphical "yum" installer to search, find and install unixODBC.
+ Otherwise you can <ulink url="http://www.unixodbc.org/unixODBC-2.3.0.tar.gz">download</ulink> the unixODBC manager here.
+ To install, simply untar the contents of the file to a temporary location and execute the following commands as super user.</para>
+ <programlisting><![CDATA[
+ ./configure
+ make
+ make install
+ ]]></programlisting>
+ <para>Check <ulink url="http://www.unixodbc.org/">unixODBC</ulink> website site for more information, if you
+ run into any issues during the installation.</para>
+
+ <para>Now, to o verify that PostgreSQL driver installed correctly from earlier step, execute the following command</para>
+ <programlisting><![CDATA[
+ odbcinst -q -d
+ ]]></programlisting>
+
+ <para>That should show you all the ODBC drivers installed in your system. Now it is time to create a DSN.
+ Edit "/etc/odbc.ini" file and add the following </para>
+
+ <programlisting><![CDATA[
+ [<DSN name>]
+ Driver = /usr/lib/psqlodbc.so
+ Description = PostgreSQL Data Source
+ Servername = <Teiid Host name or ip>
+ Port = 35432
+ Protocol = 7.4
+ UserName = <user-name>
+ Password = <password>
+ Database = <vdb-name>
+ ReadOnly = no
+ ServerType = Postgres
+ ConnSettings =
+ UseServerSidePrepare=0
+ ByteaAsLongVarBinary=1
+ Optimizer=0
+ Ksqo=0
+ Trace = No
+ TraceFile = /var/log/trace.log
+ Debug = No
+ DebugFile = /var/log/debug.log
+ ]]></programlisting>
+
+ <para>Note that you need "sudo" permissions to edit the "/etc/odbc.ini" file.
+ For all the available configurable options that you can use in defining a DSN can be found <ulink url="http://psqlodbc.projects.postgresql.org/config.html">
+ here</ulink> on postgreSQL ODBC page.</para>
+
+ <para>Once you are done with defining the DSN, you can verify your DSN using the following command
+ </para>
+ <programlisting><![CDATA[
+ isql <DSN-name> [<user-name> <password>] < commands.sql
+ ]]></programlisting>
+
+ <para>where "commands.sql" file contains the SQL commands you would like to execute.</para>
+ </section>
+
+ </section>
+
+ <section>
+ <title>DSN Less Connection</title>
+ <para>You can also connect to Teiid VDB using ODBC with out explicitly creating a DSN. However, in these scenarios your
+ application needs, what is called as "DSN less connection string". The below is a sample connection string </para>
+
+ <para>For Windows:</para>
+ <programlisting><![CDATA[
+ ODBC;DRIVER={PostgreSQL Unicode};DATABASE=<vdb-name>;SERVER=<host-name>;PORT=<port>;Uid=<username>;Pwd=<password>
+ ]]></programlisting>
+
+ <para>>For *nix:</para>
+ <programlisting><![CDATA[
+ ODBC;DRIVER={PostgreSQL};DATABASE=<vdb-name>;SERVER=<host-name>;PORT=<port>;Uid=<username>;Pwd=<password>
+ ]]></programlisting>
+
+ </section>
+</chapter>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/ssl.xml
===================================================================
--- trunk/documentation/client-developers-guide/src/main/docbook/en-US/content/ssl.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/ssl.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,190 +0,0 @@
-<?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" [
-<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
-%CustomDTD;
-]>
-<chapter id="ssl">
- <title>SSL Client Connections</title>
-
- <para>This chapter will shows you various security configurations
- that can be used with Teiid in securing your data access. Note that data level
- security called as "data roles" are explained in Reference Guide. This chapter pertains to transport level security.</para>
-
- <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
- 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>
- </section>
-
- <section id="ssl_modes">
- <title>SSL Modes</title>
- <para>Teiid supports SSL based channel between the client JDBC application and Teiid Server. Teiid supports the following
- SSL modes.</para>
- <orderedlist>
- <listitem><para>Anonymous – No certificates are required, but all communications are still
- encrypted using the TLS_DH_anon_WITH_AES_128_CBC_SHA SSL suite.</para></listitem>
- <listitem><para>1-way – Only authenticates the server to the client traffic. Requires a private key keystore to be created
- for the server and a truststore at the client that authenticates that key. The SSL suite is negotiated.</para></listitem>
- <listitem><para>2-way – Mutual client and server authentication. The server and client applications
- each have a keystore for their private keys and each has a truststore that authenticates the other.</para></listitem>
- </orderedlist>
-
- <para>Depending upon the SSL mode, follow the guidelines of your organization around creating/obtaining
- private keys. If you have no organizational requirements, then follow this guide to create
- <link linkend="appendix-selfcerts">self-signed certificates</link> with their respective keystores and truststores.</para>
- <para>The following keystore and truststore combinations are required for different SSL modes. The names of
- the files can be chosen by the user. The following files are shown for example purposes only.</para>
-
- <para><emphasis>1-way</emphasis> </para>
- <orderedlist>
- <listitem><para>server.keystore - has server's private key</para></listitem>
- <listitem><para>server.truststore - has server's public key</para></listitem>
- </orderedlist>
-
- <para><emphasis>2-way</emphasis> </para>
- <orderedlist>
- <listitem><para>server.keystore - has server's private key</para></listitem>
- <listitem><para>server.truststore - has server's public key</para></listitem>
- <listitem><para>client.keystore - client's private key</para></listitem>
- <listitem><para>client.truststore - has client's public key</para></listitem>
- </orderedlist>
- </section>
-
- <section id="configure_client">
- <title>Client SSL Settings</title>
- <para>The
- following sections define the properties required for each SSL mode. Note that when
- connecting to Teiid Server with SSL enabled, you <emphasis>MUST</emphasis> use
- the <emphasis>"mms"</emphasis> protocol, instead of "mm" in the JDBC connection URL, for example</para>
-
- <para>jdbc:teiid:<myVdb>@<emphasis>mms</emphasis>://<host>:<port></para>
-
- <para>There are two different sets of properties that a client can configure to enable 1-way or 2-way SSL.</para>
-
- <section>
- <title>Option 1: Java SSL properties</title>
- <para>These are standard Java defined system properties to configure the SSL under any JVM, Teiid is not
- unique in its use of SSL. Provide the following system properties to the client VM process.</para>
-
- <example>
- <title>1-way SSL</title>
- <programlisting><![CDATA[-Djavax.net.ssl.trustStore=<dir>/server.truststore (required)
--Djavax.net.ssl.trustStorePassword=<password> (optional)
--Djavax.net.ssl.keyStoreType (optional)]]></programlisting>
- </example>
-
- <example>
- <title>2-way SSL</title>
- <programlisting><![CDATA[-Djavax.net.ssl.keyStore=<dir>/client.keystore (required)
--Djavax.net.ssl.keyStrorePassword=<password> (optional)
--Djavax.net.ssl.trustStore=<dir>/server.truststore (required)
--Djavax.net.ssl.trustStorePassword=<password> (optioanl)
--Djavax.net.ssl.keyStroreType=<keystore type> (optional)]]></programlisting>
- </example>
- </section>
-
- <section>
- <title>Option 2: Teiid Specific Properties</title>
- <para>Use this option for <emphasis>anonymous</emphasis> mode or when the above "javax" based properties
- are already in use by the host process. For example if your client application is a Tomcat
- process that is configured for https protocol and the above Java based properties are
- already in use, and importing Teiid-specific certificate keys into those https
- certificate keystores is not allowed.</para>
-
- <para>In this scenario, a different set of Teiid-specific SSL properties can be set as system properties or defined inside
- the "teiid-client-settings.properties" file. The "teiid-client-settings.properties" file
- can be found inside the "teiid-&versionNumber;-client.jar" file at the root.
- Extract this file, or make a copy, change the property values required for the chosen SSL mode,
- and place this file in the client application's classpath before
- the "teiid-&versionNumber;-client.jar" file.</para>
-
- <para>SSL properties and definitions inside the "teiid-client-settings.properties" are shown below.</para>
-
- <programlisting><![CDATA[########################################
-# SSL Settings
-########################################
-
-#
-# The key store type. Defaults to JKS
-#
-
-org.teiid.ssl.keyStoreType=JKS
-
-#
-# The key store algorithm, defaults to
-# the system property "ssl.TrustManagerFactory.algorithm"
-#
-
-#org.teiid.ssl.algorithm=
-
-#
-# The classpath or filesystem location of the
-# key store.
-#
-# This property is required only if performing 2-way
-# authentication that requires a specific private
-# key.
-#
-
-#org.teiid.ssl.keyStore=
-
-#
-# The key store password (not required)
-#
-
-#org.teiid.ssl.keyStorePassword=
-
-#
-# The classpath or filesystem location of the
-# trust store.
-#
-# This property is required if performing 1-way
-# authentication that requires trust not provided
-# by the system defaults.
-#
-
-#org.teiid.ssl.trustStore=
-
-#
-# The trust store password (not required)
-#
-
-#org.teiid.ssl.trustStorePassword=
-
-#
-# The cipher protocol, defaults to SSLv3
-#
-
-org.teiid.ssl.protocol=SSLv3
-
-#
-# Whether to allow anonymous SSL
-# (the TLS_DH_anon_WITH_AES_128_CBC_SHA cipher suite)
-# defaults to true
-#
-
-org.teiid.ssl.allowAnon=true]]></programlisting>
-
- <example>
- <title>1-way SSL</title>
- <programlisting><![CDATA[org.teiid.ssl.trustStore=<dir>/server.truststore (required)]]></programlisting>
- </example>
-
- <example>
- <title>2-way SSL</title>
- <programlisting><![CDATA[org.teiid.ssl.keyStore=<dir>/client.keystore (required)
-org.teiid.ssl.trustStore=<dir>/server.truststore (required)]]></programlisting>
- </example>
- <example>
- <title>Anonymous</title>
- <programlisting><![CDATA[org.teiid.ssl.trustStore=NONE]]></programlisting>
- </example>
- </section>
- </section>
-</chapter>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/ssl.xml (from rev 3218, trunk/documentation/client-developers-guide/src/main/docbook/en-US/content/ssl.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/ssl.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/client-developers-guide/src/main/docbook/en-US/content/ssl.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,190 @@
+<?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" [
+<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
+%CustomDTD;
+]>
+<chapter id="ssl">
+ <title>SSL Client Connections</title>
+
+ <para>This chapter will shows you various security configurations
+ that can be used with Teiid in securing your data access. Note that data level
+ security called as "data roles" are explained in Reference Guide. This chapter pertains to transport level security.</para>
+
+ <section id="default_security">
+ <title>Default Security</title>
+
+ <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">
+ <title>SSL Modes</title>
+ <para>Teiid supports SSL based channel between the client JDBC application and Teiid Server. Teiid supports the following
+ SSL modes.</para>
+ <orderedlist>
+ <listitem><para>Anonymous – No certificates are required, but all communications are still
+ encrypted using the TLS_DH_anon_WITH_AES_128_CBC_SHA SSL suite.</para></listitem>
+ <listitem><para>1-way – Only authenticates the server to the client traffic. Requires a private key keystore to be created
+ for the server and a truststore at the client that authenticates that key. The SSL suite is negotiated.</para></listitem>
+ <listitem><para>2-way – Mutual client and server authentication. The server and client applications
+ each have a keystore for their private keys and each has a truststore that authenticates the other.</para></listitem>
+ </orderedlist>
+
+ <para>Depending upon the SSL mode, follow the guidelines of your organization around creating/obtaining
+ private keys. If you have no organizational requirements, then follow this guide to create
+ <link linkend="appendix-selfcerts">self-signed certificates</link> with their respective keystores and truststores.</para>
+ <para>The following keystore and truststore combinations are required for different SSL modes. The names of
+ the files can be chosen by the user. The following files are shown for example purposes only.</para>
+
+ <para><emphasis>1-way</emphasis> </para>
+ <orderedlist>
+ <listitem><para>server.keystore - has server's private key</para></listitem>
+ <listitem><para>server.truststore - has server's public key</para></listitem>
+ </orderedlist>
+
+ <para><emphasis>2-way</emphasis> </para>
+ <orderedlist>
+ <listitem><para>server.keystore - has server's private key</para></listitem>
+ <listitem><para>server.truststore - has server's public key</para></listitem>
+ <listitem><para>client.keystore - client's private key</para></listitem>
+ <listitem><para>client.truststore - has client's public key</para></listitem>
+ </orderedlist>
+ </section>
+
+ <section id="configure_client">
+ <title>Client SSL Settings</title>
+ <para>The
+ following sections define the properties required for each SSL mode. Note that when
+ connecting to Teiid Server with SSL enabled, you <emphasis>MUST</emphasis> use
+ the <emphasis>"mms"</emphasis> protocol, instead of "mm" in the JDBC connection URL, for example</para>
+
+ <para>jdbc:teiid:<myVdb>@<emphasis>mms</emphasis>://<host>:<port></para>
+
+ <para>There are two different sets of properties that a client can configure to enable 1-way or 2-way SSL.</para>
+
+ <section>
+ <title>Option 1: Java SSL properties</title>
+ <para>These are standard Java defined system properties to configure the SSL under any JVM, Teiid is not
+ unique in its use of SSL. Provide the following system properties to the client VM process.</para>
+
+ <example>
+ <title>1-way SSL</title>
+ <programlisting><![CDATA[-Djavax.net.ssl.trustStore=<dir>/server.truststore (required)
+-Djavax.net.ssl.trustStorePassword=<password> (optional)
+-Djavax.net.ssl.keyStoreType (optional)]]></programlisting>
+ </example>
+
+ <example>
+ <title>2-way SSL</title>
+ <programlisting><![CDATA[-Djavax.net.ssl.keyStore=<dir>/client.keystore (required)
+-Djavax.net.ssl.keyStrorePassword=<password> (optional)
+-Djavax.net.ssl.trustStore=<dir>/server.truststore (required)
+-Djavax.net.ssl.trustStorePassword=<password> (optioanl)
+-Djavax.net.ssl.keyStroreType=<keystore type> (optional)]]></programlisting>
+ </example>
+ </section>
+
+ <section>
+ <title>Option 2: Teiid Specific Properties</title>
+ <para>Use this option for <emphasis>anonymous</emphasis> mode or when the above "javax" based properties
+ are already in use by the host process. For example if your client application is a Tomcat
+ process that is configured for https protocol and the above Java based properties are
+ already in use, and importing Teiid-specific certificate keys into those https
+ certificate keystores is not allowed.</para>
+
+ <para>In this scenario, a different set of Teiid-specific SSL properties can be set as system properties or defined inside
+ the "teiid-client-settings.properties" file. The "teiid-client-settings.properties" file
+ can be found inside the "teiid-&versionNumber;-client.jar" file at the root.
+ Extract this file, or make a copy, change the property values required for the chosen SSL mode,
+ and place this file in the client application's classpath before
+ the "teiid-&versionNumber;-client.jar" file.</para>
+
+ <para>SSL properties and definitions inside the "teiid-client-settings.properties" are shown below.</para>
+
+ <programlisting><![CDATA[########################################
+# SSL Settings
+########################################
+
+#
+# The key store type. Defaults to JKS
+#
+
+org.teiid.ssl.keyStoreType=JKS
+
+#
+# The key store algorithm, defaults to
+# the system property "ssl.TrustManagerFactory.algorithm"
+#
+
+#org.teiid.ssl.algorithm=
+
+#
+# The classpath or filesystem location of the
+# key store.
+#
+# This property is required only if performing 2-way
+# authentication that requires a specific private
+# key.
+#
+
+#org.teiid.ssl.keyStore=
+
+#
+# The key store password (not required)
+#
+
+#org.teiid.ssl.keyStorePassword=
+
+#
+# The classpath or filesystem location of the
+# trust store.
+#
+# This property is required if performing 1-way
+# authentication that requires trust not provided
+# by the system defaults.
+#
+
+#org.teiid.ssl.trustStore=
+
+#
+# The trust store password (not required)
+#
+
+#org.teiid.ssl.trustStorePassword=
+
+#
+# The cipher protocol, defaults to SSLv3
+#
+
+org.teiid.ssl.protocol=SSLv3
+
+#
+# Whether to allow anonymous SSL
+# (the TLS_DH_anon_WITH_AES_128_CBC_SHA cipher suite)
+# defaults to true
+#
+
+org.teiid.ssl.allowAnon=true]]></programlisting>
+
+ <example>
+ <title>1-way SSL</title>
+ <programlisting><![CDATA[org.teiid.ssl.trustStore=<dir>/server.truststore (required)]]></programlisting>
+ </example>
+
+ <example>
+ <title>2-way SSL</title>
+ <programlisting><![CDATA[org.teiid.ssl.keyStore=<dir>/client.keystore (required)
+org.teiid.ssl.trustStore=<dir>/server.truststore (required)]]></programlisting>
+ </example>
+ <example>
+ <title>Anonymous</title>
+ <programlisting><![CDATA[org.teiid.ssl.trustStore=NONE]]></programlisting>
+ </example>
+ </section>
+ </section>
+</chapter>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/pom.xml
===================================================================
--- trunk/documentation/developer-guide/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,77 +0,0 @@
-<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/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>documentation</artifactId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>developer-guide</artifactId>
- <groupId>org.jboss.teiid.documentation</groupId>
- <packaging>jdocbook</packaging>
- <name>Developer's Guide</name>
- <description>The Teiid Developer's Guide</description>
- <build>
- <plugins>
- <plugin>
- <groupId>org.jboss.maven.plugins</groupId>
- <artifactId>maven-jdocbook-plugin</artifactId>
- <version>2.1.2</version>
- <extensions>true</extensions>
- <dependencies>
- <dependency>
- <groupId>net.sf.docbook</groupId>
- <artifactId>docbook</artifactId>
- <version>1.74.0</version>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jbossorg-docbook-xslt</artifactId>
- <version>1.1.0</version>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jbossorg-jdocbook-style</artifactId>
- <version>1.1.0</version>
- <type>jdocbook-style</type>
- </dependency>
- </dependencies>
- <configuration>
- <sourceDocumentName>Developer_Guide.xml</sourceDocumentName>
- <imageResource>
- <directory>${basedir}/src/main/docbook/en-US</directory>
- <excludes>
- <exclude>*.xml</exclude>
- <exclude>**/*.xml</exclude>
- <exclude>*.zargo</exclude>
- <exclude>**/*.zargo</exclude>
- </excludes>
- </imageResource>
- <formats>
- <format>
- <formatName>pdf</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
- <finalName>teiid_developer_guide.pdf</finalName>
- </format>
- <format>
- <formatName>html_single</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
- <finalName>index.html</finalName>
- </format>
- <format>
- <formatName>html</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
- <finalName>index.html</finalName>
- </format>
- </formats>
- <options>
- <xincludeSupported>true</xincludeSupported>
- <xmlTransformerType>saxon</xmlTransformerType>
- <docbookVersion>1.72.0</docbookVersion>
- <localeSeparator>-</localeSeparator>
- <useRelativeImageUris>false</useRelativeImageUris>
- </options>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/pom.xml (from rev 3220, trunk/documentation/developer-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,77 @@
+<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/xsd/maven-4.0.0.xsd">
+ <parent>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>documentation</artifactId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>developer-guide</artifactId>
+ <groupId>org.jboss.teiid.documentation</groupId>
+ <packaging>jdocbook</packaging>
+ <name>Developer's Guide</name>
+ <description>The Teiid Developer's Guide</description>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.jboss.maven.plugins</groupId>
+ <artifactId>maven-jdocbook-plugin</artifactId>
+ <version>2.1.2</version>
+ <extensions>true</extensions>
+ <dependencies>
+ <dependency>
+ <groupId>net.sf.docbook</groupId>
+ <artifactId>docbook</artifactId>
+ <version>1.74.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jbossorg-docbook-xslt</artifactId>
+ <version>1.1.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jbossorg-jdocbook-style</artifactId>
+ <version>1.1.0</version>
+ <type>jdocbook-style</type>
+ </dependency>
+ </dependencies>
+ <configuration>
+ <sourceDocumentName>Developer_Guide.xml</sourceDocumentName>
+ <imageResource>
+ <directory>${basedir}/src/main/docbook/en-US</directory>
+ <excludes>
+ <exclude>*.xml</exclude>
+ <exclude>**/*.xml</exclude>
+ <exclude>*.zargo</exclude>
+ <exclude>**/*.zargo</exclude>
+ </excludes>
+ </imageResource>
+ <formats>
+ <format>
+ <formatName>pdf</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
+ <finalName>teiid_developer_guide.pdf</finalName>
+ </format>
+ <format>
+ <formatName>html_single</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ <format>
+ <formatName>html</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ </formats>
+ <options>
+ <xincludeSupported>true</xincludeSupported>
+ <xmlTransformerType>saxon</xmlTransformerType>
+ <docbookVersion>1.72.0</docbookVersion>
+ <localeSeparator>-</localeSeparator>
+ <useRelativeImageUris>false</useRelativeImageUris>
+ </options>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/logging.xml
===================================================================
--- trunk/documentation/developer-guide/src/main/docbook/en-US/content/logging.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/logging.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,51 +0,0 @@
-<?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" [
-<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
-%CustomDTD;
-]>
-<chapter id="logging">
- <title>Logging</title>
- <section id="custom_logging">
- <title>Customized Logging</title>
- <para>
- The Teiid system provides a wealth of information using logging. To control logging level,
- contexts, and log locations, you should be familiar with log4j and the container's
- <filename>jboss-log4j.xml</filename> configuration file. Teiid also provides a
- <filename><replaceable>PROFILE</replaceable>/conf/jboss-teiid-log4j.xml</filename> containing
- much of information from this chapter. Refer to the Administrator Guide for more details about
- different Teiid contexts available. Refer to <ulink url="http://logging.apache.org/log4j/"/>
- for more information about log4j.
- </para>
-
- <para>
- If the default log4j logging mechanisms are not sufficient for your
- logging needs you may need a different appender, refer to the log4j javadocs at
- <ulink url="http://logging.apache.org/log4j/1.2/apidocs/index.html"/>.
- Note that log4j already provides quite a few appenders including JMS, RDBMS, and SMTP.
- </para>
- <para>If you want a custom appender, follow the Log4J directions to write a custom appender. Refer to
- the instructions at <ulink url="http://logging.apache.org/log4net/release/faq.html"/>. If you develop a custom
- logging solution, the implementation jar should be placed in the "lib" directory of the JBoss AS server profile
- Teiid is installed in.
- </para>
-
- <section>
- <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.
- </para>
- </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>
- </section>
- </section>
-</chapter>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/logging.xml (from rev 3218, trunk/documentation/developer-guide/src/main/docbook/en-US/content/logging.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/logging.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/logging.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,99 @@
+<?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" [
+<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
+%CustomDTD;
+]>
+<chapter id="logging">
+ <title>Logging</title>
+ <section id="custom_logging">
+ <title>Customized Logging</title>
+ <para>
+ The Teiid system provides a wealth of information using logging. To control logging level,
+ contexts, and log locations, you should be familiar with log4j and the container's
+ <filename>jboss-log4j.xml</filename> configuration file. Teiid also provides a
+ <filename><replaceable>PROFILE</replaceable>/conf/jboss-teiid-log4j.xml</filename> containing
+ much of information from this chapter. Refer to the Administrator Guide for more details about
+ different Teiid contexts available. Refer to <ulink url="http://logging.apache.org/log4j/"/>
+ for more information about log4j.
+ </para>
+
+ <para>
+ If the default log4j logging mechanisms are not sufficient for your
+ logging needs you may need a different appender, refer to the log4j javadocs at
+ <ulink url="http://logging.apache.org/log4j/1.2/apidocs/index.html"/>.
+ Note that log4j already provides quite a few appenders including JMS, RDBMS, and SMTP.
+ </para>
+ <para>If you want a custom appender, follow the Log4J directions to write a custom appender. Refer to
+ the instructions at <ulink url="http://logging.apache.org/log4net/release/faq.html"/>. If you develop a custom
+ logging solution, the implementation jar should be placed in the "lib" directory of the JBoss AS server profile
+ Teiid is installed in.
+ </para>
+
+ <section>
+ <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, 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 "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
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/udf.xml
===================================================================
--- trunk/documentation/developer-guide/src/main/docbook/en-US/content/udf.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/udf.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,247 +0,0 @@
-<?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="udfs">
- <title>User Defined Functions</title>
- <para>If you need to extends Teiid's scalar function library,
- then Teiid provides a means to define custom scalar functions or
- User Defined Functions(UDF). The following steps need to be taken in
- creating a UDF.</para>
- <section id="define_udf">
- <title>UDF Definition</title>
- <para>A {FunctionDefinition}.xmi file provides metadata to the query engine on User Defined Functions.
- See the Designer Documentation for more on creating a Function Definition Model.</para>
- <itemizedlist>
- <para>The following are used to define a UDF.</para>
- <listitem>
- <para>
- <emphasis>Function Name</emphasis>
- When you create the function name, keep these requirements in
- mind:
- <itemizedlist>
- <listitem>
- <para>You cannot overload existing Teiid System functions.</para>
- </listitem>
- <listitem>
- <para>The function name must be unique among user-defined
- functions in its model for the number of arguments. You can use the
- same function name for different numbers of types of
- arguments. Hence, you can overload your user-defined
- functions.</para>
- </listitem>
- <listitem>
- <para>The function name cannot contain the '.' character.</para>
- </listitem>
- <listitem>
- <para>The function name cannot exceed 255 characters.
- </para>
- </listitem>
- </itemizedlist>
- </para>
- </listitem>
- <listitem>
- <para>
- <emphasis>Input Parameters</emphasis>
- - defines a type specific signature list. All arguments are
- considered required.
- </para>
- </listitem>
- <listitem>
- <para>
- <emphasis>Return Type</emphasis>
- - the expected type of the returned scalar value.
- </para>
- </listitem>
- <listitem>
- <para>
- <emphasis>Pushdown</emphasis>
- - can be one of REQUIRED, NEVER, ALLOWED. Indicates the expected
- pushdown behavior. If NEVER or ALLOWED are specified then a Java
- implementation of the function should be supplied. If REQUIRED is used, then user must extend the
- Translator for the source and add this function to its pushdown function library.
- </para>
- </listitem>
- <listitem>
- <para>
- <emphasis>invocationClass/invocationMethod
- </emphasis>
- - optional properties indicating the static method to invoke when
- the UDF is not pushed down.
- </para>
- </listitem>
- <listitem>
- <para>
- <emphasis>Deterministic</emphasis>
- - if the method will always return the same result for the same
- input parameters.
- </para>
- </listitem>
- </itemizedlist>
- <para>Even pushdown required functions need to be added as a UDF to allow
- Teiid to properly parse and resolve the function. Pushdown scalar functions differ from normal user-defined functions in that no code is provided for evaluation in the engine.
- An exception will be raised if a pushdown required function cannot be evaluated by the appropriate source.</para>
-
- <note>
- <title>Dynamic VDBs</title>
- <para>Currently there is no provision to add UDF when you are working with the Dynamic VDBs. However, you can
- extend the Translator to define source pushdown functions.</para>
- </note>
- </section>
- <section>
- <title>Source Supported UDF</title>
- <para>While Teiid provides an extensive scalar function
- library, it contains only those functions that can be evaluated
- within the query engine. In many circumstances, especially for
- performance, a user defined function allows for calling a source
- specific function.</para>
-
- <para>For example, suppose you want to use the Oracle-specific
- functions score and contains:
- </para>
- <informalexample>
- <programlisting language="SQL">SELECT score(1), ID, FREEDATA FROM Docs WHERE contains(freedata, 'nick', 1) > 0</programlisting>
- </informalexample>
- <para>
- The
- <function>score</function>
- and
- <function>contains</function>
- functions are not part of built-in scalar function library. While
- you could write your own custom scalar function to mimic their
- behavior, it's more likely that you would want to use the actual
- Oracle functions that are provided by Oracle when using the Oracle
- Free Text functionality.
- </para>
- <para>
- In addition to the normal steps outlined in the section to create and
- install a function model (FunctionDefinitions.xmi), you will need to
- extend the appropriate connector(s).
- </para>
- <itemizedlist>
- <para>For example, to extend the Oracle Connector</para>
- <listitem>
- <para>
- <emphasis>Required</emphasis>
- - extend the OracleExecutionFactory and add SCORE and CONTAINS as
- supported pushdown functions by either overriding or adding additional functions in "getPushDownFunctions" method.
- For this example, we'll call the class MyOracleExecutionFactory. Add the
- <code>org.teiid.translator.Translator</code>
- annotation to the class, e.g.
- <code>@Translator(name="myoracle")</code>
- </para>
- </listitem>
- <listitem>
- <para>Optionally register new FunctionModifiers on the start of the
- ExecutionFactory to handle translation of these functions. Given
- that the syntax of these functions is same as other typical
- functions, this probably isn't needed - the default translation
- should work.</para>
- </listitem>
- <listitem>
- <para>
- Create a new translator jar containing your custom
- ExecutionFactory. Refer to <xref linkend="translator_package"/> and
- <xref linkend="translator_deploy"/> for instructions on using the JAR file. Once this is extended
- translator is deployed in the Teiid Server, use "myoracle" as
- translator name instead of the "oracle" in your VDB's Oracle source configuration.
- </para>
- </listitem>
- </itemizedlist>
- </section>
- <section>
- <title>Non-pushdown Support for User-Defined Functions</title>
- <para>Non-pushdown support requires a Java function
- that matches the metadata supplied in the FunctionDefinitions.xmi
- file. You must create a Java method that contains the function’s
- logic. This Java method should accept the necessary arguments, which
- the Teiid System will pass to it at runtime, and function should
- return the calculated or altered value.</para>
- <section>
- <title>Java Code</title>
- <itemizedlist>
- <para>Code Requirements</para>
- <listitem>
- <para>The java class containing the function method must be defined
- public.
- </para>
- </listitem>
- <listitem>
- <para>The function method must be public and static.</para>
- </listitem>
- <listitem>
- <para>
- Number of input arguments and types must match the function metadata defined
- in <xref linkend="define_udf"/>.
- </para>
- </listitem>
- <listitem>
- <para>
- Any exception can be thrown, but Teiid will rethrow the exception
- as a
- <classname>FunctionExecutionException</classname>
- .
- </para>
- </listitem>
- </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>
- <example>
- <title>Sample code</title>
- <programlisting language="Java" role="JAVA"><![CDATA[package org.something;
-
-public class TempConv
-{
- /**
- * Converts the given Celsius temperature to Fahrenheit, and returns the
- * value.
- * @param doubleCelsiusTemp
- * @return Fahrenheit
- */
- public static Double celsiusToFahrenheit(Double doubleCelsiusTemp)
- {
- if (doubleCelsiusTemp == null)
- {
- return null;
- }
- return (doubleCelsiusTemp)*9/5 + 32;
- }
-}]]></programlisting>
- </example>
- </section>
- <section>
- <title>Post Code Activities</title>
- <orderedlist>
- <listitem>
- <para> After coding the functions you should compile the Java
- code into a Java Archive (JAR) file.</para>
- </listitem>
- <listitem>
- <para>The JAR should be available in the classpath of Teiid - this
- could be the server profile lib, or the deployers/teiid.deployer
- directory depending upon your preference.</para>
- </listitem>
- </orderedlist>
- </section>
- </section>
- <section>
- <title>Installing user-defined functions</title>
- <para>
- Once a user-defined function model (FunctionDefinitions.xmi) has been
- created in in the Designer Tool, it can be added to the VDB for use
- by Teiid.</para>
- </section>
- <section>
- <title>User Defined Functions in Dynamic VDBs</title>
- <para>Dynamic VDBs do not use Designer generated artifacts, such as a FunctionDefinition.xmi file.
- Even with that limitation dynamic vdbs may still utilize UDFs through custom coding.
- The <code>ExecutionFactory.getMetadata</code> call allows for the definition of metadata via a <code>MetadataFactory.</code>
- Use the <code>MetadataFactory.addFunction</code> to add function for use only by that translator instance.
- Functions added directly to the source schema are specific to that schema - their fully qualified name will include the schema and the function can not be pushed to a different source.
- </para>
- <para>The <code>ExecutionFactory.getPushdownFunctions</code> method can be used to describe functions that are valid against all instances of a given translator type. The function names are expected to be
- prefixed by the translator type, or some other logical grouping, e.g. salesforce.includes. The full name of the function once imported into the system will qualified by the SYS schema, e.g. SYS.salesforce.includes.
- </para>
- <para>Any funcitons added via these mechanisms do not need to be declared in <code>ExecutionFactory.getSupportedFunctions.</code> Any of the additional handling, such as adding a <code>FunctionModifier</code>, covered above is also applicable here. All pushdown functions will have function name set to only the simple name. Schema or other qualification will be removed.
- Handling, such as function modifiers, can check the function metadata if there is the potential for an ambiguity.</para>
- </section>
-</chapter>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/udf.xml (from rev 3218, trunk/documentation/developer-guide/src/main/docbook/en-US/content/udf.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/udf.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/developer-guide/src/main/docbook/en-US/content/udf.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,264 @@
+<?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="udfs">
+ <title>User Defined Functions</title>
+ <para>If you need to extends Teiid's scalar function library,
+ then Teiid provides a means to define custom scalar functions or
+ User Defined Functions(UDF). The following steps need to be taken in
+ creating a UDF.</para>
+ <section id="define_udf">
+ <title>UDF Definition</title>
+ <para>A {FunctionDefinition}.xmi file provides metadata to the query engine on User Defined Functions.
+ See the Designer Documentation for more on creating a Function Definition Model.</para>
+ <itemizedlist>
+ <para>The following are used to define a UDF.</para>
+ <listitem>
+ <para>
+ <emphasis>Function Name</emphasis>
+ When you create the function name, keep these requirements in
+ mind:
+ <itemizedlist>
+ <listitem>
+ <para>You cannot overload existing Teiid System functions.</para>
+ </listitem>
+ <listitem>
+ <para>The function name must be unique among user-defined
+ functions in its model for the number of arguments. You can use the
+ same function name for different numbers of types of
+ arguments. Hence, you can overload your user-defined
+ functions.</para>
+ </listitem>
+ <listitem>
+ <para>The function name cannot contain the '.' character.</para>
+ </listitem>
+ <listitem>
+ <para>The function name cannot exceed 255 characters.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <emphasis>Input Parameters</emphasis>
+ - defines a type specific signature list. All arguments are
+ considered required.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <emphasis>Return Type</emphasis>
+ - the expected type of the returned scalar value.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <emphasis>Pushdown</emphasis>
+ - can be one of REQUIRED, NEVER, ALLOWED. Indicates the expected
+ pushdown behavior. If NEVER or ALLOWED are specified then a Java
+ implementation of the function should be supplied. If REQUIRED is used, then user must extend the
+ Translator for the source and add this function to its pushdown function library.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <emphasis>invocationClass/invocationMethod
+ </emphasis>
+ - optional properties indicating the static method to invoke when
+ the UDF is not pushed down.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <emphasis>Deterministic</emphasis>
+ - if the method will always return the same result for the same
+ input parameters.
+ </para>
+ </listitem>
+ </itemizedlist>
+ <para>Even pushdown required functions need to be added as a UDF to allow
+ Teiid to properly parse and resolve the function. Pushdown scalar functions differ from normal user-defined functions in that no code is provided for evaluation in the engine.
+ An exception will be raised if a pushdown required function cannot be evaluated by the appropriate source.</para>
+
+ <note>
+ <title>Dynamic VDBs</title>
+ <para>Currently there is no provision to add UDF when you are working with the Dynamic VDBs. However, you can
+ extend the Translator to define source pushdown functions.</para>
+ </note>
+ </section>
+ <section>
+ <title>Source Supported UDF</title>
+ <para>While Teiid provides an extensive scalar function
+ library, it contains only those functions that can be evaluated
+ within the query engine. In many circumstances, especially for
+ performance, a user defined function allows for calling a source
+ specific function.</para>
+
+ <para>For example, suppose you want to use the Oracle-specific
+ functions score and contains:
+ </para>
+ <informalexample>
+ <programlisting language="SQL">SELECT score(1), ID, FREEDATA FROM Docs WHERE contains(freedata, 'nick', 1) > 0</programlisting>
+ </informalexample>
+ <para>
+ The
+ <function>score</function>
+ and
+ <function>contains</function>
+ functions are not part of built-in scalar function library. While
+ you could write your own custom scalar function to mimic their
+ behavior, it's more likely that you would want to use the actual
+ Oracle functions that are provided by Oracle when using the Oracle
+ Free Text functionality.
+ </para>
+ <para>
+ In addition to the normal steps outlined in the section to create and
+ install a function model (FunctionDefinitions.xmi), you will need to
+ extend the appropriate connector(s).
+ </para>
+ <itemizedlist>
+ <para>For example, to extend the Oracle Connector</para>
+ <listitem>
+ <para>
+ <emphasis>Required</emphasis>
+ - extend the OracleExecutionFactory and add SCORE and CONTAINS as
+ supported pushdown functions by either overriding or adding additional functions in "getPushDownFunctions" method.
+ For this example, we'll call the class MyOracleExecutionFactory. Add the
+ <code>org.teiid.translator.Translator</code>
+ annotation to the class, e.g.
+ <code>@Translator(name="myoracle")</code>
+ </para>
+ </listitem>
+ <listitem>
+ <para>Optionally register new FunctionModifiers on the start of the
+ ExecutionFactory to handle translation of these functions. Given
+ that the syntax of these functions is same as other typical
+ functions, this probably isn't needed - the default translation
+ should work.</para>
+ </listitem>
+ <listitem>
+ <para>
+ Create a new translator jar containing your custom
+ ExecutionFactory. Refer to <xref linkend="translator_package"/> and
+ <xref linkend="translator_deploy"/> for instructions on using the JAR file. Once this is extended
+ translator is deployed in the Teiid Server, use "myoracle" as
+ translator name instead of the "oracle" in your VDB's Oracle source configuration.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </section>
+ <section>
+ <title>Non-pushdown Support for User-Defined Functions</title>
+ <para>Non-pushdown support requires a Java function
+ that matches the metadata supplied in the FunctionDefinitions.xmi
+ file. You must create a Java method that contains the function’s
+ logic. This Java method should accept the necessary arguments, which
+ the Teiid System will pass to it at runtime, and function should
+ return the calculated or altered value.</para>
+ <section>
+ <title>Java Code</title>
+ <itemizedlist>
+ <para>Code Requirements</para>
+ <listitem>
+ <para>The java class containing the function method must be defined
+ public. <note><para>As many UDF methods as you want can be declared on the same class.</para></note>
+ </para>
+ </listitem>
+ <listitem>
+ <para>The function method must be public and static.</para>
+ </listitem>
+ <listitem>
+ <para>
+ Number of input arguments and types must match the function metadata defined
+ in <xref linkend="define_udf"/>.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ Any exception can be thrown, but Teiid will rethrow the exception
+ as a
+ <classname>FunctionExecutionException</classname>
+ .
+ </para>
+ </listitem>
+ </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 should not be delared in the function metadata.</para>
+ <example>
+ <title>Sample code</title>
+ <programlisting language="Java" role="JAVA"><![CDATA[package org.something;
+
+public class TempConv
+{
+ /**
+ * Converts the given Celsius temperature to Fahrenheit, and returns the
+ * value.
+ * @param doubleCelsiusTemp
+ * @return Fahrenheit
+ */
+ public static Double celsiusToFahrenheit(Double doubleCelsiusTemp)
+ {
+ if (doubleCelsiusTemp == null)
+ {
+ return null;
+ }
+ return (doubleCelsiusTemp)*9/5 + 32;
+ }
+}]]></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>
+ <orderedlist>
+ <listitem>
+ <para> After coding the functions you should compile the Java
+ code into a Java Archive (JAR) file.</para>
+ </listitem>
+ <listitem>
+ <para>The JAR should be available in the classpath of Teiid - this
+ could be the server profile lib, or the deployers/teiid.deployer
+ directory depending upon your preference.</para>
+ </listitem>
+ </orderedlist>
+ </section>
+ </section>
+ <section>
+ <title>Installing user-defined functions</title>
+ <para>
+ Once a user-defined function model (FunctionDefinitions.xmi) has been
+ created in in the Designer Tool, it can be added to the VDB for use
+ by Teiid.</para>
+ </section>
+ <section>
+ <title>User Defined Functions in Dynamic VDBs</title>
+ <para>Dynamic VDBs do not use Designer generated artifacts, such as a FunctionDefinition.xmi file.
+ Even with that limitation dynamic vdbs may still utilize UDFs through custom coding.
+ The <code>ExecutionFactory.getMetadata</code> call allows for the definition of metadata via a <code>MetadataFactory.</code>
+ Use the <code>MetadataFactory.addFunction</code> to add function for use only by that translator instance.
+ Functions added directly to the source schema are specific to that schema - their fully qualified name will include the schema and the function can not be pushed to a different source.
+ </para>
+ <para>The <code>ExecutionFactory.getPushdownFunctions</code> method can be used to describe functions that are valid against all instances of a given translator type. The function names are expected to be
+ prefixed by the translator type, or some other logical grouping, e.g. salesforce.includes. The full name of the function once imported into the system will qualified by the SYS schema, e.g. SYS.salesforce.includes.
+ </para>
+ <para>Any funcitons added via these mechanisms do not need to be declared in <code>ExecutionFactory.getSupportedFunctions.</code> Any of the additional handling, such as adding a <code>FunctionModifier</code>, covered above is also applicable here. All pushdown functions will have function name set to only the simple name. Schema or other qualification will be removed.
+ Handling, such as function modifiers, can check the function metadata if there is the potential for an ambiguity.</para>
+ </section>
+</chapter>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/pom.xml
===================================================================
--- trunk/documentation/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,21 +0,0 @@
-<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>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>documentation</artifactId>
- <packaging>pom</packaging>
- <name>Documents</name>
- <description>Teiid Documentation Aggregator</description>
- <modules>
- <module>admin-guide</module>
- <module>reference</module>
- <module>developer-guide</module>
- <module>quick-start-example</module>
- <module>client-developers-guide</module>
- <module>caching-guide</module>
- </modules>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/pom.xml (from rev 3220, trunk/documentation/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,21 @@
+<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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>documentation</artifactId>
+ <packaging>pom</packaging>
+ <name>Documents</name>
+ <description>Teiid Documentation Aggregator</description>
+ <modules>
+ <module>admin-guide</module>
+ <module>reference</module>
+ <module>developer-guide</module>
+ <module>quick-start-example</module>
+ <module>client-developers-guide</module>
+ <module>caching-guide</module>
+ </modules>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/quick-start-example/pom.xml
===================================================================
--- trunk/documentation/quick-start-example/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/quick-start-example/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,77 +0,0 @@
-<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/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>documentation</artifactId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>quick-start-example</artifactId>
- <groupId>org.jboss.teiid.documentation</groupId>
- <packaging>jdocbook</packaging>
- <name>Quick Start Guide</name>
- <description>The Teiid Quick Start guide</description>
- <build>
- <plugins>
- <plugin>
- <groupId>org.jboss.maven.plugins</groupId>
- <artifactId>maven-jdocbook-plugin</artifactId>
- <version>2.1.2</version>
- <extensions>true</extensions>
- <dependencies>
- <dependency>
- <groupId>net.sf.docbook</groupId>
- <artifactId>docbook</artifactId>
- <version>1.74.0</version>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jbossorg-docbook-xslt</artifactId>
- <version>1.1.0</version>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jbossorg-jdocbook-style</artifactId>
- <version>1.1.0</version>
- <type>jdocbook-style</type>
- </dependency>
- </dependencies>
- <configuration>
- <sourceDocumentName>quick_start_example.xml</sourceDocumentName>
- <imageResource>
- <directory>${basedir}/src/main/docbook/en-US</directory>
- <excludes>
- <exclude>*.xml</exclude>
- <exclude>**/*.xml</exclude>
- <exclude>*.zargo</exclude>
- <exclude>**/*.zargo</exclude>
- </excludes>
- </imageResource>
- <formats>
- <format>
- <formatName>pdf</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
- <finalName>teiid_quick_start_example.pdf</finalName>
- </format>
- <format>
- <formatName>html_single</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
- <finalName>index.html</finalName>
- </format>
- <format>
- <formatName>html</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
- <finalName>index.html</finalName>
- </format>
- </formats>
- <options>
- <xincludeSupported>true</xincludeSupported>
- <xmlTransformerType>saxon</xmlTransformerType>
- <docbookVersion>1.72.0</docbookVersion>
- <localeSeparator>-</localeSeparator>
- <useRelativeImageUris>false</useRelativeImageUris>
- </options>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/quick-start-example/pom.xml (from rev 3220, trunk/documentation/quick-start-example/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/quick-start-example/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/quick-start-example/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,77 @@
+<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/xsd/maven-4.0.0.xsd">
+ <parent>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>documentation</artifactId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>quick-start-example</artifactId>
+ <groupId>org.jboss.teiid.documentation</groupId>
+ <packaging>jdocbook</packaging>
+ <name>Quick Start Guide</name>
+ <description>The Teiid Quick Start guide</description>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.jboss.maven.plugins</groupId>
+ <artifactId>maven-jdocbook-plugin</artifactId>
+ <version>2.1.2</version>
+ <extensions>true</extensions>
+ <dependencies>
+ <dependency>
+ <groupId>net.sf.docbook</groupId>
+ <artifactId>docbook</artifactId>
+ <version>1.74.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jbossorg-docbook-xslt</artifactId>
+ <version>1.1.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jbossorg-jdocbook-style</artifactId>
+ <version>1.1.0</version>
+ <type>jdocbook-style</type>
+ </dependency>
+ </dependencies>
+ <configuration>
+ <sourceDocumentName>quick_start_example.xml</sourceDocumentName>
+ <imageResource>
+ <directory>${basedir}/src/main/docbook/en-US</directory>
+ <excludes>
+ <exclude>*.xml</exclude>
+ <exclude>**/*.xml</exclude>
+ <exclude>*.zargo</exclude>
+ <exclude>**/*.zargo</exclude>
+ </excludes>
+ </imageResource>
+ <formats>
+ <format>
+ <formatName>pdf</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
+ <finalName>teiid_quick_start_example.pdf</finalName>
+ </format>
+ <format>
+ <formatName>html_single</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ <format>
+ <formatName>html</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ </formats>
+ <options>
+ <xincludeSupported>true</xincludeSupported>
+ <xmlTransformerType>saxon</xmlTransformerType>
+ <docbookVersion>1.72.0</docbookVersion>
+ <localeSeparator>-</localeSeparator>
+ <useRelativeImageUris>false</useRelativeImageUris>
+ </options>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/reference/pom.xml
===================================================================
--- trunk/documentation/reference/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/reference/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,77 +0,0 @@
-<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/xsd/maven-4.0.0.xsd">
- <parent>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>documentation</artifactId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>reference</artifactId>
- <groupId>org.jboss.teiid.documentation</groupId>
- <packaging>jdocbook</packaging>
- <name>Teiid Reference</name>
- <description>The Teiid reference manual</description>
- <build>
- <plugins>
- <plugin>
- <groupId>org.jboss.maven.plugins</groupId>
- <artifactId>maven-jdocbook-plugin</artifactId>
- <version>2.1.2</version>
- <extensions>true</extensions>
- <dependencies>
- <dependency>
- <groupId>net.sf.docbook</groupId>
- <artifactId>docbook</artifactId>
- <version>1.74.0</version>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jbossorg-docbook-xslt</artifactId>
- <version>1.1.0</version>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jbossorg-jdocbook-style</artifactId>
- <version>1.1.0</version>
- <type>jdocbook-style</type>
- </dependency>
- </dependencies>
- <configuration>
- <sourceDocumentName>Reference.xml</sourceDocumentName>
- <imageResource>
- <directory>${basedir}/src/main/docbook/en-US</directory>
- <excludes>
- <exclude>*.xml</exclude>
- <exclude>**/*.xml</exclude>
- <exclude>*.zargo</exclude>
- <exclude>**/*.zargo</exclude>
- </excludes>
- </imageResource>
- <formats>
- <format>
- <formatName>pdf</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
- <finalName>teiid_reference.pdf</finalName>
- </format>
- <format>
- <formatName>html_single</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
- <finalName>index.html</finalName>
- </format>
- <format>
- <formatName>html</formatName>
- <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
- <finalName>index.html</finalName>
- </format>
- </formats>
- <options>
- <xmlTransformerType>saxon</xmlTransformerType>
- <docbookVersion>1.72.0</docbookVersion>
- <xincludeSupported>true</xincludeSupported>
- <localeSeparator>-</localeSeparator>
- <useRelativeImageUris>false</useRelativeImageUris>
- </options>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/reference/pom.xml (from rev 3220, trunk/documentation/reference/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/reference/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/reference/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,77 @@
+<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/xsd/maven-4.0.0.xsd">
+ <parent>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>documentation</artifactId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>reference</artifactId>
+ <groupId>org.jboss.teiid.documentation</groupId>
+ <packaging>jdocbook</packaging>
+ <name>Teiid Reference</name>
+ <description>The Teiid reference manual</description>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.jboss.maven.plugins</groupId>
+ <artifactId>maven-jdocbook-plugin</artifactId>
+ <version>2.1.2</version>
+ <extensions>true</extensions>
+ <dependencies>
+ <dependency>
+ <groupId>net.sf.docbook</groupId>
+ <artifactId>docbook</artifactId>
+ <version>1.74.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jbossorg-docbook-xslt</artifactId>
+ <version>1.1.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jbossorg-jdocbook-style</artifactId>
+ <version>1.1.0</version>
+ <type>jdocbook-style</type>
+ </dependency>
+ </dependencies>
+ <configuration>
+ <sourceDocumentName>Reference.xml</sourceDocumentName>
+ <imageResource>
+ <directory>${basedir}/src/main/docbook/en-US</directory>
+ <excludes>
+ <exclude>*.xml</exclude>
+ <exclude>**/*.xml</exclude>
+ <exclude>*.zargo</exclude>
+ <exclude>**/*.zargo</exclude>
+ </excludes>
+ </imageResource>
+ <formats>
+ <format>
+ <formatName>pdf</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/pdf.xsl</stylesheetResource>
+ <finalName>teiid_reference.pdf</finalName>
+ </format>
+ <format>
+ <formatName>html_single</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/xhtml-single.xsl</stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ <format>
+ <formatName>html</formatName>
+ <stylesheetResource>classpath:/xslt/org/jboss/xhtml.xsl</stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ </formats>
+ <options>
+ <xmlTransformerType>saxon</xmlTransformerType>
+ <docbookVersion>1.72.0</docbookVersion>
+ <xincludeSupported>true</xincludeSupported>
+ <localeSeparator>-</localeSeparator>
+ <useRelativeImageUris>false</useRelativeImageUris>
+ </options>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/federated_planning.xml
===================================================================
--- trunk/documentation/reference/src/main/docbook/en-US/content/federated_planning.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/federated_planning.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1071 +0,0 @@
-<?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="federated_planning">
- <title>Federated Planning</title>
- <para>Teiid at its core is a federated relational query
- engine. This query engine allows you to treat all of your data
- sources as one virtual database and access them in a single SQL
- query. This allows you to focus on building your application, not on
- hand-coding joins, and other relational operations, between data
- sources.</para>
- <section>
- <title>Overview</title>
- <para>When the query engine receives an incoming SQL query it
- performs the following operations:</para>
- <orderedlist>
- <listitem>
- <para>Parsing - validate syntax and convert to internal
- form</para>
- </listitem>
- <listitem>
- <para>Resolving - link all identifiers to metadata and
- functions to the function library</para>
- </listitem>
- <listitem>
- <para>Validating - validate SQL semantics based on
- metadata references and type signatures</para>
- </listitem>
- <listitem>
- <para>Rewriting - rewrite SQL to simplify expressions
- and criteria</para>
- </listitem>
- <listitem>
- <para>
- Logical plan optimization - the rewritten canonical SQL is
- converted into a logical plan for in-depth optimization. The
- Teiid optimizer is predominantly rule-based. Based upon the
- query structure and hints a certain rule set will be applied.
- These rules may trigger in turn trigger the execution of more
- rules. Within several rules, Teiid also takes advantage of
- costing information. The logical plan optimization steps can
- be seen by using <link linkend="show_plan">SHOWPLAN DEBUG</link>
- clause and are described in the
- <link linkend="query_planner">query planner</link>
- section.
- </para>
- </listitem>
- <listitem>
- <para>
- Processing plan conversion - the logic plan is converted into
- an executable form where the nodes are representative of basic
- processing operations. The final processing plan is displayed
- as the
- <link linkend="query_plan">query plan</link>
- .
- </para>
- </listitem>
- </orderedlist>
- <para>
- The logical query plan is a tree of operations used to transform
- data in source tables to the expected result set. In the tree,
- data flows from the bottom (tables) to the top (output). The
- primary logical operations are
- <emphasis>select</emphasis>
- (select or filter rows based on a criteria),
- <emphasis>project</emphasis>
- (project or compute column values),
- <emphasis>join</emphasis>
- ,
- <emphasis>source</emphasis>
- (retrieve data from a table),
- <emphasis>sort</emphasis>
- (ORDER BY),
- <emphasis>duplicate removal</emphasis>
- (SELECT DISTINCT),
- <emphasis>group</emphasis>
- (GROUP BY), and
- <emphasis>union</emphasis>
- (UNION).
- </para>
- <para>For example, consider the following query that retrieves
- all engineering employees born since 1970.</para>
- <example>
- <title>Example query</title>
- <programlisting>SELECT e.title, e.lastname FROM Employees AS e JOIN
-Departments AS d ON e.dept_id = d.dept_id WHERE year(e.birthday) >= 1970 AND d.dept_name = 'Engineering'</programlisting>
- </example>
- <para>Logically, the data from the Employees and Departments
- tables are retrieved, then joined, then filtered as specified, and
- finally the output columns are projected. The canonical query plan
- thus looks like this:</para>
- <mediaobject>
- <imageobject>
- <imagedata fileref="../images/query_plan.png"/>
- </imageobject>
- </mediaobject>
- <para>Data flows from the tables at the bottom upwards through the
- join, through the select, and finally through the project to produce
- the final results. The data passed between each node is logically a
- result set with columns and rows.</para>
- <para>
- Of course, this is what happens
- <emphasis>logically</emphasis>
- , not how the plan is actually executed. Starting from this initial
- plan, the query planner performs transformations on the query plan
- tree to produce an equivalent plan that retrieves the same results
- faster. Both a federated query planner and a relational database
- planner deal with the same concepts and many of the same plan
- transformations. In this example, the criteria on the Departments
- and Employees tables will be pushed down the tree to filter the
- results as early as possible.
- </para>
- <para>In both cases, the goal is to retrieve the query results in
- the fastest possible time. However, the relational database planner
- does this primarily by optimizing the access paths in pulling data
- from storage.</para>
- <para>In contrast, a federated query planner is less concerned about
- storage access because it is typically pushing that burden to the
- data source. The most important consideration for a federated query
- planner is minimizing data transfer.</para>
- </section>
- <section>
- <title>Federated Optimizations</title>
- <section id="access_patterns">
- <title>Access Patterns</title>
- <para>
- Access patterns are used on both physical tables and views to
- specify the need for criteria against a set of columns. Failure to supply the criteria will
- result in a planning error, rather than a run-away source query. Access
- patterns can be applied in a set such that only one of the access
- patterns is required to be satisfied.</para>
- <para>Currently any form of criteria referencing an affected column may satisfy an access
- pattern.</para>
- </section>
- <section>
- <title>Pushdown</title>
- <para>In federated database systems pushdown refers to
- decomposing the user level query into source queries that
- perform as much work as possible on their respective source
- system. Pushdown analysis requires knowledge of source system
- capabilities, which is provided to Teiid though the Connector
- API. Any work not performed at the source is then processed in
- Federate's relational engine.</para>
- <para>
- Based upon capabilities, Teiid will manipulate the query plan
- to ensure that each source performs as much joining, filtering,
- grouping, etc. as possible. In may cases, such as with join
- ordering, planning is a combination of
- <link linkend="standard_relational_techniques">standard relational techniques</link>
- and, cost based and heuristics for pushdown optimization.
- </para>
- <para>
- Criteria and join push down are typically the most important
- aspects of the query to push down when performance is a concern.
- See
- <link linkend="query_plan">Query Plans</link>
- on how to read a plan to ensure that source queries are as
- efficient as possible.
- </para>
- </section>
- <section id="dependent_joins">
- <title>Dependent Joins</title>
- <para>A special optimization called a dependent join is used to
- reduce the rows returned from one of the two relations involved
- in a multi-source join. In a dependent join, queries are issued
- to each source sequentially rather than in parallel, with the
- results obtained from the first source used to restrict the
- records returned from the second. Dependent joins can perform
- some joins much faster by drastically reducing the amount of
- data retrieved from the second source and the number of join
- comparisons that must be performed.</para>
- <para> The conditions when a dependent join is used are determined
- 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
- <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.
- </para>
- <tip>
- <para> The MAKEDEP 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
- inefficient join structure and may result in many source
- queries.</para>
- </tip>
- <para>The engine will for IN clauses to filter the values coming from the dependent side.
- If the number of values from the independent side exceeds the translators MaxInCriteriaSize, the values will be split into multiple IN predicates up to MaxDependentPredicates.
- When the number of independent values exceeds MaxInCriteriaSize*MaxDependentPredicates, then multiple dependent queries will be issued in parallel.</para>
- </section>
- <section>
- <title>Copy Criteria</title>
- <para> Copy criteria is an optimization that creates additional
- predicates based upon combining join and where clause criteria.
- For example, equi-join predicates (source1.table.column =
- source2.table.column) are used to create new predicates by
- substituting source1.table.column for source2.table.column and
- vice versa. In a cross source scenario, this allows for where
- criteria applied to a single side of the join to be applied to
- both source queries</para>
- </section>
- <section>
- <title>Projection Minimization</title>
- <para> Teiid ensures that each pushdown query only projects the
- symbols required for processing the user query. This is
- especially helpful when querying through large intermediate view
- layers.</para>
- </section>
- <section id="aggregate_pushdown">
- <title>Partial Aggregate Pushdown</title>
- <para> Partial aggregate pushdown allows for grouping operations
- above multi-source joins and unions to be decomposed so that some of the
- grouping and aggregate functions may be pushed down to the
- sources.</para>
- </section>
- <section id="optional_join">
- <title>Optional Join</title>
- <para>The optional join hint indicates to the
- optimizer that a joined table should be omitted if none of its
- columns are used by the output of the user query or in a meaningful way to construct the results of the user query. This hint is typically only used in view layers
- containing multi-source joins.</para>
- <para>
- The optional join hint is applied as a comment on a join clause. It can be applied in both ANSI and non-ANSI joins. With non-ANSI joins an entire joined table may be marked as optional.
- <example>
- <title>Example Optional Join Hint</title>
- <programlisting language="SQL">select a.column1, b.column2 from a, /*+ optional */ b WHERE a.key = b.key</programlisting>
- <para>Suppose this example defines a view layer X.
- If X is queried in such a way as to not need b.column2, then the
- optional join hint will cause b to be omitted from the query
- plan. The result would be the same as if X were defined as:
- </para>
- <programlisting language="SQL">select a.column1 from a</programlisting>
- </example>
- <example>
- <title>Example ANSI Optional Join Hint</title>
- <programlisting>select a.column1, b.column2, c.column3 from /*+ optional */ (a inner join b ON a.key = b.key) INNER JOIN c ON a.key = c.key</programlisting>
- <para>In this example the ANSI join syntax allows for the join of a and b to be marked as optional. Suppose this example defines a view layer X. Only if both column a.column1 and b.column2 are not needed, e.g. "SELECT column3 FROM X" will the join be removed.</para>
- </example>
- </para>
- <para>
- The optional join hint will not remove a bridging table that is still required.
- <example>
- <title>Example Briding Table</title>
- <programlisting language="SQL">select a.column1, b.column2, c.column3 from /*+ optional */ a, b, c WHERE ON a.key = b.key AND a.key = c.key</programlisting>
- <para>Suppose this example defines a view layer X. If b.column2 or c.column3 are solely required by a query to X, then the join on a be removed.
- However if a.column1 or both b.column2 and c.column3 are needed, then the optional join hint will not take effect.</para>
- </example>
- </para>
- <tip>
- <para>When a join clause is omitted via the optional join hint, the relevant criteria
- is not applied. Thus it is possible that the query results may
- not have the same cardinality or even the same row values as
- when the join is fully applied.</para>
- <para>Left/right outer joins where the inner side values are not used
- and whose rows under go a distinct operation will automatically be
- treated as an optional join and do not require a hint.
- <example>
- <title>Example Unnecessary Optional Join Hint</title>
- <programlisting language="SQL">select a.column1, b.column2 from a LEFT OUTER JOIN /*+optional*/ b ON a.key = b.key</programlisting>
- </example>
- </para>
- </tip>
- <warning><para>
- A simple "SELECT COUNT(*) FROM VIEW" against a view where all join tables are marked as optional will not return a meaningful result.
- </para>
- </warning>
- </section>
- <section id="partitioned_union">
- <title>Partitioned Union</title>
- <para>Union partitioning is inferred from the transformation/inline view. If one (or more) of the UNION columns is defined by constants and/or has WHERE clause IN predicates containing only constants
- that make each branch mutually exclusive, then the UNION is considered partitioned.
- UNION ALL must be used and the UNION cannot have a LIMIT, WITH, or ORDER BY clause (although individual branches may use LIMIT, WITH, or ORDER BY).
- Partitioning values should not be null.
- For example the view definition "select 1 as x, y from foo union all select z, a from foo1 where z in (2, 3)" would be considered partitioned on column x,
- since the first branch can only be the value 1 and the second branch can only be the values 2 or 3.
- Note that more advanced or explicit partition could be considered in the future.
- The concept of a partitioned union is used for performing partition-wise joins, in <xref linkend="updatable_views"/>, and <xref linkend="aggregate_pushdown"/>.
- </para>
- </section>
- <section id="standard_relational_techniques">
- <title>Standard Relational Techniques</title>
- <para>
- Teiid also incorporates many standard relational techniques
- to ensure efficient query plans.
- <itemizedlist>
- <listitem>
- <para>Rewrite analysis for function simplification
- and evaluation.</para>
- </listitem>
- <listitem>
- <para>Boolean optimizations for basic criteria
- simplification.</para>
- </listitem>
- <listitem>
- <para>Removal of unnecessary view layers.</para>
- </listitem>
- <listitem>
- <para>Removal of unnecessary sort operations.</para>
- </listitem>
- <listitem>
- <para>Advanced search techniques through the
- left-linear space of join trees.</para>
- </listitem>
- <listitem>
- <para>Parallelizing of source access during execution.</para>
- </listitem>
- <listitem>
- <para><xref linkend="subquery_optimization"/></para>
- </listitem>
- </itemizedlist>
- </para>
- </section>
- </section>
- <section id="subquery_optimization">
- <title>Subquery optimization</title>
- <itemizedlist>
- <listitem>
- <para>EXISTS subqueries are typically rewrite to "SELECT 1 FROM ..." to prevent unnecessary evaluation of SELECT expressions.</para>
- </listitem>
- <listitem>
- <para>Quantified compare SOME subqueries are always turned into an equivalent IN prediate or comparison against an aggregate value. e.g. col > SOME (select col1 from table) would become col > (select min(col1) from table)</para>
- </listitem>
- <listitem>
- <para>Uncorrelated EXISTs and scalar subquery that are not pushed to the source can be preevaluated prior to source command formation.</para>
- </listitem>
- <listitem>
- <para>Correlated subqueries used in DETELEs or UPDATEs that are not pushed as part of the corresponding DELETE/UPDATE will cause Teiid to perform row-by-row compensating processing.
- 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.
- <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>No Unnest Hint Usage</title>
- <programlisting language="SQL">SELECT col1 from tbl where col2 IN /*+ NO_UNNEST */ (SELECT col1 FROM tbl2)</programlisting>
- </example>
- </para>
- </listitem>
- <listitem>
- <para>The system property <link linkend="subquery_unnest">org.teiid.subqueryUnnestDefault</link> controls whether the optimizer will by default unnest subqueries.
- The default is false. If true, then most non-negated WHERE or HAVING clause non-negated EXISTS or IN subquery predicates can be converted to a traditional merge join or as antijoin or semijoin variants.</para>
- </listitem>
- <listitem>
- <para>WHERE clause EXISTs and IN predicates that can be rewriten to a traditional join with the semantics of the semi-join can preserved
- if the system property <link linkend="subquery_unnest">org.teiid.subqueryUnnestDefault</link> is set to true or the subquery has a MJ hint.</para>
- </listitem>
- <listitem>
- <para>EXISTs and scalar subqueries that are not pushed down, and not converted to merge joins, are implicitly limited to 1 and 2 result rows respectively.</para>
- </listitem>
- <listitem>
- <para>Conversion of subquery predicates to nested loop joins is not yet available.</para>
- </listitem>
- </itemizedlist>
- </section>
- <section>
- <title>Federated Failure Modes</title>
- <section>
- <title>Partial Results</title>
- <para>Teiid provides the capability to obtain "partial
- results" in the event of data source unavailability or failure. This is
- especially useful when unioning information from multiple
- sources, or when doing a left outer join, where you are
- 'appending' columns to a master record but still want the record
- if the extra information is not available.</para>
-
- <para>A source is considered to be 'unavailable' if the
- connection factory associated with the source issues an
- exception in response to a query. The exception will be
- propagated to the query processor, where it will become a
- warning on the statement. See the Client Guide for more on Partial Results Mode and SQLWarnings.</para>
- </section>
- </section>
- <section id="query_plan">
- <title>Query Plans</title>
- <para>When integrating information using a federated query
- planner, it is useful to be able to view the query plans that are
- created, to better understand how information is being accessed
- and processed, and to troubleshoot problems.</para>
- <para>A query plan is a set of instructions created by a query
- engine for executing a command submitted by a user or application.
- The purpose of the query plan is to execute the user's query in as
- efficient a way as possible.</para>
- <section id="show_plan">
- <title>Getting a Query Plan</title>
- <para> You can get a query plan any time you execute a command.
- The SQL options available are as follows:</para>
- <itemizedlist>
- <listitem>
- <para>SHOWPLAN [ON|DEBUG]- Returns the plan or the plan and the full planner debug log.</para>
- </listitem>
- </itemizedlist>
- <para>
- With the above options, the query plan is available from the
- Statement object by casting to the
- <classname>org.teiid.jdbc.TeiidStatement
- </classname>
- interface.
- </para>
- <example>
- <title>Retrieving a Query Plan</title>
- <programlisting>
-statement.execute("set showplan on");
-ResultSet rs = statement.executeQuery("select ...");
-TeiidStatement tstatement = statement.unwrap(TeiidStatement.class);
-PlanNode queryPlan = tstatement.getPlanDescription();
-System.out.println(queryPlan);</programlisting>
- </example>
- <para>The query plan is made available automatically in several
- of Teiid's tools.</para>
- </section>
- <section>
- <title>Analyzing a Query Plan</title>
- <para>
- Once a query plan has been obtained you will most commonly be
- looking for:
- <itemizedlist>
- <listitem>
- <para>Source pushdown -- what parts of the query that
- got pushed to each source</para>
- </listitem>
- <listitem>
- <para>Join ordering</para>
- </listitem>
- <listitem>
- <para>Join algorithm used - merge or nested loop.</para>
- </listitem>
- <listitem>
- <para>Presence of federated optimizations, such as
- dependent joins.</para>
- </listitem>
- <listitem>
- <para>Join criteria type mismatches.</para>
- </listitem>
- </itemizedlist>
- </para>
- <para>All of these issues presented above will be present
- subsections of the plan that are specific to relational queries.
- If you are executing a procedure or generating an XML document,
- the overall query plan will contain additional information
- related the surrounding procedural execution.</para>
- <para>A query plan consists of a set of nodes organized in a tree
- structure. As with the above example, you will typically be
- interested in analyzing the textual form of the plan.</para>
- <para> In a procedural context the ordering of child nodes implies
- the order of execution. In most other situation, child nodes may
- be executed in any order even in parallel. Only in specific
- optimizations, such as dependent join, will the children of a
- join execute serially.</para>
- </section>
- <section>
- <title>Relational Plans</title>
- <para>Relational plans represent the actually processing
- plan that is composed of nodes that are the basic building
- blocks of logical relational operations. Physical relational
- plans differ from logical relational plans in that they will
- contain additional operations and execution specifics that were
- chosen by the optimizer.</para>
- <para>The nodes for a relational query plan are:</para>
- <itemizedlist>
- <listitem>
- <para>Access - Access a source. A source query is sent
- to the connection factory associated with the source. [For a
- dependent join, this node is called Dependent Select.]
- </para>
- <para />
- </listitem>
- <listitem>
- <para>Project - Defines the columns returned from the
- node. This does not alter the number of records returned.
- [When there is a subquery in the Select clause, this node is
- called Dependent Project.]</para>
- <para />
- </listitem>
- <listitem>
- <para>Project Into - Like a normal project, but outputs
- rows into a target table.</para>
- <para />
- </listitem>
- <listitem>
- <para>Select - Select is a criteria evaluation filter
- node (WHERE / HAVING). [When there is a subquery in the
- criteria, this node is called Dependent Select.]</para>
- <para />
- </listitem>
- <listitem>
- <para>Join - Defines the join type, join criteria, and
- join strategy (merge or nested loop).</para>
- <para />
- </listitem>
- <listitem>
- <para> Union - There are no properties for this node, it just
- passes rows through from it's children</para>
- </listitem>
- <listitem>
- <para>Sort - Defines the columns to sort on, the sort
- direction for each column, and whether to remove duplicates
- or not.</para>
- <para />
- </listitem>
- <listitem>
- <para>Dup Removal - Same properties as for Sort, but the
- removeDups property is set to true</para>
- <para />
- </listitem>
- <listitem>
- <para>Group - Groups sets of rows into groups and
- evaluates aggregate functions.</para>
- <para />
- </listitem>
- <listitem>
- <para>Null - A node that produces no rows. Usually
- replaces a Select node where the criteria is always false
- (and whatever tree is underneath). There are no properties
- for this node.</para>
- </listitem>
- <listitem>
- <para>Plan Execution - Executes another sub plan.</para>
- <para />
- </listitem>
- <listitem>
- <para> Limit - Returns a specified number of rows, then stops
- processing. Also processes an offset if present.</para>
- <para />
- </listitem>
- </itemizedlist>
- <section>
- <title>Node Statistics</title>
- <para>Every node has a set of statistics that are output.
- These can be used to determine the amount of data flowing
- through the node.</para>
- <informaltable frame="all">
- <tgroup cols="3">
- <thead>
- <row>
- <entry>
- <para>Statistic</para>
- </entry>
- <entry>
- <para>Description</para>
- </entry>
- <entry>
- <para>Units</para>
- </entry>
- </row>
- </thead>
- <tbody>
- <row>
- <entry>
- <para>Node Output Rows</para>
- </entry>
- <entry>
- <para>Number of records output from the node
- </para>
- </entry>
- <entry>
- <para>count</para>
- </entry>
- </row>
- <row>
- <entry>
- <para>Node Process Time</para>
- </entry>
- <entry>
- <para>Time processing in this node only</para>
- </entry>
- <entry>
- <para>millisec</para>
- </entry>
- </row>
- <row>
- <entry>
- <para>Node Cumulative Process Time</para>
- </entry>
- <entry>
- <para>Elapsed time from beginning of processing
- to end</para>
- </entry>
- <entry>
- <para>millisec</para>
- </entry>
- </row>
- <row>
- <entry>
- <para>Node Cumulative Next Batch Process Time
- </para>
- </entry>
- <entry>
- <para>Time processing in this node + child nodes
- </para>
- </entry>
- <entry>
- <para>millisec</para>
- </entry>
- </row>
- <row>
- <entry>
- <para>Node Next Batch Calls</para>
- </entry>
- <entry>
- <para>Number of times a node was called for
- processing</para>
- </entry>
- <entry>
- <para>count</para>
- </entry>
- </row>
- <row>
- <entry>
- <para>Node Blocks</para>
- </entry>
- <entry>
- <para>Number of times a blocked exception was
- thrown by this node or a child</para>
- </entry>
- <entry>
- <para>count</para>
- </entry>
- </row>
- </tbody>
- </tgroup>
- </informaltable>
- <para>In addition to node statistics, some nodes display cost
- estimates computed at the node.</para>
- <informaltable frame="all">
- <tgroup cols="3">
- <thead>
- <row>
- <entry>
- <para>Cost Estimates</para>
- </entry>
- <entry>
- <para>Description</para>
- </entry>
- <entry>
- <para>Units</para>
- </entry>
- </row>
- </thead>
- <tbody>
- <row>
- <entry>
- <para>Estimated Node Cardinality</para>
- </entry>
- <entry>
- <para>Estimated number of records that will
- be output from the node; -1 if unknown</para>
- </entry>
- <entry>
- <para>count</para>
- </entry>
- </row>
- </tbody>
- </tgroup>
- </informaltable>
- <para />
- </section>
- </section>
- </section>
- <section id="query_planner">
- <title>Query Planner</title>
- <para>For each sub-command in the user command an appropriate kind
- of sub-planner is used (relational, XML, procedure,
- etc).</para>
- <para>Each planner has three primary phases:</para>
- <orderedlist>
- <listitem>
- <para>Generate canonical plan</para>
- </listitem>
- <listitem>
- <para>Optimization</para>
- </listitem>
- <listitem>
- <para>Plan to process converter - converts plan data structure into a processing form</para>
- </listitem>
- </orderedlist>
- <section>
- <title>Relational Planner</title>
- <para>The GenerateCanonical class generates the initial (or
- “canonical” plan). This plan is based on the typical logical order
- that a SQL query gets executed. A SQL select query has the following
- possible clauses (all but SELECT are optional): SELECT,
- FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. These clauses are
- logically executed in the following order:</para>
- <orderedlist>
- <listitem>
- <para>FROM (read and join all data from tables)</para>
- </listitem>
- <listitem>
- <para>WHERE (filter rows)</para>
- </listitem>
- <listitem>
- <para>GROUP BY (group rows into collapsed rows)</para>
- </listitem>
- <listitem>
- <para>HAVING (filter grouped rows)</para>
- </listitem>
- <listitem>
- <para>SELECT (evaluate expressions and return only requested columns)</para>
- </listitem>
- <listitem>
- <para>INTO</para>
- </listitem>
- <listitem>
- <para>ORDER BY (sort rows)</para>
- </listitem>
- <listitem>
- <para>LIMIT (limit result set to a certain range of results)</para>
- </listitem>
- </orderedlist>
- <para>These clauses translate into the following types of planning
- nodes:</para>
- <itemizedlist>
- <listitem>
- <para>FROM: Source node for each from clause item, Join node (if >1 table)</para>
- </listitem>
- <listitem>
- <para>WHERE: Select node</para>
- </listitem>
- <listitem>
- <para>GROUP BY: Group node</para>
- </listitem>
- <listitem>
- <para>HAVING: Select node</para>
- </listitem>
- <listitem>
- <para>SELECT: Project node and DupRemoval node (for SELECT DISTINCT)</para>
- </listitem>
- <listitem>
- <para>INTO: Project node with a SOURCE Node</para>
- </listitem>
- <listitem>
- <para>ORDER BY: Sort node</para>
- </listitem>
- <listitem>
- <para>LIMIT: Limit node</para>
- </listitem>
- <listitem>
- <para>UNION, EXCEPT, INTERSECT: SetOp Node</para>
- </listitem>
- </itemizedlist>
- <para>There is also a Null Node that can be created as the result
- of rewrite or planning optimizations. It represents a node that
- produces no rows</para>
- <para>Relational optimization is based upon rule
- execution that evolves the initial plan into the execution plan.
- There are a set of pre-defined rules that are dynamically
- assembled into a rule stack for every query. The rule stack is
- assembled based on the contents of the user’s query and its
- transformations. For example, if there are no view layers, then
- RuleMergeVirtual, which merges view layers together, is not
- needed and will not be added to the stack. This allows the rule
- stack to reflect the complexity of the query.</para>
- <para>Logically the plan node data structure represents a tree of nodes
- where the source data comes up from the leaf nodes (typically Access
- nodes in the final plan), flows up through the tree and produces the
- user’s results out the top. The nodes in the plan structure can have
- bidirectional links, dynamic properties, and allow any number of
- child nodes. Processing <link linkend="query_plan">plan nodes</link> in contrast typical have fixed
- properties, and only allow for binary operations - due to algorithmic limitations.</para>
- <para>Below are some of the rules included in the planner:</para>
- <itemizedlist>
- <listitem>
- <para>RuleRemoveSorts - removes sort nodes that do not have an effect on the result. This most common when a
- view has an non-limited ORDER BY.</para>
- </listitem>
- <listitem>
- <para>RulePlaceAccess - insert an Access node above every physical
- Source node. The source node represents a table typically. An access
- node represents the point at which everything below the access node
- gets pushed to the source. Later rules focus on either pushing stuff
- under the access or pulling the access node up the tree to move more
- work down to the data sources. This rule is also responsible for
- placing <xref linkend='access_patterns'/>.</para>
- </listitem>
- <listitem>
- <para>RulePushSelectCriteria - pushes select criteria down through
- unions, joins, and views into the source below the
- access node. In most cases movement down the tree is good as this
- will filter rows earlier in the plan. We currently do not undo the
- decisions made by PushSelectCriteria. However in situations where
- criteria cannot be evaluated by the source, this can lead to sub
- optimal plans.</para>
- <para>One of the most important optimization related to pushing
- criteria, is how the criteria will be pushed trough join. Consider
- the following plan tree that represents a subtree of the plan for
- the query "select ... from A inner join b on (A.x = B.x) where A.y =
- 3"</para>
-<programlisting> SELECT (B.y = 3)
- |
- JOIN - Inner Join on (A.x = B.x
- / \
- SRC (A) SRC (B)</programlisting>
-
- <para>Note: SELECT nodes represent criteria, and SRC stands for
- SOURCE.</para>
- <para>It is always valid for inner join and cross joins to push
- (single source) criteria that are above the join, below the join.
- This allows for criteria originating in the user query to eventually
- be present in source queries below the joins. This result can be
- represented visually as:</para>
-
-<programlisting> JOIN - Inner Join on (A.x = B.x)
- / \
- / SELECT (B.y = 3)
- | |
- SRC (A) SRC (B)</programlisting>
-
- <para>The same optimization is valid for criteria specified against
- the outer side of an outer join. For example:</para>
-
-<programlisting> SELECT (B.y = 3)
- |
- JOIN - Right Outer Join on (A.x = B.x)
- / \
- SRC (A) SRC (B)</programlisting>
-
- <para>Becomes</para>
-
-<programlisting> JOIN - Right Outer Join on (A.x = B.x)
- / \
- / SELECT (B.y = 3)
- | |
- SRC (A) SRC (B)</programlisting>
-
- <para>However criteria specified against the inner side of an
- outer join needs special consideration. The above scenario with a
- left or full outer join is not the same. For example:</para>
-
-<programlisting> SELECT (B.y = 3)
- |
- JOIN - Left Outer Join on (A.x = B.x)
- / \
- SRC (A) SRC (B)</programlisting>
-
- <para>Can become (available only after 5.0.2):</para>
-
-<programlisting> JOIN - Inner Join on (A.x = B.x)
- / \
- / SELECT (B.y = 3)
- | |
- SRC (A) SRC (B)</programlisting>
-
- <para>Since the criterion is not dependent upon the null values
- that may be populated from the inner side of the join, the criterion
- is eligible to be pushed below the join – but only if the join type
- is also changed to an inner join. </para>
- <para>On the other hand, criteria that are dependent upon the
- presence of null values CANNOT be moved. For example:</para>
-
-<programlisting> SELECT (B.y is null)
- |
- JOIN - Left Outer Join on (A.x = B.x)
- / \
- SRC (A) SRC (B)</programlisting>
-
- <para>This plan tree must have the criteria remain above the join,
- since the outer join may be introducing null values itself. This will
- be true regardless of which version of Teiid is used.</para>
- </listitem>
- <listitem>
- <para>RulePushNonJoinCriteria - this rule will push criteria out of
- an on clause if it is not necessary for the correctness of the join.
- </para>
- </listitem>
- <listitem>
- <para>RuleRaiseNull - this rule will raise null nodes to their
- highest possible point. Raising a null node removes the need to
- consider any part of the old plan that was below the null node.
- </para>
- </listitem>
- <listitem>
- <para>RuleMergeVirtual - merges view layers together. View
- layers are connected by nesting canonical plans under source leaf
- nodes of the parent plan. Each canonical plan is also sometimes
- referred to as a “query frame”. RuleMergeVirtual attempts to merge
- child frames into the parent frame. The merge involves renaming
- any symbols in the lower frame that overlap with symbols in the
- upper frame. It also involves merging the join information
- together.</para>
- </listitem>
- <listitem>
- <para>RuleRemoveOptionalJoins - removes optional join nodes form
- the plan tree as soon as possible so that planning will be more
- optimal.</para>
- </listitem>
- <listitem>
- <para>RulePlanJoins - this rule attempts to find an optimal
- ordering of the joins performed in the plan, while ensuring that
- <xref linkend='access_patterns'/> dependencies are met. This rule has three main
- steps. First it must determine an ordering of joins that satisfy
- the access patterns present. Second it will heuristically create
- joins that can be pushed to the source (if a set of joins are pushed
- to the source, we will not attempt to create an optimal ordering
- within that set. More than likely it will be sent to the source in
- the non-ANSI multi-join syntax and will be optimized by the
- database). Third it will use costing information to determine the
- best left-linear ordering of joins performed in the processing engine. This
- third step will do an exhaustive search for 6 or less join sources
- and is heuristically driven by join selectivity for 7 or more
- sources.</para>
- </listitem>
- <listitem>
- <para>RuleCopyCriteria - this rule copies criteria over an equality
- criteria that is present in the criteria of a join. Since the
- equality defines an equivalence, this is a valid way to create a new
- criteria that may limit results on the other side of the join
- (especially in the case of a multi-source join). </para>
- </listitem>
- <listitem>
- <para>RuleCleanCriteria - this rule cleans up criteria after all the other
- rules.</para>
- </listitem>
- <listitem>
- <para>RuleMergeCriteria - looks for adjacent criteria nodes and
- merges them together. It looks for adjacent identical conjuncts and
- removes duplicates. </para>
- </listitem>
- <listitem>
- <para>RuleRaiseAccess - this rule attempts to raise the Access
- nodes as far up the plan as possible. This is mostly done by
- looking at the source’s capabilities and determining whether the
- operations can be achieved in the source or not.</para>
- </listitem>
- <listitem>
- <para>RuleChooseDependent - this rule looks at each join node and
- determines whether the join should be made dependent and in which
- direction. Cardinality, the number of distinct values, and primary
- key information are used in several formulas to determine whether a
- dependent join is likely to be worthwhile. The dependent join
- differs in performance ideally because a fewer number of values will
- be returned from the dependent side. Also, we must consider the
- number of values passed from independent to dependent side. If that
- set is larger than the max number of values in an IN criteria on the
- dependent side, then we must break the query into a set of queries
- and combine their results. Executing each query in the connector
- has some overhead and that is taken into account. Without costing
- information a lot of common cases where the only criteria specified
- is on a non-unique (but strongly limiting) field are missed. A join
- is eligible to be dependent if:</para>
- <orderedlist>
- <listitem>
- <para>there is at least one equi-join criterion, i.e.
- tablea.col = tableb.col</para>
- </listitem>
- <listitem>
- <para>the join is not a full outer join and the dependent side of
- the join is on the inner side of the join</para>
- </listitem>
- </orderedlist>
-
- <para>The join will be made dependent if one of the following
- conditions, listed in precedence order, holds:</para>
-
- <orderedlist>
- <listitem>
- <para>There is an unsatisfied access pattern that can be
- satisfied with the dependent join criteria</para>
- </listitem>
- <listitem>
- <para>The potential dependent side of the join is marked with an
- option makedep</para>
- </listitem>
- <listitem>
- <para>(4.3.2) if costing was enabled, the estimated cost for the
- dependent join (5.0+ possibly in each direction in the case of inner
- joins) is computed and compared to not performing the dependent join.
- If the costs were all determined (which requires all relevant table
- cardinality, column ndv, and possibly nnv values to be populated) the
- lowest is chosen.</para>
- </listitem>
- <listitem>
- <para>If key metadata information indicates that the potential dependent side is not “small” and the other side is “not small” or (5.0.1) the potential dependent side is the inner side of a left outer join. </para>
- </listitem>
- </orderedlist>
- <para>Dependent join is the key optimization we use to
- efficiently process multi-source joins.</para>
- <para>Instead of reading all of source A and all of source B
- and joining them on A.x = B.x, we read all of A then build a set of
- A.x that are passed as a criteria when querying B. In cases where A
- is small and B is large, this can drastically reduce the data
- retrieved from B, thus greatly speeding the overall query.</para>
- </listitem>
- <listitem>
- <para>RuleChooseJoinStrategy - Determines the base join strategy.
- Currently this is a decision as to whether to use a merge join rather
- than the default strategy, which is a nested loop join. Ideally the
- choice of a hash join would also be evaluated here. Also costing
- should be used to determine the strategy cost. </para>
- </listitem>
- <listitem>
- <para>RuleDecomposeJoin - this rule perfomrs a partition-wise join optimization on joins of <xref linkend="partitioned_union"/>.
- The decision to decompose is based upon detecting that each side of the join is a partitioned union (note that non-ansi joins of more than 2 tables may cause the optimization to not detect the appropriate join).
- The rule currently only looks for situations where at most 1 partition matches from each side.</para>
- </listitem>
- <listitem>
- <para>RuleCollapseSource - this rule removes all nodes below an
- Access node and collapses them into an equivalent query that is
- placed in the Access node.</para>
- </listitem>
- <listitem>
- <para>RuleAssignOutputElements - this rule walks top down through
- every node and calculates the output columns for each node. Columns
- that are not needed are dropped at every node. This is done by
- keeping track of both the columns needed to feed the parent node and
- also keeping track of columns that are “created” at a certain node.
- </para>
- </listitem>
- <listitem>
- <para>RuleValidateWhereAll - this rule validates a rarely used
- model option.</para>
- </listitem>
- <listitem>
- <para>RuleAccessPatternValidation - validates that all access
- patterns have been satisfied.</para>
- </listitem>
- <listitem>
- <para>RulePushLimit - pushes limit and offset information as far as possible in the plan.</para>
- </listitem>
- </itemizedlist>
- </section>
- <section>
- <title>Procedure Planner</title>
- <para>The procedure planner is fairly simple. It converts the
- statements in the procedure into instructions in a program that will
- be run during processing. This is mostly a 1-to-1 mapping and very little optimization is performed.</para>
- </section>
- <section>
- <title>XML Planner</title>
- <para>The XML Planner creates an XML plan that is relatively close
- to the end result of the Procedure Planner – a program with instructions. Many of the
- instructions are even similar (while loop, execute SQL, etc).
- Additional instructions deal with producing the output result document
- (adding elements and attributes). </para>
- <para>The XML planner does several types of planning (not
- necessarily in this order):</para>
- <para>- Document selection - determine which tags of the virtual
- document should be excluded from the output document. This is
- done based on a combination of the model (which marks parts of the
- document excluded) and the query (which may specify a subset of
- columns to include in the SELECT clause). </para>
- <para>- Criteria evaluation - breaks apart the user’s criteria,
- determine which result set the criteria should be applied to, and
- add that criteria to that result set query.</para>
- <para>- Result set ordering - the query’s ORDER BY clause is broken
- up and the ORDER BY is applied to each result set as necessary
- </para>
- <para>- Result set planning - ultimately, each result set is
- planned using the relational planner and taking into account all
- the impacts from the user’s query</para>
- <para>- Program generation - a set of instructions to produce the
- desired output document is produced, taking into account the final
- result set queries and the excluded parts of the document.
- Generally, this involves walking through the virtual document in
- document order, executing queries as necessary and emitting
- elements and attributes.</para>
- <para>XML programs can also be recursive, which involves using
- the same document fragment for both the initial fragment and a set
- of repeated fragments (each a new query) until some termination
- criteria or limit is met.</para>
- </section>
- </section>
-</chapter>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/federated_planning.xml (from rev 3218, trunk/documentation/reference/src/main/docbook/en-US/content/federated_planning.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/federated_planning.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/federated_planning.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1087 @@
+<?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="federated_planning">
+ <title>Federated Planning</title>
+ <para>Teiid at its core is a federated relational query
+ engine. This query engine allows you to treat all of your data
+ sources as one virtual database and access them in a single SQL
+ query. This allows you to focus on building your application, not on
+ hand-coding joins, and other relational operations, between data
+ sources.</para>
+ <section>
+ <title>Overview</title>
+ <para>When the query engine receives an incoming SQL query it
+ performs the following operations:</para>
+ <orderedlist>
+ <listitem>
+ <para>Parsing - validate syntax and convert to internal
+ form</para>
+ </listitem>
+ <listitem>
+ <para>Resolving - link all identifiers to metadata and
+ functions to the function library</para>
+ </listitem>
+ <listitem>
+ <para>Validating - validate SQL semantics based on
+ metadata references and type signatures</para>
+ </listitem>
+ <listitem>
+ <para>Rewriting - rewrite SQL to simplify expressions
+ and criteria</para>
+ </listitem>
+ <listitem>
+ <para>
+ Logical plan optimization - the rewritten canonical SQL is
+ converted into a logical plan for in-depth optimization. The
+ Teiid optimizer is predominantly rule-based. Based upon the
+ query structure and hints a certain rule set will be applied.
+ These rules may trigger in turn trigger the execution of more
+ rules. Within several rules, Teiid also takes advantage of
+ costing information. The logical plan optimization steps can
+ be seen by using <link linkend="show_plan">SHOWPLAN DEBUG</link>
+ clause and are described in the
+ <link linkend="query_planner">query planner</link>
+ section.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ Processing plan conversion - the logic plan is converted into
+ an executable form where the nodes are representative of basic
+ processing operations. The final processing plan is displayed
+ as the
+ <link linkend="query_plan">query plan</link>
+ .
+ </para>
+ </listitem>
+ </orderedlist>
+ <para>
+ The logical query plan is a tree of operations used to transform
+ data in source tables to the expected result set. In the tree,
+ data flows from the bottom (tables) to the top (output). The
+ primary logical operations are
+ <emphasis>select</emphasis>
+ (select or filter rows based on a criteria),
+ <emphasis>project</emphasis>
+ (project or compute column values),
+ <emphasis>join</emphasis>
+ ,
+ <emphasis>source</emphasis>
+ (retrieve data from a table),
+ <emphasis>sort</emphasis>
+ (ORDER BY),
+ <emphasis>duplicate removal</emphasis>
+ (SELECT DISTINCT),
+ <emphasis>group</emphasis>
+ (GROUP BY), and
+ <emphasis>union</emphasis>
+ (UNION).
+ </para>
+ <para>For example, consider the following query that retrieves
+ all engineering employees born since 1970.</para>
+ <example>
+ <title>Example query</title>
+ <programlisting>SELECT e.title, e.lastname FROM Employees AS e JOIN
+Departments AS d ON e.dept_id = d.dept_id WHERE year(e.birthday) >= 1970 AND d.dept_name = 'Engineering'</programlisting>
+ </example>
+ <para>Logically, the data from the Employees and Departments
+ tables are retrieved, then joined, then filtered as specified, and
+ finally the output columns are projected. The canonical query plan
+ thus looks like this:</para>
+ <mediaobject>
+ <imageobject>
+ <imagedata fileref="../images/query_plan.png"/>
+ </imageobject>
+ </mediaobject>
+ <para>Data flows from the tables at the bottom upwards through the
+ join, through the select, and finally through the project to produce
+ the final results. The data passed between each node is logically a
+ result set with columns and rows.</para>
+ <para>
+ Of course, this is what happens
+ <emphasis>logically</emphasis>
+ , not how the plan is actually executed. Starting from this initial
+ plan, the query planner performs transformations on the query plan
+ tree to produce an equivalent plan that retrieves the same results
+ faster. Both a federated query planner and a relational database
+ planner deal with the same concepts and many of the same plan
+ transformations. In this example, the criteria on the Departments
+ and Employees tables will be pushed down the tree to filter the
+ results as early as possible.
+ </para>
+ <para>In both cases, the goal is to retrieve the query results in
+ the fastest possible time. However, the relational database planner
+ does this primarily by optimizing the access paths in pulling data
+ from storage.</para>
+ <para>In contrast, a federated query planner is less concerned about
+ storage access because it is typically pushing that burden to the
+ data source. The most important consideration for a federated query
+ planner is minimizing data transfer.</para>
+ </section>
+ <section>
+ <title>Federated Optimizations</title>
+ <section id="access_patterns">
+ <title>Access Patterns</title>
+ <para>
+ Access patterns are used on both physical tables and views to
+ specify the need for criteria against a set of columns. Failure to supply the criteria will
+ result in a planning error, rather than a run-away source query. Access
+ patterns can be applied in a set such that only one of the access
+ patterns is required to be satisfied.</para>
+ <para>Currently any form of criteria referencing an affected column may satisfy an access
+ pattern.</para>
+ </section>
+ <section>
+ <title>Pushdown</title>
+ <para>In federated database systems pushdown refers to
+ decomposing the user level query into source queries that
+ perform as much work as possible on their respective source
+ system. Pushdown analysis requires knowledge of source system
+ capabilities, which is provided to Teiid though the Connector
+ API. Any work not performed at the source is then processed in
+ Federate's relational engine.</para>
+ <para>
+ Based upon capabilities, Teiid will manipulate the query plan
+ to ensure that each source performs as much joining, filtering,
+ grouping, etc. as possible. In may cases, such as with join
+ ordering, planning is a combination of
+ <link linkend="standard_relational_techniques">standard relational techniques</link>
+ and, cost based and heuristics for pushdown optimization.
+ </para>
+ <para>
+ Criteria and join push down are typically the most important
+ aspects of the query to push down when performance is a concern.
+ See
+ <link linkend="query_plan">Query Plans</link>
+ on how to read a plan to ensure that source queries are as
+ efficient as possible.
+ </para>
+ </section>
+ <section id="dependent_joins">
+ <title>Dependent Joins</title>
+ <para>A special optimization called a dependent join is used to
+ reduce the rows returned from one of the two relations involved
+ in a multi-source join. In a dependent join, queries are issued
+ to each source sequentially rather than in parallel, with the
+ results obtained from the first source used to restrict the
+ records returned from the second. Dependent joins can perform
+ some joins much faster by drastically reducing the amount of
+ data retrieved from the second source and the number of join
+ comparisons that must be performed.</para>
+ <para> The conditions when a dependent join is used are determined
+ by the query planner based on <xref linkend='access_patterns'/>, hints, and
+ costing information.</para>
+ <para>
+ 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 MAKEIND, MAKEDEP, and
+ MAKENOTDEP hints override any use of costing information. MAKENOTDEP supersedes the other hints.
+ </para>
+ <tip>
+ <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/MAKEIND hint can force an
+ inefficient join structure and may result in many source
+ queries.</para>
+ </tip>
+ <para>The engine will for IN clauses to filter the values coming from the dependent side.
+ If the number of values from the independent side exceeds the translators MaxInCriteriaSize, the values will be split into multiple IN predicates up to MaxDependentPredicates.
+ When the number of independent values exceeds MaxInCriteriaSize*MaxDependentPredicates, then multiple dependent queries will be issued in parallel.</para>
+ </section>
+ <section>
+ <title>Copy Criteria</title>
+ <para> Copy criteria is an optimization that creates additional
+ predicates based upon combining join and where clause criteria.
+ For example, equi-join predicates (source1.table.column =
+ source2.table.column) are used to create new predicates by
+ substituting source1.table.column for source2.table.column and
+ vice versa. In a cross source scenario, this allows for where
+ criteria applied to a single side of the join to be applied to
+ both source queries</para>
+ </section>
+ <section>
+ <title>Projection Minimization</title>
+ <para> Teiid ensures that each pushdown query only projects the
+ symbols required for processing the user query. This is
+ especially helpful when querying through large intermediate view
+ layers.</para>
+ </section>
+ <section id="aggregate_pushdown">
+ <title>Partial Aggregate Pushdown</title>
+ <para> Partial aggregate pushdown allows for grouping operations
+ above multi-source joins and unions to be decomposed so that some of the
+ grouping and aggregate functions may be pushed down to the
+ sources.</para>
+ </section>
+ <section id="optional_join">
+ <title>Optional Join</title>
+ <para>The optional join hint indicates to the
+ optimizer that a joined table should be omitted if none of its
+ columns are used by the output of the user query or in a meaningful way to construct the results of the user query. This hint is typically only used in view layers
+ containing multi-source joins.</para>
+ <para>
+ The optional join hint is applied as a comment on a join clause. It can be applied in both ANSI and non-ANSI joins. With non-ANSI joins an entire joined table may be marked as optional.
+ <example>
+ <title>Example Optional Join Hint</title>
+ <programlisting language="SQL">select a.column1, b.column2 from a, /*+ optional */ b WHERE a.key = b.key</programlisting>
+ <para>Suppose this example defines a view layer X.
+ If X is queried in such a way as to not need b.column2, then the
+ optional join hint will cause b to be omitted from the query
+ plan. The result would be the same as if X were defined as:
+ </para>
+ <programlisting language="SQL">select a.column1 from a</programlisting>
+ </example>
+ <example>
+ <title>Example ANSI Optional Join Hint</title>
+ <programlisting>select a.column1, b.column2, c.column3 from /*+ optional */ (a inner join b ON a.key = b.key) INNER JOIN c ON a.key = c.key</programlisting>
+ <para>In this example the ANSI join syntax allows for the join of a and b to be marked as optional. Suppose this example defines a view layer X. Only if both column a.column1 and b.column2 are not needed, e.g. "SELECT column3 FROM X" will the join be removed.</para>
+ </example>
+ </para>
+ <para>
+ The optional join hint will not remove a bridging table that is still required.
+ <example>
+ <title>Example Briding Table</title>
+ <programlisting language="SQL">select a.column1, b.column2, c.column3 from /*+ optional */ a, b, c WHERE ON a.key = b.key AND a.key = c.key</programlisting>
+ <para>Suppose this example defines a view layer X. If b.column2 or c.column3 are solely required by a query to X, then the join on a be removed.
+ However if a.column1 or both b.column2 and c.column3 are needed, then the optional join hint will not take effect.</para>
+ </example>
+ </para>
+ <tip>
+ <para>When a join clause is omitted via the optional join hint, the relevant criteria
+ is not applied. Thus it is possible that the query results may
+ not have the same cardinality or even the same row values as
+ when the join is fully applied.</para>
+ <para>Left/right outer joins where the inner side values are not used
+ and whose rows under go a distinct operation will automatically be
+ treated as an optional join and do not require a hint.
+ <example>
+ <title>Example Unnecessary Optional Join Hint</title>
+ <programlisting language="SQL">select a.column1, b.column2 from a LEFT OUTER JOIN /*+optional*/ b ON a.key = b.key</programlisting>
+ </example>
+ </para>
+ </tip>
+ <warning><para>
+ A simple "SELECT COUNT(*) FROM VIEW" against a view where all join tables are marked as optional will not return a meaningful result.
+ </para>
+ </warning>
+ </section>
+ <section id="partitioned_union">
+ <title>Partitioned Union</title>
+ <para>Union partitioning is inferred from the transformation/inline view. If one (or more) of the UNION columns is defined by constants and/or has WHERE clause IN predicates containing only constants
+ that make each branch mutually exclusive, then the UNION is considered partitioned.
+ UNION ALL must be used and the UNION cannot have a LIMIT, WITH, or ORDER BY clause (although individual branches may use LIMIT, WITH, or ORDER BY).
+ Partitioning values should not be null.
+ For example the view definition "select 1 as x, y from foo union all select z, a from foo1 where z in (2, 3)" would be considered partitioned on column x,
+ since the first branch can only be the value 1 and the second branch can only be the values 2 or 3.
+ Note that more advanced or explicit partition could be considered in the future.
+ The concept of a partitioned union is used for performing partition-wise joins, in <xref linkend="updatable_views"/>, and <xref linkend="aggregate_pushdown"/>.
+ </para>
+ </section>
+ <section id="standard_relational_techniques">
+ <title>Standard Relational Techniques</title>
+ <para>
+ Teiid also incorporates many standard relational techniques
+ to ensure efficient query plans.
+ <itemizedlist>
+ <listitem>
+ <para>Rewrite analysis for function simplification
+ and evaluation.</para>
+ </listitem>
+ <listitem>
+ <para>Boolean optimizations for basic criteria
+ simplification.</para>
+ </listitem>
+ <listitem>
+ <para>Removal of unnecessary view layers.</para>
+ </listitem>
+ <listitem>
+ <para>Removal of unnecessary sort operations.</para>
+ </listitem>
+ <listitem>
+ <para>Advanced search techniques through the
+ left-linear space of join trees.</para>
+ </listitem>
+ <listitem>
+ <para>Parallelizing of source access during execution.</para>
+ </listitem>
+ <listitem>
+ <para><xref linkend="subquery_optimization"/></para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ </section>
+ </section>
+ <section id="subquery_optimization">
+ <title>Subquery optimization</title>
+ <itemizedlist>
+ <listitem>
+ <para>EXISTS subqueries are typically rewrite to "SELECT 1 FROM ..." to prevent unnecessary evaluation of SELECT expressions.</para>
+ </listitem>
+ <listitem>
+ <para>Quantified compare SOME subqueries are always turned into an equivalent IN prediate or comparison against an aggregate value. e.g. col > SOME (select col1 from table) would become col > (select min(col1) from table)</para>
+ </listitem>
+ <listitem>
+ <para>Uncorrelated EXISTs and scalar subquery that are not pushed to the source can be preevaluated prior to source command formation.</para>
+ </listitem>
+ <listitem>
+ <para>Correlated subqueries used in DETELEs or UPDATEs that are not pushed as part of the corresponding DELETE/UPDATE will cause Teiid to perform row-by-row compensating processing.
+ 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), 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>
+ </para>
+ </listitem>
+ <listitem>
+ <para>The system property <link linkend="subquery_unnest">org.teiid.subqueryUnnestDefault</link> controls whether the optimizer will by default unnest subqueries.
+ The default is false. If true, then most non-negated WHERE or HAVING clause non-negated EXISTS or IN subquery predicates can be converted to a traditional merge join or as antijoin or semijoin variants.</para>
+ </listitem>
+ <listitem>
+ <para>WHERE clause EXISTs and IN predicates that can be rewriten to a traditional join with the semantics of the semi-join can preserved
+ if the system property <link linkend="subquery_unnest">org.teiid.subqueryUnnestDefault</link> is set to true or the subquery has a MJ hint.</para>
+ </listitem>
+ <listitem>
+ <para>EXISTs and scalar subqueries that are not pushed down, and not converted to merge joins, are implicitly limited to 1 and 2 result rows respectively.</para>
+ </listitem>
+ <listitem>
+ <para>Conversion of subquery predicates to nested loop joins is not yet available.</para>
+ </listitem>
+ </itemizedlist>
+ </section>
+ <section>
+ <title>Federated Failure Modes</title>
+ <section>
+ <title>Partial Results</title>
+ <para>Teiid provides the capability to obtain "partial
+ results" in the event of data source unavailability or failure. This is
+ especially useful when unioning information from multiple
+ sources, or when doing a left outer join, where you are
+ 'appending' columns to a master record but still want the record
+ if the extra information is not available.</para>
+
+ <para>A source is considered to be 'unavailable' if the
+ connection factory associated with the source issues an
+ exception in response to a query. The exception will be
+ propagated to the query processor, where it will become a
+ warning on the statement. See the Client Guide for more on Partial Results Mode and SQLWarnings.</para>
+ </section>
+ </section>
+ <section id="query_plan">
+ <title>Query Plans</title>
+ <para>When integrating information using a federated query
+ planner, it is useful to be able to view the query plans that are
+ created, to better understand how information is being accessed
+ and processed, and to troubleshoot problems.</para>
+ <para>A query plan is a set of instructions created by a query
+ engine for executing a command submitted by a user or application.
+ The purpose of the query plan is to execute the user's query in as
+ efficient a way as possible.</para>
+ <section id="show_plan">
+ <title>Getting a Query Plan</title>
+ <para> You can get a query plan any time you execute a command.
+ The SQL options available are as follows:</para>
+ <itemizedlist>
+ <listitem>
+ <para>SHOWPLAN [ON|DEBUG]- Returns the plan or the plan and the full planner debug log.</para>
+ </listitem>
+ </itemizedlist>
+ <para>
+ With the above options, the query plan is available from the
+ Statement object by casting to the
+ <classname>org.teiid.jdbc.TeiidStatement
+ </classname>
+ interface.
+ </para>
+ <example>
+ <title>Retrieving a Query Plan</title>
+ <programlisting>
+statement.execute("set showplan on");
+ResultSet rs = statement.executeQuery("select ...");
+TeiidStatement tstatement = statement.unwrap(TeiidStatement.class);
+PlanNode queryPlan = tstatement.getPlanDescription();
+System.out.println(queryPlan);</programlisting>
+ </example>
+ <para>The query plan is made available automatically in several
+ of Teiid's tools.</para>
+ </section>
+ <section>
+ <title>Analyzing a Query Plan</title>
+ <para>
+ Once a query plan has been obtained you will most commonly be
+ looking for:
+ <itemizedlist>
+ <listitem>
+ <para>Source pushdown -- what parts of the query that
+ got pushed to each source</para>
+ </listitem>
+ <listitem>
+ <para>Join ordering</para>
+ </listitem>
+ <listitem>
+ <para>Join algorithm used - merge or nested loop.</para>
+ </listitem>
+ <listitem>
+ <para>Presence of federated optimizations, such as
+ dependent joins.</para>
+ </listitem>
+ <listitem>
+ <para>Join criteria type mismatches.</para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>All of these issues presented above will be present
+ subsections of the plan that are specific to relational queries.
+ If you are executing a procedure or generating an XML document,
+ the overall query plan will contain additional information
+ related the surrounding procedural execution.</para>
+ <para>A query plan consists of a set of nodes organized in a tree
+ structure. As with the above example, you will typically be
+ interested in analyzing the textual form of the plan.</para>
+ <para> In a procedural context the ordering of child nodes implies
+ the order of execution. In most other situation, child nodes may
+ be executed in any order even in parallel. Only in specific
+ optimizations, such as dependent join, will the children of a
+ join execute serially.</para>
+ </section>
+ <section>
+ <title>Relational Plans</title>
+ <para>Relational plans represent the actually processing
+ plan that is composed of nodes that are the basic building
+ blocks of logical relational operations. Physical relational
+ plans differ from logical relational plans in that they will
+ contain additional operations and execution specifics that were
+ chosen by the optimizer.</para>
+ <para>The nodes for a relational query plan are:</para>
+ <itemizedlist>
+ <listitem>
+ <para>Access - Access a source. A source query is sent
+ to the connection factory associated with the source. [For a
+ dependent join, this node is called Dependent Select.]
+ </para>
+ <para />
+ </listitem>
+ <listitem>
+ <para>Project - Defines the columns returned from the
+ node. This does not alter the number of records returned.
+ [When there is a subquery in the Select clause, this node is
+ called Dependent Project.]</para>
+ <para />
+ </listitem>
+ <listitem>
+ <para>Project Into - Like a normal project, but outputs
+ rows into a target table.</para>
+ <para />
+ </listitem>
+ <listitem>
+ <para>Select - Select is a criteria evaluation filter
+ node (WHERE / HAVING). [When there is a subquery in the
+ criteria, this node is called Dependent Select.]</para>
+ <para />
+ </listitem>
+ <listitem>
+ <para>Join - Defines the join type, join criteria, and
+ join strategy (merge or nested loop).</para>
+ <para />
+ </listitem>
+ <listitem>
+ <para> Union - There are no properties for this node, it just
+ passes rows through from it's children</para>
+ </listitem>
+ <listitem>
+ <para>Sort - Defines the columns to sort on, the sort
+ direction for each column, and whether to remove duplicates
+ or not.</para>
+ <para />
+ </listitem>
+ <listitem>
+ <para>Dup Removal - Same properties as for Sort, but the
+ removeDups property is set to true</para>
+ <para />
+ </listitem>
+ <listitem>
+ <para>Group - Groups sets of rows into groups and
+ evaluates aggregate functions.</para>
+ <para />
+ </listitem>
+ <listitem>
+ <para>Null - A node that produces no rows. Usually
+ replaces a Select node where the criteria is always false
+ (and whatever tree is underneath). There are no properties
+ for this node.</para>
+ </listitem>
+ <listitem>
+ <para>Plan Execution - Executes another sub plan.</para>
+ <para />
+ </listitem>
+ <listitem>
+ <para> Limit - Returns a specified number of rows, then stops
+ processing. Also processes an offset if present.</para>
+ <para />
+ </listitem>
+ </itemizedlist>
+ <section>
+ <title>Node Statistics</title>
+ <para>Every node has a set of statistics that are output.
+ These can be used to determine the amount of data flowing
+ through the node.</para>
+ <informaltable frame="all">
+ <tgroup cols="3">
+ <thead>
+ <row>
+ <entry>
+ <para>Statistic</para>
+ </entry>
+ <entry>
+ <para>Description</para>
+ </entry>
+ <entry>
+ <para>Units</para>
+ </entry>
+ </row>
+ </thead>
+ <tbody>
+ <row>
+ <entry>
+ <para>Node Output Rows</para>
+ </entry>
+ <entry>
+ <para>Number of records output from the node
+ </para>
+ </entry>
+ <entry>
+ <para>count</para>
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <para>Node Process Time</para>
+ </entry>
+ <entry>
+ <para>Time processing in this node only</para>
+ </entry>
+ <entry>
+ <para>millisec</para>
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <para>Node Cumulative Process Time</para>
+ </entry>
+ <entry>
+ <para>Elapsed time from beginning of processing
+ to end</para>
+ </entry>
+ <entry>
+ <para>millisec</para>
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <para>Node Cumulative Next Batch Process Time
+ </para>
+ </entry>
+ <entry>
+ <para>Time processing in this node + child nodes
+ </para>
+ </entry>
+ <entry>
+ <para>millisec</para>
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <para>Node Next Batch Calls</para>
+ </entry>
+ <entry>
+ <para>Number of times a node was called for
+ processing</para>
+ </entry>
+ <entry>
+ <para>count</para>
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <para>Node Blocks</para>
+ </entry>
+ <entry>
+ <para>Number of times a blocked exception was
+ thrown by this node or a child</para>
+ </entry>
+ <entry>
+ <para>count</para>
+ </entry>
+ </row>
+ </tbody>
+ </tgroup>
+ </informaltable>
+ <para>In addition to node statistics, some nodes display cost
+ estimates computed at the node.</para>
+ <informaltable frame="all">
+ <tgroup cols="3">
+ <thead>
+ <row>
+ <entry>
+ <para>Cost Estimates</para>
+ </entry>
+ <entry>
+ <para>Description</para>
+ </entry>
+ <entry>
+ <para>Units</para>
+ </entry>
+ </row>
+ </thead>
+ <tbody>
+ <row>
+ <entry>
+ <para>Estimated Node Cardinality</para>
+ </entry>
+ <entry>
+ <para>Estimated number of records that will
+ be output from the node; -1 if unknown</para>
+ </entry>
+ <entry>
+ <para>count</para>
+ </entry>
+ </row>
+ </tbody>
+ </tgroup>
+ </informaltable>
+ <para />
+ </section>
+ </section>
+ </section>
+ <section id="query_planner">
+ <title>Query Planner</title>
+ <para>For each sub-command in the user command an appropriate kind
+ of sub-planner is used (relational, XML, procedure,
+ etc).</para>
+ <para>Each planner has three primary phases:</para>
+ <orderedlist>
+ <listitem>
+ <para>Generate canonical plan</para>
+ </listitem>
+ <listitem>
+ <para>Optimization</para>
+ </listitem>
+ <listitem>
+ <para>Plan to process converter - converts plan data structure into a processing form</para>
+ </listitem>
+ </orderedlist>
+ <section>
+ <title>Relational Planner</title>
+ <para>The GenerateCanonical class generates the initial (or
+ “canonical” plan). This plan is based on the typical logical order
+ that a SQL query gets executed. A SQL select query has the following
+ possible clauses (all but SELECT are optional): SELECT,
+ FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. These clauses are
+ logically executed in the following order:</para>
+ <orderedlist>
+ <listitem>
+ <para>FROM (read and join all data from tables)</para>
+ </listitem>
+ <listitem>
+ <para>WHERE (filter rows)</para>
+ </listitem>
+ <listitem>
+ <para>GROUP BY (group rows into collapsed rows)</para>
+ </listitem>
+ <listitem>
+ <para>HAVING (filter grouped rows)</para>
+ </listitem>
+ <listitem>
+ <para>SELECT (evaluate expressions and return only requested columns)</para>
+ </listitem>
+ <listitem>
+ <para>INTO</para>
+ </listitem>
+ <listitem>
+ <para>ORDER BY (sort rows)</para>
+ </listitem>
+ <listitem>
+ <para>LIMIT (limit result set to a certain range of results)</para>
+ </listitem>
+ </orderedlist>
+ <para>These clauses translate into the following types of planning
+ nodes:</para>
+ <itemizedlist>
+ <listitem>
+ <para>FROM: Source node for each from clause item, Join node (if >1 table)</para>
+ </listitem>
+ <listitem>
+ <para>WHERE: Select node</para>
+ </listitem>
+ <listitem>
+ <para>GROUP BY: Group node</para>
+ </listitem>
+ <listitem>
+ <para>HAVING: Select node</para>
+ </listitem>
+ <listitem>
+ <para>SELECT: Project node and DupRemoval node (for SELECT DISTINCT)</para>
+ </listitem>
+ <listitem>
+ <para>INTO: Project node with a SOURCE Node</para>
+ </listitem>
+ <listitem>
+ <para>ORDER BY: Sort node</para>
+ </listitem>
+ <listitem>
+ <para>LIMIT: Limit node</para>
+ </listitem>
+ <listitem>
+ <para>UNION, EXCEPT, INTERSECT: SetOp Node</para>
+ </listitem>
+ </itemizedlist>
+ <para>There is also a Null Node that can be created as the result
+ of rewrite or planning optimizations. It represents a node that
+ produces no rows</para>
+ <para>Relational optimization is based upon rule
+ execution that evolves the initial plan into the execution plan.
+ There are a set of pre-defined rules that are dynamically
+ assembled into a rule stack for every query. The rule stack is
+ assembled based on the contents of the user’s query and its
+ transformations. For example, if there are no view layers, then
+ RuleMergeVirtual, which merges view layers together, is not
+ needed and will not be added to the stack. This allows the rule
+ stack to reflect the complexity of the query.</para>
+ <para>Logically the plan node data structure represents a tree of nodes
+ where the source data comes up from the leaf nodes (typically Access
+ nodes in the final plan), flows up through the tree and produces the
+ user’s results out the top. The nodes in the plan structure can have
+ bidirectional links, dynamic properties, and allow any number of
+ child nodes. Processing <link linkend="query_plan">plan nodes</link> in contrast typical have fixed
+ properties, and only allow for binary operations - due to algorithmic limitations.</para>
+ <para>Below are some of the rules included in the planner:</para>
+ <itemizedlist>
+ <listitem>
+ <para>RuleRemoveSorts - removes sort nodes that do not have an effect on the result. This most common when a
+ view has an non-limited ORDER BY.</para>
+ </listitem>
+ <listitem>
+ <para>RulePlaceAccess - insert an Access node above every physical
+ Source node. The source node represents a table typically. An access
+ node represents the point at which everything below the access node
+ gets pushed to the source. Later rules focus on either pushing stuff
+ under the access or pulling the access node up the tree to move more
+ work down to the data sources. This rule is also responsible for
+ placing <xref linkend='access_patterns'/>.</para>
+ </listitem>
+ <listitem>
+ <para>RulePushSelectCriteria - pushes select criteria down through
+ unions, joins, and views into the source below the
+ access node. In most cases movement down the tree is good as this
+ will filter rows earlier in the plan. We currently do not undo the
+ decisions made by PushSelectCriteria. However in situations where
+ criteria cannot be evaluated by the source, this can lead to sub
+ optimal plans.</para>
+ <para>One of the most important optimization related to pushing
+ criteria, is how the criteria will be pushed trough join. Consider
+ the following plan tree that represents a subtree of the plan for
+ the query "select ... from A inner join b on (A.x = B.x) where A.y =
+ 3"</para>
+<programlisting> SELECT (B.y = 3)
+ |
+ JOIN - Inner Join on (A.x = B.x
+ / \
+ SRC (A) SRC (B)</programlisting>
+
+ <para>Note: SELECT nodes represent criteria, and SRC stands for
+ SOURCE.</para>
+ <para>It is always valid for inner join and cross joins to push
+ (single source) criteria that are above the join, below the join.
+ This allows for criteria originating in the user query to eventually
+ be present in source queries below the joins. This result can be
+ represented visually as:</para>
+
+<programlisting> JOIN - Inner Join on (A.x = B.x)
+ / \
+ / SELECT (B.y = 3)
+ | |
+ SRC (A) SRC (B)</programlisting>
+
+ <para>The same optimization is valid for criteria specified against
+ the outer side of an outer join. For example:</para>
+
+<programlisting> SELECT (B.y = 3)
+ |
+ JOIN - Right Outer Join on (A.x = B.x)
+ / \
+ SRC (A) SRC (B)</programlisting>
+
+ <para>Becomes</para>
+
+<programlisting> JOIN - Right Outer Join on (A.x = B.x)
+ / \
+ / SELECT (B.y = 3)
+ | |
+ SRC (A) SRC (B)</programlisting>
+
+ <para>However criteria specified against the inner side of an
+ outer join needs special consideration. The above scenario with a
+ left or full outer join is not the same. For example:</para>
+
+<programlisting> SELECT (B.y = 3)
+ |
+ JOIN - Left Outer Join on (A.x = B.x)
+ / \
+ SRC (A) SRC (B)</programlisting>
+
+ <para>Can become (available only after 5.0.2):</para>
+
+<programlisting> JOIN - Inner Join on (A.x = B.x)
+ / \
+ / SELECT (B.y = 3)
+ | |
+ SRC (A) SRC (B)</programlisting>
+
+ <para>Since the criterion is not dependent upon the null values
+ that may be populated from the inner side of the join, the criterion
+ is eligible to be pushed below the join – but only if the join type
+ is also changed to an inner join. </para>
+ <para>On the other hand, criteria that are dependent upon the
+ presence of null values CANNOT be moved. For example:</para>
+
+<programlisting> SELECT (B.y is null)
+ |
+ JOIN - Left Outer Join on (A.x = B.x)
+ / \
+ SRC (A) SRC (B)</programlisting>
+
+ <para>This plan tree must have the criteria remain above the join,
+ since the outer join may be introducing null values itself. This will
+ be true regardless of which version of Teiid is used.</para>
+ </listitem>
+ <listitem>
+ <para>RulePushNonJoinCriteria - this rule will push criteria out of
+ an on clause if it is not necessary for the correctness of the join.
+ </para>
+ </listitem>
+ <listitem>
+ <para>RuleRaiseNull - this rule will raise null nodes to their
+ highest possible point. Raising a null node removes the need to
+ consider any part of the old plan that was below the null node.
+ </para>
+ </listitem>
+ <listitem>
+ <para>RuleMergeVirtual - merges view layers together. View
+ layers are connected by nesting canonical plans under source leaf
+ nodes of the parent plan. Each canonical plan is also sometimes
+ referred to as a “query frame”. RuleMergeVirtual attempts to merge
+ child frames into the parent frame. The merge involves renaming
+ any symbols in the lower frame that overlap with symbols in the
+ upper frame. It also involves merging the join information
+ together.</para>
+ </listitem>
+ <listitem>
+ <para>RuleRemoveOptionalJoins - removes optional join nodes form
+ the plan tree as soon as possible so that planning will be more
+ optimal.</para>
+ </listitem>
+ <listitem>
+ <para>RulePlanJoins - this rule attempts to find an optimal
+ ordering of the joins performed in the plan, while ensuring that
+ <xref linkend='access_patterns'/> dependencies are met. This rule has three main
+ steps. First it must determine an ordering of joins that satisfy
+ the access patterns present. Second it will heuristically create
+ joins that can be pushed to the source (if a set of joins are pushed
+ to the source, we will not attempt to create an optimal ordering
+ within that set. More than likely it will be sent to the source in
+ the non-ANSI multi-join syntax and will be optimized by the
+ database). Third it will use costing information to determine the
+ best left-linear ordering of joins performed in the processing engine. This
+ third step will do an exhaustive search for 6 or less join sources
+ and is heuristically driven by join selectivity for 7 or more
+ sources.</para>
+ </listitem>
+ <listitem>
+ <para>RuleCopyCriteria - this rule copies criteria over an equality
+ criteria that is present in the criteria of a join. Since the
+ equality defines an equivalence, this is a valid way to create a new
+ criteria that may limit results on the other side of the join
+ (especially in the case of a multi-source join). </para>
+ </listitem>
+ <listitem>
+ <para>RuleCleanCriteria - this rule cleans up criteria after all the other
+ rules.</para>
+ </listitem>
+ <listitem>
+ <para>RuleMergeCriteria - looks for adjacent criteria nodes and
+ merges them together. It looks for adjacent identical conjuncts and
+ removes duplicates. </para>
+ </listitem>
+ <listitem>
+ <para>RuleRaiseAccess - this rule attempts to raise the Access
+ nodes as far up the plan as possible. This is mostly done by
+ looking at the source’s capabilities and determining whether the
+ operations can be achieved in the source or not.</para>
+ </listitem>
+ <listitem>
+ <para>RuleChooseDependent - this rule looks at each join node and
+ determines whether the join should be made dependent and in which
+ direction. Cardinality, the number of distinct values, and primary
+ key information are used in several formulas to determine whether a
+ dependent join is likely to be worthwhile. The dependent join
+ differs in performance ideally because a fewer number of values will
+ be returned from the dependent side. Also, we must consider the
+ number of values passed from independent to dependent side. If that
+ set is larger than the max number of values in an IN criteria on the
+ dependent side, then we must break the query into a set of queries
+ and combine their results. Executing each query in the connector
+ has some overhead and that is taken into account. Without costing
+ information a lot of common cases where the only criteria specified
+ is on a non-unique (but strongly limiting) field are missed. A join
+ is eligible to be dependent if:</para>
+ <orderedlist>
+ <listitem>
+ <para>there is at least one equi-join criterion, i.e.
+ tablea.col = tableb.col</para>
+ </listitem>
+ <listitem>
+ <para>the join is not a full outer join and the dependent side of
+ the join is on the inner side of the join</para>
+ </listitem>
+ </orderedlist>
+
+ <para>The join will be made dependent if one of the following
+ conditions, listed in precedence order, holds:</para>
+
+ <orderedlist>
+ <listitem>
+ <para>There is an unsatisfied access pattern that can be
+ satisfied with the dependent join criteria</para>
+ </listitem>
+ <listitem>
+ <para>The potential dependent side of the join is marked with an
+ option makedep</para>
+ </listitem>
+ <listitem>
+ <para>(4.3.2) if costing was enabled, the estimated cost for the
+ dependent join (5.0+ possibly in each direction in the case of inner
+ joins) is computed and compared to not performing the dependent join.
+ If the costs were all determined (which requires all relevant table
+ cardinality, column ndv, and possibly nnv values to be populated) the
+ lowest is chosen.</para>
+ </listitem>
+ <listitem>
+ <para>If key metadata information indicates that the potential dependent side is not “small” and the other side is “not small” or (5.0.1) the potential dependent side is the inner side of a left outer join. </para>
+ </listitem>
+ </orderedlist>
+ <para>Dependent join is the key optimization we use to
+ efficiently process multi-source joins.</para>
+ <para>Instead of reading all of source A and all of source B
+ and joining them on A.x = B.x, we read all of A then build a set of
+ A.x that are passed as a criteria when querying B. In cases where A
+ is small and B is large, this can drastically reduce the data
+ retrieved from B, thus greatly speeding the overall query.</para>
+ </listitem>
+ <listitem>
+ <para>RuleChooseJoinStrategy - Determines the base join strategy.
+ Currently this is a decision as to whether to use a merge join rather
+ than the default strategy, which is a nested loop join. Ideally the
+ choice of a hash join would also be evaluated here. Also costing
+ should be used to determine the strategy cost. </para>
+ </listitem>
+ <listitem>
+ <para>RuleDecomposeJoin - this rule perfomrs a partition-wise join optimization on joins of <xref linkend="partitioned_union"/>.
+ The decision to decompose is based upon detecting that each side of the join is a partitioned union (note that non-ansi joins of more than 2 tables may cause the optimization to not detect the appropriate join).
+ The rule currently only looks for situations where at most 1 partition matches from each side.</para>
+ </listitem>
+ <listitem>
+ <para>RuleCollapseSource - this rule removes all nodes below an
+ Access node and collapses them into an equivalent query that is
+ placed in the Access node.</para>
+ </listitem>
+ <listitem>
+ <para>RuleAssignOutputElements - this rule walks top down through
+ every node and calculates the output columns for each node. Columns
+ that are not needed are dropped at every node. This is done by
+ keeping track of both the columns needed to feed the parent node and
+ also keeping track of columns that are “created” at a certain node.
+ </para>
+ </listitem>
+ <listitem>
+ <para>RuleValidateWhereAll - this rule validates a rarely used
+ model option.</para>
+ </listitem>
+ <listitem>
+ <para>RuleAccessPatternValidation - validates that all access
+ patterns have been satisfied.</para>
+ </listitem>
+ <listitem>
+ <para>RulePushLimit - pushes limit and offset information as far as possible in the plan.</para>
+ </listitem>
+ </itemizedlist>
+ </section>
+ <section>
+ <title>Procedure Planner</title>
+ <para>The procedure planner is fairly simple. It converts the
+ statements in the procedure into instructions in a program that will
+ be run during processing. This is mostly a 1-to-1 mapping and very little optimization is performed.</para>
+ </section>
+ <section>
+ <title>XML Planner</title>
+ <para>The XML Planner creates an XML plan that is relatively close
+ to the end result of the Procedure Planner – a program with instructions. Many of the
+ instructions are even similar (while loop, execute SQL, etc).
+ Additional instructions deal with producing the output result document
+ (adding elements and attributes). </para>
+ <para>The XML planner does several types of planning (not
+ necessarily in this order):</para>
+ <para>- Document selection - determine which tags of the virtual
+ document should be excluded from the output document. This is
+ done based on a combination of the model (which marks parts of the
+ document excluded) and the query (which may specify a subset of
+ columns to include in the SELECT clause). </para>
+ <para>- Criteria evaluation - breaks apart the user’s criteria,
+ determine which result set the criteria should be applied to, and
+ add that criteria to that result set query.</para>
+ <para>- Result set ordering - the query’s ORDER BY clause is broken
+ up and the ORDER BY is applied to each result set as necessary
+ </para>
+ <para>- Result set planning - ultimately, each result set is
+ planned using the relational planner and taking into account all
+ the impacts from the user’s query</para>
+ <para>- Program generation - a set of instructions to produce the
+ desired output document is produced, taking into account the final
+ result set queries and the excluded parts of the document.
+ Generally, this involves walking through the virtual document in
+ document order, executing queries as necessary and emitting
+ elements and attributes.</para>
+ <para>XML programs can also be recursive, which involves using
+ the same document fragment for both the initial fragment and a set
+ of repeated fragments (each a new query) until some termination
+ criteria or limit is met.</para>
+ </section>
+ </section>
+</chapter>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/sql_support.xml
===================================================================
--- trunk/documentation/reference/src/main/docbook/en-US/content/sql_support.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/sql_support.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1193 +0,0 @@
-<?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_support">
- <title>DML Support</title>
- <para>
- Teiid supports SQL for issuing queries and for defining view
- transformations; see also <link linkend="procedure_language">Procedure Language</link>
- for how SQL is used in virtual procedures and update procedures.
- </para>
- <para>
- Teiid provides nearly all of the functionality of SQL-92 DML.
- SQL-99 and later features are constantly being added based upon
- community need. The following does not attempt to cover SQL
- exhaustively, but rather highlights SQL's usage within Teiid. See
- the
- <link linkend="grammar">grammar</link>
- for the exact form of SQL accepted by Teiid.
- </para>
- <section id="identifiers">
- <title>Identifiers</title>
- <para> SQL commands contain references to tables and columns. These
- references are in the form of identifiers, which uniquely identify
- the tables and columns in the context of the command. All queries
- are processed in the context of a virtual database, or VDB.
- Because information can be federated across multiple sources,
- tables and columns must be scoped in some manner to avoid
- conflicts. This scoping is provided by schemas, which contain the
- information for each data source or set of views.</para>
- <itemizedlist>
- <para>Fully-qualified table and column names are of
- the following form, where the separate 'parts' of the identifier
- are delimited by periods.</para>
- <listitem>
- <para>TABLE: <schema_name>.<table_spec></para>
- </listitem>
- <listitem>
- <para>COLUMN: <schema_name>.<table_spec>.<column_name></para>
- </listitem>
- </itemizedlist>
- <itemizedlist>
- <para><emphasis>Syntax Rules:</emphasis></para>
- <listitem>
- <para>Identifiers can consist of alphanumeric characters,
- or the underscore (_) character, and must begin with an alphabetic
- character. Any Unicode character may be used in an identifier.
- </para>
- </listitem>
- <listitem>
- <para>Identifiers in double quotes can have any contents.
- The double quote character can it's be escaped with an additional double quote. e.g. "some "" id"
- </para>
- </listitem>
- <listitem>
- <para> Because different data sources organize tables in different
- ways, some prepending catalog or schema or user information,
- Teiid allows table specification to be a dot-delimited construct.
- <note>
- <para>When a table specification contains a dot resolving will allow for the match of
- a partial name against any number of the end segments in the name. e.g. a table with the
- fully-qualified name vdbname."sourcescema.sourcetable" would match the partial name
- sourcetable.
- </para>
- </note>
- </para>
- </listitem>
- <listitem>
- <para> Columns, schemas, and aliases identifiers cannot contain a dot.
- </para>
- </listitem>
- <listitem>
- <para> Identifiers, even when quoted, are not case-sensitive in Teiid.</para>
- </listitem>
- </itemizedlist>
- <itemizedlist>
- <para> Some examples of valid fully-qualified table identifiers are:
- </para>
- <listitem>
- <para>MySchema.Portfolios
- </para>
- </listitem>
- <listitem>
- <para>"MySchema.Portfolios"
- </para>
- </listitem>
- <listitem>
- <para>MySchema.MyCatalog.dbo.Authors
- </para>
- </listitem>
- </itemizedlist>
- <itemizedlist>
- <para>Some examples of valid fully-qualified column identifiers
- are:</para>
- <listitem>
- <para>MySchema.Portfolios.portfolioID
- </para>
- </listitem>
- <listitem>
- <para>"MySchema.Portfolios"."portfolioID"
- </para>
- </listitem>
- <listitem>
- <para>MySchema.MyCatalog.dbo.Authors.lastName
- </para>
- </listitem>
- </itemizedlist>
- <para> Fully-qualified identifiers can always be used in SQL commands.
- Partially- or unqualified forms can also be used, as long as the
- resulting names are unambiguous in the context of the command.
- Different forms of qualification can be mixed in the same query.
- </para>
- </section>
- <section>
- <title>Expressions</title>
- <para> Identifiers, literals, and functions can be combined into
- expressions. Expressions can be used almost anywhere in a query --
- SELECT, FROM (if specifying join criteria), WHERE, GROUP BY, HAVING, or ORDER BY.</para>
- <itemizedlist>
- <para>Teiid supports the following types of expressions:
- </para>
- <listitem>
- <para><link linkend="columnidentifiers">Column identifiers</link></para>
- </listitem>
- <listitem>
- <para><link linkend="literals">Literals</link></para>
- </listitem>
- <listitem>
- <para><link linkend="scalar_functions">Scalar functions</link></para>
- </listitem>
- <listitem>
- <para><link linkend="aggregate_functions">Aggregate functions</link></para>
- </listitem>
- <listitem>
- <para><link linkend="case">Case and searched case</link></para>
- </listitem>
- <listitem>
- <para><link linkend="scalar_subqueries">Scalar subqueries</link></para>
- </listitem>
- <listitem>
- <para><link linkend="parameter_references">Parameter references</link></para>
- </listitem>
- </itemizedlist>
- <section id="columnidentifiers">
- <title>Column Identifiers</title>
- <para>
- Column identifiers are used to specify the output columns in SELECT
- statements, the columns and their values for INSERT and UPDATE
- statements, and criteria used in WHERE and FROM clauses. They are
- also used in GROUP BY, HAVING, and ORDER BY clauses. The syntax for
- column identifiers was defined in the
- <link linkend="identifiers">Identifiers</link>
- section above.
- </para>
- </section>
- <section id="literals">
- <title>Literals</title>
- <para>
- Literal values represent fixed values. These can any of the 'standard' <link linkend="datatypes">data types</link>.
- </para>
- <itemizedlist>
- <para>Syntax Rules:</para>
- <listitem>
- <para>Integer values will be assigned an integral data type big enough to hold the value (integer, long, or biginteger).</para>
- </listitem>
- <listitem>
- <para>Floating point values will always be parsed as a double.</para>
- </listitem>
- <listitem>
- <para>The keyword 'null' is used to represent an absent or unknown value and is inherently untyped. In many cases, a null literal value will be assigned an implied type based on context. For example, in the function '5 + null', the null value will be assigned the type 'integer' to match the type of the value '5'. A null literal used in the SELECT clause of a query with no implied context will be assigned to type 'string'.</para>
- </listitem>
- </itemizedlist>
- <itemizedlist>
- <para>Some examples of simple literal values are:</para>
- <listitem>
- <para><literal>‘abc’</literal></para>
- </listitem>
- <listitem>
- <para><literal>‘isn’’t true’</literal> - use an extra single tick to escape a tick in a string with single ticks</para>
- </listitem>
- <listitem>
- <para><literal>5</literal></para>
- </listitem>
- <listitem>
- <para><literal>-37.75e01</literal> - scientific notation</para>
- </listitem>
- <listitem>
- <para><literal>100.0</literal> - parsed as double</para>
- </listitem>
- <listitem>
- <para><literal>true</literal></para>
- </listitem>
- <listitem>
- <para><literal>false</literal></para>
- </listitem>
- <listitem>
- <para><literal>'\u0027'</literal> - unicode character</para>
- </listitem>
- </itemizedlist>
- </section>
- <section id="aggregate_functions">
- <title>Aggregate Functions</title>
- <para>Aggregate functions take sets of values from a group produced by an explicit or implicit GROUP BY and return a single scalar value computed from the group.</para>
- <itemizedlist>
- <para>Teiid supports the following aggregate functions:</para>
- <listitem>
- <para>COUNT(*) – count the number of values (including nulls and duplicates) in a group</para>
- </listitem>
- <listitem>
- <para>COUNT(x) – count the number of values (excluding nulls) in a group</para>
- </listitem>
- <listitem>
- <para>SUM(x) – sum of the values (excluding nulls) in a group</para>
- </listitem>
- <listitem>
- <para>AVG(x) – average of the values (excluding nulls) in a group</para>
- </listitem>
- <listitem>
- <para>MIN(x) – minimum value in a group (excluding null)</para>
- </listitem>
- <listitem>
- <para>MAX(x) – maximum value in a group (excluding null)</para>
- </listitem>
- <listitem>
- <para>ANY(x)/SOME(x) – returns TRUE if any value in the group is TRUE (excluding null)</para>
- </listitem>
- <listitem>
- <para>EVERY(x) – returns TRUE if every value in the group is TRUE (excluding null)</para>
- </listitem>
- <listitem>
- <para>VAR_POP(x) – biased variance (excluding null) logically equals (sum(x^2) - sum(x)^2/count(x))/count(x); returns a double; null if count = 0</para>
- </listitem>
- <listitem>
- <para>VAR_SAMP(x) – sample variance (excluding null) logically equals (sum(x^2) - sum(x)^2/count(x))/(count(x) - 1); returns a double; null if count < 2</para>
- </listitem>
- <listitem>
- <para>STDDEV_POP(x) – standard deviation (excluding null) logically equals SQRT(VAR_POP(x))</para>
- </listitem>
- <listitem>
- <para>STDDEV_SAMP(x) – sample standar deviation (excluding null) logically equals SQRT(VAR_SAMP(x))</para>
- </listitem>
- <listitem>
- <para>TEXTAGG(FOR (expression [as name], ... [DELIMITER char] [QUOTE char] [HEADER] [ENCODING id]
- <link linkend="orderby_clause">[ORDER BY ...]</link>) – CSV text aggregation of all expressions in each row of a group.
- When DELIMITER is not specified, by default comma(,) is used as delimiter. Double quotes(") is the default quote character.
- Use QUOTE to specify a differnt value. All non-null values will be quoted.
- If HEADER is specified, the result contains the header row as the first line - the header line will be present even if there are no rows in a group.
- This aggregation returns a blob.
- </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>
- </listitem>
- </itemizedlist>
- <itemizedlist>
- <para>Syntax Rules:
- </para>
- <listitem>
- <para>Some aggregate functions may contain a keyword 'DISTINCT' before the expression, indicating that duplicate expression values should be ignored. DISTINCT is not allowed in COUNT(*) and is not meaningful in MIN or MAX (result would be unchanged), so it can be used in COUNT, SUM, and AVG.
- </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>
- </listitem>
- <listitem>
- <para>Aggregate functions may be nested inside other functions.
- </para>
- </listitem>
- </itemizedlist>
- <para>
- For more information on aggregates, see the sections on GROUP BY or HAVING.
- </para>
- </section>
- <section id="case">
- <title>Case and searched case</title>
- <para>
- Teiid supports two forms of the CASE expression which allows conditional logic in a scalar expression.
- </para>
- <itemizedlist>
- <para>Supported forms:
- </para>
- <listitem>
- <para>CASE <expr> ( WHEN <expr> THEN <expr>)+ [ELSE expr] END
- </para>
- </listitem>
- <listitem>
- <para>CASE ( WHEN <criteria> THEN <expr>)+ [ELSE expr] END
- </para>
- </listitem>
- </itemizedlist>
- <para>
- Each form allows for an output based on conditional logic. The first
- form starts with an initial expression and evaluates WHEN expressions
- until the values match, and outputs the THEN expression. If no WHEN is
- matched, the ELSE expression is output. If no WHEN is matched and no
- ELSE is specified, a null literal value is output. The second form
- (the searched case expression) searches the WHEN clauses, which
- specify an arbitrary criteria to evaluate. If any criteria evaluates
- to true, the THEN expression is evaluated and output. If no WHEN is
- true, the ELSE is evaluated or NULL is output if none exists.</para>
- </section>
- <section id="scalar_subqueries">
- <title>Scalar subqueries</title>
- <para>
- Subqueries can be used to produce a single scalar value in the SELECT,
- WHERE, or HAVING clauses only. A scalar subquery must have a single
- column in the SELECT clause and should return either 0 or 1 row. If no
- rows are returned, null will be returned as the scalar subquery value.
- For other types of subqueries, see the
- <link linkend="subqueires">Subqueries</link>
- section below.</para>
- </section>
- <section id="parameter_references">
- <title>Parameter references</title>
- <para> Parameters are specified using a '?' symbol. Parameters may
- only be used with PreparedStatement or CallableStatements in JDBC.
- Each parameter is linked to a value specified by 1-based index in
- the JDBC API.</para>
- </section>
- </section>
- <section id="criteria">
- <title>Criteria</title>
- <itemizedlist>
- <para>Criteria may be:
- </para>
- <listitem>
- <para>Predicates that evaluate to true or false
- </para>
- </listitem>
- <listitem>
- <para>Logical criteria that combines criteria (AND, OR, NOT)
- </para>
- </listitem>
- <listitem>
- <para>A value expression with type boolean
- </para>
- </listitem>
- </itemizedlist>
- <itemizedlist>
- <para>Syntax Rules:
- </para>
- <listitem>
- <para>expression (=|<>|!=|<|>|<=|>=) (expression|((ANY|ALL|SOME) subquery))
- </para>
- </listitem>
- <listitem>
- <para>expression [NOT] IS NULL
- </para>
- </listitem>
- <listitem>
- <para>expression [NOT] IN (expression[,expression]*)|subquery
- </para>
- </listitem>
- <listitem>
- <para>expression [NOT] LIKE expression [ESCAPE char]
- </para>
- </listitem>
- <listitem>
- <para>EXISTS(subquery)
- </para>
- </listitem>
- <listitem>
- <para>expression BETWEEN minExpression AND maxExpression
- </para>
- </listitem>
- <listitem>
- <para>criteria AND|OR criteria
- </para>
- </listitem>
- <listitem>
- <para>NOT criteria
- </para>
- </listitem>
- <listitem>
- <para>expression
- </para>
- </listitem>
- <listitem>
- <para>Criteria may be nested using parenthesis.
- </para>
- </listitem>
- </itemizedlist>
- <itemizedlist>
- <para>Some examples of valid criteria are:
- </para>
- <listitem>
- <para>(balance > 2500.0)
- </para>
- </listitem>
- <listitem>
- <para>100*(50 - x)/(25 - y) > z
- </para>
- </listitem>
- <listitem>
- <para>concat(areaCode,concat('-',phone)) LIKE '314%1'
- </para>
- </listitem>
- </itemizedlist>
- <note>
- <title>Comparing null Values</title>
- <para>Null values represent an unknown value. Comparison with a null value will evaluate to 'unknown', which can never be true even if 'not' is used.</para>
- </note>
- </section>
- <section id="sql_commands">
- <title>SQL Commands</title>
- <para>There are 4 basic commands for manipulating data in SQL, corresponding to the CRUD create, read, update, and delete operations: INSERT, SELECT, UPDATE, and DELETE. In addition, procedures can be executed using the EXECUTE command or through a <link linkend="procedural_relational">procedural relational command</link>.</para>
- <section id="select_command">
- <title>SELECT Command</title>
- <para>The SELECT command is used to retrieve records any number of relations.</para>
- <itemizedlist>
- <para>A SELECT command has a number of clauses:</para>
- <listitem>
- <para>
- <link linkend="with_clause">WITH ...</link>
- </para>
- </listitem>
- <listitem>
- <para>
- <link linkend="select_clause">SELECT ...</link>
- </para>
- </listitem>
- <listitem>
- <para>
- <link linkend="from_clause">[FROM ...]</link>
- </para>
- </listitem>
- <listitem>
- <para>
- <link linkend="where_clause">[WHERE ...]</link>
- </para>
- </listitem>
- <listitem>
- <para>
- <link linkend="groupby_clause">[GROUP BY ...]</link>
- </para>
- </listitem>
- <listitem>
- <para>
- <link linkend="having_clause">[HAVING ...]</link>
- </para>
- </listitem>
- <listitem>
- <para>
- <link linkend="orderby_clause">[ORDER BY ...]</link>
- </para>
- </listitem>
- <listitem>
- <para>
- <link linkend="limit_clause">[LIMIT [offset,] limit]</link>
- </para>
- </listitem>
- <listitem>
- <para>
- <link linkend="option_clause">[OPTION ...]</link>
- </para>
- </listitem>
- </itemizedlist>
- <para>
- All of these clauses other than OPTION are defined by the SQL specification. The specification also specifies the order that these clauses will be logically processed. Below is the processing order where each stage passes a set of rows to the following stage. Note that this processing model is logical and does not represent the way any actual database engine performs the processing, although it is a useful model for understanding questions about SQL.
- </para>
- <itemizedlist>
- <listitem>
- <para>WITH stage - gathers all rows from all with items in the order listed. Subsequent with items and the main query can reference the a with item as if it is a table.
- </para>
- </listitem>
- <listitem>
- <para>FROM stage - gathers all rows from all tables involved in the query and logically joins them with a Cartesian product, producing a single large table with all columns from all tables. Joins and join criteria are then applied to filter rows that do not match the join structure.
- </para>
- </listitem>
- <listitem>
- <para>WHERE stage - applies a criteria to every output row from the FROM stage, further reducing the number of rows.
- </para>
- </listitem>
- <listitem>
- <para>GROUP BY stage - groups sets of rows with matching values in the group by columns.
- </para>
- </listitem>
- <listitem>
- <para>HAVING stage - applies criteria to each group of rows. Criteria can only be applied to columns that will have constant values within a group (those in the grouping columns or aggregate functions applied across the group).
- </para>
- </listitem>
- <listitem>
- <para>SELECT stage - specifies the column expressions that should be returned from the query. Expressions are evaluated, including aggregate functions based on the groups of rows, which will no longer exist after this point. The output columns are named using either column aliases or an implicit name determined by the engine. If SELECT DISTINCT is specified, duplicate removal will be performed on the rows being returned from the SELECT stage.
- </para>
- </listitem>
- <listitem>
- <para>ORDER BY stage - sorts the rows returned from the SELECT stage as desired. Supports sorting on multiple columns in specified order, ascending or descending. The output columns will be identical to those columns returned from the SELECT stage and will have the same name.
- </para>
- </listitem>
- <listitem>
- <para>LIMIT stage - returns only the specified rows (with skip and limit values).
- </para>
- </listitem>
- </itemizedlist>
- <para> This model can be used to understand many questions about SQL.
- For example, columns aliased in the SELECT clause can only be
- referenced by alias in the ORDER BY clause. Without knowledge of the
- processing model, this can be somewhat confusing. Seen in light of
- the model, it is clear that the ORDER BY stage is the only stage
- occurring after the SELECT stage, which is where the columns are
- named. Because the WHERE clause is processed before the SELECT, the
- columns have not yet been named and the aliases are not yet known.
- </para>
- <note>
- <para>
- The explicit table syntax <code>TABLE x</code> may be used as a shortcut for <code>SELECT * FROM x</code>.
- </para>
- </note>
- </section>
- <section id="insert_command">
- <title>INSERT Command</title>
- <para>The INSERT command is used to add a record to a table.</para>
- <itemizedlist>
- <para>Example Syntax</para>
- <listitem>
- <para>INSERT INTO table (column,...) VALUES (value,...)
- </para>
- </listitem>
- <listitem>
- <para>INSERT INTO table (column,...) query
- </para>
- </listitem>
- </itemizedlist>
- </section>
- <section id="update_command">
- <title>UPDATE Command</title>
- <para>The UPDATE command is used to modify records in a table. The operation may result in 1 or more records being updated, or in no records being updated if none match the criteria.</para>
- <itemizedlist>
- <para>Example Syntax</para>
- <listitem>
- <para>UPDATE table SET (column=value,...) [WHERE criteria]
- </para>
- </listitem>
- </itemizedlist>
- </section>
- <section id="delete_command">
- <title>DELETE Command</title>
- <para>The DELETE command is used to remove records from a table. The operation may result in 1 or more records being deleted, or in no records being deleted if none match the criteria. </para>
- <itemizedlist>
- <para>Example Syntax</para>
- <listitem>
- <para>DELETE FROM table [WHERE criteria]
- </para>
- </listitem>
- </itemizedlist>
- </section>
- <section id="exec_command">
- <title>EXECUTE Command</title>
- <para>The EXECUTE command is used to execute a procedure, such as a virtual procedure or a stored procedure. Procedures may have zero or more scalar input parameters. The return value from a procedure is a result set, the same as is returned from a SELECT. Note that EXEC or CALL can be used as a short form of this command.
- </para>
- <itemizedlist>
- <para>Example Syntax</para>
- <listitem>
- <para>EXECUTE proc()
- </para>
- </listitem>
- <listitem>
- <para>EXECUTE proc(value, ...)
- </para>
- </listitem>
- <listitem>
- <para>EXECUTE proc(name1=>value1,name4=>param4, ...) - named parameter syntax
- </para>
- </listitem>
- </itemizedlist>
- <itemizedlist>
- <para>Syntax Rules:
- </para>
- <listitem>
- <para>The default order of parameter specification is the same
- as how they are defined in the procedure definition.
- </para>
- </listitem>
- <listitem>
- <para>You can specify the parameters in any order by name. Parameters that are have
- default values and/or are nullable in the metadata, can be omitted
- from the named parameter call and will have the appropriate value
- passed at runtime.
- </para>
- </listitem>
- <listitem>
- <para>If the procedure does not return a result set, the values from the RETURN, OUT, and IN_OUT parameters will be returned as a single row when used as an inline view query.
- </para>
- </listitem>
- </itemizedlist>
- </section>
- <section id="procedural_relational">
- <title>Procedural Relational Command</title>
- <para> Procedural relational commands use the syntax of a SELECT to
- emulate an EXEC. In a procedural relational command a procedure group
- names is used in a FROM clause in place of a table. That procedure
- will be executed in place of a normal table access if all of the
- necessary input values can be found in criteria against the procedure.
- Each combination of input values found in the criteria results in an execution of the procedure.
- </para>
- <para>
- <itemizedlist>
- <para>Example Syntax</para>
- <listitem>
- <para>select * from proc
- </para>
- </listitem>
- <listitem>
- <para>select output_param1, output_param2 from proc where input_param1 = 'x'
- </para>
- </listitem>
- <listitem>
- <para>select output_param1, output_param2 from proc, table where input_param1 = table.col1 and input_param2 = table.col2
- </para>
- </listitem>
- </itemizedlist>
- <itemizedlist>
- <para>Syntax Rules:</para>
- <listitem>
- <para>The procedure as a table projects the same columns as an exec with the addition of the input parameters.
- For procedures that do not return a result set, IN_OUT columns will be projected as two columns, one that represents
- the output value and one named {column name}_IN that represents the
- input of the parameter.</para>
- </listitem>
- <listitem>
- <para>Input values are passed via criteria. Values can be passed by '=','is null', or 'in' predicates. Disjuncts are not allowed.
- It is also not possible to pass the value of a non-comparable column through an equality predicate.
- </para>
- </listitem>
- <listitem>
- <para>The procedure view automatically has an access pattern on its IN and IN_OUT parameters which
- allows it to be planned correctly as a dependent join when necessary or fail when sufficient criteria cannot be found.
- </para>
- </listitem>
- <listitem>
- <para>Procedures containing duplicate names between the parameters (IN, IN_OUT, OUT, RETURN) and result set columns
- cannot be used in a procedural relational command.
- </para>
- </listitem>
- <listitem>
- <para>Default values for IN, IN_OUT parameters are not used if there is no criteria present for a given input. Default values are
- only valid for <link linkend="exec_command">named procedure syntax</link>.
- </para>
- </listitem>
- </itemizedlist>
- </para>
- <note>
- <title>Multiple Execution</title>
- <para>The usage of 'in' or join criteria can result in
- the procedure being executed multiple times.</para>
- </note>
- <note>
- <title>Alternative Syntax</title>
- <para>
- None of issues listed in the syntax rules above exist if a <link linkend="nested_table">nested table reference</link> is used.
- </para>
- </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 <COLUMN>, ... [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([<NSP>,] xquery-expression [<PASSING>] [COLUMNS <COLUMN>, ... )] 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 '<a id="1"/>') 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 <COLUMN>, ...) 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>
- <para>
- Usage:
- <synopsis label="Usage">queryExpression (UNION|INTERSECT|EXCEPT) [ALL] queryExpression [ORDER BY...]</synopsis>
- </para>
- <itemizedlist>
- <para>Syntax Rules:
- </para>
- <listitem>
- <para>The output columns will be named by the output columns of the first set operation branch.
- </para>
- </listitem>
- <listitem>
- <para>Each SELECT must have the same number of output columns and compatible data types for each relative column. Data type conversion will be performed if data types are inconsistent and implicit conversions exist.
- </para>
- </listitem>
- <listitem>
- <para>If UNION, INTERSECT, or EXCEPT is specified without all, then the output columns must be comparable types.
- </para>
- </listitem>
- <listitem>
- <para>INTERSECT ALL, and EXCEPT ALL are currently not supported.</para>
- </listitem>
- </itemizedlist>
- </section>
- <section id="subqueries">
- <title>Subqueries</title>
- <para>A subquery is a SQL query embedded within another SQL query. The query containing the subquery is the outer query.</para>
- <itemizedlist>
- <para>Supported subquery types:
- </para>
- <listitem>
- <para>Scalar subquery - a subquery that returns only a single column with a single value. Scalar subqueries are a type of expression and can be used where single valued expressions are expected.
- </para>
- </listitem>
- <listitem>
- <para>Correlated subquery - a subquery that contains a column reference to from the outer query.
- </para>
- </listitem>
- <listitem>
- <para>Uncorrelated subquery - a subquery that contains no references to the outer sub-query.
- </para>
- </listitem>
- </itemizedlist>
- <section id="from_subquery">
- <title>Inline views</title>
- <para>Subqueries in the FROM clause of the outer query (also known as
- "inline views") can return any number of rows and columns. This type
- of subquery must always be given an alias. An inline view is nearly identical to a traditional view. See also <xref linkend="with_clause"/>.</para>
- <example>
- <title>Example Subquery in FROM Clause (Inline View)</title>
- <programlisting language="SQL">SELECT a FROM (SELECT Y.b, Y.c FROM Y WHERE Y.d = ‘3’) AS X WHERE a = X.c AND b = X.b</programlisting>
- </example>
- </section>
- <section id="other_subqueries">
- <title>Subqueries can appear anywhere where an expression or criteria is expected.</title>
- <para>Subqueries are supported in quantified criteria, the EXISTS predicate, the IN predicate, and as <xref linkend="scalar_subqueries"/>.</para>
- <example>
- <title>Example Subquery in WHERE Using EXISTS</title>
- <programlisting>SELECT a FROM X WHERE EXISTS (SELECT 1 FROM Y WHERE c=X.a)</programlisting>
- </example>
- <example>
- <title>Example Quantified Comparison Subqueries</title>
- <programlisting language="SQL">SELECT a FROM X WHERE a >= ANY (SELECT b FROM Y WHERE c=3)
-SELECT a FROM X WHERE a < SOME (SELECT b FROM Y WHERE c=4)
-SELECT a FROM X WHERE a = ALL (SELECT b FROM Y WHERE c=2)</programlisting>
- </example>
- <example>
- <title>Example IN Subquery</title>
- <programlisting language="SQL">SELECT a FROM X WHERE a IN (SELECT b FROM Y WHERE c=3)</programlisting>
- </example>
- <para>See also <xref linkend="subquery_optimization"/>.</para>
- </section>
- </section>
-</chapter>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/sql_support.xml (from rev 3218, trunk/documentation/reference/src/main/docbook/en-US/content/sql_support.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/sql_support.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/sql_support.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1195 @@
+<?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_support">
+ <title>DML Support</title>
+ <para>
+ Teiid supports SQL for issuing queries and for defining view
+ transformations; see also <link linkend="procedure_language">Procedure Language</link>
+ for how SQL is used in virtual procedures and update procedures.
+ </para>
+ <para>
+ Teiid provides nearly all of the functionality of SQL-92 DML.
+ SQL-99 and later features are constantly being added based upon
+ community need. The following does not attempt to cover SQL
+ exhaustively, but rather highlights SQL's usage within Teiid. See
+ the
+ <link linkend="grammar">grammar</link>
+ for the exact form of SQL accepted by Teiid.
+ </para>
+ <section id="identifiers">
+ <title>Identifiers</title>
+ <para> SQL commands contain references to tables and columns. These
+ references are in the form of identifiers, which uniquely identify
+ the tables and columns in the context of the command. All queries
+ are processed in the context of a virtual database, or VDB.
+ Because information can be federated across multiple sources,
+ tables and columns must be scoped in some manner to avoid
+ conflicts. This scoping is provided by schemas, which contain the
+ information for each data source or set of views.</para>
+ <itemizedlist>
+ <para>Fully-qualified table and column names are of
+ the following form, where the separate 'parts' of the identifier
+ are delimited by periods.</para>
+ <listitem>
+ <para>TABLE: <schema_name>.<table_spec></para>
+ </listitem>
+ <listitem>
+ <para>COLUMN: <schema_name>.<table_spec>.<column_name></para>
+ </listitem>
+ </itemizedlist>
+ <itemizedlist>
+ <para><emphasis>Syntax Rules:</emphasis></para>
+ <listitem>
+ <para>Identifiers can consist of alphanumeric characters,
+ or the underscore (_) character, and must begin with an alphabetic
+ character. Any Unicode character may be used in an identifier.
+ </para>
+ </listitem>
+ <listitem>
+ <para>Identifiers in double quotes can have any contents.
+ The double quote character can it's be escaped with an additional double quote. e.g. "some "" id"
+ </para>
+ </listitem>
+ <listitem>
+ <para> Because different data sources organize tables in different
+ ways, some prepending catalog or schema or user information,
+ Teiid allows table specification to be a dot-delimited construct.
+ <note>
+ <para>When a table specification contains a dot resolving will allow for the match of
+ a partial name against any number of the end segments in the name. e.g. a table with the
+ fully-qualified name vdbname."sourcescema.sourcetable" would match the partial name
+ sourcetable.
+ </para>
+ </note>
+ </para>
+ </listitem>
+ <listitem>
+ <para> Columns, schemas, and aliases identifiers cannot contain a dot.
+ </para>
+ </listitem>
+ <listitem>
+ <para> Identifiers, even when quoted, are not case-sensitive in Teiid.</para>
+ </listitem>
+ </itemizedlist>
+ <itemizedlist>
+ <para> Some examples of valid fully-qualified table identifiers are:
+ </para>
+ <listitem>
+ <para>MySchema.Portfolios
+ </para>
+ </listitem>
+ <listitem>
+ <para>"MySchema.Portfolios"
+ </para>
+ </listitem>
+ <listitem>
+ <para>MySchema.MyCatalog.dbo.Authors
+ </para>
+ </listitem>
+ </itemizedlist>
+ <itemizedlist>
+ <para>Some examples of valid fully-qualified column identifiers
+ are:</para>
+ <listitem>
+ <para>MySchema.Portfolios.portfolioID
+ </para>
+ </listitem>
+ <listitem>
+ <para>"MySchema.Portfolios"."portfolioID"
+ </para>
+ </listitem>
+ <listitem>
+ <para>MySchema.MyCatalog.dbo.Authors.lastName
+ </para>
+ </listitem>
+ </itemizedlist>
+ <para> Fully-qualified identifiers can always be used in SQL commands.
+ Partially- or unqualified forms can also be used, as long as the
+ resulting names are unambiguous in the context of the command.
+ Different forms of qualification can be mixed in the same query.
+ </para>
+ </section>
+ <section>
+ <title>Expressions</title>
+ <para> Identifiers, literals, and functions can be combined into
+ expressions. Expressions can be used almost anywhere in a query --
+ SELECT, FROM (if specifying join criteria), WHERE, GROUP BY, HAVING, or ORDER BY.</para>
+ <itemizedlist>
+ <para>Teiid supports the following types of expressions:
+ </para>
+ <listitem>
+ <para><link linkend="columnidentifiers">Column identifiers</link></para>
+ </listitem>
+ <listitem>
+ <para><link linkend="literals">Literals</link></para>
+ </listitem>
+ <listitem>
+ <para><link linkend="scalar_functions">Scalar functions</link></para>
+ </listitem>
+ <listitem>
+ <para><link linkend="aggregate_functions">Aggregate functions</link></para>
+ </listitem>
+ <listitem>
+ <para><link linkend="case">Case and searched case</link></para>
+ </listitem>
+ <listitem>
+ <para><link linkend="scalar_subqueries">Scalar subqueries</link></para>
+ </listitem>
+ <listitem>
+ <para><link linkend="parameter_references">Parameter references</link></para>
+ </listitem>
+ </itemizedlist>
+ <section id="columnidentifiers">
+ <title>Column Identifiers</title>
+ <para>
+ Column identifiers are used to specify the output columns in SELECT
+ statements, the columns and their values for INSERT and UPDATE
+ statements, and criteria used in WHERE and FROM clauses. They are
+ also used in GROUP BY, HAVING, and ORDER BY clauses. The syntax for
+ column identifiers was defined in the
+ <link linkend="identifiers">Identifiers</link>
+ section above.
+ </para>
+ </section>
+ <section id="literals">
+ <title>Literals</title>
+ <para>
+ Literal values represent fixed values. These can any of the 'standard' <link linkend="datatypes">data types</link>.
+ </para>
+ <itemizedlist>
+ <para>Syntax Rules:</para>
+ <listitem>
+ <para>Integer values will be assigned an integral data type big enough to hold the value (integer, long, or biginteger).</para>
+ </listitem>
+ <listitem>
+ <para>Floating point values will always be parsed as a double.</para>
+ </listitem>
+ <listitem>
+ <para>The keyword 'null' is used to represent an absent or unknown value and is inherently untyped. In many cases, a null literal value will be assigned an implied type based on context. For example, in the function '5 + null', the null value will be assigned the type 'integer' to match the type of the value '5'. A null literal used in the SELECT clause of a query with no implied context will be assigned to type 'string'.</para>
+ </listitem>
+ </itemizedlist>
+ <itemizedlist>
+ <para>Some examples of simple literal values are:</para>
+ <listitem>
+ <para><literal>‘abc’</literal></para>
+ </listitem>
+ <listitem>
+ <para><literal>‘isn’’t true’</literal> - use an extra single tick to escape a tick in a string with single ticks</para>
+ </listitem>
+ <listitem>
+ <para><literal>5</literal></para>
+ </listitem>
+ <listitem>
+ <para><literal>-37.75e01</literal> - scientific notation</para>
+ </listitem>
+ <listitem>
+ <para><literal>100.0</literal> - parsed as double</para>
+ </listitem>
+ <listitem>
+ <para><literal>true</literal></para>
+ </listitem>
+ <listitem>
+ <para><literal>false</literal></para>
+ </listitem>
+ <listitem>
+ <para><literal>'\u0027'</literal> - unicode character</para>
+ </listitem>
+ </itemizedlist>
+ </section>
+ <section id="aggregate_functions">
+ <title>Aggregate Functions</title>
+ <para>Aggregate functions take sets of values from a group produced by an explicit or implicit GROUP BY and return a single scalar value computed from the group.</para>
+ <itemizedlist>
+ <para>Teiid supports the following aggregate functions:</para>
+ <listitem>
+ <para>COUNT(*) – count the number of values (including nulls and duplicates) in a group</para>
+ </listitem>
+ <listitem>
+ <para>COUNT(x) – count the number of values (excluding nulls) in a group</para>
+ </listitem>
+ <listitem>
+ <para>SUM(x) – sum of the values (excluding nulls) in a group</para>
+ </listitem>
+ <listitem>
+ <para>AVG(x) – average of the values (excluding nulls) in a group</para>
+ </listitem>
+ <listitem>
+ <para>MIN(x) – minimum value in a group (excluding null)</para>
+ </listitem>
+ <listitem>
+ <para>MAX(x) – maximum value in a group (excluding null)</para>
+ </listitem>
+ <listitem>
+ <para>ANY(x)/SOME(x) – returns TRUE if any value in the group is TRUE (excluding null)</para>
+ </listitem>
+ <listitem>
+ <para>EVERY(x) – returns TRUE if every value in the group is TRUE (excluding null)</para>
+ </listitem>
+ <listitem>
+ <para>VAR_POP(x) – biased variance (excluding null) logically equals (sum(x^2) - sum(x)^2/count(x))/count(x); returns a double; null if count = 0</para>
+ </listitem>
+ <listitem>
+ <para>VAR_SAMP(x) – sample variance (excluding null) logically equals (sum(x^2) - sum(x)^2/count(x))/(count(x) - 1); returns a double; null if count < 2</para>
+ </listitem>
+ <listitem>
+ <para>STDDEV_POP(x) – standard deviation (excluding null) logically equals SQRT(VAR_POP(x))</para>
+ </listitem>
+ <listitem>
+ <para>STDDEV_SAMP(x) – sample standar deviation (excluding null) logically equals SQRT(VAR_SAMP(x))</para>
+ </listitem>
+ <listitem>
+ <para>TEXTAGG(FOR (expression [as name], ... [DELIMITER char] [QUOTE char] [HEADER] [ENCODING id]
+ <link linkend="orderby_clause">[ORDER BY ...]</link>) – CSV text aggregation of all expressions in each row of a group.
+ When DELIMITER is not specified, by default comma(,) is used as delimiter. Double quotes(") is the default quote character.
+ Use QUOTE to specify a differnt value. All non-null values will be quoted.
+ If HEADER is specified, the result contains the header row as the first line - the header line will be present even if there are no rows in a group.
+ This aggregation returns a blob.
+ </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>
+ </listitem>
+ </itemizedlist>
+ <itemizedlist>
+ <para>Syntax Rules:
+ </para>
+ <listitem>
+ <para>Some aggregate functions may contain a keyword 'DISTINCT' before the expression, indicating that duplicate expression values should be ignored. DISTINCT is not allowed in COUNT(*) and is not meaningful in MIN or MAX (result would be unchanged), so it can be used in COUNT, SUM, and AVG.
+ </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>
+ </listitem>
+ <listitem>
+ <para>Aggregate functions may be nested inside other functions.
+ </para>
+ </listitem>
+ </itemizedlist>
+ <para>
+ For more information on aggregates, see the sections on GROUP BY or HAVING.
+ </para>
+ </section>
+ <section id="case">
+ <title>Case and searched case</title>
+ <para>
+ Teiid supports two forms of the CASE expression which allows conditional logic in a scalar expression.
+ </para>
+ <itemizedlist>
+ <para>Supported forms:
+ </para>
+ <listitem>
+ <para>CASE <expr> ( WHEN <expr> THEN <expr>)+ [ELSE expr] END
+ </para>
+ </listitem>
+ <listitem>
+ <para>CASE ( WHEN <criteria> THEN <expr>)+ [ELSE expr] END
+ </para>
+ </listitem>
+ </itemizedlist>
+ <para>
+ Each form allows for an output based on conditional logic. The first
+ form starts with an initial expression and evaluates WHEN expressions
+ until the values match, and outputs the THEN expression. If no WHEN is
+ matched, the ELSE expression is output. If no WHEN is matched and no
+ ELSE is specified, a null literal value is output. The second form
+ (the searched case expression) searches the WHEN clauses, which
+ specify an arbitrary criteria to evaluate. If any criteria evaluates
+ to true, the THEN expression is evaluated and output. If no WHEN is
+ true, the ELSE is evaluated or NULL is output if none exists.</para>
+ </section>
+ <section id="scalar_subqueries">
+ <title>Scalar subqueries</title>
+ <para>
+ Subqueries can be used to produce a single scalar value in the SELECT,
+ WHERE, or HAVING clauses only. A scalar subquery must have a single
+ column in the SELECT clause and should return either 0 or 1 row. If no
+ rows are returned, null will be returned as the scalar subquery value.
+ For other types of subqueries, see the
+ <link linkend="subqueires">Subqueries</link>
+ section below.</para>
+ </section>
+ <section id="parameter_references">
+ <title>Parameter references</title>
+ <para> Parameters are specified using a '?' symbol. Parameters may
+ only be used with PreparedStatement or CallableStatements in JDBC.
+ Each parameter is linked to a value specified by 1-based index in
+ the JDBC API.</para>
+ </section>
+ </section>
+ <section id="criteria">
+ <title>Criteria</title>
+ <itemizedlist>
+ <para>Criteria may be:
+ </para>
+ <listitem>
+ <para>Predicates that evaluate to true or false
+ </para>
+ </listitem>
+ <listitem>
+ <para>Logical criteria that combines criteria (AND, OR, NOT)
+ </para>
+ </listitem>
+ <listitem>
+ <para>A value expression with type boolean
+ </para>
+ </listitem>
+ </itemizedlist>
+ <itemizedlist>
+ <para>Syntax Rules:
+ </para>
+ <listitem>
+ <para>expression (=|<>|!=|<|>|<=|>=) (expression|((ANY|ALL|SOME) subquery))
+ </para>
+ </listitem>
+ <listitem>
+ <para>expression [NOT] IS NULL
+ </para>
+ </listitem>
+ <listitem>
+ <para>expression [NOT] IN (expression[,expression]*)|subquery
+ </para>
+ </listitem>
+ <listitem>
+ <para>expression [NOT] LIKE expression [ESCAPE char]
+ </para>
+ </listitem>
+ <listitem>
+ <para>EXISTS(subquery)
+ </para>
+ </listitem>
+ <listitem>
+ <para>expression BETWEEN minExpression AND maxExpression
+ </para>
+ </listitem>
+ <listitem>
+ <para>criteria AND|OR criteria
+ </para>
+ </listitem>
+ <listitem>
+ <para>NOT criteria
+ </para>
+ </listitem>
+ <listitem>
+ <para>expression
+ </para>
+ </listitem>
+ <listitem>
+ <para>Criteria may be nested using parenthesis.
+ </para>
+ </listitem>
+ </itemizedlist>
+ <itemizedlist>
+ <para>Some examples of valid criteria are:
+ </para>
+ <listitem>
+ <para>(balance > 2500.0)
+ </para>
+ </listitem>
+ <listitem>
+ <para>100*(50 - x)/(25 - y) > z
+ </para>
+ </listitem>
+ <listitem>
+ <para>concat(areaCode,concat('-',phone)) LIKE '314%1'
+ </para>
+ </listitem>
+ </itemizedlist>
+ <note>
+ <title>Comparing null Values</title>
+ <para>Null values represent an unknown value. Comparison with a null value will evaluate to 'unknown', which can never be true even if 'not' is used.</para>
+ </note>
+ </section>
+ <section id="sql_commands">
+ <title>SQL Commands</title>
+ <para>There are 4 basic commands for manipulating data in SQL, corresponding to the CRUD create, read, update, and delete operations: INSERT, SELECT, UPDATE, and DELETE. In addition, procedures can be executed using the EXECUTE command or through a <link linkend="procedural_relational">procedural relational command</link>.</para>
+ <section id="select_command">
+ <title>SELECT Command</title>
+ <para>The SELECT command is used to retrieve records any number of relations.</para>
+ <itemizedlist>
+ <para>A SELECT command has a number of clauses:</para>
+ <listitem>
+ <para>
+ <link linkend="with_clause">WITH ...</link>
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <link linkend="select_clause">SELECT ...</link>
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <link linkend="from_clause">[FROM ...]</link>
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <link linkend="where_clause">[WHERE ...]</link>
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <link linkend="groupby_clause">[GROUP BY ...]</link>
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <link linkend="having_clause">[HAVING ...]</link>
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <link linkend="orderby_clause">[ORDER BY ...]</link>
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <link linkend="limit_clause">[LIMIT [offset,] limit]</link>
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <link linkend="option_clause">[OPTION ...]</link>
+ </para>
+ </listitem>
+ </itemizedlist>
+ <para>
+ All of these clauses other than OPTION are defined by the SQL specification. The specification also specifies the order that these clauses will be logically processed. Below is the processing order where each stage passes a set of rows to the following stage. Note that this processing model is logical and does not represent the way any actual database engine performs the processing, although it is a useful model for understanding questions about SQL.
+ </para>
+ <itemizedlist>
+ <listitem>
+ <para>WITH stage - gathers all rows from all with items in the order listed. Subsequent with items and the main query can reference the a with item as if it is a table.
+ </para>
+ </listitem>
+ <listitem>
+ <para>FROM stage - gathers all rows from all tables involved in the query and logically joins them with a Cartesian product, producing a single large table with all columns from all tables. Joins and join criteria are then applied to filter rows that do not match the join structure.
+ </para>
+ </listitem>
+ <listitem>
+ <para>WHERE stage - applies a criteria to every output row from the FROM stage, further reducing the number of rows.
+ </para>
+ </listitem>
+ <listitem>
+ <para>GROUP BY stage - groups sets of rows with matching values in the group by columns.
+ </para>
+ </listitem>
+ <listitem>
+ <para>HAVING stage - applies criteria to each group of rows. Criteria can only be applied to columns that will have constant values within a group (those in the grouping columns or aggregate functions applied across the group).
+ </para>
+ </listitem>
+ <listitem>
+ <para>SELECT stage - specifies the column expressions that should be returned from the query. Expressions are evaluated, including aggregate functions based on the groups of rows, which will no longer exist after this point. The output columns are named using either column aliases or an implicit name determined by the engine. If SELECT DISTINCT is specified, duplicate removal will be performed on the rows being returned from the SELECT stage.
+ </para>
+ </listitem>
+ <listitem>
+ <para>ORDER BY stage - sorts the rows returned from the SELECT stage as desired. Supports sorting on multiple columns in specified order, ascending or descending. The output columns will be identical to those columns returned from the SELECT stage and will have the same name.
+ </para>
+ </listitem>
+ <listitem>
+ <para>LIMIT stage - returns only the specified rows (with skip and limit values).
+ </para>
+ </listitem>
+ </itemizedlist>
+ <para> This model can be used to understand many questions about SQL.
+ For example, columns aliased in the SELECT clause can only be
+ referenced by alias in the ORDER BY clause. Without knowledge of the
+ processing model, this can be somewhat confusing. Seen in light of
+ the model, it is clear that the ORDER BY stage is the only stage
+ occurring after the SELECT stage, which is where the columns are
+ named. Because the WHERE clause is processed before the SELECT, the
+ columns have not yet been named and the aliases are not yet known.
+ </para>
+ <note>
+ <para>
+ The explicit table syntax <code>TABLE x</code> may be used as a shortcut for <code>SELECT * FROM x</code>.
+ </para>
+ </note>
+ </section>
+ <section id="insert_command">
+ <title>INSERT Command</title>
+ <para>The INSERT command is used to add a record to a table.</para>
+ <itemizedlist>
+ <para>Example Syntax</para>
+ <listitem>
+ <para>INSERT INTO table (column,...) VALUES (value,...)
+ </para>
+ </listitem>
+ <listitem>
+ <para>INSERT INTO table (column,...) query
+ </para>
+ </listitem>
+ </itemizedlist>
+ </section>
+ <section id="update_command">
+ <title>UPDATE Command</title>
+ <para>The UPDATE command is used to modify records in a table. The operation may result in 1 or more records being updated, or in no records being updated if none match the criteria.</para>
+ <itemizedlist>
+ <para>Example Syntax</para>
+ <listitem>
+ <para>UPDATE table SET (column=value,...) [WHERE criteria]
+ </para>
+ </listitem>
+ </itemizedlist>
+ </section>
+ <section id="delete_command">
+ <title>DELETE Command</title>
+ <para>The DELETE command is used to remove records from a table. The operation may result in 1 or more records being deleted, or in no records being deleted if none match the criteria. </para>
+ <itemizedlist>
+ <para>Example Syntax</para>
+ <listitem>
+ <para>DELETE FROM table [WHERE criteria]
+ </para>
+ </listitem>
+ </itemizedlist>
+ </section>
+ <section id="exec_command">
+ <title>EXECUTE Command</title>
+ <para>The EXECUTE command is used to execute a procedure, such as a virtual procedure or a stored procedure. Procedures may have zero or more scalar input parameters. The return value from a procedure is a result set, the same as is returned from a SELECT. Note that EXEC or CALL can be used as a short form of this command.
+ </para>
+ <itemizedlist>
+ <para>Example Syntax</para>
+ <listitem>
+ <para>EXECUTE proc()
+ </para>
+ </listitem>
+ <listitem>
+ <para>EXECUTE proc(value, ...)
+ </para>
+ </listitem>
+ <listitem>
+ <para>EXECUTE proc(name1=>value1,name4=>param4, ...) - named parameter syntax
+ </para>
+ </listitem>
+ </itemizedlist>
+ <itemizedlist>
+ <para>Syntax Rules:
+ </para>
+ <listitem>
+ <para>The default order of parameter specification is the same
+ as how they are defined in the procedure definition.
+ </para>
+ </listitem>
+ <listitem>
+ <para>You can specify the parameters in any order by name. Parameters that are have
+ default values and/or are nullable in the metadata, can be omitted
+ from the named parameter call and will have the appropriate value
+ passed at runtime.
+ </para>
+ </listitem>
+ <listitem>
+ <para>If the procedure does not return a result set, the values from the RETURN, OUT, and IN_OUT parameters will be returned as a single row when used as an inline view query.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </section>
+ <section id="procedural_relational">
+ <title>Procedural Relational Command</title>
+ <para> Procedural relational commands use the syntax of a SELECT to
+ emulate an EXEC. In a procedural relational command a procedure group
+ names is used in a FROM clause in place of a table. That procedure
+ will be executed in place of a normal table access if all of the
+ necessary input values can be found in criteria against the procedure.
+ Each combination of input values found in the criteria results in an execution of the procedure.
+ </para>
+ <para>
+ <itemizedlist>
+ <para>Example Syntax</para>
+ <listitem>
+ <para>select * from proc
+ </para>
+ </listitem>
+ <listitem>
+ <para>select output_param1, output_param2 from proc where input_param1 = 'x'
+ </para>
+ </listitem>
+ <listitem>
+ <para>select output_param1, output_param2 from proc, table where input_param1 = table.col1 and input_param2 = table.col2
+ </para>
+ </listitem>
+ </itemizedlist>
+ <itemizedlist>
+ <para>Syntax Rules:</para>
+ <listitem>
+ <para>The procedure as a table projects the same columns as an exec with the addition of the input parameters.
+ For procedures that do not return a result set, IN_OUT columns will be projected as two columns, one that represents
+ the output value and one named {column name}_IN that represents the
+ input of the parameter.</para>
+ </listitem>
+ <listitem>
+ <para>Input values are passed via criteria. Values can be passed by '=','is null', or 'in' predicates. Disjuncts are not allowed.
+ It is also not possible to pass the value of a non-comparable column through an equality predicate.
+ </para>
+ </listitem>
+ <listitem>
+ <para>The procedure view automatically has an access pattern on its IN and IN_OUT parameters which
+ allows it to be planned correctly as a dependent join when necessary or fail when sufficient criteria cannot be found.
+ </para>
+ </listitem>
+ <listitem>
+ <para>Procedures containing duplicate names between the parameters (IN, IN_OUT, OUT, RETURN) and result set columns
+ cannot be used in a procedural relational command.
+ </para>
+ </listitem>
+ <listitem>
+ <para>Default values for IN, IN_OUT parameters are not used if there is no criteria present for a given input. Default values are
+ only valid for <link linkend="exec_command">named procedure syntax</link>.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <note>
+ <title>Multiple Execution</title>
+ <para>The usage of 'in' or join criteria can result in
+ the procedure being executed multiple times.</para>
+ </note>
+ <note>
+ <title>Alternative Syntax</title>
+ <para>
+ None of issues listed in the syntax rules above exist if a <link linkend="nested_table">nested table reference</link> is used.
+ </para>
+ </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 /*+ 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 <COLUMN>, ... [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([<NSP>,] xquery-expression [<PASSING>] [COLUMNS <COLUMN>, ... )] 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 '<a id="1"/>') 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 <COLUMN>, ...) 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>
+ <para>
+ Usage:
+ <synopsis label="Usage">queryExpression (UNION|INTERSECT|EXCEPT) [ALL] queryExpression [ORDER BY...]</synopsis>
+ </para>
+ <itemizedlist>
+ <para>Syntax Rules:
+ </para>
+ <listitem>
+ <para>The output columns will be named by the output columns of the first set operation branch.
+ </para>
+ </listitem>
+ <listitem>
+ <para>Each SELECT must have the same number of output columns and compatible data types for each relative column. Data type conversion will be performed if data types are inconsistent and implicit conversions exist.
+ </para>
+ </listitem>
+ <listitem>
+ <para>If UNION, INTERSECT, or EXCEPT is specified without all, then the output columns must be comparable types.
+ </para>
+ </listitem>
+ <listitem>
+ <para>INTERSECT ALL, and EXCEPT ALL are currently not supported.</para>
+ </listitem>
+ </itemizedlist>
+ </section>
+ <section id="subqueries">
+ <title>Subqueries</title>
+ <para>A subquery is a SQL query embedded within another SQL query. The query containing the subquery is the outer query.</para>
+ <itemizedlist>
+ <para>Supported subquery types:
+ </para>
+ <listitem>
+ <para>Scalar subquery - a subquery that returns only a single column with a single value. Scalar subqueries are a type of expression and can be used where single valued expressions are expected.
+ </para>
+ </listitem>
+ <listitem>
+ <para>Correlated subquery - a subquery that contains a column reference to from the outer query.
+ </para>
+ </listitem>
+ <listitem>
+ <para>Uncorrelated subquery - a subquery that contains no references to the outer sub-query.
+ </para>
+ </listitem>
+ </itemizedlist>
+ <section id="from_subquery">
+ <title>Inline views</title>
+ <para>Subqueries in the FROM clause of the outer query (also known as
+ "inline views") can return any number of rows and columns. This type
+ of subquery must always be given an alias. An inline view is nearly identical to a traditional view. See also <xref linkend="with_clause"/>.</para>
+ <example>
+ <title>Example Subquery in FROM Clause (Inline View)</title>
+ <programlisting language="SQL">SELECT a FROM (SELECT Y.b, Y.c FROM Y WHERE Y.d = ‘3’) AS X WHERE a = X.c AND b = X.b</programlisting>
+ </example>
+ </section>
+ <section id="other_subqueries">
+ <title>Subqueries can appear anywhere where an expression or criteria is expected.</title>
+ <para>Subqueries are supported in quantified criteria, the EXISTS predicate, the IN predicate, and as <xref linkend="scalar_subqueries"/>.</para>
+ <example>
+ <title>Example Subquery in WHERE Using EXISTS</title>
+ <programlisting>SELECT a FROM X WHERE EXISTS (SELECT 1 FROM Y WHERE c=X.a)</programlisting>
+ </example>
+ <example>
+ <title>Example Quantified Comparison Subqueries</title>
+ <programlisting language="SQL">SELECT a FROM X WHERE a >= ANY (SELECT b FROM Y WHERE c=3)
+SELECT a FROM X WHERE a < SOME (SELECT b FROM Y WHERE c=4)
+SELECT a FROM X WHERE a = ALL (SELECT b FROM Y WHERE c=2)</programlisting>
+ </example>
+ <example>
+ <title>Example IN Subquery</title>
+ <programlisting language="SQL">SELECT a FROM X WHERE a IN (SELECT b FROM Y WHERE c=3)</programlisting>
+ </example>
+ <para>See also <xref linkend="subquery_optimization"/>.</para>
+ </section>
+ </section>
+</chapter>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/pom.xml
===================================================================
--- trunk/engine/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,97 +0,0 @@
-<?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>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>javacc-maven-plugin</artifactId>
- <version>2.4</version>
- <executions>
- <execution>
- <id>javacc</id>
- <goals>
- <goal>javacc</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-
- <dependencies>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <type>test-jar</type>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- <type>test-jar</type>
- </dependency>
-
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- </dependency>
-
- <dependency>
- <groupId>javax.transaction</groupId>
- <artifactId>jta</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.deployers</groupId>
- <artifactId>jboss-deployers-vfs-spi</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.deployers</groupId>
- <artifactId>jboss-deployers-vfs</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>net.sourceforge.saxon</groupId>
- <artifactId>saxon</artifactId>
- </dependency>
-
- <dependency>
- <groupId>net.sourceforge.saxon</groupId>
- <classifier>dom</classifier>
- <artifactId>saxon</artifactId>
- </dependency>
-
- <dependency>
- <groupId>com.googlecode.json-simple</groupId>
- <artifactId>json-simple</artifactId>
- </dependency>
-
- </dependencies>
-
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/pom.xml (from rev 3220, trunk/engine/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,97 @@
+<?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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>teiid-engine</artifactId>
+ <name>Engine</name>
+ <description>Relational, procedural, and xml core engine.</description>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>javacc-maven-plugin</artifactId>
+ <version>2.4</version>
+ <executions>
+ <execution>
+ <id>javacc</id>
+ <goals>
+ <goal>javacc</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <type>test-jar</type>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ <type>test-jar</type>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.transaction</groupId>
+ <artifactId>jta</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.deployers</groupId>
+ <artifactId>jboss-deployers-vfs-spi</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.deployers</groupId>
+ <artifactId>jboss-deployers-vfs</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>net.sourceforge.saxon</groupId>
+ <artifactId>saxon</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>net.sourceforge.saxon</groupId>
+ <classifier>dom</classifier>
+ <artifactId>saxon</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>com.googlecode.json-simple</groupId>
+ <artifactId>json-simple</artifactId>
+ </dependency>
+
+ </dependencies>
+
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/BlockedException.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/common/buffer/BlockedException.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/BlockedException.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,43 +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.common.buffer;
-
-import org.teiid.core.TeiidComponentException;
-
-/**
- * This exception is thrown if the buffer manager blocks waiting on input during
- * processing. This is an indication that more data will be available, but is
- * not currently available.
- */
-public class BlockedException extends TeiidComponentException {
-
- public static final BlockedException INSTANCE = new BlockedException();
-
- /**
- * No-arg costructor required by Externalizable semantics
- */
- public BlockedException() {
- super();
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/BlockedException.java (from rev 3218, trunk/engine/src/main/java/org/teiid/common/buffer/BlockedException.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/BlockedException.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/BlockedException.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,53 @@
+/*
+ * 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;
+
+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
+ * processing. This is an indication that more data will be available, but is
+ * not currently available.
+ */
+public class BlockedException extends TeiidComponentException {
+
+ public static final BlockedException INSTANCE = new BlockedException();
+
+ /**
+ * No-arg costructor required by Externalizable semantics
+ */
+ public BlockedException() {
+ 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;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,368 +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.common.buffer;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-import java.util.TreeMap;
-
-import org.teiid.common.buffer.BatchManager.ManagedBatch;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.types.Streamable;
-import org.teiid.core.util.Assertion;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.logging.MessageLevel;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.sql.symbol.Expression;
-
-
-public class TupleBuffer {
-
- /**
- * Gets the data type names for each of the input expressions, in order.
- * @param expressions List of Expressions
- * @return
- * @since 4.2
- */
- public static String[] getTypeNames(List expressions) {
- if (expressions == null) {
- return null;
- }
- String[] types = new String[expressions.size()];
- for (ListIterator i = expressions.listIterator(); i.hasNext();) {
- Expression expr = (Expression)i.next();
- types[i.previousIndex()] = DataTypeManager.getDataTypeName(expr.getType());
- }
- return types;
- }
-
- //construction state
- private BatchManager manager;
- private String tupleSourceID;
- private List<?> schema;
- private String[] types;
- private int batchSize;
-
- private int rowCount;
- private boolean isFinal;
- private TreeMap<Integer, BatchManager.ManagedBatch> batches = new TreeMap<Integer, BatchManager.ManagedBatch>();
- private ArrayList<List<?>> batchBuffer;
- private boolean removed;
- private boolean forwardOnly;
- private boolean prefersMemory;
-
- private LobManager lobManager;
- private int[] lobIndexes;
- private String uuid;
- private FileStore lobStore;
-
- public TupleBuffer(BatchManager manager, String id, List<?> schema, int[] lobIndexes, int batchSize) {
- this.manager = manager;
- this.tupleSourceID = id;
- this.schema = schema;
- this.types = getTypeNames(schema);
- this.lobIndexes = lobIndexes;
- if (this.lobIndexes != null) {
- this.lobManager = new LobManager();
- this.lobStore = this.manager.createStorage("_lobs"); //$NON-NLS-1$
- this.lobStore.setCleanupReference(this);
- }
- this.batchSize = batchSize;
- }
-
- public String getId() {
- if (this.uuid == null) {
- this.uuid = java.util.UUID.randomUUID().toString();
- }
- return this.uuid;
- }
-
- public boolean isLobs() {
- return lobIndexes != null;
- }
-
- public void addTuple(List<?> tuple) throws TeiidComponentException {
- if (isLobs()) {
- lobManager.updateReferences(lobIndexes, tuple);
- }
- this.rowCount++;
- if (batchBuffer == null) {
- batchBuffer = new ArrayList<List<?>>(batchSize/4);
- }
- batchBuffer.add(tuple);
- if (batchBuffer.size() == batchSize) {
- saveBatch(false, false);
- }
- }
-
- /**
- * Adds the given batch preserving row offsets.
- * @param batch
- * @throws TeiidComponentException
- */
- public void addTupleBatch(TupleBatch batch, boolean save) throws TeiidComponentException {
- setRowCount(batch.getBeginRow() - 1);
- if (save) {
- for (List<?> tuple : batch.getTuples()) {
- addTuple(tuple);
- }
- } else {
- //add the lob references only, since they may still be referenced later
- if (isLobs()) {
- for (List<?> tuple : batch.getTuples()) {
- lobManager.updateReferences(lobIndexes, tuple);
- }
- }
- }
- }
-
- public void setRowCount(int rowCount)
- throws TeiidComponentException {
- assert this.rowCount <= rowCount;
- if (this.rowCount != rowCount) {
- saveBatch(false, true);
- this.rowCount = rowCount;
- }
- }
-
- public void purge() {
- if (this.batchBuffer != null) {
- this.batchBuffer.clear();
- }
- for (BatchManager.ManagedBatch batch : this.batches.values()) {
- batch.remove();
- }
- this.batches.clear();
- }
-
- public void persistLobs() throws TeiidComponentException {
- if (this.lobManager != null) {
- this.lobManager.persist(this.lobStore);
- }
- }
-
- /**
- * Force the persistence of any rows held in memory.
- * @throws TeiidComponentException
- */
- public void saveBatch() throws TeiidComponentException {
- this.saveBatch(false, false);
- }
-
- void saveBatch(boolean finalBatch, boolean force) throws TeiidComponentException {
- Assertion.assertTrue(!this.isRemoved());
- if (batchBuffer == null || batchBuffer.isEmpty() || (!force && batchBuffer.size() < Math.max(1, batchSize / 32))) {
- return;
- }
- TupleBatch writeBatch = new TupleBatch(rowCount - batchBuffer.size() + 1, batchBuffer);
- if (finalBatch) {
- writeBatch.setTerminationFlag(true);
- }
- writeBatch.setDataTypes(types);
- BatchManager.ManagedBatch mbatch = manager.createManagedBatch(writeBatch, prefersMemory);
- this.batches.put(writeBatch.getBeginRow(), mbatch);
- batchBuffer = null;
- }
-
- public void close() throws TeiidComponentException {
- saveBatch(true, false);
- this.isFinal = true;
- }
-
- /**
- * Get the batch containing the given row.
- * NOTE: the returned batch may be empty or may begin with a row other
- * than the one specified.
- * @param row
- * @return
- * @throws TeiidComponentException
- */
- public TupleBatch getBatch(int row) throws TeiidComponentException {
- TupleBatch result = null;
- if (row > rowCount) {
- result = new TupleBatch(rowCount + 1, new List[] {});
- } else if (this.batchBuffer != null && row > rowCount - this.batchBuffer.size()) {
- result = new TupleBatch(rowCount - this.batchBuffer.size() + 1, batchBuffer);
- if (forwardOnly) {
- this.batchBuffer = null;
- }
- } else {
- if (this.batchBuffer != null && !this.batchBuffer.isEmpty()) {
- //this is just a sanity check to ensure we're not holding too many
- //hard references to batches.
- saveBatch(isFinal, false);
- }
- Map.Entry<Integer, BatchManager.ManagedBatch> entry = batches.floorEntry(row);
- Assertion.isNotNull(entry);
- BatchManager.ManagedBatch batch = entry.getValue();
- result = batch.getBatch(!forwardOnly, types);
- if (forwardOnly) {
- batches.remove(entry.getKey());
- }
- }
- result.setDataTypes(types);
- if (isFinal && result.getEndRow() == rowCount) {
- result.setTerminationFlag(true);
- }
- return result;
- }
-
- public void remove() {
- if (!removed) {
- if (LogManager.isMessageToBeRecorded(LogConstants.CTX_BUFFER_MGR, MessageLevel.DETAIL)) {
- LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, "Removing TupleBuffer:", this.tupleSourceID); //$NON-NLS-1$
- }
- if (this.lobStore != null) {
- this.lobStore.remove();
- }
- this.batchBuffer = null;
- purge();
- this.manager.remove();
- removed = true;
- }
- }
-
- /**
- * Returns the total number of rows contained in managed batches
- * @return
- */
- public int getManagedRowCount() {
- if (!this.batches.isEmpty()) {
- int start = this.batches.firstKey();
- return rowCount - start + 1;
- } else if (this.batchBuffer != null) {
- return this.batchBuffer.size();
- }
- return 0;
- }
-
- /**
- * Returns the last row number
- * @return
- */
- public int getRowCount() {
- return rowCount;
- }
-
- public boolean isFinal() {
- return isFinal;
- }
-
- public void setFinal(boolean isFinal) {
- this.isFinal = isFinal;
- }
-
- public List<?> getSchema() {
- return schema;
- }
-
- public int getBatchSize() {
- return batchSize;
- }
-
- public void setBatchSize(int batchSize) {
- this.batchSize = batchSize;
- }
-
- public Streamable<?> getLobReference(String id) throws TeiidComponentException {
- if (lobManager == null) {
- throw new TeiidComponentException(QueryPlugin.Util.getString("ProcessWorker.wrongdata")); //$NON-NLS-1$
- }
- return lobManager.getLobReference(id);
- }
-
- public void setForwardOnly(boolean forwardOnly) {
- this.forwardOnly = forwardOnly;
- }
-
- public IndexedTupleSource createIndexedTupleSource() {
- return createIndexedTupleSource(false);
- }
-
- /**
- * Create a new iterator for this buffer
- * @return
- */
- public IndexedTupleSource createIndexedTupleSource(final boolean singleUse) {
- if (singleUse) {
- setForwardOnly(true);
- }
- return new AbstractTupleSource() {
-
- @Override
- protected List<?> finalRow() throws BlockedException {
- if(isFinal) {
- return null;
- }
- throw BlockedException.INSTANCE;
- }
-
- @Override
- public int available() {
- return rowCount - getCurrentIndex() + 1;
- }
-
- @Override
- protected TupleBatch getBatch(int row) throws TeiidComponentException {
- return TupleBuffer.this.getBatch(row);
- }
-
- @Override
- public void closeSource() {
- super.closeSource();
- if (singleUse) {
- remove();
- }
- }
- };
- }
-
- @Override
- public String toString() {
- return this.tupleSourceID;
- }
-
- public boolean isRemoved() {
- return removed;
- }
-
- public boolean isForwardOnly() {
- return forwardOnly;
- }
-
- public void setPrefersMemory(boolean prefersMemory) {
- this.prefersMemory = prefersMemory;
- for (ManagedBatch batch : this.batches.values()) {
- batch.setPrefersMemory(prefersMemory);
- }
- }
-
- public boolean isPrefersMemory() {
- return prefersMemory;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java (from rev 3218, trunk/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,368 @@
+/*
+ * 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;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.teiid.common.buffer.BatchManager.ManagedBatch;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.Streamable;
+import org.teiid.core.util.Assertion;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.sql.symbol.Expression;
+
+
+public class TupleBuffer {
+
+ /**
+ * Gets the data type names for each of the input expressions, in order.
+ * @param expressions List of Expressions
+ * @return
+ * @since 4.2
+ */
+ public static String[] getTypeNames(List expressions) {
+ if (expressions == null) {
+ return null;
+ }
+ String[] types = new String[expressions.size()];
+ for (ListIterator i = expressions.listIterator(); i.hasNext();) {
+ Expression expr = (Expression)i.next();
+ types[i.previousIndex()] = DataTypeManager.getDataTypeName(expr.getType());
+ }
+ return types;
+ }
+
+ //construction state
+ private BatchManager manager;
+ private String tupleSourceID;
+ private List<?> schema;
+ private String[] types;
+ private int batchSize;
+
+ private int rowCount;
+ private boolean isFinal;
+ private TreeMap<Integer, BatchManager.ManagedBatch> batches = new TreeMap<Integer, BatchManager.ManagedBatch>();
+ private ArrayList<List<?>> batchBuffer;
+ private boolean removed;
+ private boolean forwardOnly;
+ private boolean prefersMemory;
+
+ private LobManager lobManager;
+ private int[] lobIndexes;
+ private String uuid;
+ private FileStore lobStore;
+
+ public TupleBuffer(BatchManager manager, String id, List<?> schema, int[] lobIndexes, int batchSize) {
+ this.manager = manager;
+ this.tupleSourceID = id;
+ this.schema = schema;
+ this.types = getTypeNames(schema);
+ this.lobIndexes = lobIndexes;
+ if (this.lobIndexes != null) {
+ this.lobManager = new LobManager();
+ this.lobStore = this.manager.createStorage("_lobs"); //$NON-NLS-1$
+ this.lobStore.setCleanupReference(this);
+ }
+ this.batchSize = batchSize;
+ }
+
+ public String getId() {
+ if (this.uuid == null) {
+ this.uuid = java.util.UUID.randomUUID().toString();
+ }
+ return this.uuid;
+ }
+
+ public boolean isLobs() {
+ return lobIndexes != null;
+ }
+
+ public void addTuple(List<?> tuple) throws TeiidComponentException {
+ if (isLobs()) {
+ lobManager.updateReferences(lobIndexes, tuple);
+ }
+ this.rowCount++;
+ if (batchBuffer == null) {
+ batchBuffer = new ArrayList<List<?>>(batchSize/4);
+ }
+ batchBuffer.add(tuple);
+ if (batchBuffer.size() == batchSize) {
+ saveBatch(false, false);
+ }
+ }
+
+ /**
+ * Adds the given batch preserving row offsets.
+ * @param batch
+ * @throws TeiidComponentException
+ */
+ public void addTupleBatch(TupleBatch batch, boolean save) throws TeiidComponentException {
+ setRowCount(batch.getBeginRow() - 1);
+ if (save) {
+ for (List<?> tuple : batch.getTuples()) {
+ addTuple(tuple);
+ }
+ } else {
+ //add the lob references only, since they may still be referenced later
+ if (isLobs()) {
+ for (List<?> tuple : batch.getTuples()) {
+ lobManager.updateReferences(lobIndexes, tuple);
+ }
+ }
+ }
+ }
+
+ public void setRowCount(int rowCount)
+ throws TeiidComponentException {
+ assert this.rowCount <= rowCount;
+ if (this.rowCount != rowCount) {
+ saveBatch(false, true);
+ this.rowCount = rowCount;
+ }
+ }
+
+ public void purge() {
+ if (this.batchBuffer != null) {
+ this.batchBuffer.clear();
+ }
+ for (BatchManager.ManagedBatch batch : this.batches.values()) {
+ batch.remove();
+ }
+ this.batches.clear();
+ }
+
+ public void persistLobs() throws TeiidComponentException {
+ if (this.lobManager != null) {
+ this.lobManager.persist(this.lobStore);
+ }
+ }
+
+ /**
+ * Force the persistence of any rows held in memory.
+ * @throws TeiidComponentException
+ */
+ public void saveBatch() throws TeiidComponentException {
+ this.saveBatch(false, false);
+ }
+
+ void saveBatch(boolean finalBatch, boolean force) throws TeiidComponentException {
+ Assertion.assertTrue(!this.isRemoved());
+ if (batchBuffer == null || batchBuffer.isEmpty() || (!force && batchBuffer.size() < Math.max(1, batchSize / 32))) {
+ return;
+ }
+ TupleBatch writeBatch = new TupleBatch(rowCount - batchBuffer.size() + 1, batchBuffer);
+ if (finalBatch) {
+ writeBatch.setTerminationFlag(true);
+ }
+ writeBatch.setDataTypes(types);
+ BatchManager.ManagedBatch mbatch = manager.createManagedBatch(writeBatch, prefersMemory);
+ this.batches.put(writeBatch.getBeginRow(), mbatch);
+ batchBuffer = null;
+ }
+
+ public void close() throws TeiidComponentException {
+ saveBatch(true, false);
+ this.isFinal = true;
+ }
+
+ /**
+ * Get the batch containing the given row.
+ * NOTE: the returned batch may be empty or may begin with a row other
+ * than the one specified.
+ * @param row
+ * @return
+ * @throws TeiidComponentException
+ */
+ public TupleBatch getBatch(int row) throws TeiidComponentException {
+ TupleBatch result = null;
+ if (row > rowCount) {
+ result = new TupleBatch(rowCount + 1, new List[] {});
+ } else if (this.batchBuffer != null && row > rowCount - this.batchBuffer.size()) {
+ result = new TupleBatch(rowCount - this.batchBuffer.size() + 1, batchBuffer);
+ if (forwardOnly) {
+ this.batchBuffer = null;
+ }
+ } else {
+ if (this.batchBuffer != null && !this.batchBuffer.isEmpty()) {
+ //this is just a sanity check to ensure we're not holding too many
+ //hard references to batches.
+ saveBatch(isFinal, false);
+ }
+ Map.Entry<Integer, BatchManager.ManagedBatch> entry = batches.floorEntry(row);
+ Assertion.isNotNull(entry);
+ BatchManager.ManagedBatch batch = entry.getValue();
+ result = batch.getBatch(!forwardOnly, types);
+ if (forwardOnly) {
+ batches.remove(entry.getKey());
+ }
+ }
+ result.setDataTypes(types);
+ if (isFinal && result.getEndRow() == rowCount) {
+ result.setTerminationFlag(true);
+ }
+ return result;
+ }
+
+ public void remove() {
+ if (!removed) {
+ if (LogManager.isMessageToBeRecorded(LogConstants.CTX_BUFFER_MGR, MessageLevel.DETAIL)) {
+ LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, "Removing TupleBuffer:", this.tupleSourceID); //$NON-NLS-1$
+ }
+ if (this.lobStore != null) {
+ this.lobStore.remove();
+ }
+ this.batchBuffer = null;
+ purge();
+ this.manager.remove();
+ removed = true;
+ }
+ }
+
+ /**
+ * Returns the total number of rows contained in managed batches
+ * @return
+ */
+ public int getManagedRowCount() {
+ if (!this.batches.isEmpty()) {
+ int start = this.batches.firstKey();
+ return rowCount - start + 1;
+ } else if (this.batchBuffer != null) {
+ return this.batchBuffer.size();
+ }
+ return 0;
+ }
+
+ /**
+ * Returns the last row number
+ * @return
+ */
+ public int getRowCount() {
+ return rowCount;
+ }
+
+ public boolean isFinal() {
+ return isFinal;
+ }
+
+ public void setFinal(boolean isFinal) {
+ this.isFinal = isFinal;
+ }
+
+ public List<?> getSchema() {
+ return schema;
+ }
+
+ public int getBatchSize() {
+ return batchSize;
+ }
+
+ public void setBatchSize(int batchSize) {
+ this.batchSize = batchSize;
+ }
+
+ public Streamable<?> getLobReference(String id) throws TeiidComponentException {
+ if (lobManager == null) {
+ throw new TeiidComponentException(QueryPlugin.Util.getString("ProcessWorker.wrongdata")); //$NON-NLS-1$
+ }
+ return lobManager.getLobReference(id);
+ }
+
+ public void setForwardOnly(boolean forwardOnly) {
+ this.forwardOnly = forwardOnly;
+ }
+
+ public IndexedTupleSource createIndexedTupleSource() {
+ return createIndexedTupleSource(false);
+ }
+
+ /**
+ * Create a new iterator for this buffer
+ * @return
+ */
+ public IndexedTupleSource createIndexedTupleSource(final boolean singleUse) {
+ if (singleUse) {
+ setForwardOnly(true);
+ }
+ return new AbstractTupleSource() {
+
+ @Override
+ protected List<?> finalRow() throws BlockedException {
+ if(isFinal) {
+ return null;
+ }
+ throw BlockedException.block("Blocking on non-final TupleBuffer", tupleSourceID); //$NON-NLS-1$
+ }
+
+ @Override
+ public int available() {
+ return rowCount - getCurrentIndex() + 1;
+ }
+
+ @Override
+ protected TupleBatch getBatch(int row) throws TeiidComponentException {
+ return TupleBuffer.this.getBatch(row);
+ }
+
+ @Override
+ public void closeSource() {
+ super.closeSource();
+ if (singleUse) {
+ remove();
+ }
+ }
+ };
+ }
+
+ @Override
+ public String toString() {
+ return this.tupleSourceID;
+ }
+
+ public boolean isRemoved() {
+ return removed;
+ }
+
+ public boolean isForwardOnly() {
+ return forwardOnly;
+ }
+
+ public void setPrefersMemory(boolean prefersMemory) {
+ this.prefersMemory = prefersMemory;
+ for (ManagedBatch batch : this.batches.values()) {
+ batch.setPrefersMemory(prefersMemory);
+ }
+ }
+
+ public boolean isPrefersMemory() {
+ return prefersMemory;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,293 +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.
- */
-
-/*
- * Date: Aug 25, 2003
- * Time: 3:53:37 PM
- */
-package org.teiid.dqp.internal.datamgr;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.resource.ResourceException;
-
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.util.Assertion;
-import org.teiid.dqp.message.AtomicRequestID;
-import org.teiid.dqp.message.AtomicRequestMessage;
-import org.teiid.logging.CommandLogMessage;
-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.Datatype;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.MetadataFactory;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Scope;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.resource.spi.WrappedConnection;
-import org.teiid.translator.ExecutionContext;
-import org.teiid.translator.ExecutionFactory;
-import org.teiid.translator.TranslatorException;
-
-
-/**
- * The <code>ConnectorManager</code> manages a {@link org.teiid.translator.BasicExecutionFactory Connector}
- * and its associated workers' state.
- */
-public class ConnectorManager {
-
- private static final String JAVA_CONTEXT = "java:"; //$NON-NLS-1$
-
- private String translatorName;
- private String connectionName;
- private String modelName;
-
- // known requests
- private ConcurrentHashMap<AtomicRequestID, ConnectorWorkItem> requestStates = new ConcurrentHashMap<AtomicRequestID, ConnectorWorkItem>();
-
- private SourceCapabilities cachedCapabilities;
-
- private volatile boolean stopped;
- private ExecutionFactory<Object, Object> executionFactory;
-
- public ConnectorManager(String translatorName, String connectionName) {
- this.translatorName = translatorName;
- this.connectionName = connectionName;
- }
-
- public String getStausMessage() {
- StringBuilder sb = new StringBuilder();
- ExecutionFactory<Object, Object> ef = getExecutionFactory();
-
- if(ef != null) {
- if (ef.isSourceRequired()) {
-
- Object conn = null;
- try {
- conn = getConnectionFactory();
- } catch (TranslatorException e) {
- // treat this as connection not found.
- }
-
- if (conn == null) {
- sb.append(QueryPlugin.Util.getString("datasource_not_found", this.connectionName)); //$NON-NLS-1$
- }
- }
- }
- else {
- sb.append(QueryPlugin.Util.getString("translator_not_found", this.translatorName)); //$NON-NLS-1$
- }
- return sb.toString();
- }
-
- 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 unwrapped = null;
-
- if (connection instanceof WrappedConnection) {
- try {
- unwrapped = ((WrappedConnection)connection).unwrap();
- } catch (ResourceException e) {
- throw new TranslatorException(QueryPlugin.Util.getString("failed_to_unwrap_connection")); //$NON-NLS-1$
- }
- }
-
- try {
- executionFactory.getMetadata(factory, (unwrapped == null) ? connection:unwrapped);
- } finally {
- executionFactory.closeConnection(connection, connectionFactory);
- }
- return factory.getMetadataStore();
- }
-
- public List<FunctionMethod> getPushDownFunctions(){
- return getExecutionFactory().getPushDownFunctions();
- }
-
- public SourceCapabilities getCapabilities() throws TeiidComponentException {
- if (cachedCapabilities != null) {
- return cachedCapabilities;
- }
-
- checkStatus();
- ExecutionFactory<Object, Object> translator = getExecutionFactory();
- BasicSourceCapabilities resultCaps = CapabilitiesConverter.convertCapabilities(translator, Arrays.asList(translatorName, connectionName));
- resultCaps.setScope(Scope.SCOPE_GLOBAL);
- cachedCapabilities = resultCaps;
- return resultCaps;
- }
-
- public ConnectorWork registerRequest(AtomicRequestMessage message) throws TeiidComponentException {
- checkStatus();
- AtomicRequestID atomicRequestId = message.getAtomicRequestID();
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {atomicRequestId, "Create State"}); //$NON-NLS-1$
-
- ConnectorWorkItem item = new ConnectorWorkItem(message, this);
- Assertion.isNull(requestStates.put(atomicRequestId, item), "State already existed"); //$NON-NLS-1$
- return item;
- }
-
- ConnectorWork getState(AtomicRequestID requestId) {
- return requestStates.get(requestId);
- }
-
- /**
- * Remove the state associated with
- * the given <code>RequestID</code>.
- */
- void removeState(AtomicRequestID id) {
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {id, "Remove State"}); //$NON-NLS-1$
- requestStates.remove(id);
- }
-
- int size() {
- return requestStates.size();
- }
-
- /**
- * initialize this <code>ConnectorManager</code>.
- * @throws TranslatorException
- */
- public void start() {
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, QueryPlugin.Util.getString("ConnectorManagerImpl.Initializing_connector", translatorName)); //$NON-NLS-1$
- }
-
- /**
- * Stop this connector.
- */
- public void stop() {
- stopped = true;
- //ensure that all requests receive a response
- for (ConnectorWork workItem : this.requestStates.values()) {
- workItem.cancel();
- }
- }
-
- /**
- * Add begin point to transaction monitoring table.
- * @param qr Request that contains the MetaMatrix command information in the transaction.
- */
- void logSRCCommand(AtomicRequestMessage qr, ExecutionContext context, Event cmdStatus, Integer finalRowCnt) {
- if (!LogManager.isMessageToBeRecorded(LogConstants.CTX_COMMANDLOGGING, MessageLevel.DETAIL)) {
- return;
- }
- String sqlStr = null;
- if(cmdStatus == Event.NEW){
- Command cmd = qr.getCommand();
- sqlStr = cmd != null ? cmd.toString() : null;
- }
- String userName = qr.getWorkContext().getUserName();
- String transactionID = null;
- if ( qr.isTransactional() ) {
- transactionID = qr.getTransactionContext().getTransactionId();
- }
-
- String modelName = qr.getModelName();
- AtomicRequestID id = qr.getAtomicRequestID();
-
- String principal = userName == null ? "unknown" : userName; //$NON-NLS-1$
-
- CommandLogMessage message = null;
- if (cmdStatus == Event.NEW) {
- message = new CommandLogMessage(System.currentTimeMillis(), qr.getRequestID().toString(), id.getNodeID(), transactionID, modelName, translatorName, qr.getWorkContext().getSessionId(), principal, sqlStr, context);
- }
- else {
- message = new CommandLogMessage(System.currentTimeMillis(), qr.getRequestID().toString(), id.getNodeID(), transactionID, modelName, translatorName, qr.getWorkContext().getSessionId(), principal, finalRowCnt, cmdStatus, context);
- }
- LogManager.log(MessageLevel.DETAIL, LogConstants.CTX_COMMANDLOGGING, message);
- }
-
- /**
- * Get the <code>Translator</code> object managed by this manager.
- * @return the <code>ExecutionFactory</code>.
- */
- protected ExecutionFactory<Object, Object> getExecutionFactory() {
- return this.executionFactory;
- }
-
- public void setExecutionFactory(ExecutionFactory<Object, Object> ef) {
- this.executionFactory = ef;
- }
-
-
- /**
- * Get the ConnectionFactory object required by this manager
- * @return
- */
- protected Object getConnectionFactory() throws TranslatorException {
- if (this.connectionName != null) {
- String jndiName = this.connectionName;
- if (!this.connectionName.startsWith(JAVA_CONTEXT)) {
- jndiName = JAVA_CONTEXT + jndiName;
- }
-
- try {
- InitialContext ic = new InitialContext();
- try {
- return ic.lookup(jndiName);
- } catch (NamingException e) {
- if (!jndiName.equals(this.connectionName)) {
- return ic.lookup(this.connectionName);
- }
- }
- } catch (NamingException e) {
- throw new TranslatorException(e, QueryPlugin.Util.getString("connection_factory_not_found", this.connectionName)); //$NON-NLS-1$
- }
- }
- return null;
- }
-
- private void checkStatus() throws TeiidComponentException {
- if (stopped) {
- throw new TeiidComponentException(QueryPlugin.Util.getString("ConnectorManager.not_in_valid_state", this.translatorName)); //$NON-NLS-1$
- }
- }
-
- public String getTranslatorName() {
- return this.translatorName;
- }
-
- public String getConnectionName() {
- return this.connectionName;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- public String getModelName() {
- return this.modelName;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,293 @@
+/*
+ * 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.
+ */
+
+/*
+ * Date: Aug 25, 2003
+ * Time: 3:53:37 PM
+ */
+package org.teiid.dqp.internal.datamgr;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import javax.resource.ResourceException;
+
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.util.Assertion;
+import org.teiid.dqp.message.AtomicRequestID;
+import org.teiid.dqp.message.AtomicRequestMessage;
+import org.teiid.logging.CommandLogMessage;
+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.Datatype;
+import org.teiid.metadata.FunctionMethod;
+import org.teiid.metadata.MetadataFactory;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Scope;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.resource.spi.WrappedConnection;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.ExecutionFactory;
+import org.teiid.translator.TranslatorException;
+
+
+/**
+ * The <code>ConnectorManager</code> manages a {@link org.teiid.translator.BasicExecutionFactory Connector}
+ * and its associated workers' state.
+ */
+public class ConnectorManager {
+
+ private static final String JAVA_CONTEXT = "java:"; //$NON-NLS-1$
+
+ private String translatorName;
+ private String connectionName;
+ private String modelName;
+
+ // known requests
+ private ConcurrentHashMap<AtomicRequestID, ConnectorWorkItem> requestStates = new ConcurrentHashMap<AtomicRequestID, ConnectorWorkItem>();
+
+ private SourceCapabilities cachedCapabilities;
+
+ private volatile boolean stopped;
+ private ExecutionFactory<Object, Object> executionFactory;
+
+ public ConnectorManager(String translatorName, String connectionName) {
+ this.translatorName = translatorName;
+ this.connectionName = connectionName;
+ }
+
+ public String getStausMessage() {
+ StringBuilder sb = new StringBuilder();
+ ExecutionFactory<Object, Object> ef = getExecutionFactory();
+
+ if(ef != null) {
+ if (ef.isSourceRequired()) {
+
+ Object conn = null;
+ try {
+ conn = getConnectionFactory();
+ } catch (TranslatorException e) {
+ // treat this as connection not found.
+ }
+
+ if (conn == null) {
+ sb.append(QueryPlugin.Util.getString("datasource_not_found", this.connectionName)); //$NON-NLS-1$
+ }
+ }
+ }
+ else {
+ sb.append(QueryPlugin.Util.getString("translator_not_found", this.translatorName)); //$NON-NLS-1$
+ }
+ return sb.toString();
+ }
+
+ 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, null);
+ Object unwrapped = null;
+
+ if (connection instanceof WrappedConnection) {
+ try {
+ unwrapped = ((WrappedConnection)connection).unwrap();
+ } catch (ResourceException e) {
+ throw new TranslatorException(QueryPlugin.Util.getString("failed_to_unwrap_connection")); //$NON-NLS-1$
+ }
+ }
+
+ try {
+ executionFactory.getMetadata(factory, (unwrapped == null) ? connection:unwrapped);
+ } finally {
+ executionFactory.closeConnection(connection, connectionFactory);
+ }
+ return factory.getMetadataStore();
+ }
+
+ public List<FunctionMethod> getPushDownFunctions(){
+ return getExecutionFactory().getPushDownFunctions();
+ }
+
+ public SourceCapabilities getCapabilities() throws TeiidComponentException {
+ if (cachedCapabilities != null) {
+ return cachedCapabilities;
+ }
+
+ checkStatus();
+ ExecutionFactory<Object, Object> translator = getExecutionFactory();
+ BasicSourceCapabilities resultCaps = CapabilitiesConverter.convertCapabilities(translator, Arrays.asList(translatorName, connectionName));
+ resultCaps.setScope(Scope.SCOPE_GLOBAL);
+ cachedCapabilities = resultCaps;
+ return resultCaps;
+ }
+
+ public ConnectorWork registerRequest(AtomicRequestMessage message) throws TeiidComponentException {
+ checkStatus();
+ AtomicRequestID atomicRequestId = message.getAtomicRequestID();
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {atomicRequestId, "Create State"}); //$NON-NLS-1$
+
+ ConnectorWorkItem item = new ConnectorWorkItem(message, this);
+ Assertion.isNull(requestStates.put(atomicRequestId, item), "State already existed"); //$NON-NLS-1$
+ return item;
+ }
+
+ ConnectorWork getState(AtomicRequestID requestId) {
+ return requestStates.get(requestId);
+ }
+
+ /**
+ * Remove the state associated with
+ * the given <code>RequestID</code>.
+ */
+ void removeState(AtomicRequestID id) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {id, "Remove State"}); //$NON-NLS-1$
+ requestStates.remove(id);
+ }
+
+ int size() {
+ return requestStates.size();
+ }
+
+ /**
+ * initialize this <code>ConnectorManager</code>.
+ * @throws TranslatorException
+ */
+ public void start() {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, QueryPlugin.Util.getString("ConnectorManagerImpl.Initializing_connector", translatorName)); //$NON-NLS-1$
+ }
+
+ /**
+ * Stop this connector.
+ */
+ public void stop() {
+ stopped = true;
+ //ensure that all requests receive a response
+ for (ConnectorWork workItem : this.requestStates.values()) {
+ workItem.cancel();
+ }
+ }
+
+ /**
+ * Add begin point to transaction monitoring table.
+ * @param qr Request that contains the MetaMatrix command information in the transaction.
+ */
+ void logSRCCommand(AtomicRequestMessage qr, ExecutionContext context, Event cmdStatus, Integer finalRowCnt) {
+ if (!LogManager.isMessageToBeRecorded(LogConstants.CTX_COMMANDLOGGING, MessageLevel.DETAIL)) {
+ return;
+ }
+ String sqlStr = null;
+ if(cmdStatus == Event.NEW){
+ Command cmd = qr.getCommand();
+ sqlStr = cmd != null ? cmd.toString() : null;
+ }
+ String userName = qr.getWorkContext().getUserName();
+ String transactionID = null;
+ if ( qr.isTransactional() ) {
+ transactionID = qr.getTransactionContext().getTransactionId();
+ }
+
+ String modelName = qr.getModelName();
+ AtomicRequestID id = qr.getAtomicRequestID();
+
+ String principal = userName == null ? "unknown" : userName; //$NON-NLS-1$
+
+ CommandLogMessage message = null;
+ if (cmdStatus == Event.NEW) {
+ message = new CommandLogMessage(System.currentTimeMillis(), qr.getRequestID().toString(), id.getNodeID(), transactionID, modelName, translatorName, qr.getWorkContext().getSessionId(), principal, sqlStr, context);
+ }
+ else {
+ message = new CommandLogMessage(System.currentTimeMillis(), qr.getRequestID().toString(), id.getNodeID(), transactionID, modelName, translatorName, qr.getWorkContext().getSessionId(), principal, finalRowCnt, cmdStatus, context);
+ }
+ LogManager.log(MessageLevel.DETAIL, LogConstants.CTX_COMMANDLOGGING, message);
+ }
+
+ /**
+ * Get the <code>Translator</code> object managed by this manager.
+ * @return the <code>ExecutionFactory</code>.
+ */
+ protected ExecutionFactory<Object, Object> getExecutionFactory() {
+ return this.executionFactory;
+ }
+
+ public void setExecutionFactory(ExecutionFactory<Object, Object> ef) {
+ this.executionFactory = ef;
+ }
+
+
+ /**
+ * Get the ConnectionFactory object required by this manager
+ * @return
+ */
+ protected Object getConnectionFactory() throws TranslatorException {
+ if (this.connectionName != null) {
+ String jndiName = this.connectionName;
+ if (!this.connectionName.startsWith(JAVA_CONTEXT)) {
+ jndiName = JAVA_CONTEXT + jndiName;
+ }
+
+ try {
+ InitialContext ic = new InitialContext();
+ try {
+ return ic.lookup(jndiName);
+ } catch (NamingException e) {
+ if (!jndiName.equals(this.connectionName)) {
+ return ic.lookup(this.connectionName);
+ }
+ }
+ } catch (NamingException e) {
+ throw new TranslatorException(e, QueryPlugin.Util.getString("connection_factory_not_found", this.connectionName)); //$NON-NLS-1$
+ }
+ }
+ return null;
+ }
+
+ private void checkStatus() throws TeiidComponentException {
+ if (stopped) {
+ throw new TeiidComponentException(QueryPlugin.Util.getString("ConnectorManager.not_in_valid_state", this.translatorName)); //$NON-NLS-1$
+ }
+ }
+
+ public String getTranslatorName() {
+ return this.translatorName;
+ }
+
+ public String getConnectionName() {
+ return this.connectionName;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ public String getModelName() {
+ return this.modelName;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,362 +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.datamgr;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.resource.ResourceException;
-
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.TupleBuffer;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.util.Assertion;
-import org.teiid.dqp.message.AtomicRequestID;
-import org.teiid.dqp.message.AtomicRequestMessage;
-import org.teiid.dqp.message.AtomicResultsMessage;
-import org.teiid.language.Call;
-import org.teiid.language.QueryExpression;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.logging.CommandLogMessage.Event;
-import org.teiid.metadata.RuntimeMetadata;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.metadata.TempMetadataStore;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.resource.spi.WrappedConnection;
-import org.teiid.translator.DataNotAvailableException;
-import org.teiid.translator.Execution;
-import org.teiid.translator.ExecutionFactory;
-import org.teiid.translator.ProcedureExecution;
-import org.teiid.translator.ResultSetExecution;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.UpdateExecution;
-
-
-public class ConnectorWorkItem implements ConnectorWork {
-
- /* Permanent state members */
- private AtomicRequestID id;
- private ConnectorManager manager;
- private AtomicRequestMessage requestMsg;
- private ExecutionFactory connector;
- private QueryMetadataInterface queryMetadata;
-
- /* Created on new request */
- private Object connection;
- private Object connectionFactory;
- private ExecutionContextImpl securityContext;
- private volatile ResultSetExecution execution;
- private ProcedureBatchHandler procedureBatchHandler;
- private org.teiid.language.Command translatedCommand;
- private int expectedColumns;
-
- /* End state information */
- private boolean lastBatch;
- private int rowCount;
- private boolean error;
-
- private AtomicBoolean isCancelled = new AtomicBoolean();
-
- ConnectorWorkItem(AtomicRequestMessage message, ConnectorManager manager) {
- this.id = message.getAtomicRequestID();
- this.requestMsg = message;
- this.manager = manager;
- AtomicRequestID requestID = this.requestMsg.getAtomicRequestID();
- this.securityContext = new ExecutionContextImpl(requestMsg.getWorkContext().getVdbName(),
- requestMsg.getWorkContext().getVdbVersion(),
- requestMsg.getExecutionPayload(),
- requestMsg.getWorkContext().getSessionId(),
- requestMsg.getConnectorName(),
- requestMsg.getRequestID().toString(),
- Integer.toString(requestID.getNodeID()),
- Integer.toString(requestID.getExecutionId())
- );
- this.securityContext.setUser(requestMsg.getWorkContext().getSubject());
- this.securityContext.setBatchSize(this.requestMsg.getFetchSize());
-
- this.connector = manager.getExecutionFactory();
- VDBMetaData vdb = requestMsg.getWorkContext().getVDB();
- this.queryMetadata = vdb.getAttachment(QueryMetadataInterface.class);
- this.queryMetadata = new TempMetadataAdapter(this.queryMetadata, new TempMetadataStore());
- this.securityContext.setTransactional(requestMsg.isTransactional());
- }
-
- public AtomicRequestID getId() {
- return id;
- }
-
- public void cancel() {
- try {
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Processing CANCEL request"}); //$NON-NLS-1$
- if (this.isCancelled.compareAndSet(false, true)) {
- this.manager.logSRCCommand(this.requestMsg, this.securityContext, Event.CANCEL, -1);
- if(execution != null) {
- execution.cancel();
- }
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, QueryPlugin.Util.getString("DQPCore.The_atomic_request_has_been_cancelled", this.id)); //$NON-NLS-1$
- }
- } catch (TranslatorException e) {
- LogManager.logWarning(LogConstants.CTX_CONNECTOR, e, QueryPlugin.Util.getString("Cancel_request_failed", this.id)); //$NON-NLS-1$
- }
- }
-
- public AtomicResultsMessage more() throws TranslatorException {
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Processing MORE request"}); //$NON-NLS-1$
- try {
- return handleBatch();
- } catch (Throwable t) {
- throw handleError(t);
- }
- }
-
- public void close() {
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Processing Close :", this.requestMsg.getCommand()}); //$NON-NLS-1$
- if (!error) {
- manager.logSRCCommand(this.requestMsg, this.securityContext, Event.END, this.rowCount);
- }
- try {
- if (execution != null) {
- execution.close();
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Closed execution"}); //$NON-NLS-1$
- }
- } catch (Throwable e) {
- LogManager.logError(LogConstants.CTX_CONNECTOR, e, e.getMessage());
- } finally {
- try {
- this.connector.closeConnection(connection, connectionFactory);
- } catch (Throwable e) {
- LogManager.logError(LogConstants.CTX_CONNECTOR, e, e.getMessage());
- } finally {
- manager.removeState(this.id);
- }
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Closed connection"}); //$NON-NLS-1$
- }
- }
-
- private TranslatorException handleError(Throwable t) {
- if (t instanceof DataNotAvailableException) {
- throw (DataNotAvailableException)t;
- }
- error = true;
- if (t instanceof RuntimeException && t.getCause() != null) {
- t = t.getCause();
- }
- manager.logSRCCommand(this.requestMsg, this.securityContext, Event.ERROR, null);
-
- String msg = QueryPlugin.Util.getString("ConnectorWorker.process_failed", this.id); //$NON-NLS-1$
- if (isCancelled.get()) {
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, msg);
- } else if (t instanceof TranslatorException || t instanceof TeiidProcessingException) {
- LogManager.logWarning(LogConstants.CTX_CONNECTOR, t, msg);
- } else {
- LogManager.logError(LogConstants.CTX_CONNECTOR, t, msg);
- }
- if (t instanceof TranslatorException) {
- return (TranslatorException)t;
- }
- if (t instanceof RuntimeException) {
- throw (RuntimeException)t;
- }
- return new TranslatorException(t);
- }
-
- public AtomicResultsMessage execute() throws TranslatorException, BlockedException {
- if(isCancelled()) {
- throw new TranslatorException("Request canceled"); //$NON-NLS-1$
- }
-
- 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);
-
- Object unwrapped = null;
- if (connection instanceof WrappedConnection) {
- try {
- unwrapped = ((WrappedConnection)connection).unwrap();
- } catch (ResourceException e) {
- throw new TranslatorException(QueryPlugin.Util.getString("failed_to_unwrap_connection")); //$NON-NLS-1$
- }
- }
-
- // Translate the command
- Command command = this.requestMsg.getCommand();
- this.expectedColumns = command.getProjectedSymbols().size();
- LanguageBridgeFactory factory = new LanguageBridgeFactory(queryMetadata);
- this.translatedCommand = factory.translate(command);
-
- RuntimeMetadata rmd = new RuntimeMetadataImpl(queryMetadata);
-
- // Create the execution based on mode
- final Execution exec = connector.createExecution(this.translatedCommand, this.securityContext, rmd, (unwrapped == null) ? this.connection:unwrapped);
- if (this.translatedCommand instanceof Call) {
- this.execution = Assertion.isInstanceOf(exec, ProcedureExecution.class, "Call Executions are expected to be ProcedureExecutions"); //$NON-NLS-1$
- StoredProcedure proc = (StoredProcedure)command;
- if (proc.returnParameters()) {
- this.procedureBatchHandler = new ProcedureBatchHandler((Call)this.translatedCommand, (ProcedureExecution)exec);
- }
- } else if (this.translatedCommand instanceof QueryExpression){
- this.execution = Assertion.isInstanceOf(exec, ResultSetExecution.class, "QueryExpression Executions are expected to be ResultSetExecutions"); //$NON-NLS-1$
- } else {
- Assertion.isInstanceOf(exec, UpdateExecution.class, "Update Executions are expected to be UpdateExecutions"); //$NON-NLS-1$
- this.execution = new ResultSetExecution() {
- private int[] results;
- private int index;
-
- @Override
- public void cancel() throws TranslatorException {
- exec.cancel();
- }
- @Override
- public void close() {
- exec.close();
- }
- @Override
- public void execute() throws TranslatorException {
- exec.execute();
- }
- @Override
- public List<?> next() throws TranslatorException,
- DataNotAvailableException {
- if (results == null) {
- results = ((UpdateExecution)exec).getUpdateCounts();
- }
- if (index < results.length) {
- return Arrays.asList(results[index++]);
- }
- return null;
- }
- };
- }
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.requestMsg.getAtomicRequestID(), "Obtained execution"}); //$NON-NLS-1$
- //Log the Source Command (Must be after obtaining the execution context)
- manager.logSRCCommand(this.requestMsg, this.securityContext, Event.NEW, null);
-
- // Execute query
- this.execution.execute();
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Executed command"}); //$NON-NLS-1$
-
- return handleBatch();
- } catch (Throwable t) {
- throw handleError(t);
- }
- }
-
- protected AtomicResultsMessage handleBatch() throws TranslatorException {
- Assertion.assertTrue(!this.lastBatch);
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Getting results from connector"}); //$NON-NLS-1$
- int batchSize = 0;
- List<List> rows = new ArrayList<List>(batchSize/4);
-
- try {
- while (batchSize < this.requestMsg.getFetchSize()) {
-
- List row = this.execution.next();
- if (row == null) {
- this.lastBatch = true;
- break;
- }
- if (row.size() != this.expectedColumns) {
- throw new AssertionError("Inproper results returned. Expected " + this.expectedColumns + " columns, but was " + row.size()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- this.rowCount += 1;
- batchSize++;
- if (this.procedureBatchHandler != null) {
- row = this.procedureBatchHandler.padRow(row);
- }
-
- rows.add(row);
- // Check for max result rows exceeded
- if(this.requestMsg.getMaxResultRows() > -1 && this.rowCount >= this.requestMsg.getMaxResultRows()){
- if (this.rowCount == this.requestMsg.getMaxResultRows() && !this.requestMsg.isExceptionOnMaxRows()) {
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Exceeded max, returning", this.requestMsg.getMaxResultRows()}); //$NON-NLS-1$
- this.lastBatch = true;
- break;
- } else if (this.rowCount > this.requestMsg.getMaxResultRows() && this.requestMsg.isExceptionOnMaxRows()) {
- String msg = QueryPlugin.Util.getString("ConnectorWorker.MaxResultRowsExceed", this.requestMsg.getMaxResultRows()); //$NON-NLS-1$
- throw new TranslatorException(msg);
- }
- }
- }
- } catch (DataNotAvailableException e) {
- if (rows.size() == 0) {
- throw e;
- }
- }
-
- if (lastBatch) {
- if (this.procedureBatchHandler != null) {
- List row = this.procedureBatchHandler.getParameterRow();
- if (row != null) {
- rows.add(row);
- this.rowCount++;
- }
- }
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Obtained last batch, total row count:", rowCount}); //$NON-NLS-1$\
- } else {
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Obtained results from connector, current row count:", rowCount}); //$NON-NLS-1$
- }
-
- int currentRowCount = rows.size();
- if ( !lastBatch && currentRowCount == 0 ) {
- // Defect 13366 - Should send all batches, even if they're zero size.
- // Log warning if received a zero-size non-last batch from the connector.
- LogManager.logWarning(LogConstants.CTX_CONNECTOR, QueryPlugin.Util.getString("ConnectorWorker.zero_size_non_last_batch", requestMsg.getConnectorName())); //$NON-NLS-1$
- }
-
- AtomicResultsMessage response = createResultsMessage(rows.toArray(new List[currentRowCount]), requestMsg.getCommand().getProjectedSymbols());
-
- // if we need to keep the execution alive, then we can not support implicit close.
- response.setSupportsImplicitClose(!this.securityContext.keepExecutionAlive());
- response.setTransactional(this.securityContext.isTransactional());
- response.setWarnings(this.securityContext.getWarnings());
- response.setSupportsCloseWithLobs(this.connector.areLobsUsableAfterClose());
-
- if ( lastBatch ) {
- response.setFinalRow(rowCount);
- }
- return response;
- }
-
- public static AtomicResultsMessage createResultsMessage(List[] batch, List columnSymbols) {
- String[] dataTypes = TupleBuffer.getTypeNames(columnSymbols);
- return new AtomicResultsMessage(batch, dataTypes);
- }
-
- boolean isCancelled() {
- return this.isCancelled.get();
- }
-
- @Override
- public String toString() {
- return this.id.toString();
- }
-
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,363 @@
+/*
+ * 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.datamgr;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.resource.ResourceException;
+
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.util.Assertion;
+import org.teiid.dqp.message.AtomicRequestID;
+import org.teiid.dqp.message.AtomicRequestMessage;
+import org.teiid.dqp.message.AtomicResultsMessage;
+import org.teiid.language.Call;
+import org.teiid.language.QueryExpression;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.CommandLogMessage.Event;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.resource.spi.WrappedConnection;
+import org.teiid.translator.DataNotAvailableException;
+import org.teiid.translator.Execution;
+import org.teiid.translator.ExecutionFactory;
+import org.teiid.translator.ProcedureExecution;
+import org.teiid.translator.ResultSetExecution;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.UpdateExecution;
+
+
+public class ConnectorWorkItem implements ConnectorWork {
+
+ /* Permanent state members */
+ private AtomicRequestID id;
+ private ConnectorManager manager;
+ private AtomicRequestMessage requestMsg;
+ private ExecutionFactory connector;
+ private QueryMetadataInterface queryMetadata;
+
+ /* Created on new request */
+ private Object connection;
+ private Object connectionFactory;
+ private ExecutionContextImpl securityContext;
+ private volatile ResultSetExecution execution;
+ private ProcedureBatchHandler procedureBatchHandler;
+ private org.teiid.language.Command translatedCommand;
+ private int expectedColumns;
+
+ /* End state information */
+ private boolean lastBatch;
+ private int rowCount;
+ private boolean error;
+
+ private AtomicBoolean isCancelled = new AtomicBoolean();
+
+ ConnectorWorkItem(AtomicRequestMessage message, ConnectorManager manager) {
+ this.id = message.getAtomicRequestID();
+ this.requestMsg = message;
+ this.manager = manager;
+ AtomicRequestID requestID = this.requestMsg.getAtomicRequestID();
+ this.securityContext = new ExecutionContextImpl(requestMsg.getWorkContext().getVdbName(),
+ requestMsg.getWorkContext().getVdbVersion(),
+ requestMsg.getExecutionPayload(),
+ requestMsg.getWorkContext().getSessionId(),
+ requestMsg.getConnectorName(),
+ requestMsg.getRequestID().toString(),
+ Integer.toString(requestID.getNodeID()),
+ Integer.toString(requestID.getExecutionId())
+ );
+ 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();
+ this.queryMetadata = vdb.getAttachment(QueryMetadataInterface.class);
+ this.queryMetadata = new TempMetadataAdapter(this.queryMetadata, new TempMetadataStore());
+ this.securityContext.setTransactional(requestMsg.isTransactional());
+ }
+
+ public AtomicRequestID getId() {
+ return id;
+ }
+
+ public void cancel() {
+ try {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Processing CANCEL request"}); //$NON-NLS-1$
+ if (this.isCancelled.compareAndSet(false, true)) {
+ this.manager.logSRCCommand(this.requestMsg, this.securityContext, Event.CANCEL, -1);
+ if(execution != null) {
+ execution.cancel();
+ }
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, QueryPlugin.Util.getString("DQPCore.The_atomic_request_has_been_cancelled", this.id)); //$NON-NLS-1$
+ }
+ } catch (TranslatorException e) {
+ LogManager.logWarning(LogConstants.CTX_CONNECTOR, e, QueryPlugin.Util.getString("Cancel_request_failed", this.id)); //$NON-NLS-1$
+ }
+ }
+
+ public AtomicResultsMessage more() throws TranslatorException {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Processing MORE request"}); //$NON-NLS-1$
+ try {
+ return handleBatch();
+ } catch (Throwable t) {
+ throw handleError(t);
+ }
+ }
+
+ public void close() {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Processing Close :", this.requestMsg.getCommand()}); //$NON-NLS-1$
+ if (!error) {
+ manager.logSRCCommand(this.requestMsg, this.securityContext, Event.END, this.rowCount);
+ }
+ try {
+ if (execution != null) {
+ execution.close();
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Closed execution"}); //$NON-NLS-1$
+ }
+ } catch (Throwable e) {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, e, e.getMessage());
+ } finally {
+ try {
+ this.connector.closeConnection(connection, connectionFactory);
+ } catch (Throwable e) {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, e, e.getMessage());
+ } finally {
+ manager.removeState(this.id);
+ }
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Closed connection"}); //$NON-NLS-1$
+ }
+ }
+
+ private TranslatorException handleError(Throwable t) {
+ if (t instanceof DataNotAvailableException) {
+ throw (DataNotAvailableException)t;
+ }
+ error = true;
+ if (t instanceof RuntimeException && t.getCause() != null) {
+ t = t.getCause();
+ }
+ manager.logSRCCommand(this.requestMsg, this.securityContext, Event.ERROR, null);
+
+ String msg = QueryPlugin.Util.getString("ConnectorWorker.process_failed", this.id); //$NON-NLS-1$
+ if (isCancelled.get()) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, msg);
+ } else if (t instanceof TranslatorException || t instanceof TeiidProcessingException) {
+ LogManager.logWarning(LogConstants.CTX_CONNECTOR, t, msg);
+ } else {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, t, msg);
+ }
+ if (t instanceof TranslatorException) {
+ return (TranslatorException)t;
+ }
+ if (t instanceof RuntimeException) {
+ throw (RuntimeException)t;
+ }
+ return new TranslatorException(t);
+ }
+
+ public AtomicResultsMessage execute() throws TranslatorException, BlockedException {
+ if(isCancelled()) {
+ throw new TranslatorException("Request canceled"); //$NON-NLS-1$
+ }
+
+ 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, securityContext);
+
+ Object unwrapped = null;
+ if (connection instanceof WrappedConnection) {
+ try {
+ unwrapped = ((WrappedConnection)connection).unwrap();
+ } catch (ResourceException e) {
+ throw new TranslatorException(QueryPlugin.Util.getString("failed_to_unwrap_connection")); //$NON-NLS-1$
+ }
+ }
+
+ // Translate the command
+ Command command = this.requestMsg.getCommand();
+ this.expectedColumns = command.getProjectedSymbols().size();
+ LanguageBridgeFactory factory = new LanguageBridgeFactory(queryMetadata);
+ this.translatedCommand = factory.translate(command);
+
+ RuntimeMetadata rmd = new RuntimeMetadataImpl(queryMetadata);
+
+ // Create the execution based on mode
+ final Execution exec = connector.createExecution(this.translatedCommand, this.securityContext, rmd, (unwrapped == null) ? this.connection:unwrapped);
+ if (this.translatedCommand instanceof Call) {
+ this.execution = Assertion.isInstanceOf(exec, ProcedureExecution.class, "Call Executions are expected to be ProcedureExecutions"); //$NON-NLS-1$
+ StoredProcedure proc = (StoredProcedure)command;
+ if (proc.returnParameters()) {
+ this.procedureBatchHandler = new ProcedureBatchHandler((Call)this.translatedCommand, (ProcedureExecution)exec);
+ }
+ } else if (this.translatedCommand instanceof QueryExpression){
+ this.execution = Assertion.isInstanceOf(exec, ResultSetExecution.class, "QueryExpression Executions are expected to be ResultSetExecutions"); //$NON-NLS-1$
+ } else {
+ Assertion.isInstanceOf(exec, UpdateExecution.class, "Update Executions are expected to be UpdateExecutions"); //$NON-NLS-1$
+ this.execution = new ResultSetExecution() {
+ private int[] results;
+ private int index;
+
+ @Override
+ public void cancel() throws TranslatorException {
+ exec.cancel();
+ }
+ @Override
+ public void close() {
+ exec.close();
+ }
+ @Override
+ public void execute() throws TranslatorException {
+ exec.execute();
+ }
+ @Override
+ public List<?> next() throws TranslatorException,
+ DataNotAvailableException {
+ if (results == null) {
+ results = ((UpdateExecution)exec).getUpdateCounts();
+ }
+ if (index < results.length) {
+ return Arrays.asList(results[index++]);
+ }
+ return null;
+ }
+ };
+ }
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.requestMsg.getAtomicRequestID(), "Obtained execution"}); //$NON-NLS-1$
+ //Log the Source Command (Must be after obtaining the execution context)
+ manager.logSRCCommand(this.requestMsg, this.securityContext, Event.NEW, null);
+
+ // Execute query
+ this.execution.execute();
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Executed command"}); //$NON-NLS-1$
+
+ return handleBatch();
+ } catch (Throwable t) {
+ throw handleError(t);
+ }
+ }
+
+ protected AtomicResultsMessage handleBatch() throws TranslatorException {
+ Assertion.assertTrue(!this.lastBatch);
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Getting results from connector"}); //$NON-NLS-1$
+ int batchSize = 0;
+ List<List> rows = new ArrayList<List>(batchSize/4);
+
+ try {
+ while (batchSize < this.requestMsg.getFetchSize()) {
+
+ List row = this.execution.next();
+ if (row == null) {
+ this.lastBatch = true;
+ break;
+ }
+ if (row.size() != this.expectedColumns) {
+ throw new AssertionError("Inproper results returned. Expected " + this.expectedColumns + " columns, but was " + row.size()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ this.rowCount += 1;
+ batchSize++;
+ if (this.procedureBatchHandler != null) {
+ row = this.procedureBatchHandler.padRow(row);
+ }
+
+ rows.add(row);
+ // Check for max result rows exceeded
+ if(this.requestMsg.getMaxResultRows() > -1 && this.rowCount >= this.requestMsg.getMaxResultRows()){
+ if (this.rowCount == this.requestMsg.getMaxResultRows() && !this.requestMsg.isExceptionOnMaxRows()) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Exceeded max, returning", this.requestMsg.getMaxResultRows()}); //$NON-NLS-1$
+ this.lastBatch = true;
+ break;
+ } else if (this.rowCount > this.requestMsg.getMaxResultRows() && this.requestMsg.isExceptionOnMaxRows()) {
+ String msg = QueryPlugin.Util.getString("ConnectorWorker.MaxResultRowsExceed", this.requestMsg.getMaxResultRows()); //$NON-NLS-1$
+ throw new TranslatorException(msg);
+ }
+ }
+ }
+ } catch (DataNotAvailableException e) {
+ if (rows.size() == 0) {
+ throw e;
+ }
+ }
+
+ if (lastBatch) {
+ if (this.procedureBatchHandler != null) {
+ List row = this.procedureBatchHandler.getParameterRow();
+ if (row != null) {
+ rows.add(row);
+ this.rowCount++;
+ }
+ }
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Obtained last batch, total row count:", rowCount}); //$NON-NLS-1$\
+ } else {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Obtained results from connector, current row count:", rowCount}); //$NON-NLS-1$
+ }
+
+ int currentRowCount = rows.size();
+ if ( !lastBatch && currentRowCount == 0 ) {
+ // Defect 13366 - Should send all batches, even if they're zero size.
+ // Log warning if received a zero-size non-last batch from the connector.
+ LogManager.logWarning(LogConstants.CTX_CONNECTOR, QueryPlugin.Util.getString("ConnectorWorker.zero_size_non_last_batch", requestMsg.getConnectorName())); //$NON-NLS-1$
+ }
+
+ AtomicResultsMessage response = createResultsMessage(rows.toArray(new List[currentRowCount]), requestMsg.getCommand().getProjectedSymbols());
+
+ // if we need to keep the execution alive, then we can not support implicit close.
+ response.setSupportsImplicitClose(!this.securityContext.keepExecutionAlive());
+ response.setTransactional(this.securityContext.isTransactional());
+ response.setWarnings(this.securityContext.getWarnings());
+ response.setSupportsCloseWithLobs(this.connector.areLobsUsableAfterClose());
+
+ if ( lastBatch ) {
+ response.setFinalRow(rowCount);
+ }
+ return response;
+ }
+
+ public static AtomicResultsMessage createResultsMessage(List[] batch, List columnSymbols) {
+ String[] dataTypes = TupleBuffer.getTypeNames(columnSymbols);
+ return new AtomicResultsMessage(batch, dataTypes);
+ }
+
+ boolean isCancelled() {
+ return this.isCancelled.get();
+ }
+
+ @Override
+ public String toString() {
+ return this.id.toString();
+ }
+
+}
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ExecutionContextImpl.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/ExecutionContextImpl.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ExecutionContextImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,207 +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.datamgr;
-
-import java.io.Serializable;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.LinkedList;
-import java.util.List;
-
-import javax.security.auth.Subject;
-
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.core.util.HashCodeUtil;
-import org.teiid.translator.ExecutionContext;
-
-
-/**
- */
-public class ExecutionContextImpl implements ExecutionContext {
-
- // Orginal request non-atomic request id
- private String requestID;
- // Access Node ID
- private String partID;
- // currentConnector ID
- private String connectorName;
- // current VDB
- private String vdbName;
- // Current VDB's version
- private int vdbVersion;
- // User Name
- private Subject user;
- // Payload setup on the Statement object
- private Serializable executionPayload;
- // ID of the parent JDBC Connection which is executing the statement
- private String requestConnectionID;
- // Execute count of the query
- private String executeCount;
- // keep the execution object alive during the processing. default:false
- private boolean keepAlive = false;
-
- private boolean isTransactional;
-
- private int batchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
- private List<Exception> warnings = new LinkedList<Exception>();
-
- public ExecutionContextImpl(String vdbName, int vdbVersion, Serializable executionPayload,
- String originalConnectionID, String connectorName, String requestId, String partId, String execCount) {
-
- this.vdbName = vdbName;
- this.vdbVersion = vdbVersion;
- this.executionPayload = executionPayload;
- this.connectorName = connectorName;
- this.requestID = requestId;
- this.partID = partId;
- this.requestConnectionID = originalConnectionID;
- this.executeCount = execCount;
- }
-
- public String getConnectorIdentifier() {
- return this.connectorName;
- }
-
- @Override
- public String getRequestIdentifier() {
- return this.requestID;
- }
-
- @Override
- public String getPartIdentifier() {
- return this.partID;
- }
-
- @Override
- public String getExecutionCountIdentifier() {
- return this.executeCount;
- }
- @Override
- public String getVirtualDatabaseName() {
- return this.vdbName;
- }
- @Override
- public int getVirtualDatabaseVersion() {
- return this.vdbVersion;
- }
- @Override
- public Subject getSubject() {
- return this.user;
- }
-
- public void setUser(Subject user) {
- this.user = user;
- }
-
- @Override
- public Serializable getExecutionPayload() {
- return executionPayload;
- }
-
- @Override
- public String getConnectionIdentifier() {
- return requestConnectionID;
- }
- @Override
- public void keepExecutionAlive(boolean alive) {
- this.keepAlive = alive;
- }
-
- boolean keepExecutionAlive() {
- return this.keepAlive;
- }
-
- public boolean equals(Object obj) {
- if(obj == this) {
- return true;
- }
- if(! (obj instanceof ExecutionContext)) {
- return false;
- }
- ExecutionContext other = (ExecutionContext) obj;
- return compareWithNull(this.getRequestIdentifier(), other.getRequestIdentifier()) &&
- compareWithNull(this.getPartIdentifier(), other.getPartIdentifier());
- }
-
- private 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);
- }
-
- public int hashCode() {
- return HashCodeUtil.hashCode(HashCodeUtil.hashCode(0, requestID), partID);
- }
-
- public String toString() {
- String userName = null;
- if (this.user != null) {
- for(Principal p:this.user.getPrincipals()) {
- userName = p.getName();
- }
- }
- return "ExecutionContext<vdb=" + this.vdbName + ", version=" + this.vdbVersion + ", user=" + userName + ">"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Override
- public boolean isTransactional() {
- return isTransactional;
- }
-
- void setTransactional(boolean isTransactional) {
- this.isTransactional = isTransactional;
- }
-
- @Override
- public int getBatchSize() {
- return batchSize;
- }
-
- public void setBatchSize(int batchSize) {
- this.batchSize = batchSize;
- }
-
- /**
- * Add an exception as a warning to this Execution.
- */
- @Override
- public void addWarning(Exception ex) {
- if (ex == null) {
- return;
- }
- this.warnings.add(ex);
- }
-
- public List<Exception> getWarnings() {
- List<Exception> result = new ArrayList<Exception>(warnings);
- warnings.clear();
- return result;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ExecutionContextImpl.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/ExecutionContextImpl.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ExecutionContextImpl.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/ExecutionContextImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,218 @@
+/*
+ * 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.datamgr;
+
+import java.io.Serializable;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+
+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;
+
+
+/**
+ */
+public class ExecutionContextImpl implements ExecutionContext {
+
+ // Orginal request non-atomic request id
+ private String requestID;
+ // Access Node ID
+ private String partID;
+ // currentConnector ID
+ private String connectorName;
+ // current VDB
+ private String vdbName;
+ // Current VDB's version
+ private int vdbVersion;
+ // User Name
+ private Subject user;
+ // Payload setup on the Statement object
+ private Serializable executionPayload;
+ // ID of the parent JDBC Connection which is executing the statement
+ private String requestConnectionID;
+ // Execute count of the query
+ private String executeCount;
+ // keep the execution object alive during the processing. default:false
+ private boolean keepAlive = false;
+
+ private boolean isTransactional;
+
+ 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) {
+
+ this.vdbName = vdbName;
+ this.vdbVersion = vdbVersion;
+ this.executionPayload = executionPayload;
+ this.connectorName = connectorName;
+ this.requestID = requestId;
+ this.partID = partId;
+ this.requestConnectionID = originalConnectionID;
+ this.executeCount = execCount;
+ }
+
+ public String getConnectorIdentifier() {
+ return this.connectorName;
+ }
+
+ @Override
+ public String getRequestIdentifier() {
+ return this.requestID;
+ }
+
+ @Override
+ public String getPartIdentifier() {
+ return this.partID;
+ }
+
+ @Override
+ public String getExecutionCountIdentifier() {
+ return this.executeCount;
+ }
+ @Override
+ public String getVirtualDatabaseName() {
+ return this.vdbName;
+ }
+ @Override
+ public int getVirtualDatabaseVersion() {
+ return this.vdbVersion;
+ }
+ @Override
+ public Subject getSubject() {
+ return this.user;
+ }
+
+ public void setUser(Subject user) {
+ this.user = user;
+ }
+
+ @Override
+ public Serializable getExecutionPayload() {
+ return executionPayload;
+ }
+
+ @Override
+ public String getConnectionIdentifier() {
+ return requestConnectionID;
+ }
+ @Override
+ public void keepExecutionAlive(boolean alive) {
+ this.keepAlive = alive;
+ }
+
+ boolean keepExecutionAlive() {
+ return this.keepAlive;
+ }
+
+ public boolean equals(Object obj) {
+ if(obj == this) {
+ return true;
+ }
+ if(! (obj instanceof ExecutionContext)) {
+ return false;
+ }
+ ExecutionContext other = (ExecutionContext) obj;
+ return compareWithNull(this.getRequestIdentifier(), other.getRequestIdentifier()) &&
+ compareWithNull(this.getPartIdentifier(), other.getPartIdentifier());
+ }
+
+ private 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);
+ }
+
+ public int hashCode() {
+ return HashCodeUtil.hashCode(HashCodeUtil.hashCode(0, requestID), partID);
+ }
+
+ public String toString() {
+ String userName = null;
+ if (this.user != null) {
+ for(Principal p:this.user.getPrincipals()) {
+ userName = p.getName();
+ }
+ }
+ return "ExecutionContext<vdb=" + this.vdbName + ", version=" + this.vdbVersion + ", user=" + userName + ">"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Override
+ public boolean isTransactional() {
+ return isTransactional;
+ }
+
+ void setTransactional(boolean isTransactional) {
+ this.isTransactional = isTransactional;
+ }
+
+ @Override
+ public int getBatchSize() {
+ return batchSize;
+ }
+
+ public void setBatchSize(int batchSize) {
+ this.batchSize = batchSize;
+ }
+
+ /**
+ * Add an exception as a warning to this Execution.
+ */
+ @Override
+ public void addWarning(Exception ex) {
+ if (ex == null) {
+ return;
+ }
+ this.warnings.add(ex);
+ }
+
+ public List<Exception> getWarnings() {
+ List<Exception> result = new ArrayList<Exception>(warnings);
+ warnings.clear();
+ return result;
+ }
+
+ @Override
+ public Session getSession() {
+ return this.session;
+ }
+
+ public void setSession(Session session) {
+ this.session = session;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/LanguageBridgeFactory.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/LanguageBridgeFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/LanguageBridgeFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,765 +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.datamgr;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.common.buffer.TupleSource;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidException;
-import org.teiid.core.TeiidRuntimeException;
-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.Condition;
-import org.teiid.language.DerivedColumn;
-import org.teiid.language.DerivedTable;
-import org.teiid.language.Exists;
-import org.teiid.language.ExpressionValueSource;
-import org.teiid.language.In;
-import org.teiid.language.InsertValueSource;
-import org.teiid.language.IsNull;
-import org.teiid.language.IteratorValueSource;
-import org.teiid.language.Join;
-import org.teiid.language.Like;
-import org.teiid.language.Literal;
-import org.teiid.language.NamedTable;
-import org.teiid.language.Not;
-import org.teiid.language.QueryExpression;
-import org.teiid.language.SearchedCase;
-import org.teiid.language.SearchedWhenClause;
-import org.teiid.language.Select;
-import org.teiid.language.SortSpecification;
-import org.teiid.language.SubqueryComparison;
-import org.teiid.language.SubqueryIn;
-import org.teiid.language.TableReference;
-import org.teiid.language.With;
-import org.teiid.language.WithItem;
-import org.teiid.language.Argument.Direction;
-import org.teiid.language.Comparison.Operator;
-import org.teiid.language.SortSpecification.Ordering;
-import org.teiid.language.SubqueryComparison.Quantifier;
-import org.teiid.metadata.Procedure;
-import org.teiid.metadata.ProcedureParameter;
-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;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.FromClause;
-import org.teiid.query.sql.lang.GroupBy;
-import org.teiid.query.sql.lang.Insert;
-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;
-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.SPParameter;
-import org.teiid.query.sql.lang.SetClause;
-import org.teiid.query.sql.lang.SetClauseList;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.SubqueryCompareCriteria;
-import org.teiid.query.sql.lang.SubqueryFromClause;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.lang.UnaryFromClause;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.lang.WithQueryCommand;
-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.Function;
-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.SingleElementSymbol;
-import org.teiid.translator.TranslatorException;
-
-
-public class LanguageBridgeFactory {
- private RuntimeMetadataImpl metadataFactory = null;
-
- public LanguageBridgeFactory(QueryMetadataInterface metadata) {
- if (metadata != null) {
- metadataFactory = new RuntimeMetadataImpl(metadata);
- }
- }
-
- public org.teiid.language.Command translate(Command command) {
- if (command == null) return null;
- if (command instanceof Query) {
- return translate((Query)command);
- } else if (command instanceof SetQuery) {
- return translate((SetQuery)command);
- } else if (command instanceof Insert) {
- return translate((Insert)command);
- } else if (command instanceof Update) {
- return translate((Update)command);
- } else if (command instanceof Delete) {
- return translate((Delete)command);
- } else if (command instanceof StoredProcedure) {
- return translate((StoredProcedure)command);
- } else if (command instanceof BatchedUpdateCommand) {
- return translate((BatchedUpdateCommand)command);
- }
- throw new AssertionError();
- }
-
- QueryExpression translate(QueryCommand command) {
- if (command instanceof Query) {
- return translate((Query)command);
- }
- return translate((SetQuery)command);
- }
-
- org.teiid.language.SetQuery translate(SetQuery union) {
- org.teiid.language.SetQuery result = new org.teiid.language.SetQuery();
- result.setAll(union.isAll());
- switch (union.getOperation()) {
- case UNION:
- result.setOperation(org.teiid.language.SetQuery.Operation.UNION);
- break;
- case INTERSECT:
- result.setOperation(org.teiid.language.SetQuery.Operation.INTERSECT);
- break;
- case EXCEPT:
- result.setOperation(org.teiid.language.SetQuery.Operation.EXCEPT);
- break;
- }
- result.setLeftQuery(translate(union.getLeftQuery()));
- result.setRightQuery(translate(union.getRightQuery()));
- result.setOrderBy(translate(union.getOrderBy(), true));
- result.setLimit(translate(union.getLimit()));
- result.setWith(translate(union.getWith()));
- return result;
- }
-
- /* Query */
- Select translate(Query query) {
- List symbols = query.getSelect().getSymbols();
- List<DerivedColumn> translatedSymbols = new ArrayList<DerivedColumn>(symbols.size());
- for (Iterator i = symbols.iterator(); i.hasNext();) {
- SingleElementSymbol symbol = (SingleElementSymbol)i.next();
- String alias = null;
- if(symbol instanceof AliasSymbol) {
- alias = symbol.getOutputName();
- 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());
- }
-
- DerivedColumn selectSymbol = new DerivedColumn(alias, iExp);
- translatedSymbols.add(selectSymbol);
- }
- List<TableReference> items = null;
- if (query.getFrom() != null) {
- List clauses = query.getFrom().getClauses();
- items = new ArrayList<TableReference>(clauses.size());
- for (Iterator i = clauses.iterator(); i.hasNext();) {
- items.add(translate((FromClause)i.next()));
- }
- }
- Select q = new Select(translatedSymbols, query
- .getSelect().isDistinct(), items,
- translate(query.getCriteria()), translate(query.getGroupBy()),
- translate(query.getHaving()), translate(query.getOrderBy(), false));
- q.setLimit(translate(query.getLimit()));
- q.setWith(translate(query.getWith()));
- return q;
- }
-
- public With translate(List<WithQueryCommand> with) {
- if (with == null || with.isEmpty()) {
- return null;
- }
- With result = new With();
- ArrayList<WithItem> items = new ArrayList<WithItem>(with.size());
- for (WithQueryCommand withQueryCommand : with) {
- WithItem item = new WithItem();
- item.setTable(translate(withQueryCommand.getGroupSymbol()));
- if (withQueryCommand.getColumns() != null) {
- List<ColumnReference> translatedElements = new ArrayList<ColumnReference>(withQueryCommand.getColumns().size());
- for (ElementSymbol es: withQueryCommand.getColumns()) {
- translatedElements.add(translate(es));
- }
- }
- item.setSubquery(translate(withQueryCommand.getCommand()));
- }
- result.setItems(items);
- return result;
- }
-
- public TableReference translate(FromClause clause) {
- if (clause == null) return null;
- if (clause instanceof JoinPredicate) {
- return translate((JoinPredicate)clause);
- } else if (clause instanceof SubqueryFromClause) {
- return translate((SubqueryFromClause)clause);
- } else if (clause instanceof UnaryFromClause) {
- return translate((UnaryFromClause)clause);
- }
- throw new AssertionError();
- }
-
- Join translate(JoinPredicate join) {
- List crits = join.getJoinCriteria();
- Criteria crit = null;
- if (crits.size() == 1) {
- crit = (Criteria)crits.get(0);
- } else if (crits.size() > 1) {
- crit = new CompoundCriteria(crits);
- }
-
- Join.JoinType joinType = Join.JoinType.INNER_JOIN;
- if(join.getJoinType().equals(JoinType.JOIN_INNER)) {
- joinType = Join.JoinType.INNER_JOIN;
- } else if(join.getJoinType().equals(JoinType.JOIN_LEFT_OUTER)) {
- joinType = Join.JoinType.LEFT_OUTER_JOIN;
- } else if(join.getJoinType().equals(JoinType.JOIN_RIGHT_OUTER)) {
- joinType = Join.JoinType.RIGHT_OUTER_JOIN;
- } else if(join.getJoinType().equals(JoinType.JOIN_FULL_OUTER)) {
- joinType = Join.JoinType.FULL_OUTER_JOIN;
- } else if(join.getJoinType().equals(JoinType.JOIN_CROSS)) {
- joinType = Join.JoinType.CROSS_JOIN;
- }
-
- return new Join(translate(join.getLeftClause()),
- translate(join.getRightClause()),
- joinType,
- translate(crit));
- }
-
- TableReference translate(SubqueryFromClause clause) {
- return new DerivedTable(translate((QueryCommand)clause.getCommand()), clause.getOutputName());
- }
-
- NamedTable translate(UnaryFromClause clause) {
- return translate(clause.getGroup());
- }
-
- public Condition translate(Criteria criteria) {
- if (criteria == null) return null;
- if (criteria instanceof CompareCriteria) {
- return translate((CompareCriteria)criteria);
- } else if (criteria instanceof CompoundCriteria) {
- return translate((CompoundCriteria)criteria);
- } else if (criteria instanceof ExistsCriteria) {
- return translate((ExistsCriteria)criteria);
- } else if (criteria instanceof IsNullCriteria) {
- return translate((IsNullCriteria)criteria);
- }else if (criteria instanceof MatchCriteria) {
- return translate((MatchCriteria)criteria);
- } else if (criteria instanceof NotCriteria) {
- return translate((NotCriteria)criteria);
- } else if (criteria instanceof SetCriteria) {
- return translate((SetCriteria)criteria);
- } else if (criteria instanceof SubqueryCompareCriteria) {
- return translate((SubqueryCompareCriteria)criteria);
- } else if (criteria instanceof SubquerySetCriteria) {
- return translate((SubquerySetCriteria)criteria);
- }
- throw new AssertionError();
- }
-
- org.teiid.language.Comparison translate(CompareCriteria criteria) {
- Operator operator = Operator.EQ;
- switch(criteria.getOperator()) {
- case CompareCriteria.EQ:
- operator = Operator.EQ;
- break;
- case CompareCriteria.NE:
- operator = Operator.NE;
- break;
- case CompareCriteria.LT:
- operator = Operator.LT;
- break;
- case CompareCriteria.LE:
- operator = Operator.LE;
- break;
- case CompareCriteria.GT:
- operator = Operator.GT;
- break;
- case CompareCriteria.GE:
- operator = Operator.GE;
- break;
-
- }
-
- return new org.teiid.language.Comparison(translate(criteria.getLeftExpression()),
- translate(criteria.getRightExpression()), operator);
- }
-
- AndOr translate(CompoundCriteria criteria) {
- List nestedCriteria = criteria.getCriteria();
- int size = nestedCriteria.size();
- AndOr.Operator op = criteria.getOperator() == CompoundCriteria.AND?AndOr.Operator.AND:AndOr.Operator.OR;
- AndOr result = new AndOr(translate((Criteria)nestedCriteria.get(size - 2)), translate((Criteria)nestedCriteria.get(size - 1)), op);
- for (int i = nestedCriteria.size() - 3; i >= 0; i--) {
- result = new AndOr(translate((Criteria)nestedCriteria.get(i)), result, op);
- }
- return result;
- }
-
- Condition translate(ExistsCriteria criteria) {
- Exists exists = new Exists(translate(criteria.getCommand()));
- if (criteria.isNegated()) {
- return new Not(exists);
- }
- return exists;
- }
-
- IsNull translate(IsNullCriteria criteria) {
- return new IsNull(translate(criteria.getExpression()), criteria.isNegated());
- }
-
- Like translate(MatchCriteria criteria) {
- Character escapeChar = null;
- if(criteria.getEscapeChar() != MatchCriteria.NULL_ESCAPE_CHAR) {
- escapeChar = new Character(criteria.getEscapeChar());
- }
- return new Like(translate(criteria.getLeftExpression()),
- translate(criteria.getRightExpression()),
- escapeChar,
- criteria.isNegated());
- }
-
- In translate(SetCriteria criteria) {
- Collection expressions = criteria.getValues();
- List translatedExpressions = new ArrayList();
- for (Iterator i = expressions.iterator(); i.hasNext();) {
- translatedExpressions.add(translate((Expression)i.next()));
- }
- return new In(translate(criteria.getExpression()),
- translatedExpressions,
- criteria.isNegated());
- }
-
- SubqueryComparison translate(SubqueryCompareCriteria criteria) {
- Quantifier quantifier = Quantifier.ALL;
- switch(criteria.getPredicateQuantifier()) {
- case SubqueryCompareCriteria.ALL:
- quantifier = Quantifier.ALL;
- break;
- case SubqueryCompareCriteria.ANY:
- quantifier = Quantifier.SOME;
- break;
- case SubqueryCompareCriteria.SOME:
- quantifier = Quantifier.SOME;
- break;
- }
-
- Operator operator = Operator.EQ;
- switch(criteria.getOperator()) {
- case SubqueryCompareCriteria.EQ:
- operator = Operator.EQ;
- break;
- case SubqueryCompareCriteria.NE:
- operator = Operator.NE;
- break;
- case SubqueryCompareCriteria.LT:
- operator = Operator.LT;
- break;
- case SubqueryCompareCriteria.LE:
- operator = Operator.LE;
- break;
- case SubqueryCompareCriteria.GT:
- operator = Operator.GT;
- break;
- case SubqueryCompareCriteria.GE:
- operator = Operator.GE;
- break;
- }
-
- return new SubqueryComparison(translate(criteria.getLeftExpression()),
- operator,
- quantifier,
- translate((QueryCommand)criteria.getCommand()));
- }
-
- SubqueryIn translate(SubquerySetCriteria criteria) {
- return new SubqueryIn(translate(criteria.getExpression()),
- criteria.isNegated(),
- translate((QueryCommand)criteria.getCommand()));
- }
-
- Not translate(NotCriteria criteria) {
- return new Not(translate(criteria.getCriteria()));
- }
-
- public org.teiid.language.GroupBy translate(GroupBy groupBy) {
- if(groupBy == null){
- return null;
- }
- List items = groupBy.getSymbols();
- List<org.teiid.language.Expression> translatedItems = new ArrayList<org.teiid.language.Expression>();
- for (Iterator i = items.iterator(); i.hasNext();) {
- translatedItems.add(translate((Expression)i.next()));
- }
- return new org.teiid.language.GroupBy(translatedItems);
- }
-
- public org.teiid.language.OrderBy translate(OrderBy orderBy, boolean set) {
- if(orderBy == null){
- return null;
- }
- List<OrderByItem> items = orderBy.getOrderByItems();
- List<SortSpecification> translatedItems = new ArrayList<SortSpecification>();
- for (int i = 0; i < items.size(); i++) {
- SingleElementSymbol symbol = items.get(i).getSymbol();
- Ordering direction = items.get(i).isAscending() ? Ordering.ASC: Ordering.DESC;
-
- SortSpecification orderByItem = null;
- if(items.get(i).isUnrelated() || (!set && symbol instanceof ElementSymbol)){
- orderByItem = new SortSpecification(direction, translate(symbol));
- } else {
- orderByItem = new SortSpecification(direction, new ColumnReference(null, symbol.getOutputName(), null, symbol.getType()));
- }
- orderByItem.setNullOrdering(items.get(i).getNullOrdering());
- translatedItems.add(orderByItem);
- }
- return new org.teiid.language.OrderBy(translatedItems);
- }
-
-
- /* Expressions */
- public org.teiid.language.Expression translate(Expression expr) {
- if (expr == null) return null;
- if (expr instanceof Constant) {
- return translate((Constant)expr);
- } else if (expr instanceof Function) {
- return translate((Function)expr);
- } else if (expr instanceof ScalarSubquery) {
- 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 Criteria) {
- return translate((Criteria)expr);
- }
- throw new AssertionError();
- }
-
- Literal translate(Constant constant) {
- Literal result = new Literal(constant.getValue(), constant.getType());
- result.setBindValue(constant.isMultiValued());
- result.setMultiValued(constant.isMultiValued());
- result.setBindEligible(constant.isBindEligible());
- return result;
- }
-
- org.teiid.language.Function translate(Function function) {
- Expression [] args = function.getArgs();
- List<org.teiid.language.Expression> params = new ArrayList<org.teiid.language.Expression>(args.length);
- for (int i = 0; i < args.length; i++) {
- params.add(translate(args[i]));
- }
- String name = function.getName();
- if (function.getFunctionDescriptor() != null) {
- name = function.getFunctionDescriptor().getName();
- }
- 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
- org.teiid.language.Function result = new org.teiid.language.Function(name, params, function.getType());
- if (function.getFunctionDescriptor() != null) {
- result.setMetadataObject(function.getFunctionDescriptor().getMethod());
- }
- return result;
- }
-
- SearchedCase translate(SearchedCaseExpression expr) {
- ArrayList<SearchedWhenClause> whens = new ArrayList<SearchedWhenClause>();
- for (int i = 0; i < expr.getWhenCount(); i++) {
- whens.add(new SearchedWhenClause(translate(expr.getWhenCriteria(i)), translate(expr.getThenExpression(i))));
- }
- return new SearchedCase(whens,
- translate(expr.getElseExpression()),
- expr.getType());
- }
-
-
- org.teiid.language.Expression translate(ScalarSubquery ss) {
- 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());
- if (element.getTable().getMetadataObject() == null) {
- return element;
- }
-
- Object mid = symbol.getMetadataID();
-
- if(! (mid instanceof TempMetadataID)) {
- element.setMetadataObject(metadataFactory.getElement(mid));
- }
- return element;
- }
-
- AggregateFunction translate(AggregateSymbol symbol) {
- return new AggregateFunction(symbol.getAggregateFunction().name(),
- symbol.isDistinct(),
- translate(symbol.getExpression()),
- symbol.getType());
- }
-
- org.teiid.language.Expression translate(ExpressionSymbol symbol) {
- return translate(symbol.getExpression());
- }
-
-
- /* Insert */
- org.teiid.language.Insert translate(Insert insert) {
- List<ElementSymbol> elements = insert.getVariables();
- List<ColumnReference> translatedElements = new ArrayList<ColumnReference>();
-
- for (ElementSymbol elementSymbol : elements) {
- translatedElements.add(translate(elementSymbol));
- }
-
- InsertValueSource valueSource = null;
- if (insert.getQueryExpression() != null) {
- valueSource = translate(insert.getQueryExpression());
- } else if (insert.getTupleSource() != null) {
- final TupleSource ts = insert.getTupleSource();
- valueSource = new IteratorValueSource<List<?>>(new Iterator<List<?>>() {
-
- List<?> next;
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public List<?> next() {
- if (hasNext()) {
- List<?> result = next;
- next = null;
- return result;
- }
- throw new NoSuchElementException();
- }
-
- @Override
- public boolean hasNext() {
- if (next != null) {
- return true;
- }
- try {
- next = ts.nextTuple();
- } catch (TeiidException e) {
- throw new TeiidRuntimeException(e);
- }
- return next != null;
- }
- }, elements.size());
- } else {
- // This is for the simple one row insert.
- List values = insert.getValues();
- List<org.teiid.language.Expression> translatedValues = new ArrayList<org.teiid.language.Expression>();
- for (Iterator i = values.iterator(); i.hasNext();) {
- translatedValues.add(translate((Expression)i.next()));
- }
- valueSource = new ExpressionValueSource(translatedValues);
- }
-
- return new org.teiid.language.Insert(translate(insert.getGroup()),
- translatedElements,
- valueSource);
- }
-
- /* Update */
- org.teiid.language.Update translate(Update update) {
- return new org.teiid.language.Update(translate(update.getGroup()),
- translate(update.getChangeList()),
- translate(update.getCriteria()));
- }
-
- List<org.teiid.language.SetClause> translate(SetClauseList setClauseList) {
- List<org.teiid.language.SetClause> clauses = new ArrayList<org.teiid.language.SetClause>(setClauseList.getClauses().size());
- for (SetClause setClause : setClauseList.getClauses()) {
- clauses.add(translate(setClause));
- }
- return clauses;
- }
-
- org.teiid.language.SetClause translate(SetClause setClause) {
- return new org.teiid.language.SetClause(translate(setClause.getSymbol()), translate(setClause.getValue()));
- }
-
- /* Delete */
- org.teiid.language.Delete translate(Delete delete) {
- org.teiid.language.Delete deleteImpl = new org.teiid.language.Delete(translate(delete.getGroup()),
- translate(delete.getCriteria()));
- return deleteImpl;
- }
-
- /* Execute */
- Call translate(StoredProcedure sp) {
- Procedure proc = null;
- if(sp.getProcedureID() != null) {
- try {
- proc = this.metadataFactory.getProcedure(sp.getGroup().getName());
- } catch (TranslatorException e) {
- throw new TeiidRuntimeException(e);
- }
- }
- Class<?> returnType = null;
- List<Argument> translatedParameters = new ArrayList<Argument>();
- for (SPParameter param : sp.getParameters()) {
- Direction direction = Direction.IN;
- switch(param.getParameterType()) {
- case ParameterInfo.IN:
- direction = Direction.IN;
- break;
- case ParameterInfo.INOUT:
- direction = Direction.INOUT;
- break;
- case ParameterInfo.OUT:
- direction = Direction.OUT;
- break;
- case ParameterInfo.RESULT_SET:
- continue; //already part of the metadata
- case ParameterInfo.RETURN_VALUE:
- returnType = param.getClassType();
- continue;
- }
-
- ProcedureParameter metadataParam = metadataFactory.getParameter(param);
- //we can assume for now that all arguments will be literals, which may be multivalued
- Literal value = null;
- if (direction != Direction.OUT) {
- value = (Literal)translate(param.getExpression());
- }
- Argument arg = new Argument(direction, value, param.getClassType(), metadataParam);
- translatedParameters.add(arg);
- }
-
- Call call = new Call(removeSchemaName(sp.getProcedureName()), translatedParameters, proc);
- call.setReturnType(returnType);
- return call;
- }
-
- public NamedTable translate(GroupSymbol symbol) {
- String alias = null;
- String fullGroup = symbol.getOutputName();
- if(symbol.getOutputDefinition() != null) {
- alias = symbol.getOutputName();
- fullGroup = symbol.getOutputDefinition();
- }
- 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) {
- throw new TeiidRuntimeException(e);
- } catch (TeiidComponentException e) {
- throw new TeiidRuntimeException(e);
- }
- return group;
- }
-
- private String removeSchemaName(String fullGroup) {
- //remove the model name
- int index = fullGroup.indexOf(ElementSymbol.SEPARATOR);
- if (index > 0) {
- fullGroup = fullGroup.substring(index + 1);
- }
- return fullGroup;
- }
-
- /* Batched Updates */
- BatchedUpdates translate(BatchedUpdateCommand command) {
- List 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()));
- }
- return new BatchedUpdates(translatedUpdates);
- }
-
- org.teiid.language.Limit translate(Limit limit) {
- if (limit == null) {
- return null;
- }
- int rowOffset = 0;
- if (limit.getOffset() != null) {
- Literal c1 = (Literal)translate(limit.getOffset());
- rowOffset = ((Integer)c1.getValue()).intValue();
- }
- Literal c2 = (Literal)translate(limit.getRowLimit());
- int rowLimit = ((Integer)c2.getValue()).intValue();
- return new org.teiid.language.Limit(rowOffset, rowLimit);
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/LanguageBridgeFactory.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/LanguageBridgeFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/LanguageBridgeFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/LanguageBridgeFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,768 @@
+/*
+ * 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.datamgr;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+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;
+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.Condition;
+import org.teiid.language.DerivedColumn;
+import org.teiid.language.DerivedTable;
+import org.teiid.language.Exists;
+import org.teiid.language.ExpressionValueSource;
+import org.teiid.language.In;
+import org.teiid.language.InsertValueSource;
+import org.teiid.language.IsNull;
+import org.teiid.language.IteratorValueSource;
+import org.teiid.language.Join;
+import org.teiid.language.Like;
+import org.teiid.language.Literal;
+import org.teiid.language.NamedTable;
+import org.teiid.language.Not;
+import org.teiid.language.QueryExpression;
+import org.teiid.language.SearchedCase;
+import org.teiid.language.SearchedWhenClause;
+import org.teiid.language.Select;
+import org.teiid.language.SortSpecification;
+import org.teiid.language.SubqueryComparison;
+import org.teiid.language.SubqueryIn;
+import org.teiid.language.TableReference;
+import org.teiid.language.With;
+import org.teiid.language.WithItem;
+import org.teiid.language.Argument.Direction;
+import org.teiid.language.Comparison.Operator;
+import org.teiid.language.SortSpecification.Ordering;
+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.sql.lang.BatchedUpdateCommand;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.FromClause;
+import org.teiid.query.sql.lang.GroupBy;
+import org.teiid.query.sql.lang.Insert;
+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;
+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.SPParameter;
+import org.teiid.query.sql.lang.SetClause;
+import org.teiid.query.sql.lang.SetClauseList;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.SubqueryCompareCriteria;
+import org.teiid.query.sql.lang.SubqueryFromClause;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.lang.WithQueryCommand;
+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.Function;
+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.SingleElementSymbol;
+import org.teiid.translator.TranslatorException;
+
+
+public class LanguageBridgeFactory {
+ private RuntimeMetadataImpl metadataFactory = null;
+
+ public LanguageBridgeFactory(QueryMetadataInterface metadata) {
+ if (metadata != null) {
+ metadataFactory = new RuntimeMetadataImpl(metadata);
+ }
+ }
+
+ public org.teiid.language.Command translate(Command command) {
+ if (command == null) return null;
+ if (command instanceof Query) {
+ return translate((Query)command);
+ } else if (command instanceof SetQuery) {
+ return translate((SetQuery)command);
+ } else if (command instanceof Insert) {
+ return translate((Insert)command);
+ } else if (command instanceof Update) {
+ return translate((Update)command);
+ } else if (command instanceof Delete) {
+ return translate((Delete)command);
+ } else if (command instanceof StoredProcedure) {
+ return translate((StoredProcedure)command);
+ } else if (command instanceof BatchedUpdateCommand) {
+ return translate((BatchedUpdateCommand)command);
+ }
+ throw new AssertionError();
+ }
+
+ QueryExpression translate(QueryCommand command) {
+ if (command instanceof Query) {
+ return translate((Query)command);
+ }
+ return translate((SetQuery)command);
+ }
+
+ org.teiid.language.SetQuery translate(SetQuery union) {
+ org.teiid.language.SetQuery result = new org.teiid.language.SetQuery();
+ result.setAll(union.isAll());
+ switch (union.getOperation()) {
+ case UNION:
+ result.setOperation(org.teiid.language.SetQuery.Operation.UNION);
+ break;
+ case INTERSECT:
+ result.setOperation(org.teiid.language.SetQuery.Operation.INTERSECT);
+ break;
+ case EXCEPT:
+ result.setOperation(org.teiid.language.SetQuery.Operation.EXCEPT);
+ break;
+ }
+ result.setLeftQuery(translate(union.getLeftQuery()));
+ result.setRightQuery(translate(union.getRightQuery()));
+ result.setOrderBy(translate(union.getOrderBy(), true));
+ result.setLimit(translate(union.getLimit()));
+ result.setWith(translate(union.getWith()));
+ return result;
+ }
+
+ /* Query */
+ Select translate(Query query) {
+ List symbols = query.getSelect().getSymbols();
+ List<DerivedColumn> translatedSymbols = new ArrayList<DerivedColumn>(symbols.size());
+ for (Iterator i = symbols.iterator(); i.hasNext();) {
+ SingleElementSymbol symbol = (SingleElementSymbol)i.next();
+ String alias = null;
+ if(symbol instanceof AliasSymbol) {
+ alias = symbol.getOutputName();
+ 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());
+ }
+
+ DerivedColumn selectSymbol = new DerivedColumn(alias, iExp);
+ translatedSymbols.add(selectSymbol);
+ }
+ List<TableReference> items = null;
+ if (query.getFrom() != null) {
+ List clauses = query.getFrom().getClauses();
+ items = new ArrayList<TableReference>(clauses.size());
+ for (Iterator i = clauses.iterator(); i.hasNext();) {
+ items.add(translate((FromClause)i.next()));
+ }
+ }
+ Select q = new Select(translatedSymbols, query
+ .getSelect().isDistinct(), items,
+ translate(query.getCriteria()), translate(query.getGroupBy()),
+ translate(query.getHaving()), translate(query.getOrderBy(), false));
+ q.setLimit(translate(query.getLimit()));
+ q.setWith(translate(query.getWith()));
+ return q;
+ }
+
+ public With translate(List<WithQueryCommand> with) {
+ if (with == null || with.isEmpty()) {
+ return null;
+ }
+ With result = new With();
+ ArrayList<WithItem> items = new ArrayList<WithItem>(with.size());
+ for (WithQueryCommand withQueryCommand : with) {
+ WithItem item = new WithItem();
+ item.setTable(translate(withQueryCommand.getGroupSymbol()));
+ if (withQueryCommand.getColumns() != null) {
+ List<ColumnReference> translatedElements = new ArrayList<ColumnReference>(withQueryCommand.getColumns().size());
+ for (ElementSymbol es: withQueryCommand.getColumns()) {
+ translatedElements.add(translate(es));
+ }
+ }
+ item.setSubquery(translate(withQueryCommand.getCommand()));
+ }
+ result.setItems(items);
+ return result;
+ }
+
+ public TableReference translate(FromClause clause) {
+ if (clause == null) return null;
+ if (clause instanceof JoinPredicate) {
+ return translate((JoinPredicate)clause);
+ } else if (clause instanceof SubqueryFromClause) {
+ return translate((SubqueryFromClause)clause);
+ } else if (clause instanceof UnaryFromClause) {
+ return translate((UnaryFromClause)clause);
+ }
+ throw new AssertionError();
+ }
+
+ Join translate(JoinPredicate join) {
+ List crits = join.getJoinCriteria();
+ Criteria crit = null;
+ if (crits.size() == 1) {
+ crit = (Criteria)crits.get(0);
+ } else if (crits.size() > 1) {
+ crit = new CompoundCriteria(crits);
+ }
+
+ Join.JoinType joinType = Join.JoinType.INNER_JOIN;
+ if(join.getJoinType().equals(JoinType.JOIN_INNER)) {
+ joinType = Join.JoinType.INNER_JOIN;
+ } else if(join.getJoinType().equals(JoinType.JOIN_LEFT_OUTER)) {
+ joinType = Join.JoinType.LEFT_OUTER_JOIN;
+ } else if(join.getJoinType().equals(JoinType.JOIN_RIGHT_OUTER)) {
+ joinType = Join.JoinType.RIGHT_OUTER_JOIN;
+ } else if(join.getJoinType().equals(JoinType.JOIN_FULL_OUTER)) {
+ joinType = Join.JoinType.FULL_OUTER_JOIN;
+ } else if(join.getJoinType().equals(JoinType.JOIN_CROSS)) {
+ joinType = Join.JoinType.CROSS_JOIN;
+ }
+
+ return new Join(translate(join.getLeftClause()),
+ translate(join.getRightClause()),
+ joinType,
+ translate(crit));
+ }
+
+ TableReference translate(SubqueryFromClause clause) {
+ return new DerivedTable(translate((QueryCommand)clause.getCommand()), clause.getOutputName());
+ }
+
+ NamedTable translate(UnaryFromClause clause) {
+ return translate(clause.getGroup());
+ }
+
+ public Condition translate(Criteria criteria) {
+ if (criteria == null) return null;
+ if (criteria instanceof CompareCriteria) {
+ return translate((CompareCriteria)criteria);
+ } else if (criteria instanceof CompoundCriteria) {
+ return translate((CompoundCriteria)criteria);
+ } else if (criteria instanceof ExistsCriteria) {
+ return translate((ExistsCriteria)criteria);
+ } else if (criteria instanceof IsNullCriteria) {
+ return translate((IsNullCriteria)criteria);
+ }else if (criteria instanceof MatchCriteria) {
+ return translate((MatchCriteria)criteria);
+ } else if (criteria instanceof NotCriteria) {
+ return translate((NotCriteria)criteria);
+ } else if (criteria instanceof SetCriteria) {
+ return translate((SetCriteria)criteria);
+ } else if (criteria instanceof SubqueryCompareCriteria) {
+ return translate((SubqueryCompareCriteria)criteria);
+ } else if (criteria instanceof SubquerySetCriteria) {
+ return translate((SubquerySetCriteria)criteria);
+ }
+ throw new AssertionError();
+ }
+
+ org.teiid.language.Comparison translate(CompareCriteria criteria) {
+ Operator operator = Operator.EQ;
+ switch(criteria.getOperator()) {
+ case CompareCriteria.EQ:
+ operator = Operator.EQ;
+ break;
+ case CompareCriteria.NE:
+ operator = Operator.NE;
+ break;
+ case CompareCriteria.LT:
+ operator = Operator.LT;
+ break;
+ case CompareCriteria.LE:
+ operator = Operator.LE;
+ break;
+ case CompareCriteria.GT:
+ operator = Operator.GT;
+ break;
+ case CompareCriteria.GE:
+ operator = Operator.GE;
+ break;
+
+ }
+
+ return new org.teiid.language.Comparison(translate(criteria.getLeftExpression()),
+ translate(criteria.getRightExpression()), operator);
+ }
+
+ AndOr translate(CompoundCriteria criteria) {
+ List nestedCriteria = criteria.getCriteria();
+ int size = nestedCriteria.size();
+ AndOr.Operator op = criteria.getOperator() == CompoundCriteria.AND?AndOr.Operator.AND:AndOr.Operator.OR;
+ AndOr result = new AndOr(translate((Criteria)nestedCriteria.get(size - 2)), translate((Criteria)nestedCriteria.get(size - 1)), op);
+ for (int i = nestedCriteria.size() - 3; i >= 0; i--) {
+ result = new AndOr(translate((Criteria)nestedCriteria.get(i)), result, op);
+ }
+ return result;
+ }
+
+ Condition translate(ExistsCriteria criteria) {
+ Exists exists = new Exists(translate(criteria.getCommand()));
+ if (criteria.isNegated()) {
+ return new Not(exists);
+ }
+ return exists;
+ }
+
+ IsNull translate(IsNullCriteria criteria) {
+ return new IsNull(translate(criteria.getExpression()), criteria.isNegated());
+ }
+
+ Like translate(MatchCriteria criteria) {
+ Character escapeChar = null;
+ if(criteria.getEscapeChar() != MatchCriteria.NULL_ESCAPE_CHAR) {
+ escapeChar = new Character(criteria.getEscapeChar());
+ }
+ return new Like(translate(criteria.getLeftExpression()),
+ translate(criteria.getRightExpression()),
+ escapeChar,
+ criteria.isNegated());
+ }
+
+ In translate(SetCriteria criteria) {
+ Collection expressions = criteria.getValues();
+ List translatedExpressions = new ArrayList();
+ for (Iterator i = expressions.iterator(); i.hasNext();) {
+ translatedExpressions.add(translate((Expression)i.next()));
+ }
+ return new In(translate(criteria.getExpression()),
+ translatedExpressions,
+ criteria.isNegated());
+ }
+
+ SubqueryComparison translate(SubqueryCompareCriteria criteria) {
+ Quantifier quantifier = Quantifier.ALL;
+ switch(criteria.getPredicateQuantifier()) {
+ case SubqueryCompareCriteria.ALL:
+ quantifier = Quantifier.ALL;
+ break;
+ case SubqueryCompareCriteria.ANY:
+ quantifier = Quantifier.SOME;
+ break;
+ case SubqueryCompareCriteria.SOME:
+ quantifier = Quantifier.SOME;
+ break;
+ }
+
+ Operator operator = Operator.EQ;
+ switch(criteria.getOperator()) {
+ case SubqueryCompareCriteria.EQ:
+ operator = Operator.EQ;
+ break;
+ case SubqueryCompareCriteria.NE:
+ operator = Operator.NE;
+ break;
+ case SubqueryCompareCriteria.LT:
+ operator = Operator.LT;
+ break;
+ case SubqueryCompareCriteria.LE:
+ operator = Operator.LE;
+ break;
+ case SubqueryCompareCriteria.GT:
+ operator = Operator.GT;
+ break;
+ case SubqueryCompareCriteria.GE:
+ operator = Operator.GE;
+ break;
+ }
+
+ return new SubqueryComparison(translate(criteria.getLeftExpression()),
+ operator,
+ quantifier,
+ translate((QueryCommand)criteria.getCommand()));
+ }
+
+ SubqueryIn translate(SubquerySetCriteria criteria) {
+ return new SubqueryIn(translate(criteria.getExpression()),
+ criteria.isNegated(),
+ translate((QueryCommand)criteria.getCommand()));
+ }
+
+ Not translate(NotCriteria criteria) {
+ return new Not(translate(criteria.getCriteria()));
+ }
+
+ public org.teiid.language.GroupBy translate(GroupBy groupBy) {
+ if(groupBy == null){
+ return null;
+ }
+ List items = groupBy.getSymbols();
+ List<org.teiid.language.Expression> translatedItems = new ArrayList<org.teiid.language.Expression>();
+ for (Iterator i = items.iterator(); i.hasNext();) {
+ translatedItems.add(translate((Expression)i.next()));
+ }
+ return new org.teiid.language.GroupBy(translatedItems);
+ }
+
+ public org.teiid.language.OrderBy translate(OrderBy orderBy, boolean set) {
+ if(orderBy == null){
+ return null;
+ }
+ List<OrderByItem> items = orderBy.getOrderByItems();
+ List<SortSpecification> translatedItems = new ArrayList<SortSpecification>();
+ for (int i = 0; i < items.size(); i++) {
+ SingleElementSymbol symbol = items.get(i).getSymbol();
+ Ordering direction = items.get(i).isAscending() ? Ordering.ASC: Ordering.DESC;
+
+ SortSpecification orderByItem = null;
+ if(items.get(i).isUnrelated() || (!set && symbol instanceof ElementSymbol)){
+ orderByItem = new SortSpecification(direction, translate(symbol));
+ } else {
+ orderByItem = new SortSpecification(direction, new ColumnReference(null, symbol.getOutputName(), null, symbol.getType()));
+ }
+ orderByItem.setNullOrdering(items.get(i).getNullOrdering());
+ translatedItems.add(orderByItem);
+ }
+ return new org.teiid.language.OrderBy(translatedItems);
+ }
+
+
+ /* Expressions */
+ public org.teiid.language.Expression translate(Expression expr) {
+ if (expr == null) return null;
+ if (expr instanceof Constant) {
+ return translate((Constant)expr);
+ } else if (expr instanceof Function) {
+ return translate((Function)expr);
+ } else if (expr instanceof ScalarSubquery) {
+ 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 Criteria) {
+ return translate((Criteria)expr);
+ }
+ throw new AssertionError();
+ }
+
+ Literal translate(Constant constant) {
+ Literal result = new Literal(constant.getValue(), constant.getType());
+ result.setBindValue(constant.isMultiValued());
+ result.setMultiValued(constant.isMultiValued());
+ result.setBindEligible(constant.isBindEligible());
+ return result;
+ }
+
+ org.teiid.language.Function translate(Function function) {
+ Expression [] args = function.getArgs();
+ List<org.teiid.language.Expression> params = new ArrayList<org.teiid.language.Expression>(args.length);
+ for (int i = 0; i < args.length; i++) {
+ params.add(translate(args[i]));
+ }
+ 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);
+ }
+
+ //if there is any ambiguity in the function name it will be up to the translator logic to check the
+ //metadata
+ org.teiid.language.Function result = new org.teiid.language.Function(name, params, function.getType());
+ if (function.getFunctionDescriptor() != null) {
+ result.setMetadataObject(function.getFunctionDescriptor().getMethod());
+ }
+ return result;
+ }
+
+ SearchedCase translate(SearchedCaseExpression expr) {
+ ArrayList<SearchedWhenClause> whens = new ArrayList<SearchedWhenClause>();
+ for (int i = 0; i < expr.getWhenCount(); i++) {
+ whens.add(new SearchedWhenClause(translate(expr.getWhenCriteria(i)), translate(expr.getThenExpression(i))));
+ }
+ return new SearchedCase(whens,
+ translate(expr.getElseExpression()),
+ expr.getType());
+ }
+
+
+ org.teiid.language.Expression translate(ScalarSubquery ss) {
+ 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());
+ if (element.getTable().getMetadataObject() == null) {
+ return element;
+ }
+
+ Object mid = symbol.getMetadataID();
+
+ element.setMetadataObject(metadataFactory.getElement(mid));
+ return element;
+ }
+
+ AggregateFunction translate(AggregateSymbol symbol) {
+ return new AggregateFunction(symbol.getAggregateFunction().name(),
+ symbol.isDistinct(),
+ translate(symbol.getExpression()),
+ symbol.getType());
+ }
+
+ org.teiid.language.Expression translate(ExpressionSymbol symbol) {
+ return translate(symbol.getExpression());
+ }
+
+
+ /* Insert */
+ org.teiid.language.Insert translate(Insert insert) {
+ List<ElementSymbol> elements = insert.getVariables();
+ List<ColumnReference> translatedElements = new ArrayList<ColumnReference>();
+
+ for (ElementSymbol elementSymbol : elements) {
+ translatedElements.add(translate(elementSymbol));
+ }
+
+ InsertValueSource valueSource = null;
+ if (insert.getQueryExpression() != null) {
+ valueSource = translate(insert.getQueryExpression());
+ } else if (insert.getTupleSource() != null) {
+ final TupleSource ts = insert.getTupleSource();
+ valueSource = new IteratorValueSource<List<?>>(new Iterator<List<?>>() {
+
+ List<?> next;
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public List<?> next() {
+ if (hasNext()) {
+ List<?> result = next;
+ next = null;
+ return result;
+ }
+ throw new NoSuchElementException();
+ }
+
+ @Override
+ public boolean hasNext() {
+ if (next != null) {
+ return true;
+ }
+ try {
+ next = ts.nextTuple();
+ } catch (TeiidException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ return next != null;
+ }
+ }, elements.size());
+ } else {
+ // This is for the simple one row insert.
+ List values = insert.getValues();
+ List<org.teiid.language.Expression> translatedValues = new ArrayList<org.teiid.language.Expression>();
+ for (Iterator i = values.iterator(); i.hasNext();) {
+ translatedValues.add(translate((Expression)i.next()));
+ }
+ valueSource = new ExpressionValueSource(translatedValues);
+ }
+
+ return new org.teiid.language.Insert(translate(insert.getGroup()),
+ translatedElements,
+ valueSource);
+ }
+
+ /* Update */
+ org.teiid.language.Update translate(Update update) {
+ return new org.teiid.language.Update(translate(update.getGroup()),
+ translate(update.getChangeList()),
+ translate(update.getCriteria()));
+ }
+
+ List<org.teiid.language.SetClause> translate(SetClauseList setClauseList) {
+ List<org.teiid.language.SetClause> clauses = new ArrayList<org.teiid.language.SetClause>(setClauseList.getClauses().size());
+ for (SetClause setClause : setClauseList.getClauses()) {
+ clauses.add(translate(setClause));
+ }
+ return clauses;
+ }
+
+ org.teiid.language.SetClause translate(SetClause setClause) {
+ return new org.teiid.language.SetClause(translate(setClause.getSymbol()), translate(setClause.getValue()));
+ }
+
+ /* Delete */
+ org.teiid.language.Delete translate(Delete delete) {
+ org.teiid.language.Delete deleteImpl = new org.teiid.language.Delete(translate(delete.getGroup()),
+ translate(delete.getCriteria()));
+ return deleteImpl;
+ }
+
+ /* Execute */
+ Call translate(StoredProcedure sp) {
+ Procedure proc = null;
+ if(sp.getProcedureID() != null) {
+ try {
+ proc = this.metadataFactory.getProcedure(sp.getGroup().getName());
+ } catch (TranslatorException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+ Class<?> returnType = null;
+ List<Argument> translatedParameters = new ArrayList<Argument>();
+ for (SPParameter param : sp.getParameters()) {
+ Direction direction = Direction.IN;
+ switch(param.getParameterType()) {
+ case ParameterInfo.IN:
+ direction = Direction.IN;
+ break;
+ case ParameterInfo.INOUT:
+ direction = Direction.INOUT;
+ break;
+ case ParameterInfo.OUT:
+ direction = Direction.OUT;
+ break;
+ case ParameterInfo.RESULT_SET:
+ continue; //already part of the metadata
+ case ParameterInfo.RETURN_VALUE:
+ returnType = param.getClassType();
+ continue;
+ }
+
+ ProcedureParameter metadataParam = metadataFactory.getParameter(param);
+ //we can assume for now that all arguments will be literals, which may be multivalued
+ Literal value = null;
+ if (direction != Direction.OUT) {
+ value = (Literal)translate(param.getExpression());
+ }
+ Argument arg = new Argument(direction, value, param.getClassType(), metadataParam);
+ translatedParameters.add(arg);
+ }
+
+ Call call = new Call(removeSchemaName(sp.getProcedureName()), translatedParameters, proc);
+ call.setReturnType(returnType);
+ return call;
+ }
+
+ public NamedTable translate(GroupSymbol symbol) {
+ String alias = null;
+ String fullGroup = symbol.getOutputName();
+ if(symbol.getOutputDefinition() != null) {
+ alias = symbol.getOutputName();
+ fullGroup = symbol.getOutputDefinition();
+ }
+ fullGroup = removeSchemaName(fullGroup);
+ NamedTable group = new NamedTable(fullGroup, alias, null);
+ try {
+ group.setMetadataObject(metadataFactory.getGroup(symbol.getMetadataID()));
+ } catch (QueryMetadataException e) {
+ throw new TeiidRuntimeException(e);
+ } catch (TeiidComponentException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ return group;
+ }
+
+ private String removeSchemaName(String fullGroup) {
+ //remove the model name
+ int index = fullGroup.indexOf(ElementSymbol.SEPARATOR);
+ if (index > 0) {
+ fullGroup = fullGroup.substring(index + 1);
+ }
+ return fullGroup;
+ }
+
+ /* Batched Updates */
+ BatchedUpdates translate(BatchedUpdateCommand command) {
+ List 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()));
+ }
+ return new BatchedUpdates(translatedUpdates);
+ }
+
+ org.teiid.language.Limit translate(Limit limit) {
+ if (limit == null) {
+ return null;
+ }
+ int rowOffset = 0;
+ if (limit.getOffset() != null) {
+ Literal c1 = (Literal)translate(limit.getOffset());
+ rowOffset = ((Integer)c1.getValue()).intValue();
+ }
+ Literal c2 = (Literal)translate(limit.getRowLimit());
+ int rowLimit = ((Integer)c2.getValue()).intValue();
+ return new org.teiid.language.Limit(rowOffset, rowLimit);
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/RuntimeMetadataImpl.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/RuntimeMetadataImpl.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/RuntimeMetadataImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,148 +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.datamgr;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.util.ArgCheck;
-import org.teiid.metadata.Column;
-import org.teiid.metadata.Procedure;
-import org.teiid.metadata.ProcedureParameter;
-import org.teiid.metadata.RuntimeMetadata;
-import org.teiid.metadata.Table;
-import org.teiid.query.metadata.*;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.translator.TranslatorException;
-
-
-/**
- */
-public class RuntimeMetadataImpl implements RuntimeMetadata {
- private QueryMetadataInterface metadata;
-
- public RuntimeMetadataImpl(QueryMetadataInterface metadata){
- ArgCheck.isNotNull(metadata);
- this.metadata = metadata;
- }
-
- @Override
- public Column getColumn(String fullName) throws TranslatorException {
- try {
- Object metadataId = metadata.getElementID(fullName);
- return getElement(metadataId);
- } catch (QueryMetadataException e) {
- throw new TranslatorException(e);
- } catch (TeiidComponentException e) {
- throw new TranslatorException(e);
- }
- }
-
- public Column getElement(Object elementId) {
- if (elementId instanceof Column) {
- return (Column)elementId;
- }
- return null;
- }
-
- @Override
- public Table getTable(String fullName) throws TranslatorException {
- try {
- Object groupId = metadata.getGroupID(fullName);
- return getGroup(groupId);
- } catch (QueryMetadataException e) {
- throw new TranslatorException(e);
- } catch (TeiidComponentException e) {
- throw new TranslatorException(e);
- }
- }
-
- public Table getGroup(Object groupId) throws QueryMetadataException, TeiidComponentException {
- if (!metadata.isVirtualGroup(groupId) && groupId instanceof Table) {
- return (Table)groupId;
- }
- return null;
- }
-
- @Override
- public Procedure getProcedure(String fullName) throws TranslatorException {
- try {
- StoredProcedureInfo sp = metadata.getStoredProcedureInfoForProcedure(fullName);
- return getProcedure(sp);
- } catch (QueryMetadataException e) {
- throw new TranslatorException(e);
- } catch (TeiidComponentException e) {
- throw new TranslatorException(e);
- }
- }
-
- public Procedure getProcedure(StoredProcedureInfo sp) {
- if (sp.getProcedureID() instanceof Procedure) {
- return (Procedure)sp.getProcedureID();
- }
- return null;
- }
-
- public ProcedureParameter getParameter(SPParameter param) {
- if (param.getMetadataID() instanceof ProcedureParameter) {
- return (ProcedureParameter)param.getMetadataID();
- }
- return null;
- }
-
- public byte[] getBinaryVDBResource(String resourcePath) throws TranslatorException {
- try {
- return metadata.getBinaryVDBResource(resourcePath);
- } catch (QueryMetadataException e) {
- throw new TranslatorException(e);
- } catch (TeiidComponentException e) {
- throw new TranslatorException(e);
- }
- }
-
- public String getCharacterVDBResource(String resourcePath) throws TranslatorException {
- try {
- return metadata.getCharacterVDBResource(resourcePath);
- } catch (QueryMetadataException e) {
- throw new TranslatorException(e);
- } catch (TeiidComponentException e) {
- throw new TranslatorException(e);
- }
- }
-
- public String[] getVDBResourcePaths() throws TranslatorException {
- try {
- return metadata.getVDBResourcePaths();
- } catch (QueryMetadataException e) {
- throw new TranslatorException(e);
- } catch (TeiidComponentException e) {
- throw new TranslatorException(e);
- }
- }
-
- public QueryMetadataInterface getMetadata() {
- return metadata;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/RuntimeMetadataImpl.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/RuntimeMetadataImpl.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/RuntimeMetadataImpl.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/datamgr/RuntimeMetadataImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,148 @@
+/*
+ * 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.datamgr;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.util.ArgCheck;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.ProcedureParameter;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.metadata.Table;
+import org.teiid.query.metadata.*;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.translator.TranslatorException;
+
+
+/**
+ */
+public class RuntimeMetadataImpl implements RuntimeMetadata {
+ private QueryMetadataInterface metadata;
+
+ public RuntimeMetadataImpl(QueryMetadataInterface metadata){
+ ArgCheck.isNotNull(metadata);
+ this.metadata = metadata;
+ }
+
+ @Override
+ public Column getColumn(String fullName) throws TranslatorException {
+ try {
+ Object metadataId = metadata.getElementID(fullName);
+ return getElement(metadataId);
+ } catch (QueryMetadataException e) {
+ throw new TranslatorException(e);
+ } catch (TeiidComponentException e) {
+ throw new TranslatorException(e);
+ }
+ }
+
+ public Column getElement(Object elementId) {
+ if (elementId instanceof Column) {
+ return (Column)elementId;
+ }
+ return null;
+ }
+
+ @Override
+ public Table getTable(String fullName) throws TranslatorException {
+ try {
+ Object groupId = metadata.getGroupID(fullName);
+ return getGroup(groupId);
+ } catch (QueryMetadataException e) {
+ throw new TranslatorException(e);
+ } catch (TeiidComponentException e) {
+ throw new TranslatorException(e);
+ }
+ }
+
+ public Table getGroup(Object groupId) throws QueryMetadataException, TeiidComponentException {
+ if (groupId instanceof Table && !metadata.isVirtualGroup(groupId)) {
+ return (Table)groupId;
+ }
+ return null;
+ }
+
+ @Override
+ public Procedure getProcedure(String fullName) throws TranslatorException {
+ try {
+ StoredProcedureInfo sp = metadata.getStoredProcedureInfoForProcedure(fullName);
+ return getProcedure(sp);
+ } catch (QueryMetadataException e) {
+ throw new TranslatorException(e);
+ } catch (TeiidComponentException e) {
+ throw new TranslatorException(e);
+ }
+ }
+
+ public Procedure getProcedure(StoredProcedureInfo sp) {
+ if (sp.getProcedureID() instanceof Procedure) {
+ return (Procedure)sp.getProcedureID();
+ }
+ return null;
+ }
+
+ public ProcedureParameter getParameter(SPParameter param) {
+ if (param.getMetadataID() instanceof ProcedureParameter) {
+ return (ProcedureParameter)param.getMetadataID();
+ }
+ return null;
+ }
+
+ public byte[] getBinaryVDBResource(String resourcePath) throws TranslatorException {
+ try {
+ return metadata.getBinaryVDBResource(resourcePath);
+ } catch (QueryMetadataException e) {
+ throw new TranslatorException(e);
+ } catch (TeiidComponentException e) {
+ throw new TranslatorException(e);
+ }
+ }
+
+ public String getCharacterVDBResource(String resourcePath) throws TranslatorException {
+ try {
+ return metadata.getCharacterVDBResource(resourcePath);
+ } catch (QueryMetadataException e) {
+ throw new TranslatorException(e);
+ } catch (TeiidComponentException e) {
+ throw new TranslatorException(e);
+ }
+ }
+
+ public String[] getVDBResourcePaths() throws TranslatorException {
+ try {
+ return metadata.getVDBResourcePaths();
+ } catch (QueryMetadataException e) {
+ throw new TranslatorException(e);
+ } catch (TeiidComponentException e) {
+ throw new TranslatorException(e);
+ }
+ }
+
+ public QueryMetadataInterface getMetadata() {
+ return metadata;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,208 +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 javax.resource.spi.work.Work;
-import javax.resource.spi.work.WorkEvent;
-import javax.resource.spi.work.WorkListener;
-
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.logging.LogManager;
-
-
-
-/**
- * Represents a task that performs work that may take more than one processing pass to complete.
- * During processing the WorkItem may receive events asynchronously through the moreWork method.
- */
-public abstract class AbstractWorkItem implements Work, WorkListener {
-
- enum ThreadState {
- MORE_WORK, WORKING, IDLE, DONE
- }
-
- 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());
- }
-
- synchronized ThreadState getThreadState() {
- return this.threadState;
- }
-
- public boolean isProcessing() {
- return isProcessing;
- }
-
- private synchronized void startProcessing() {
- isProcessing = true;
- logTrace("start processing"); //$NON-NLS-1$
- if (this.threadState != ThreadState.MORE_WORK) {
- throw new IllegalStateException("Must be in MORE_WORK"); //$NON-NLS-1$
- }
- this.threadState = ThreadState.WORKING;
- }
-
- /**
- * @return true if processing should be continued
- */
- final private synchronized boolean endProcessing() {
- isProcessing = false;
- logTrace("end processing"); //$NON-NLS-1$
- switch (this.threadState) {
- case WORKING:
- if (isDoneProcessing()) {
- logTrace("done processing"); //$NON-NLS-1$
- this.threadState = ThreadState.DONE;
- } else {
- this.threadState = ThreadState.IDLE;
- return pauseProcessing();
- }
- break;
- case MORE_WORK:
- if (isDoneProcessing()) {
- logTrace("done processing - ignoring more"); //$NON-NLS-1$
- this.threadState = ThreadState.DONE;
- } else if (!this.useCallingThread) {
- resumeProcessing();
- }
- break;
- default:
- throw new IllegalStateException("Should not END on " + this.threadState); //$NON-NLS-1$
- }
- return useCallingThread;
- }
-
- protected boolean isIdle() {
- return this.threadState == ThreadState.IDLE;
- }
-
- public void moreWork() {
- moreWork(true);
- }
-
- final protected synchronized void moreWork(boolean ignoreDone) {
- logTrace("more work"); //$NON-NLS-1$
- switch (this.threadState) {
- case WORKING:
- this.threadState = ThreadState.MORE_WORK;
- break;
- case MORE_WORK:
- 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();
- }
- break;
- default:
- if (!ignoreDone) {
- throw new IllegalStateException("More work is not valid once DONE"); //$NON-NLS-1$
- }
- LogManager.logDetail(org.teiid.logging.LogConstants.CTX_DQP, new Object[] {this, "ignoring more work, since the work item is done"}); //$NON-NLS-1$
- }
- }
-
- private void logTrace(String msg) {
- LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, new Object[] {this, msg, this.threadState});
- }
-
- 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;
- }
-
- /**
- * 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();
-
- protected abstract boolean isDoneProcessing();
-
- public abstract String toString();
-
- @Override
- public void release() {
-
- }
-
- @Override
- public void workAccepted(WorkEvent arg0) {
- }
-
- @Override
- public void workCompleted(WorkEvent arg0) {
- }
-
- @Override
- public void workRejected(WorkEvent event) {
- }
-
- @Override
- public void workStarted(WorkEvent arg0) {
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,208 @@
+/*
+ * 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 javax.resource.spi.work.Work;
+import javax.resource.spi.work.WorkEvent;
+import javax.resource.spi.work.WorkListener;
+
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.logging.LogManager;
+
+
+
+/**
+ * Represents a task that performs work that may take more than one processing pass to complete.
+ * During processing the WorkItem may receive events asynchronously through the moreWork method.
+ */
+public abstract class AbstractWorkItem implements Work, WorkListener {
+
+ enum ThreadState {
+ MORE_WORK, WORKING, IDLE, DONE
+ }
+
+ private ThreadState threadState = ThreadState.MORE_WORK;
+ private volatile boolean isProcessing;
+ private Thread callingThread;
+
+ public AbstractWorkItem(Thread callingThread) {
+ this.callingThread = callingThread;
+ }
+
+ public void run() {
+ do {
+ startProcessing();
+ try {
+ process();
+ } finally {
+ if (!endProcessing()) {
+ break;
+ }
+ }
+ } while (!isDoneProcessing());
+ }
+
+ synchronized ThreadState getThreadState() {
+ return this.threadState;
+ }
+
+ public boolean isProcessing() {
+ return isProcessing;
+ }
+
+ private synchronized void startProcessing() {
+ isProcessing = true;
+ logTrace("start processing"); //$NON-NLS-1$
+ if (this.threadState != ThreadState.MORE_WORK) {
+ throw new IllegalStateException("Must be in MORE_WORK"); //$NON-NLS-1$
+ }
+ this.threadState = ThreadState.WORKING;
+ }
+
+ /**
+ * @return true if processing should be continued
+ */
+ final private synchronized boolean endProcessing() {
+ isProcessing = false;
+ logTrace("end processing"); //$NON-NLS-1$
+ switch (this.threadState) {
+ case WORKING:
+ if (isDoneProcessing()) {
+ logTrace("done processing"); //$NON-NLS-1$
+ this.threadState = ThreadState.DONE;
+ } else {
+ this.threadState = ThreadState.IDLE;
+ return pauseProcessing();
+ }
+ break;
+ case MORE_WORK:
+ if (isDoneProcessing()) {
+ logTrace("done processing - ignoring more"); //$NON-NLS-1$
+ this.threadState = ThreadState.DONE;
+ } else if (this.callingThread == null) {
+ resumeProcessing();
+ }
+ break;
+ default:
+ throw new IllegalStateException("Should not END on " + this.threadState); //$NON-NLS-1$
+ }
+ return this.callingThread != null;
+ }
+
+ protected boolean isIdle() {
+ return this.threadState == ThreadState.IDLE;
+ }
+
+ public void moreWork() {
+ moreWork(true);
+ }
+
+ final protected synchronized void moreWork(boolean ignoreDone) {
+ logTrace("more work"); //$NON-NLS-1$
+ switch (this.threadState) {
+ case WORKING:
+ this.threadState = ThreadState.MORE_WORK;
+ break;
+ case MORE_WORK:
+ break;
+ case IDLE:
+ this.threadState = ThreadState.MORE_WORK;
+ if (this.callingThread != null) {
+ if (this.callingThread == Thread.currentThread()) {
+ run(); //restart with the calling thread
+ } else {
+ this.notifyAll(); //notify the waiting caller
+ }
+ } else {
+ resumeProcessing();
+ }
+ break;
+ default:
+ if (!ignoreDone) {
+ throw new IllegalStateException("More work is not valid once DONE"); //$NON-NLS-1$
+ }
+ LogManager.logDetail(org.teiid.logging.LogConstants.CTX_DQP, new Object[] {this, "ignoring more work, since the work item is done"}); //$NON-NLS-1$
+ }
+ }
+
+ private void logTrace(String msg) {
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, new Object[] {this, msg, this.threadState});
+ }
+
+ protected abstract void process();
+
+ protected boolean pauseProcessing() {
+ if (this.callingThread != null && !shouldPause()) {
+ return false;
+ }
+ while (this.callingThread != null && this.getThreadState() == ThreadState.IDLE) {
+ try {
+ this.wait(); //the lock should already be held
+ } catch (InterruptedException e) {
+ interrupted(e);
+ }
+ }
+ return this.callingThread != null;
+ }
+
+ /**
+ * 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();
+
+ protected abstract boolean isDoneProcessing();
+
+ public abstract String toString();
+
+ @Override
+ public void release() {
+
+ }
+
+ @Override
+ public void workAccepted(WorkEvent arg0) {
+ }
+
+ @Override
+ public void workCompleted(WorkEvent arg0) {
+ }
+
+ @Override
+ public void workRejected(WorkEvent event) {
+ }
+
+ @Override
+ public void workStarted(WorkEvent arg0) {
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,413 +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 java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.teiid.adminapi.DataPolicy;
-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;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.dqp.internal.process.multisource.MultiSourceElement;
-import org.teiid.logging.AuditMessage;
-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.FunctionLibrary;
-import org.teiid.query.metadata.TempMetadataID;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.lang.AlterProcedure;
-import org.teiid.query.sql.lang.AlterTrigger;
-import org.teiid.query.sql.lang.AlterView;
-import org.teiid.query.sql.lang.Create;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.Drop;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.Into;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.sql.symbol.GroupSymbol;
-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.validator.AbstractValidationVisitor;
-
-
-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;
-
- public AuthorizationValidationVisitor(HashMap<String, DataPolicy> policies, String user) {
- this.allowedPolicies = policies;
- this.userName = user;
- }
-
- 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);
- }
-
- @Override
- public void visit(AlterProcedure obj) {
- validateEntitlements(Arrays.asList(obj.getTarget()), DataPolicy.PermissionType.ALTER, Context.ALTER);
- }
-
- @Override
- public void visit(AlterTrigger obj) {
- validateEntitlements(Arrays.asList(obj.getTarget()), DataPolicy.PermissionType.ALTER, obj.isCreate()?Context.CREATE:Context.ALTER);
- }
-
- @Override
- public void visit(AlterView obj) {
- validateEntitlements(Arrays.asList(obj.getTarget()), DataPolicy.PermissionType.ALTER, Context.ALTER);
- }
-
- private void validateTemp(Set<String> resources,
- Collection<GroupSymbol> symbols, Context context) {
- 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;
- }
- }
-
- 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);
- }
- }
-
- 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$
- 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);
- }
-
- public void visit(Delete obj) {
- validateEntitlements(obj);
- }
-
- public void visit(Insert obj) {
- validateEntitlements(obj);
- }
-
- public void visit(Query obj) {
- validateEntitlements(obj);
- }
-
- public void visit(Update obj) {
- validateEntitlements(obj);
- }
-
- public void visit(StoredProcedure obj) {
- validateEntitlements(obj);
- }
-
- public void visit(Function obj) {
- if (FunctionLibrary.LOOKUP.equalsIgnoreCase(obj.getName())) {
- try {
- ResolverUtil.ResolvedLookup lookup = ResolverUtil.resolveLookup(obj, this.getMetadata());
- List<Symbol> symbols = new LinkedList<Symbol>();
- symbols.add(lookup.getGroup());
- symbols.add(lookup.getKeyElement());
- symbols.add(lookup.getReturnElement());
- validateEntitlements(symbols, DataPolicy.PermissionType.READ, Context.QUERY);
- } catch (TeiidComponentException e) {
- handleException(e, obj);
- } catch (TeiidProcessingException e) {
- handleException(e, obj);
- }
- } else if (!allowFunctionCallsByDefault) {
- String schema = obj.getFunctionDescriptor().getSchema();
- if (schema != null && !isSystemSchema(schema)) {
- Map<String, Function> map = new HashMap<String, Function>();
- map.put(schema + '.' + obj.getFunctionDescriptor().getName(), obj);
- validateEntitlements(PermissionType.EXECUTE, Context.FUNCTION, map);
- }
- }
- }
-
- // ######################### Validation methods #########################
-
- /**
- * Validate insert entitlements
- */
- protected void validateEntitlements(Insert obj) {
- validateEntitlements(
- obj.getVariables(),
- DataPolicy.PermissionType.CREATE,
- Context.INSERT);
- }
-
- /**
- * Validate update entitlements
- */
- protected void validateEntitlements(Update obj) {
- // Check that all elements used in criteria have read permission
- HashSet<ElementSymbol> elements = new HashSet<ElementSymbol>();
- ElementCollectorVisitor.getElements(obj.getChangeList().getClauseMap().values(), elements);
- if (obj.getCriteria() != null) {
- ElementCollectorVisitor.getElements(obj.getCriteria(), elements);
- }
- validateEntitlements(
- elements,
- DataPolicy.PermissionType.READ,
- Context.UPDATE);
-
- // 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);
- }
-
- /**
- * Validate delete entitlements
- */
- protected void validateEntitlements(Delete obj) {
- // Check that all elements used in criteria have read permission
- if (obj.getCriteria() != null) {
- validateEntitlements(
- ElementCollectorVisitor.getElements(obj.getCriteria(), true),
- DataPolicy.PermissionType.READ,
- Context.DELETE);
- }
-
- // Check that all elements of group being deleted have delete permission
- validateEntitlements(Arrays.asList(obj.getGroup()), DataPolicy.PermissionType.DELETE, Context.DELETE);
- }
-
- /**
- * Validate query entitlements
- */
- protected void validateEntitlements(Query obj) {
- // If query contains SELECT INTO, validate INTO portion
- Into intoObj = obj.getInto();
- if ( intoObj != null ) {
- GroupSymbol intoGroup = intoObj.getGroup();
- List<ElementSymbol> intoElements = null;
- try {
- intoElements = ResolverUtil.resolveElementsInGroup(intoGroup, getMetadata());
- } catch (QueryMetadataException err) {
- handleException(err, intoGroup);
- } catch (TeiidComponentException err) {
- handleException(err, intoGroup);
- }
- validateEntitlements(intoElements,
- DataPolicy.PermissionType.CREATE,
- Context.INSERT);
- }
-
- // Validate this query's entitlements
- Collection entitledObjects = GroupCollectorVisitor.getGroups(obj, true);
- if (!isXMLCommand(obj)) {
- entitledObjects.addAll(ElementCollectorVisitor.getElements(obj, true));
- }
-
- if(entitledObjects.size() == 0) {
- return;
- }
-
- validateEntitlements(entitledObjects, DataPolicy.PermissionType.READ, Context.QUERY);
- }
-
- /**
- * Validate query entitlements
- */
- protected void validateEntitlements(StoredProcedure obj) {
- validateEntitlements(Arrays.asList(obj.getGroup()), DataPolicy.PermissionType.EXECUTE, Context.STORED_PROCEDURE);
- }
-
- /**
- * Check that the user is entitled to access all data elements in the command.
- *
- * @param symbols The collection of <code>Symbol</code>s affected by these actions.
- * @param actionCode The actions to validate for
- * @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>();
- for (LanguageObject symbol : symbols) {
- try {
- String fullName = null;
- Object metadataID = null;
- if(symbol instanceof ElementSymbol) {
- metadataID = ((ElementSymbol)symbol).getMetadataID();
- if (metadataID instanceof MultiSourceElement || metadataID instanceof TempMetadataID) {
- continue;
- }
- } else if(symbol instanceof GroupSymbol) {
- GroupSymbol group = (GroupSymbol)symbol;
- metadataID = group.getMetadataID();
- if (metadataID instanceof TempMetadataID && !group.isProcedure()) {
- continue;
- }
- }
- fullName = getMetadata().getFullName(metadataID);
- Object modelId = getMetadata().getModelID(metadataID);
- String modelName = getMetadata().getFullName(modelId);
- if (isSystemSchema(modelName)) {
- continue;
- }
- nameToSymbolMap.put(fullName, symbol);
- } catch(QueryMetadataException e) {
- handleException(e);
- } catch(TeiidComponentException e) {
- handleException(e);
- }
- }
-
- validateEntitlements(actionCode, auditContext, nameToSymbolMap);
- }
-
- private boolean isSystemSchema(String modelName) {
- return CoreConstants.SYSTEM_MODEL.equalsIgnoreCase(modelName) || CoreConstants.ODBC_MODEL.equalsIgnoreCase(modelName);
- }
-
- private void validateEntitlements(DataPolicy.PermissionType actionCode,
- Context auditContext, Map<String, ? extends LanguageObject> nameToSymbolMap) {
- if (nameToSymbolMap.isEmpty()) {
- return;
- }
- Collection<String> inaccessibleResources = getInaccessibleResources(actionCode, nameToSymbolMap.keySet(), auditContext);
- if(inaccessibleResources.isEmpty()) {
- return;
- }
- List<LanguageObject> inaccessibleSymbols = new ArrayList<LanguageObject>(inaccessibleResources.size());
- for (String name : inaccessibleResources) {
- inaccessibleSymbols.add(nameToSymbolMap.get(name));
- }
-
- // CASE 2362 - do not include the names of the elements for which the user
- // is not authorized in the exception message
-
- handleValidationError(
- QueryPlugin.Util.getString("ERR.018.005.0095", userName, actionCode), //$NON-NLS-1$
- inaccessibleSymbols);
- }
-
- /**
- * Out of 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();
- }
- }
- }
-
- logResult(resources, context, results.isEmpty());
- return results;
- }
-
- private void logResult(Set<String> resources, Context context,
- 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$
- 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$
- LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
- }
- }
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,421 @@
+/*
+ * 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 java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.teiid.CommandContext;
+import org.teiid.adminapi.DataPolicy;
+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;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.dqp.internal.process.multisource.MultiSourceElement;
+import org.teiid.logging.AuditMessage;
+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.FunctionLibrary;
+import org.teiid.query.metadata.TempMetadataID;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.lang.AlterProcedure;
+import org.teiid.query.sql.lang.AlterTrigger;
+import org.teiid.query.sql.lang.AlterView;
+import org.teiid.query.sql.lang.Create;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.Drop;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.Into;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Function;
+import org.teiid.query.sql.symbol.GroupSymbol;
+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.validator.AbstractValidationVisitor;
+
+
+public class AuthorizationValidationVisitor extends AbstractValidationVisitor {
+
+ public enum Context {
+ CREATE,
+ DROP,
+ QUERY,
+ INSERT,
+ UPDATE,
+ DELETE,
+ FUNCTION,
+ ALTER,
+ STORED_PROCEDURE;
+ }
+
+ private HashMap<String, DataPolicy> allowedPolicies;
+ private boolean allowCreateTemporaryTablesDefault = true;
+ private boolean allowFunctionCallsByDefault = true;
+ private CommandContext commandContext;
+
+ public AuthorizationValidationVisitor(HashMap<String, DataPolicy> policies, CommandContext commandContext) {
+ this.allowedPolicies = policies;
+ 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);
+ }
+
+ @Override
+ public void visit(AlterProcedure obj) {
+ validateEntitlements(Arrays.asList(obj.getTarget()), DataPolicy.PermissionType.ALTER, Context.ALTER);
+ }
+
+ @Override
+ public void visit(AlterTrigger obj) {
+ validateEntitlements(Arrays.asList(obj.getTarget()), DataPolicy.PermissionType.ALTER, obj.isCreate()?Context.CREATE:Context.ALTER);
+ }
+
+ @Override
+ public void visit(AlterView obj) {
+ validateEntitlements(Arrays.asList(obj.getTarget()), DataPolicy.PermissionType.ALTER, Context.ALTER);
+ }
+
+ private void validateTemp(Set<String> resources,
+ Collection<GroupSymbol> symbols, Context context) {
+ 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;
+ }
+ }
+
+ logResult(resources, context, allowed);
+ if (!allowed) {
+ handleValidationError(
+ QueryPlugin.Util.getString("ERR.018.005.0095", commandContext.getUserName(), "CREATE_TEMPORARY_TABLES"), //$NON-NLS-1$ //$NON-NLS-2$
+ symbols);
+ }
+ }
+
+ 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", 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);
+ }
+
+ public void visit(Delete obj) {
+ validateEntitlements(obj);
+ }
+
+ public void visit(Insert obj) {
+ validateEntitlements(obj);
+ }
+
+ public void visit(Query obj) {
+ validateEntitlements(obj);
+ }
+
+ public void visit(Update obj) {
+ validateEntitlements(obj);
+ }
+
+ public void visit(StoredProcedure obj) {
+ validateEntitlements(obj);
+ }
+
+ public void visit(Function obj) {
+ if (FunctionLibrary.LOOKUP.equalsIgnoreCase(obj.getName())) {
+ try {
+ ResolverUtil.ResolvedLookup lookup = ResolverUtil.resolveLookup(obj, this.getMetadata());
+ List<Symbol> symbols = new LinkedList<Symbol>();
+ symbols.add(lookup.getGroup());
+ symbols.add(lookup.getKeyElement());
+ symbols.add(lookup.getReturnElement());
+ validateEntitlements(symbols, DataPolicy.PermissionType.READ, Context.QUERY);
+ } catch (TeiidComponentException e) {
+ handleException(e, obj);
+ } catch (TeiidProcessingException e) {
+ handleException(e, obj);
+ }
+ } else if (!allowFunctionCallsByDefault) {
+ String schema = obj.getFunctionDescriptor().getSchema();
+ if (schema != null && !isSystemSchema(schema)) {
+ Map<String, Function> map = new HashMap<String, Function>();
+ map.put(schema + '.' + obj.getFunctionDescriptor().getName(), obj);
+ validateEntitlements(PermissionType.EXECUTE, Context.FUNCTION, map);
+ }
+ }
+ }
+
+ // ######################### Validation methods #########################
+
+ /**
+ * Validate insert entitlements
+ */
+ protected void validateEntitlements(Insert obj) {
+ validateEntitlements(
+ obj.getVariables(),
+ DataPolicy.PermissionType.CREATE,
+ Context.INSERT);
+
+ if (obj.getGroup().isTempTable()) {
+ validateTemp(Collections.singleton(obj.getGroup().getNonCorrelationName()), Arrays.asList(obj.getGroup()), Context.INSERT);
+ }
+ }
+
+ /**
+ * Validate update entitlements
+ */
+ protected void validateEntitlements(Update obj) {
+ // Check that all elements used in criteria have read permission
+ HashSet<ElementSymbol> elements = new HashSet<ElementSymbol>();
+ ElementCollectorVisitor.getElements(obj.getChangeList().getClauseMap().values(), elements);
+ if (obj.getCriteria() != null) {
+ ElementCollectorVisitor.getElements(obj.getCriteria(), elements);
+ }
+ validateEntitlements(
+ elements,
+ DataPolicy.PermissionType.READ,
+ Context.UPDATE);
+
+ // 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);
+ }
+
+ /**
+ * Validate delete entitlements
+ */
+ protected void validateEntitlements(Delete obj) {
+ // Check that all elements used in criteria have read permission
+ if (obj.getCriteria() != null) {
+ validateEntitlements(
+ ElementCollectorVisitor.getElements(obj.getCriteria(), true),
+ DataPolicy.PermissionType.READ,
+ Context.DELETE);
+ }
+
+ // Check that all elements of group being deleted have delete permission
+ validateEntitlements(Arrays.asList(obj.getGroup()), DataPolicy.PermissionType.DELETE, Context.DELETE);
+ }
+
+ /**
+ * Validate query entitlements
+ */
+ protected void validateEntitlements(Query obj) {
+ // If query contains SELECT INTO, validate INTO portion
+ Into intoObj = obj.getInto();
+ if ( intoObj != null ) {
+ GroupSymbol intoGroup = intoObj.getGroup();
+ if (intoGroup.isTempTable()) {
+ validateTemp(Collections.singleton(intoGroup.getNonCorrelationName()), Arrays.asList(intoGroup), Context.INSERT);
+ }
+ List<ElementSymbol> intoElements = null;
+ try {
+ intoElements = ResolverUtil.resolveElementsInGroup(intoGroup, getMetadata());
+ } catch (QueryMetadataException err) {
+ handleException(err, intoGroup);
+ } catch (TeiidComponentException err) {
+ handleException(err, intoGroup);
+ }
+ validateEntitlements(intoElements,
+ DataPolicy.PermissionType.CREATE,
+ Context.INSERT);
+ }
+
+ // Validate this query's entitlements
+ Collection entitledObjects = GroupCollectorVisitor.getGroups(obj, true);
+ if (!isXMLCommand(obj)) {
+ entitledObjects.addAll(ElementCollectorVisitor.getElements(obj, true));
+ }
+
+ if(entitledObjects.size() == 0) {
+ return;
+ }
+
+ validateEntitlements(entitledObjects, DataPolicy.PermissionType.READ, Context.QUERY);
+ }
+
+ /**
+ * Validate query entitlements
+ */
+ protected void validateEntitlements(StoredProcedure obj) {
+ validateEntitlements(Arrays.asList(obj.getGroup()), DataPolicy.PermissionType.EXECUTE, Context.STORED_PROCEDURE);
+ }
+
+ /**
+ * Check that the user is entitled to access all data elements in the command.
+ *
+ * @param symbols The collection of <code>Symbol</code>s affected by these actions.
+ * @param actionCode The actions to validate for
+ * @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>();
+ for (LanguageObject symbol : symbols) {
+ try {
+ String fullName = null;
+ Object metadataID = null;
+ if(symbol instanceof ElementSymbol) {
+ metadataID = ((ElementSymbol)symbol).getMetadataID();
+ if (metadataID instanceof MultiSourceElement || metadataID instanceof TempMetadataID) {
+ continue;
+ }
+ } else if(symbol instanceof GroupSymbol) {
+ GroupSymbol group = (GroupSymbol)symbol;
+ metadataID = group.getMetadataID();
+ if (metadataID instanceof TempMetadataID && !group.isProcedure()) {
+ continue;
+ }
+ }
+ fullName = getMetadata().getFullName(metadataID);
+ Object modelId = getMetadata().getModelID(metadataID);
+ String modelName = getMetadata().getFullName(modelId);
+ if (isSystemSchema(modelName)) {
+ continue;
+ }
+ nameToSymbolMap.put(fullName, symbol);
+ } catch(QueryMetadataException e) {
+ handleException(e);
+ } catch(TeiidComponentException e) {
+ handleException(e);
+ }
+ }
+
+ validateEntitlements(actionCode, auditContext, nameToSymbolMap);
+ }
+
+ private boolean isSystemSchema(String modelName) {
+ return CoreConstants.SYSTEM_MODEL.equalsIgnoreCase(modelName) || CoreConstants.ODBC_MODEL.equalsIgnoreCase(modelName);
+ }
+
+ private void validateEntitlements(DataPolicy.PermissionType actionCode,
+ Context auditContext, Map<String, ? extends LanguageObject> nameToSymbolMap) {
+ if (nameToSymbolMap.isEmpty()) {
+ return;
+ }
+ Collection<String> inaccessibleResources = getInaccessibleResources(actionCode, nameToSymbolMap.keySet(), auditContext);
+ if(inaccessibleResources.isEmpty()) {
+ return;
+ }
+ List<LanguageObject> inaccessibleSymbols = new ArrayList<LanguageObject>(inaccessibleResources.size());
+ for (String name : inaccessibleResources) {
+ inaccessibleSymbols.add(nameToSymbolMap.get(name));
+ }
+
+ // CASE 2362 - do not include the names of the elements for which the user
+ // is not authorized in the exception message
+
+ handleValidationError(
+ 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.
+ */
+ 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();
+ }
+ }
+ }
+
+ logResult(resources, context, results.isEmpty());
+ return results;
+ }
+
+ private void logResult(Set<String> resources, Context context,
+ boolean granted) {
+ if (LogManager.isMessageToBeRecorded(LogConstants.CTX_AUDITLOGGING, MessageLevel.DETAIL)) {
+ if (granted) {
+ 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", resources.toArray(new String[resources.size()]), commandContext); //$NON-NLS-1$
+ LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
+ }
+ }
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidator.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidator.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,39 +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;
-
-/**
- * Defines a validator that checks for proper authorization.
- */
-public interface AuthorizationValidator {
-
- void validate(Command command, QueryMetadataInterface metadata,
- DQPWorkContext workContext) throws QueryValidatorException, TeiidComponentException;
-
- boolean hasRole(String roleName, DQPWorkContext workContext);
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidator.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidator.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidator.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.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;
+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, CommandContext commandContext) throws QueryValidatorException, TeiidComponentException;
+
+ boolean hasRole(String roleName, DQPWorkContext workContext);
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,253 +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.jboss.managed.api.annotation.ManagementProperty;
-import org.teiid.cache.CacheConfiguration;
-import org.teiid.client.RequestMessage;
-import org.teiid.core.util.ApplicationInfo;
-import org.teiid.metadata.MetadataRepository;
-
-
-public class DQPConfiguration{
-
- //Constants
- static final int DEFAULT_FETCH_SIZE = RequestMessage.DEFAULT_FETCH_SIZE * 10;
- static final int DEFAULT_PROCESSOR_TIMESLICE = 2000;
- static final int DEFAULT_MAX_RESULTSET_CACHE_ENTRIES = 1024;
- static final int DEFAULT_QUERY_THRESHOLD = 600;
- static final String PROCESS_PLAN_QUEUE_NAME = "QueryProcessorQueue"; //$NON-NLS-1$
- public static final int DEFAULT_MAX_PROCESS_WORKERS = 64;
- public static final int DEFAULT_MAX_SOURCE_ROWS = -1;
- public static final int DEFAULT_MAX_ACTIVE_PLANS = 20;
- public static final int DEFAULT_USER_REQUEST_SOURCE_CONCURRENCY = 0;
-
- private int maxThreads = DEFAULT_MAX_PROCESS_WORKERS;
- private int timeSliceInMilli = DEFAULT_PROCESSOR_TIMESLICE;
- private int maxRowsFetchSize = DEFAULT_FETCH_SIZE;
- private int lobChunkSizeInKB = 100;
- private boolean useDataRoles = true;
- private boolean allowCreateTemporaryTablesByDefault = true;
- private int queryThresholdInSecs = DEFAULT_QUERY_THRESHOLD;
- private boolean exceptionOnMaxSourceRows = true;
- private int maxSourceRows = -1;
- private int maxActivePlans = DEFAULT_MAX_ACTIVE_PLANS;
- private CacheConfiguration resultsetCacheConfig;
- private CacheConfiguration preparedPlanCacheConfig = new CacheConfiguration();
- private int maxODBCLobSizeAllowed = 5*1024*1024; // 5 MB
- private int userRequestSourceConcurrency = DEFAULT_USER_REQUEST_SOURCE_CONCURRENCY;
- private boolean detectingChangeEvents = true;
-
- private transient AuthorizationValidator authorizationValidator;
- private boolean allowFunctionCallsByDefault;
-
- @ManagementProperty(description="Max active plans (default 20). Increase this value, and max threads, on highly concurrent systems - but ensure that the underlying pools can handle the increased load without timeouts.")
- public int getMaxActivePlans() {
- return maxActivePlans;
- }
-
- public void setMaxActivePlans(int maxActivePlans) {
- this.maxActivePlans = maxActivePlans;
- }
-
- @ManagementProperty(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). " +
- "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.")
- public int getUserRequestSourceConcurrency() {
- return userRequestSourceConcurrency;
- }
-
- public void setUserRequestSourceConcurrency(int userRequestSourceConcurrency) {
- this.userRequestSourceConcurrency = userRequestSourceConcurrency;
- }
-
- @ManagementProperty(description="Process pool maximum thread count. (default 64)")
- public int getMaxThreads() {
- return maxThreads;
- }
-
- public void setMaxThreads(int maxThreads) {
- this.maxThreads = maxThreads;
- }
-
- @ManagementProperty(description="Query processor time slice, in milliseconds. (default 2000)")
- public int getTimeSliceInMilli() {
- return timeSliceInMilli;
- }
-
- public void setTimeSliceInMilli(int timeSliceInMilli) {
- this.timeSliceInMilli = timeSliceInMilli;
- }
-
- @ManagementProperty(description="Maximum allowed fetch size, set via JDBC. User requested value ignored above this value. (default 20480)")
- public int getMaxRowsFetchSize() {
- return maxRowsFetchSize;
- }
-
- public void setMaxRowsFetchSize(int maxRowsFetchSize) {
- this.maxRowsFetchSize = maxRowsFetchSize;
- }
-
- @ManagementProperty(description="The max lob chunk size in KB transferred to the client for xml, blobs, clobs (default 100KB)")
- public int getLobChunkSizeInKB() {
- return this.lobChunkSizeInKB;
- }
-
- public void setLobChunkSizeInKB(int lobChunkSizeInKB) {
- this.lobChunkSizeInKB = lobChunkSizeInKB;
- }
-
- public CacheConfiguration getResultsetCacheConfig() {
- return this.resultsetCacheConfig;
- }
-
- public void setResultsetCacheConfig(CacheConfiguration config) {
- this.resultsetCacheConfig = config;
- }
-
- @ManagementProperty(description="Denotes whether or not result set caching is enabled. (default true)")
- public boolean isResultSetCacheEnabled() {
- return this.resultsetCacheConfig != null && this.resultsetCacheConfig.isEnabled();
- }
-
- /**
- * Determine whether role checking is enabled on the server.
- * @return <code>true</code> if server-side role checking is enabled.
- */
- @ManagementProperty(description="Turn on role checking based upon the data roles defined in VDBs. (default true)")
- public boolean getUseDataRoles() {
- return useDataRoles;
- }
-
- public void setUseDataRoles(boolean useEntitlements) {
- this.useDataRoles = useEntitlements;
- }
-
- /**
- * Whether temporary table usage is enabled by default.
- * @return <code>true</code> if temporary table usage is enabled by default.
- */
- @ManagementProperty(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)")
- 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.
- */
- @ManagementProperty(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)")
- public boolean isAllowFunctionCallsByDefault() {
- return allowFunctionCallsByDefault;
- }
-
- public void setAllowFunctionCallsByDefault(boolean allowFunctionCallsDefault) {
- this.allowFunctionCallsByDefault = allowFunctionCallsDefault;
- }
-
- @ManagementProperty(description="Long running query threshold, after which a alert can be generated by tooling if configured")
- public int getQueryThresholdInSecs() {
- return queryThresholdInSecs;
- }
-
- public void setQueryThresholdInSecs(int queryThresholdInSecs) {
- this.queryThresholdInSecs = queryThresholdInSecs;
- }
-
- @ManagementProperty(description="Teiid runtime version", readOnly=true)
- public String getRuntimeVersion() {
- return ApplicationInfo.getInstance().getBuildNumber();
- }
-
- /**
- * Throw exception if there are more rows in the result set than specified in the MaxSourceRows setting.
- * @return
- */
- @ManagementProperty(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.")
- public boolean isExceptionOnMaxSourceRows() {
- return exceptionOnMaxSourceRows;
- }
-
- public void setExceptionOnMaxSourceRows(boolean exceptionOnMaxSourceRows) {
- this.exceptionOnMaxSourceRows = exceptionOnMaxSourceRows;
- }
-
- /**
- * Maximum source set rows to fetch
- * @return
- */
- @ManagementProperty(description="Maximum rows allowed from a source query. -1 indicates no limit. (default -1)")
- public int getMaxSourceRows() {
- return maxSourceRows;
- }
-
- public void setMaxSourceRows(int maxSourceRows) {
- this.maxSourceRows = maxSourceRows;
- }
-
- @ManagementProperty(description="Maximum Lob Size allowed over ODBC (default 5MB)")
- public int getMaxODBCLobSizeAllowed() {
- return this.maxODBCLobSizeAllowed;
- }
-
- public void setMaxODBCLobSizeAllowed(int lobSize) {
- this.maxODBCLobSizeAllowed = lobSize;
- }
-
- public AuthorizationValidator getAuthorizationValidator() {
- return authorizationValidator;
- }
-
- public void setAuthorizationValidator(
- AuthorizationValidator authorizationValidator) {
- this.authorizationValidator = authorizationValidator;
- }
-
- public MetadataRepository getMetadataRepository() {
- return null;
- }
-
- public CacheConfiguration getPreparedPlanCacheConfig() {
- return preparedPlanCacheConfig;
- }
-
- public void setPreparedPlanCacheConfig(
- CacheConfiguration preparedPlanCacheConfig) {
- this.preparedPlanCacheConfig = preparedPlanCacheConfig;
- }
-
- public boolean isDetectingChangeEvents() {
- return detectingChangeEvents;
- }
-
- @ManagementProperty(description="Set to true for the engine to detect local change events. Should be disabled if using external change data capture tools. (default true)")
- public void setDetectingChangeEvents(boolean detectingChangeEvents) {
- this.detectingChangeEvents = detectingChangeEvents;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,248 @@
+/*
+ * 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.jboss.managed.api.annotation.ManagementProperty;
+import org.teiid.cache.CacheConfiguration;
+import org.teiid.client.RequestMessage;
+import org.teiid.core.util.ApplicationInfo;
+
+
+public class DQPConfiguration{
+
+ //Constants
+ static final int DEFAULT_FETCH_SIZE = RequestMessage.DEFAULT_FETCH_SIZE * 10;
+ static final int DEFAULT_PROCESSOR_TIMESLICE = 2000;
+ static final int DEFAULT_MAX_RESULTSET_CACHE_ENTRIES = 1024;
+ static final int DEFAULT_QUERY_THRESHOLD = 600;
+ static final String PROCESS_PLAN_QUEUE_NAME = "QueryProcessorQueue"; //$NON-NLS-1$
+ public static final int DEFAULT_MAX_PROCESS_WORKERS = 64;
+ public static final int DEFAULT_MAX_SOURCE_ROWS = -1;
+ public static final int DEFAULT_MAX_ACTIVE_PLANS = 20;
+ public static final int DEFAULT_USER_REQUEST_SOURCE_CONCURRENCY = 0;
+
+ private int maxThreads = DEFAULT_MAX_PROCESS_WORKERS;
+ private int timeSliceInMilli = DEFAULT_PROCESSOR_TIMESLICE;
+ private int maxRowsFetchSize = DEFAULT_FETCH_SIZE;
+ private int lobChunkSizeInKB = 100;
+ private boolean useDataRoles = true;
+ private boolean allowCreateTemporaryTablesByDefault = true;
+ private int queryThresholdInSecs = DEFAULT_QUERY_THRESHOLD;
+ private boolean exceptionOnMaxSourceRows = true;
+ private int maxSourceRows = -1;
+ private int maxActivePlans = DEFAULT_MAX_ACTIVE_PLANS;
+ private CacheConfiguration resultsetCacheConfig;
+ private CacheConfiguration preparedPlanCacheConfig = new CacheConfiguration();
+ private int maxODBCLobSizeAllowed = 5*1024*1024; // 5 MB
+ private int userRequestSourceConcurrency = DEFAULT_USER_REQUEST_SOURCE_CONCURRENCY;
+ private boolean detectingChangeEvents = true;
+
+ private transient AuthorizationValidator authorizationValidator;
+ private boolean allowFunctionCallsByDefault;
+
+ @ManagementProperty(description="Max active plans (default 20). Increase this value, and max threads, on highly concurrent systems - but ensure that the underlying pools can handle the increased load without timeouts.")
+ public int getMaxActivePlans() {
+ return maxActivePlans;
+ }
+
+ public void setMaxActivePlans(int maxActivePlans) {
+ this.maxActivePlans = maxActivePlans;
+ }
+
+ @ManagementProperty(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). " +
+ "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.")
+ public int getUserRequestSourceConcurrency() {
+ return userRequestSourceConcurrency;
+ }
+
+ public void setUserRequestSourceConcurrency(int userRequestSourceConcurrency) {
+ this.userRequestSourceConcurrency = userRequestSourceConcurrency;
+ }
+
+ @ManagementProperty(description="Process pool maximum thread count. (default 64)")
+ public int getMaxThreads() {
+ return maxThreads;
+ }
+
+ public void setMaxThreads(int maxThreads) {
+ this.maxThreads = maxThreads;
+ }
+
+ @ManagementProperty(description="Query processor time slice, in milliseconds. (default 2000)")
+ public int getTimeSliceInMilli() {
+ return timeSliceInMilli;
+ }
+
+ public void setTimeSliceInMilli(int timeSliceInMilli) {
+ this.timeSliceInMilli = timeSliceInMilli;
+ }
+
+ @ManagementProperty(description="Maximum allowed fetch size, set via JDBC. User requested value ignored above this value. (default 20480)")
+ public int getMaxRowsFetchSize() {
+ return maxRowsFetchSize;
+ }
+
+ public void setMaxRowsFetchSize(int maxRowsFetchSize) {
+ this.maxRowsFetchSize = maxRowsFetchSize;
+ }
+
+ @ManagementProperty(description="The max lob chunk size in KB transferred to the client for xml, blobs, clobs (default 100KB)")
+ public int getLobChunkSizeInKB() {
+ return this.lobChunkSizeInKB;
+ }
+
+ public void setLobChunkSizeInKB(int lobChunkSizeInKB) {
+ this.lobChunkSizeInKB = lobChunkSizeInKB;
+ }
+
+ public CacheConfiguration getResultsetCacheConfig() {
+ return this.resultsetCacheConfig;
+ }
+
+ public void setResultsetCacheConfig(CacheConfiguration config) {
+ this.resultsetCacheConfig = config;
+ }
+
+ @ManagementProperty(description="Denotes whether or not result set caching is enabled. (default true)")
+ public boolean isResultSetCacheEnabled() {
+ return this.resultsetCacheConfig != null && this.resultsetCacheConfig.isEnabled();
+ }
+
+ /**
+ * Determine whether role checking is enabled on the server.
+ * @return <code>true</code> if server-side role checking is enabled.
+ */
+ @ManagementProperty(description="Turn on role checking based upon the data roles defined in VDBs. (default true)")
+ public boolean getUseDataRoles() {
+ return useDataRoles;
+ }
+
+ public void setUseDataRoles(boolean useEntitlements) {
+ this.useDataRoles = useEntitlements;
+ }
+
+ /**
+ * Whether temporary table usage is enabled by default.
+ * @return <code>true</code> if temporary table usage is enabled by default.
+ */
+ @ManagementProperty(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)")
+ 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.
+ */
+ @ManagementProperty(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)")
+ public boolean isAllowFunctionCallsByDefault() {
+ return allowFunctionCallsByDefault;
+ }
+
+ public void setAllowFunctionCallsByDefault(boolean allowFunctionCallsDefault) {
+ this.allowFunctionCallsByDefault = allowFunctionCallsDefault;
+ }
+
+ @ManagementProperty(description="Long running query threshold, after which a alert can be generated by tooling if configured")
+ public int getQueryThresholdInSecs() {
+ return queryThresholdInSecs;
+ }
+
+ public void setQueryThresholdInSecs(int queryThresholdInSecs) {
+ this.queryThresholdInSecs = queryThresholdInSecs;
+ }
+
+ @ManagementProperty(description="Teiid runtime version", readOnly=true)
+ public String getRuntimeVersion() {
+ return ApplicationInfo.getInstance().getBuildNumber();
+ }
+
+ /**
+ * Throw exception if there are more rows in the result set than specified in the MaxSourceRows setting.
+ * @return
+ */
+ @ManagementProperty(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.")
+ public boolean isExceptionOnMaxSourceRows() {
+ return exceptionOnMaxSourceRows;
+ }
+
+ public void setExceptionOnMaxSourceRows(boolean exceptionOnMaxSourceRows) {
+ this.exceptionOnMaxSourceRows = exceptionOnMaxSourceRows;
+ }
+
+ /**
+ * Maximum source set rows to fetch
+ * @return
+ */
+ @ManagementProperty(description="Maximum rows allowed from a source query. -1 indicates no limit. (default -1)")
+ public int getMaxSourceRows() {
+ return maxSourceRows;
+ }
+
+ public void setMaxSourceRows(int maxSourceRows) {
+ this.maxSourceRows = maxSourceRows;
+ }
+
+ @ManagementProperty(description="Maximum Lob Size allowed over ODBC (default 5MB)")
+ public int getMaxODBCLobSizeAllowed() {
+ return this.maxODBCLobSizeAllowed;
+ }
+
+ public void setMaxODBCLobSizeAllowed(int lobSize) {
+ this.maxODBCLobSizeAllowed = lobSize;
+ }
+
+ public AuthorizationValidator getAuthorizationValidator() {
+ return authorizationValidator;
+ }
+
+ public void setAuthorizationValidator(
+ AuthorizationValidator authorizationValidator) {
+ this.authorizationValidator = authorizationValidator;
+ }
+
+ public CacheConfiguration getPreparedPlanCacheConfig() {
+ return preparedPlanCacheConfig;
+ }
+
+ public void setPreparedPlanCacheConfig(
+ CacheConfiguration preparedPlanCacheConfig) {
+ this.preparedPlanCacheConfig = preparedPlanCacheConfig;
+ }
+
+ public boolean isDetectingChangeEvents() {
+ return detectingChangeEvents;
+ }
+
+ @ManagementProperty(description="Set to true for the engine to detect local change events. Should be disabled if using external change data capture tools. (default true)")
+ public void setDetectingChangeEvents(boolean detectingChangeEvents) {
+ this.detectingChangeEvents = detectingChangeEvents;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataRoleAuthorizationValidator.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataRoleAuthorizationValidator.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataRoleAuthorizationValidator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataRoleAuthorizationValidator.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataRoleAuthorizationValidator.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataRoleAuthorizationValidator.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataRoleAuthorizationValidator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,65 @@
+/*
+ * 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;
+import org.teiid.query.util.CommandContext;
+
+/**
+ * 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, CommandContext commandContext) throws QueryValidatorException, TeiidComponentException {
+ if (useEntitlements && !workContext.getVDB().getDataPolicies().isEmpty()) {
+ AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(workContext.getAllowedDataPolicies(), commandContext);
+ 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);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,455 +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 java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.activation.DataSource;
-import javax.xml.transform.Source;
-
-import org.teiid.client.SourceWarning;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.FileStore;
-import org.teiid.common.buffer.FileStoreInputStreamFactory;
-import org.teiid.common.buffer.TupleSource;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.TeiidRuntimeException;
-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.types.SQLXMLImpl;
-import org.teiid.core.types.StandardXMLTranslator;
-import org.teiid.core.types.Streamable;
-import org.teiid.core.types.TransformationException;
-import org.teiid.core.types.XMLType;
-import org.teiid.core.util.Assertion;
-import org.teiid.core.util.ObjectConverterUtil;
-import org.teiid.dqp.internal.datamgr.ConnectorWork;
-import org.teiid.dqp.internal.process.DQPCore.CompletionListener;
-import org.teiid.dqp.internal.process.DQPCore.FutureWork;
-import org.teiid.dqp.message.AtomicRequestMessage;
-import org.teiid.dqp.message.AtomicResultsMessage;
-import org.teiid.events.EventDistributor;
-import org.teiid.metadata.Table;
-import org.teiid.query.function.source.XMLSystemFunctions;
-import org.teiid.query.processor.relational.RelationalNodeUtil;
-import org.teiid.query.sql.lang.BatchedUpdateCommand;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.ProcedureContainer;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.translator.DataNotAvailableException;
-import org.teiid.translator.TranslatorException;
-
-
-/**
- * This tuple source impl can only be used once; once it is closed, it
- * cannot be reopened and reused.
- *
- * TODO: the handling of DataNotAvailable is awkward.
- * In the multi-threaded case we'd like to not even
- * notify the parent plan and just schedule the next poll.
- */
-public class DataTierTupleSource implements TupleSource, CompletionListener<AtomicResultsMessage> {
-
- // Construction state
- private final AtomicRequestMessage aqr;
- private final RequestWorkItem workItem;
- private final ConnectorWork cwi;
- private final DataTierManagerImpl dtm;
-
- private boolean[] convertToRuntimeType;
- private boolean[] convertToDesiredRuntimeType;
- private Class<?>[] schema;
-
- private int limit = -1;
-
- // Data state
- private int index;
- private int rowsProcessed;
- private AtomicResultsMessage arm;
- private AtomicBoolean closed = new AtomicBoolean();
- private volatile boolean canAsynchClose;
- private volatile boolean canceled;
- private volatile boolean cancelAsynch;
- private boolean executed;
- private volatile boolean done;
- private boolean explicitClose;
-
- private volatile FutureWork<AtomicResultsMessage> futureResult;
- private volatile boolean running;
-
- public DataTierTupleSource(AtomicRequestMessage aqr, RequestWorkItem workItem, ConnectorWork cwi, DataTierManagerImpl dtm, int limit) {
- this.aqr = aqr;
- this.workItem = workItem;
- this.cwi = cwi;
- this.dtm = dtm;
- this.limit = limit;
- List<SingleElementSymbol> symbols = this.aqr.getCommand().getProjectedSymbols();
- this.schema = new Class[symbols.size()];
- this.convertToDesiredRuntimeType = new boolean[symbols.size()];
- this.convertToRuntimeType = new boolean[symbols.size()];
- for (int i = 0; i < symbols.size(); i++) {
- SingleElementSymbol symbol = symbols.get(i);
- this.schema[i] = symbol.getType();
- this.convertToDesiredRuntimeType[i] = true;
- this.convertToRuntimeType[i] = true;
- }
-
- Assertion.isNull(workItem.getConnectorRequest(aqr.getAtomicRequestID()));
- workItem.addConnectorRequest(aqr.getAtomicRequestID(), this);
- if (!aqr.isSerial()) {
- addWork();
- }
- }
-
- private void addWork() {
- this.canAsynchClose = true;
- futureResult = workItem.addWork(new Callable<AtomicResultsMessage>() {
- @Override
- public AtomicResultsMessage call() throws Exception {
- return getResults();
- }
- }, this, 100);
- }
-
- private List<?> correctTypes(List<Object> row) throws TransformationException {
- //TODO: add a proper intermediate schema
- for (int i = 0; i < row.size(); i++) {
- Object value = row.get(i);
- if (value == null) {
- continue;
- }
- if (convertToRuntimeType[i]) {
- boolean lob = !arm.supportsCloseWithLobs() && DataTypeManager.isLOB(value.getClass());
- Object result = convertToRuntimeType(value, this.schema[i]);
- if (value == result && !DataTypeManager.DefaultDataClasses.OBJECT.equals(this.schema[i])) {
- convertToRuntimeType[i] = false;
- } else {
- if (lob && DataTypeManager.isLOB(result.getClass()) && DataTypeManager.isLOB(this.schema[i])) {
- explicitClose = true;
- }
- row.set(i, result);
- value = result;
- }
- }
- if (convertToDesiredRuntimeType[i]) {
- if (value != null) {
- Object result = DataTypeManager.transformValue(value, value.getClass(), this.schema[i]);
- if (value == result) {
- convertToDesiredRuntimeType[i] = false;
- continue;
- }
- row.set(i, result);
- }
- } else {
- row.set(i, DataTypeManager.getCanonicalValue(value));
- }
- }
- return row;
- }
-
- private Object convertToRuntimeType(Object value, Class<?> desiredType) throws TransformationException {
- if (value instanceof DataSource && (!(value instanceof Source) || desiredType != DataTypeManager.DefaultDataClasses.XML)) {
- if (value instanceof InputStreamFactory) {
- return new BlobType(new BlobImpl((InputStreamFactory)value));
- }
- FileStore fs = dtm.getBufferManager().createFileStore("bytes"); //$NON-NLS-1$
- //TODO: guess at the encoding from the content type
- FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(fs, Streamable.ENCODING);
-
- try {
- ObjectConverterUtil.write(fsisf.getOuputStream(), ((DataSource)value).getInputStream(), -1);
- } catch (IOException e) {
- throw new TransformationException(e, e.getMessage());
- }
- return new BlobType(new BlobImpl(fsisf));
- }
- if (value instanceof Source) {
- if (value instanceof InputStreamFactory) {
- return new XMLType(new SQLXMLImpl((InputStreamFactory)value));
- }
- StandardXMLTranslator sxt = new StandardXMLTranslator((Source)value);
- SQLXMLImpl sqlxml;
- try {
- sqlxml = XMLSystemFunctions.saveToBufferManager(dtm.getBufferManager(), sxt);
- } catch (TeiidComponentException e) {
- throw new TeiidRuntimeException(e);
- } catch (TeiidProcessingException e) {
- throw new TeiidRuntimeException(e);
- }
- return new XMLType(sqlxml);
- }
- return DataTypeManager.convertToRuntimeType(value);
- }
-
- public List<?> nextTuple() throws TeiidComponentException, TeiidProcessingException {
- while (true) {
- if (arm == null) {
- AtomicResultsMessage results = null;
- try {
- if (futureResult != null || !aqr.isSerial()) {
- results = asynchGet();
- } else {
- results = getResults();
- }
- //check for update events
- if (index == 0 && this.dtm.detectChangeEvents()) {
- Command command = aqr.getCommand();
- int commandIndex = 0;
- if (RelationalNodeUtil.isUpdate(command)) {
- long ts = System.currentTimeMillis();
- checkForUpdates(results, command, dtm.getEventDistributor(), commandIndex, ts);
- } else if (command instanceof BatchedUpdateCommand) {
- long ts = System.currentTimeMillis();
- BatchedUpdateCommand bac = (BatchedUpdateCommand)command;
- for (Command uc : bac.getUpdateCommands()) {
- checkForUpdates(results, uc, dtm.getEventDistributor(), commandIndex++, ts);
- }
- }
- }
- } catch (TranslatorException e) {
- results = exceptionOccurred(e, true);
- } catch (DataNotAvailableException e) {
- workItem.scheduleWork(new Runnable() {
- @Override
- public void run() {
- workItem.moreWork();
- }
- }, 10, e.getRetryDelay());
- throw BlockedException.INSTANCE;
- }
- receiveResults(results);
- }
- if (index < arm.getResults().length) {
- if (limit-- == 0) {
- this.done = true;
- arm = null;
- return null;
- }
- return correctTypes(this.arm.getResults()[index++]);
- }
- arm = null;
- if (isDone()) {
- return null;
- }
- }
- }
-
- private void checkForUpdates(AtomicResultsMessage results, Command command,
- EventDistributor distributor, int commandIndex, long ts) {
- if (!RelationalNodeUtil.isUpdate(command) || !(command instanceof ProcedureContainer)) {
- return;
- }
- ProcedureContainer pc = (ProcedureContainer)aqr.getCommand();
- GroupSymbol gs = pc.getGroup();
- Integer zero = Integer.valueOf(0);
- if (results.getResults().length <= commandIndex || zero.equals(results.getResults()[commandIndex].get(0))) {
- return;
- }
- Object metadataId = gs.getMetadataID();
- if (metadataId == null) {
- return;
- }
- if (!(metadataId instanceof Table)) {
- return;
- }
- Table t = (Table)metadataId;
- t.setLastDataModification(ts);
- if (distributor != null) {
- distributor.dataModification(this.workItem.getDqpWorkContext().getVdbName(), this.workItem.getDqpWorkContext().getVdbVersion(), t.getParent().getName(), t.getName());
- }
- }
-
- private AtomicResultsMessage asynchGet()
- throws BlockedException, TeiidProcessingException,
- TeiidComponentException, TranslatorException {
- if (futureResult == null) {
- addWork();
- }
- if (!futureResult.isDone()) {
- throw BlockedException.INSTANCE;
- }
- FutureWork<AtomicResultsMessage> currentResults = futureResult;
- futureResult = null;
- AtomicResultsMessage results = null;
- try {
- results = currentResults.get();
- if (results.getFinalRow() < 0) {
- addWork();
- }
- } catch (InterruptedException e) {
- throw new TeiidRuntimeException(e);
- } catch (ExecutionException e) {
- if (e.getCause() instanceof TeiidProcessingException) {
- throw (TeiidProcessingException)e.getCause();
- }
- if (e.getCause() instanceof TeiidComponentException) {
- throw (TeiidComponentException)e.getCause();
- }
- if (e.getCause() instanceof TranslatorException) {
- throw (TranslatorException)e.getCause();
- }
- if (e.getCause() instanceof RuntimeException) {
- throw (RuntimeException)e.getCause();
- }
- //shouldn't happen
- throw new RuntimeException(e);
- }
- return results;
- }
-
- private AtomicResultsMessage getResults()
- throws BlockedException, TeiidComponentException,
- TranslatorException {
- AtomicResultsMessage results = null;
- if (cancelAsynch) {
- return null;
- }
- running = true;
- if (!executed) {
- results = cwi.execute();
- executed = true;
- } else {
- results = cwi.more();
- }
- return results;
- }
-
- public boolean isQueued() {
- FutureWork<AtomicResultsMessage> future = futureResult;
- return !running && future != null && !future.isDone();
- }
-
- public boolean isDone() {
- return done;
- }
-
- public boolean isRunning() {
- return running;
- }
-
- public void fullyCloseSource() {
- cancelAsynch = true;
- if (closed.compareAndSet(false, true)) {
- workItem.closeAtomicRequest(this.aqr.getAtomicRequestID());
- if (aqr.isSerial()) {
- this.cwi.close();
- } else if (!canAsynchClose) {
- workItem.addHighPriorityWork(new Callable<Void>() {
- @Override
- public Void call() throws Exception {
- cwi.close();
- return null;
- }
- });
- }
- }
- }
-
- public boolean isCanceled() {
- return canceled;
- }
-
- public void cancelRequest() {
- this.canceled = true;
- this.cwi.cancel();
- }
-
- /**
- * @see TupleSource#closeSource()
- */
- public void closeSource() {
- cancelAsynch = true;
- if (!explicitClose) {
- fullyCloseSource();
- }
- }
-
- AtomicResultsMessage exceptionOccurred(TranslatorException exception, boolean removeState) throws TeiidComponentException, TeiidProcessingException {
- if (removeState) {
- fullyCloseSource();
- }
- if(workItem.requestMsg.supportsPartialResults()) {
- AtomicResultsMessage emptyResults = new AtomicResultsMessage(new List[0], null);
- emptyResults.setWarnings(Arrays.asList((Exception)exception));
- emptyResults.setFinalRow(this.rowsProcessed);
- return emptyResults;
- }
- if (exception.getCause() instanceof TeiidComponentException) {
- throw (TeiidComponentException)exception.getCause();
- }
- if (exception.getCause() instanceof TeiidProcessingException) {
- throw (TeiidProcessingException)exception.getCause();
- }
- throw new TeiidProcessingException(exception);
- }
-
- void receiveResults(AtomicResultsMessage response) {
- this.arm = response;
- explicitClose |= !arm.supportsImplicitClose();
- rowsProcessed += response.getResults().length;
- index = 0;
- if (response.getWarnings() != null) {
- for (Exception warning : response.getWarnings()) {
- SourceWarning sourceFailure = new SourceWarning(this.aqr.getModelName(), aqr.getConnectorName(), warning, true);
- workItem.addSourceFailureDetails(sourceFailure);
- }
- }
- if (response.getFinalRow() >= 0) {
- done = true;
- }
- }
-
- public AtomicRequestMessage getAtomicRequestMessage() {
- return aqr;
- }
-
- public String getConnectorName() {
- return this.aqr.getConnectorName();
- }
-
- public boolean isTransactional() {
- return this.aqr.isTransactional();
- }
-
- @Override
- public void onCompletion(FutureWork<AtomicResultsMessage> future) {
- if (!cancelAsynch) {
- workItem.moreWork();
- }
- canAsynchClose = false;
- if (closed.get()) {
- cwi.close();
- }
- running = false;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,457 @@
+/*
+ * 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 java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.activation.DataSource;
+import javax.xml.transform.Source;
+
+import org.teiid.client.SourceWarning;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.FileStore;
+import org.teiid.common.buffer.FileStoreInputStreamFactory;
+import org.teiid.common.buffer.TupleSource;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.TeiidRuntimeException;
+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.types.SQLXMLImpl;
+import org.teiid.core.types.StandardXMLTranslator;
+import org.teiid.core.types.Streamable;
+import org.teiid.core.types.TransformationException;
+import org.teiid.core.types.XMLType;
+import org.teiid.core.util.Assertion;
+import org.teiid.core.util.ObjectConverterUtil;
+import org.teiid.dqp.internal.datamgr.ConnectorWork;
+import org.teiid.dqp.internal.process.DQPCore.CompletionListener;
+import org.teiid.dqp.internal.process.DQPCore.FutureWork;
+import org.teiid.dqp.message.AtomicRequestMessage;
+import org.teiid.dqp.message.AtomicResultsMessage;
+import org.teiid.events.EventDistributor;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.Table;
+import org.teiid.query.function.source.XMLSystemFunctions;
+import org.teiid.query.processor.relational.RelationalNodeUtil;
+import org.teiid.query.sql.lang.BatchedUpdateCommand;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.ProcedureContainer;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.translator.DataNotAvailableException;
+import org.teiid.translator.TranslatorException;
+
+
+/**
+ * This tuple source impl can only be used once; once it is closed, it
+ * cannot be reopened and reused.
+ *
+ * TODO: the handling of DataNotAvailable is awkward.
+ * In the multi-threaded case we'd like to not even
+ * notify the parent plan and just schedule the next poll.
+ */
+public class DataTierTupleSource implements TupleSource, CompletionListener<AtomicResultsMessage> {
+
+ // Construction state
+ private final AtomicRequestMessage aqr;
+ private final RequestWorkItem workItem;
+ private final ConnectorWork cwi;
+ private final DataTierManagerImpl dtm;
+
+ private boolean[] convertToRuntimeType;
+ private boolean[] convertToDesiredRuntimeType;
+ private Class<?>[] schema;
+
+ private int limit = -1;
+
+ // Data state
+ private int index;
+ private int rowsProcessed;
+ private AtomicResultsMessage arm;
+ private AtomicBoolean closed = new AtomicBoolean();
+ private volatile boolean canAsynchClose;
+ private volatile boolean canceled;
+ private volatile boolean cancelAsynch;
+ private boolean executed;
+ private volatile boolean done;
+ private boolean explicitClose;
+
+ private volatile FutureWork<AtomicResultsMessage> futureResult;
+ private volatile boolean running;
+
+ public DataTierTupleSource(AtomicRequestMessage aqr, RequestWorkItem workItem, ConnectorWork cwi, DataTierManagerImpl dtm, int limit) {
+ this.aqr = aqr;
+ this.workItem = workItem;
+ this.cwi = cwi;
+ this.dtm = dtm;
+ this.limit = limit;
+ List<SingleElementSymbol> symbols = this.aqr.getCommand().getProjectedSymbols();
+ this.schema = new Class[symbols.size()];
+ this.convertToDesiredRuntimeType = new boolean[symbols.size()];
+ this.convertToRuntimeType = new boolean[symbols.size()];
+ for (int i = 0; i < symbols.size(); i++) {
+ SingleElementSymbol symbol = symbols.get(i);
+ this.schema[i] = symbol.getType();
+ this.convertToDesiredRuntimeType[i] = true;
+ this.convertToRuntimeType[i] = true;
+ }
+
+ Assertion.isNull(workItem.getConnectorRequest(aqr.getAtomicRequestID()));
+ workItem.addConnectorRequest(aqr.getAtomicRequestID(), this);
+ if (!aqr.isSerial()) {
+ addWork();
+ }
+ }
+
+ private void addWork() {
+ this.canAsynchClose = true;
+ futureResult = workItem.addWork(new Callable<AtomicResultsMessage>() {
+ @Override
+ public AtomicResultsMessage call() throws Exception {
+ return getResults();
+ }
+ }, this, 100);
+ }
+
+ private List<?> correctTypes(List<Object> row) throws TransformationException {
+ //TODO: add a proper intermediate schema
+ for (int i = 0; i < row.size(); i++) {
+ Object value = row.get(i);
+ if (value == null) {
+ continue;
+ }
+ if (convertToRuntimeType[i]) {
+ boolean lob = !arm.supportsCloseWithLobs() && DataTypeManager.isLOB(value.getClass());
+ Object result = convertToRuntimeType(value, this.schema[i]);
+ if (value == result && !DataTypeManager.DefaultDataClasses.OBJECT.equals(this.schema[i])) {
+ convertToRuntimeType[i] = false;
+ } else {
+ if (lob && DataTypeManager.isLOB(result.getClass()) && DataTypeManager.isLOB(this.schema[i])) {
+ explicitClose = true;
+ }
+ row.set(i, result);
+ value = result;
+ }
+ }
+ if (convertToDesiredRuntimeType[i]) {
+ if (value != null) {
+ Object result = DataTypeManager.transformValue(value, value.getClass(), this.schema[i]);
+ if (value == result) {
+ convertToDesiredRuntimeType[i] = false;
+ continue;
+ }
+ row.set(i, result);
+ }
+ } else {
+ row.set(i, DataTypeManager.getCanonicalValue(value));
+ }
+ }
+ return row;
+ }
+
+ private Object convertToRuntimeType(Object value, Class<?> desiredType) throws TransformationException {
+ if (value instanceof DataSource && (!(value instanceof Source) || desiredType != DataTypeManager.DefaultDataClasses.XML)) {
+ if (value instanceof InputStreamFactory) {
+ return new BlobType(new BlobImpl((InputStreamFactory)value));
+ }
+ FileStore fs = dtm.getBufferManager().createFileStore("bytes"); //$NON-NLS-1$
+ //TODO: guess at the encoding from the content type
+ FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(fs, Streamable.ENCODING);
+
+ try {
+ ObjectConverterUtil.write(fsisf.getOuputStream(), ((DataSource)value).getInputStream(), -1);
+ } catch (IOException e) {
+ throw new TransformationException(e, e.getMessage());
+ }
+ return new BlobType(new BlobImpl(fsisf));
+ }
+ if (value instanceof Source) {
+ if (value instanceof InputStreamFactory) {
+ return new XMLType(new SQLXMLImpl((InputStreamFactory)value));
+ }
+ StandardXMLTranslator sxt = new StandardXMLTranslator((Source)value);
+ SQLXMLImpl sqlxml;
+ try {
+ sqlxml = XMLSystemFunctions.saveToBufferManager(dtm.getBufferManager(), sxt);
+ } catch (TeiidComponentException e) {
+ throw new TeiidRuntimeException(e);
+ } catch (TeiidProcessingException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ return new XMLType(sqlxml);
+ }
+ return DataTypeManager.convertToRuntimeType(value);
+ }
+
+ public List<?> nextTuple() throws TeiidComponentException, TeiidProcessingException {
+ while (true) {
+ if (arm == null) {
+ AtomicResultsMessage results = null;
+ try {
+ if (futureResult != null || !aqr.isSerial()) {
+ results = asynchGet();
+ } else {
+ results = getResults();
+ }
+ //check for update events
+ if (index == 0 && this.dtm.detectChangeEvents()) {
+ Command command = aqr.getCommand();
+ int commandIndex = 0;
+ if (RelationalNodeUtil.isUpdate(command)) {
+ long ts = System.currentTimeMillis();
+ checkForUpdates(results, command, dtm.getEventDistributor(), commandIndex, ts);
+ } else if (command instanceof BatchedUpdateCommand) {
+ long ts = System.currentTimeMillis();
+ BatchedUpdateCommand bac = (BatchedUpdateCommand)command;
+ for (Command uc : bac.getUpdateCommands()) {
+ checkForUpdates(results, uc, dtm.getEventDistributor(), commandIndex++, ts);
+ }
+ }
+ }
+ } catch (TranslatorException e) {
+ results = exceptionOccurred(e, true);
+ } catch (DataNotAvailableException e) {
+ workItem.scheduleWork(new Runnable() {
+ @Override
+ public void run() {
+ workItem.moreWork();
+ }
+ }, 10, e.getRetryDelay());
+ throw BlockedException.block(aqr.getAtomicRequestID(), "Blocking on DataNotAvailableException"); //$NON-NLS-1$
+ }
+ receiveResults(results);
+ }
+ if (index < arm.getResults().length) {
+ if (limit-- == 0) {
+ this.done = true;
+ arm = null;
+ return null;
+ }
+ return correctTypes(this.arm.getResults()[index++]);
+ }
+ arm = null;
+ if (isDone()) {
+ return null;
+ }
+ }
+ }
+
+ private void checkForUpdates(AtomicResultsMessage results, Command command,
+ EventDistributor distributor, int commandIndex, long ts) {
+ if (!RelationalNodeUtil.isUpdate(command) || !(command instanceof ProcedureContainer)) {
+ return;
+ }
+ ProcedureContainer pc = (ProcedureContainer)aqr.getCommand();
+ GroupSymbol gs = pc.getGroup();
+ Integer zero = Integer.valueOf(0);
+ if (results.getResults().length <= commandIndex || zero.equals(results.getResults()[commandIndex].get(0))) {
+ return;
+ }
+ Object metadataId = gs.getMetadataID();
+ if (metadataId == null) {
+ return;
+ }
+ if (!(metadataId instanceof Table)) {
+ return;
+ }
+ Table t = (Table)metadataId;
+ t.setLastDataModification(ts);
+ if (distributor != null) {
+ distributor.dataModification(this.workItem.getDqpWorkContext().getVdbName(), this.workItem.getDqpWorkContext().getVdbVersion(), t.getParent().getName(), t.getName());
+ }
+ }
+
+ private AtomicResultsMessage asynchGet()
+ throws BlockedException, TeiidProcessingException,
+ TeiidComponentException, TranslatorException {
+ if (futureResult == null) {
+ addWork();
+ }
+ if (!futureResult.isDone()) {
+ throw BlockedException.block(aqr.getAtomicRequestID(), "Blocking on source query"); //$NON-NLS-1$
+ }
+ FutureWork<AtomicResultsMessage> currentResults = futureResult;
+ futureResult = null;
+ AtomicResultsMessage results = null;
+ try {
+ results = currentResults.get();
+ if (results.getFinalRow() < 0) {
+ addWork();
+ }
+ } catch (InterruptedException e) {
+ throw new TeiidRuntimeException(e);
+ } catch (ExecutionException e) {
+ if (e.getCause() instanceof TeiidProcessingException) {
+ throw (TeiidProcessingException)e.getCause();
+ }
+ if (e.getCause() instanceof TeiidComponentException) {
+ throw (TeiidComponentException)e.getCause();
+ }
+ if (e.getCause() instanceof TranslatorException) {
+ throw (TranslatorException)e.getCause();
+ }
+ if (e.getCause() instanceof RuntimeException) {
+ throw (RuntimeException)e.getCause();
+ }
+ //shouldn't happen
+ throw new RuntimeException(e);
+ }
+ return results;
+ }
+
+ private AtomicResultsMessage getResults()
+ throws BlockedException, TeiidComponentException,
+ TranslatorException {
+ AtomicResultsMessage results = null;
+ if (cancelAsynch) {
+ return null;
+ }
+ running = true;
+ if (!executed) {
+ results = cwi.execute();
+ executed = true;
+ } else {
+ results = cwi.more();
+ }
+ return results;
+ }
+
+ public boolean isQueued() {
+ FutureWork<AtomicResultsMessage> future = futureResult;
+ return !running && future != null && !future.isDone();
+ }
+
+ public boolean isDone() {
+ return done;
+ }
+
+ public boolean isRunning() {
+ return running;
+ }
+
+ public void fullyCloseSource() {
+ cancelAsynch = true;
+ if (closed.compareAndSet(false, true)) {
+ workItem.closeAtomicRequest(this.aqr.getAtomicRequestID());
+ if (aqr.isSerial()) {
+ this.cwi.close();
+ } else if (!canAsynchClose) {
+ workItem.addHighPriorityWork(new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ cwi.close();
+ return null;
+ }
+ });
+ }
+ }
+ }
+
+ public boolean isCanceled() {
+ return canceled;
+ }
+
+ public void cancelRequest() {
+ this.canceled = true;
+ this.cwi.cancel();
+ }
+
+ /**
+ * @see TupleSource#closeSource()
+ */
+ public void closeSource() {
+ cancelAsynch = true;
+ if (!explicitClose) {
+ fullyCloseSource();
+ }
+ }
+
+ AtomicResultsMessage exceptionOccurred(TranslatorException exception, boolean removeState) throws TeiidComponentException, TeiidProcessingException {
+ if (removeState) {
+ fullyCloseSource();
+ }
+ if(workItem.requestMsg.supportsPartialResults()) {
+ AtomicResultsMessage emptyResults = new AtomicResultsMessage(new List[0], null);
+ emptyResults.setWarnings(Arrays.asList((Exception)exception));
+ emptyResults.setFinalRow(this.rowsProcessed);
+ return emptyResults;
+ }
+ if (exception.getCause() instanceof TeiidComponentException) {
+ throw (TeiidComponentException)exception.getCause();
+ }
+ if (exception.getCause() instanceof TeiidProcessingException) {
+ throw (TeiidProcessingException)exception.getCause();
+ }
+ throw new TeiidProcessingException(exception, this.getConnectorName() + ": " + exception.getMessage()); //$NON-NLS-1$
+ }
+
+ void receiveResults(AtomicResultsMessage response) {
+ this.arm = response;
+ explicitClose |= !arm.supportsImplicitClose();
+ rowsProcessed += response.getResults().length;
+ index = 0;
+ if (response.getWarnings() != null) {
+ for (Exception warning : response.getWarnings()) {
+ SourceWarning sourceFailure = new SourceWarning(this.aqr.getModelName(), aqr.getConnectorName(), warning, true);
+ workItem.addSourceFailureDetails(sourceFailure);
+ }
+ }
+ if (response.getFinalRow() >= 0) {
+ done = true;
+ }
+ }
+
+ public AtomicRequestMessage getAtomicRequestMessage() {
+ return aqr;
+ }
+
+ public String getConnectorName() {
+ return this.aqr.getConnectorName();
+ }
+
+ public boolean isTransactional() {
+ return this.aqr.isTransactional();
+ }
+
+ @Override
+ public void onCompletion(FutureWork<AtomicResultsMessage> future) {
+ if (!cancelAsynch) {
+ workItem.moreWork();
+ }
+ canAsynchClose = false;
+ if (closed.get()) {
+ cwi.close();
+ }
+ running = false;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,299 +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 java.util.ArrayList;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryPlannerException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.metadata.FunctionMethod.Determinism;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.eval.Evaluator;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.BatchedUpdatePlanner;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities;
-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.sql.lang.BatchedUpdateCommand;
-import org.teiid.query.sql.lang.Command;
-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.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.util.VariableContext;
-import org.teiid.query.util.CommandContext;
-
-
-/**
- * Specific request for handling prepared statement calls.
- */
-public class PreparedStatementRequest extends Request {
- private SessionAwareCache<PreparedPlan> prepPlanCache;
- private PreparedPlan prepPlan;
-
- public PreparedStatementRequest(SessionAwareCache<PreparedPlan> prepPlanCache) {
- this.prepPlanCache = prepPlanCache;
- }
-
- @Override
- protected void checkReferences(List<Reference> references)
- throws QueryValidatorException {
- prepPlan.setReferences(references);
- }
-
- /**
- * @see org.teiid.dqp.internal.process.Request#resolveCommand(org.teiid.query.sql.lang.Command)
- */
- @Override
- protected void resolveCommand(Command command) throws QueryResolverException,
- TeiidComponentException {
- handleCallableStatement(command);
-
- super.resolveCommand(command);
- }
-
- /**
- * TODO: this is a hack that maintains pre 5.6 behavior, which ignores output parameters for resolving
- * @param command
- * @param references
- */
- private void handleCallableStatement(Command command) {
- if (!this.requestMsg.isCallableStatement() || !(command instanceof StoredProcedure)) {
- return;
- }
- StoredProcedure proc = (StoredProcedure)command;
- if (!proc.isCallableStatement()) {
- return;
- }
- List<?> values = requestMsg.getParameterValues();
- List<SPParameter> spParams = proc.getParameters();
- proc.clearParameters();
- int inParameterCount = values.size();
- if (this.requestMsg.isBatchedUpdate() && values.size() > 0) {
- inParameterCount = ((List)values.get(0)).size();
- }
- int index = 1;
- for (Iterator<SPParameter> params = spParams.iterator(); params.hasNext();) {
- SPParameter param = params.next();
- if (param.getParameterType() == SPParameter.RETURN_VALUE) {
- inParameterCount++;
- } else if (param.getExpression() instanceof Reference && index > inParameterCount) {
- //assume it's an output parameter
- this.prepPlan.getReferences().remove(param.getExpression());
- continue;
- }
- param.setIndex(index++);
- proc.setParameter(param);
- }
- }
-
- /**
- * @throws TeiidComponentException
- * @throws TeiidProcessingException
- * @see org.teiid.dqp.internal.process.Request#generatePlan()
- */
- protected void generatePlan() throws TeiidComponentException, TeiidProcessingException {
- String sqlQuery = requestMsg.getCommands()[0];
- CacheID id = new CacheID(this.workContext, Request.createParseInfo(this.requestMsg), sqlQuery);
- prepPlan = prepPlanCache.get(id);
- if (prepPlan == null) {
- //if prepared plan does not exist, create one
- prepPlan = new PreparedPlan();
- LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Query does not exist in cache: ", sqlQuery}); //$NON-NLS-1$
- super.generatePlan();
- if (!this.addedLimit) { //TODO: this is a little problematic
- prepPlan.setCommand(this.userCommand);
- // Defect 13751: Clone the plan in its current state (i.e. before processing) so that it can be used for later queries
- prepPlan.setPlan(processPlan.clone(), this.context);
- prepPlan.setAnalysisRecord(analysisRecord);
-
- Determinism determinismLevel = this.context.getDeterminismLevel();
- if (userCommand.getCacheHint() != null && userCommand.getCacheHint().getDeterminism() != null) {
- LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Cache hint modified the query determinism from ",this.context.getDeterminismLevel(), " to ", determinismLevel }); //$NON-NLS-1$ //$NON-NLS-2$
- determinismLevel = userCommand.getCacheHint().getDeterminism();
- }
-
- this.prepPlanCache.put(id, determinismLevel, prepPlan, userCommand.getCacheHint() != null?userCommand.getCacheHint().getTtl():null);
- }
- } else {
- ProcessorPlan cachedPlan = prepPlan.getPlan();
- this.userCommand = prepPlan.getCommand();
- validateAccess(userCommand);
- LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Query exist in cache: ", sqlQuery }); //$NON-NLS-1$
- processPlan = cachedPlan.clone();
- //already in cache. obtain the values from cache
- analysisRecord = prepPlan.getAnalysisRecord();
-
- createCommandContext();
- }
-
- if (requestMsg.isBatchedUpdate()) {
- handlePreparedBatchUpdate();
- } else {
- List<Reference> params = prepPlan.getReferences();
- List<?> values = requestMsg.getParameterValues();
-
- PreparedStatementRequest.resolveParameterValues(params, values, this.context, this.metadata);
- }
- }
-
- /**
- * There are two cases
- * if
- * The source supports preparedBatchUpdate -> just let the command and values pass to the source
- * else
- * create a batchedupdatecommand that represents the batch operation
- * @param command
- * @throws QueryMetadataException
- * @throws TeiidComponentException
- * @throws QueryResolverException
- * @throws QueryPlannerException
- * @throws QueryValidatorException
- */
- private void handlePreparedBatchUpdate() throws QueryMetadataException,
- TeiidComponentException, QueryResolverException, QueryPlannerException, QueryValidatorException {
- List<List<?>> paramValues = (List<List<?>>) requestMsg.getParameterValues();
- if (paramValues.isEmpty()) {
- throw new QueryValidatorException("No batch values sent for prepared batch update"); //$NON-NLS-1$
- }
- boolean supportPreparedBatchUpdate = false;
- Command command = null;
- if (this.processPlan instanceof RelationalPlan) {
- RelationalPlan rPlan = (RelationalPlan)this.processPlan;
- if (rPlan.getRootNode() instanceof AccessNode) {
- AccessNode aNode = (AccessNode)rPlan.getRootNode();
- String modelName = aNode.getModelName();
- command = aNode.getCommand();
- SourceCapabilities caps = capabilitiesFinder.findCapabilities(modelName);
- supportPreparedBatchUpdate = caps.supportsCapability(SourceCapabilities.Capability.BULK_UPDATE);
- }
- }
- List<Command> commands = new LinkedList<Command>();
- List<VariableContext> contexts = new LinkedList<VariableContext>();
- List<List<Object>> multiValues = new ArrayList<List<Object>>(this.prepPlan.getReferences().size());
- for (List<?> values : paramValues) {
- PreparedStatementRequest.resolveParameterValues(this.prepPlan.getReferences(), values, this.context, this.metadata);
- contexts.add(this.context.getVariableContext());
- if(supportPreparedBatchUpdate){
- if (multiValues.isEmpty()) {
- for (int i = 0; i < values.size(); i++) {
- multiValues.add(new ArrayList<Object>(paramValues.size()));
- }
- }
- for (int i = 0; i < values.size(); i++) {
- List<Object> multiValue = multiValues.get(i);
- multiValue.add(values.get(i));
- }
- } else { //just accumulate copies of the command/plan - clones are not necessary
- if (command == null) {
- command = this.prepPlan.getCommand();
- command.setProcessorPlan(this.processPlan);
- }
- commands.add(command);
- }
- }
-
- if (paramValues.size() > 1) {
- this.context.setVariableContext(new VariableContext());
- }
-
- if (paramValues.size() == 1) {
- return; // just use the existing plan, and global reference evaluation
- }
-
- if (supportPreparedBatchUpdate) {
- for (int i = 0; i < this.prepPlan.getReferences().size(); i++) {
- Constant c = new Constant(null, this.prepPlan.getReferences().get(i).getType());
- c.setMultiValued(multiValues.get(i));
- this.context.getVariableContext().setGlobalValue(this.prepPlan.getReferences().get(i).getContextSymbol(), c);
- }
- return;
- }
-
- BatchedUpdateCommand buc = new BatchedUpdateCommand(commands);
- buc.setVariableContexts(contexts);
- BatchedUpdatePlanner planner = new BatchedUpdatePlanner();
- this.processPlan = planner.optimize(buc, idGenerator, metadata, capabilitiesFinder, analysisRecord, context);
- }
-
- /**
- * @param params
- * @param values
- * @throws QueryResolverException
- * @throws QueryValidatorException
- */
- public static void resolveParameterValues(List<Reference> params,
- List values, CommandContext context, QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException, QueryValidatorException {
- VariableContext result = new VariableContext();
- //the size of the values must be the same as that of the parameters
- if (params.size() != values.size()) {
- String msg = QueryPlugin.Util.getString("QueryUtil.wrong_number_of_values", new Object[] {new Integer(values.size()), new Integer(params.size())}); //$NON-NLS-1$
- throw new QueryResolverException(msg);
- }
-
- //the type must be the same, or the type of the value can be implicitly converted
- //to that of the reference
- for (int i = 0; i < params.size(); i++) {
- Reference param = params.get(i);
- Object value = values.get(i);
-
- //TODO: why is the list check in here
- if(value != null && !(value instanceof List)) {
- try {
- String targetTypeName = DataTypeManager.getDataTypeName(param.getType());
- Expression expr = ResolverUtil.convertExpression(new Constant(value), targetTypeName, metadata);
- value = Evaluator.evaluate(expr);
- } catch (ExpressionEvaluationException e) {
- String msg = QueryPlugin.Util.getString("QueryUtil.Error_executing_conversion_function_to_convert_value", new Integer(i + 1), value, DataTypeManager.getDataTypeName(param.getType())); //$NON-NLS-1$
- throw new QueryResolverException(msg);
- } catch (QueryResolverException e) {
- String msg = QueryPlugin.Util.getString("QueryUtil.Error_executing_conversion_function_to_convert_value", new Integer(i + 1), value, DataTypeManager.getDataTypeName(param.getType())); //$NON-NLS-1$
- throw new QueryResolverException(msg);
- }
- }
-
- if (param.getConstraint() != null) {
- param.getConstraint().validate(value);
- }
- //bind variable
- result.setGlobalValue(param.getContextSymbol(), value);
- }
-
- context.setVariableContext(result);
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,297 @@
+/*
+ * 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 java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryPlannerException;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.FunctionMethod.Determinism;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.eval.Evaluator;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.BatchedUpdatePlanner;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities;
+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.sql.lang.BatchedUpdateCommand;
+import org.teiid.query.sql.lang.Command;
+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.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.util.VariableContext;
+import org.teiid.query.util.CommandContext;
+
+
+/**
+ * Specific request for handling prepared statement calls.
+ */
+public class PreparedStatementRequest extends Request {
+ private SessionAwareCache<PreparedPlan> prepPlanCache;
+ private PreparedPlan prepPlan;
+
+ public PreparedStatementRequest(SessionAwareCache<PreparedPlan> prepPlanCache) {
+ this.prepPlanCache = prepPlanCache;
+ }
+
+ @Override
+ protected void checkReferences(List<Reference> references)
+ throws QueryValidatorException {
+ prepPlan.setReferences(references);
+ }
+
+ /**
+ * @see org.teiid.dqp.internal.process.Request#resolveCommand(org.teiid.query.sql.lang.Command)
+ */
+ @Override
+ protected void resolveCommand(Command command) throws QueryResolverException,
+ TeiidComponentException {
+ handleCallableStatement(command);
+
+ super.resolveCommand(command);
+ }
+
+ /**
+ * TODO: this is a hack that maintains pre 5.6 behavior, which ignores output parameters for resolving
+ * @param command
+ * @param references
+ */
+ private void handleCallableStatement(Command command) {
+ if (!this.requestMsg.isCallableStatement() || !(command instanceof StoredProcedure)) {
+ return;
+ }
+ StoredProcedure proc = (StoredProcedure)command;
+ if (!proc.isCallableStatement()) {
+ return;
+ }
+ List<?> values = requestMsg.getParameterValues();
+ List<SPParameter> spParams = proc.getParameters();
+ proc.clearParameters();
+ int inParameterCount = values.size();
+ if (this.requestMsg.isBatchedUpdate() && values.size() > 0) {
+ inParameterCount = ((List)values.get(0)).size();
+ }
+ int index = 1;
+ for (Iterator<SPParameter> params = spParams.iterator(); params.hasNext();) {
+ SPParameter param = params.next();
+ if (param.getParameterType() == SPParameter.RETURN_VALUE) {
+ inParameterCount++;
+ } else if (param.getExpression() instanceof Reference && index > inParameterCount) {
+ //assume it's an output parameter
+ this.prepPlan.getReferences().remove(param.getExpression());
+ continue;
+ }
+ param.setIndex(index++);
+ proc.setParameter(param);
+ }
+ }
+
+ /**
+ * @throws TeiidComponentException
+ * @throws TeiidProcessingException
+ * @see org.teiid.dqp.internal.process.Request#generatePlan()
+ */
+ protected void generatePlan() throws TeiidComponentException, TeiidProcessingException {
+ String sqlQuery = requestMsg.getCommands()[0];
+ CacheID id = new CacheID(this.workContext, Request.createParseInfo(this.requestMsg), sqlQuery);
+ prepPlan = prepPlanCache.get(id);
+ if (prepPlan == null) {
+ //if prepared plan does not exist, create one
+ prepPlan = new PreparedPlan();
+ LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Query does not exist in cache: ", sqlQuery}); //$NON-NLS-1$
+ super.generatePlan();
+ if (!this.addedLimit) { //TODO: this is a little problematic
+ prepPlan.setCommand(this.userCommand);
+ // Defect 13751: Clone the plan in its current state (i.e. before processing) so that it can be used for later queries
+ prepPlan.setPlan(processPlan.clone(), this.context);
+ prepPlan.setAnalysisRecord(analysisRecord);
+
+ Determinism determinismLevel = this.context.getDeterminismLevel();
+ if (userCommand.getCacheHint() != null && userCommand.getCacheHint().getDeterminism() != null) {
+ LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Cache hint modified the query determinism from ",this.context.getDeterminismLevel(), " to ", determinismLevel }); //$NON-NLS-1$ //$NON-NLS-2$
+ determinismLevel = userCommand.getCacheHint().getDeterminism();
+ }
+
+ this.prepPlanCache.put(id, determinismLevel, prepPlan, userCommand.getCacheHint() != null?userCommand.getCacheHint().getTtl():null);
+ }
+ } else {
+ ProcessorPlan cachedPlan = prepPlan.getPlan();
+ this.userCommand = prepPlan.getCommand();
+ validateAccess(userCommand);
+ LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Query exist in cache: ", sqlQuery }); //$NON-NLS-1$
+ processPlan = cachedPlan.clone();
+ //already in cache. obtain the values from cache
+ analysisRecord = prepPlan.getAnalysisRecord();
+ }
+
+ if (requestMsg.isBatchedUpdate()) {
+ handlePreparedBatchUpdate();
+ } else {
+ List<Reference> params = prepPlan.getReferences();
+ List<?> values = requestMsg.getParameterValues();
+
+ PreparedStatementRequest.resolveParameterValues(params, values, this.context, this.metadata);
+ }
+ }
+
+ /**
+ * There are two cases
+ * if
+ * The source supports preparedBatchUpdate -> just let the command and values pass to the source
+ * else
+ * create a batchedupdatecommand that represents the batch operation
+ * @param command
+ * @throws QueryMetadataException
+ * @throws TeiidComponentException
+ * @throws QueryResolverException
+ * @throws QueryPlannerException
+ * @throws QueryValidatorException
+ */
+ private void handlePreparedBatchUpdate() throws QueryMetadataException,
+ TeiidComponentException, QueryResolverException, QueryPlannerException, QueryValidatorException {
+ List<List<?>> paramValues = (List<List<?>>) requestMsg.getParameterValues();
+ if (paramValues.isEmpty()) {
+ throw new QueryValidatorException("No batch values sent for prepared batch update"); //$NON-NLS-1$
+ }
+ boolean supportPreparedBatchUpdate = false;
+ Command command = null;
+ if (this.processPlan instanceof RelationalPlan) {
+ RelationalPlan rPlan = (RelationalPlan)this.processPlan;
+ if (rPlan.getRootNode() instanceof AccessNode) {
+ AccessNode aNode = (AccessNode)rPlan.getRootNode();
+ String modelName = aNode.getModelName();
+ command = aNode.getCommand();
+ SourceCapabilities caps = capabilitiesFinder.findCapabilities(modelName);
+ supportPreparedBatchUpdate = caps.supportsCapability(SourceCapabilities.Capability.BULK_UPDATE);
+ }
+ }
+ List<Command> commands = new LinkedList<Command>();
+ List<VariableContext> contexts = new LinkedList<VariableContext>();
+ List<List<Object>> multiValues = new ArrayList<List<Object>>(this.prepPlan.getReferences().size());
+ for (List<?> values : paramValues) {
+ PreparedStatementRequest.resolveParameterValues(this.prepPlan.getReferences(), values, this.context, this.metadata);
+ contexts.add(this.context.getVariableContext());
+ if(supportPreparedBatchUpdate){
+ if (multiValues.isEmpty()) {
+ for (int i = 0; i < values.size(); i++) {
+ multiValues.add(new ArrayList<Object>(paramValues.size()));
+ }
+ }
+ for (int i = 0; i < values.size(); i++) {
+ List<Object> multiValue = multiValues.get(i);
+ multiValue.add(values.get(i));
+ }
+ } else { //just accumulate copies of the command/plan - clones are not necessary
+ if (command == null) {
+ command = this.prepPlan.getCommand();
+ command.setProcessorPlan(this.processPlan);
+ }
+ commands.add(command);
+ }
+ }
+
+ if (paramValues.size() > 1) {
+ this.context.setVariableContext(new VariableContext());
+ }
+
+ if (paramValues.size() == 1) {
+ return; // just use the existing plan, and global reference evaluation
+ }
+
+ if (supportPreparedBatchUpdate) {
+ for (int i = 0; i < this.prepPlan.getReferences().size(); i++) {
+ Constant c = new Constant(null, this.prepPlan.getReferences().get(i).getType());
+ c.setMultiValued(multiValues.get(i));
+ this.context.getVariableContext().setGlobalValue(this.prepPlan.getReferences().get(i).getContextSymbol(), c);
+ }
+ return;
+ }
+
+ BatchedUpdateCommand buc = new BatchedUpdateCommand(commands);
+ buc.setVariableContexts(contexts);
+ BatchedUpdatePlanner planner = new BatchedUpdatePlanner();
+ this.processPlan = planner.optimize(buc, idGenerator, metadata, capabilitiesFinder, analysisRecord, context);
+ }
+
+ /**
+ * @param params
+ * @param values
+ * @throws QueryResolverException
+ * @throws QueryValidatorException
+ */
+ public static void resolveParameterValues(List<Reference> params,
+ List values, CommandContext context, QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException, QueryValidatorException {
+ VariableContext result = new VariableContext();
+ //the size of the values must be the same as that of the parameters
+ if (params.size() != values.size()) {
+ String msg = QueryPlugin.Util.getString("QueryUtil.wrong_number_of_values", new Object[] {new Integer(values.size()), new Integer(params.size())}); //$NON-NLS-1$
+ throw new QueryResolverException(msg);
+ }
+
+ //the type must be the same, or the type of the value can be implicitly converted
+ //to that of the reference
+ for (int i = 0; i < params.size(); i++) {
+ Reference param = params.get(i);
+ Object value = values.get(i);
+
+ //TODO: why is the list check in here
+ if(value != null && !(value instanceof List)) {
+ try {
+ String targetTypeName = DataTypeManager.getDataTypeName(param.getType());
+ Expression expr = ResolverUtil.convertExpression(new Constant(value), targetTypeName, metadata);
+ value = Evaluator.evaluate(expr);
+ } catch (ExpressionEvaluationException e) {
+ String msg = QueryPlugin.Util.getString("QueryUtil.Error_executing_conversion_function_to_convert_value", new Integer(i + 1), value, DataTypeManager.getDataTypeName(param.getType())); //$NON-NLS-1$
+ throw new QueryResolverException(msg);
+ } catch (QueryResolverException e) {
+ String msg = QueryPlugin.Util.getString("QueryUtil.Error_executing_conversion_function_to_convert_value", new Integer(i + 1), value, DataTypeManager.getDataTypeName(param.getType())); //$NON-NLS-1$
+ throw new QueryResolverException(msg);
+ }
+ }
+
+ if (param.getConstraint() != null) {
+ param.getConstraint().validate(value);
+ }
+ //bind variable
+ result.setGlobalValue(param.getContextSymbol(), value);
+ }
+
+ context.setVariableContext(result);
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,470 +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 java.sql.Connection;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-
-import org.teiid.adminapi.impl.VDBMetaData;
-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.api.exception.query.QueryValidatorException;
-import org.teiid.client.RequestMessage;
-import org.teiid.client.RequestMessage.ResultsMode;
-import org.teiid.client.RequestMessage.ShowPlan;
-import org.teiid.client.xa.XATransactionException;
-import org.teiid.common.buffer.BufferManager;
-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;
-import org.teiid.dqp.internal.process.multisource.MultiSourceCapabilitiesFinder;
-import org.teiid.dqp.internal.process.multisource.MultiSourceMetadataWrapper;
-import org.teiid.dqp.internal.process.multisource.MultiSourcePlanToProcessConverter;
-import org.teiid.dqp.message.RequestID;
-import org.teiid.dqp.service.TransactionContext;
-import org.teiid.dqp.service.TransactionService;
-import org.teiid.dqp.service.TransactionContext.Scope;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.logging.MessageLevel;
-import org.teiid.metadata.FunctionMethod.Determinism;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.eval.SecurityFunctionEvaluator;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempCapabilitiesFinder;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.optimizer.QueryOptimizer;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.parser.ParseInfo;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.QueryProcessor;
-import org.teiid.query.processor.xml.XMLPlan;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.rewriter.QueryRewriter;
-import org.teiid.query.sql.lang.BatchedUpdateCommand;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.Limit;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-import org.teiid.query.sql.visitor.ReferenceCollectorVisitor;
-import org.teiid.query.tempdata.TempTableStore;
-import org.teiid.query.util.CommandContext;
-import org.teiid.query.util.ContextProperties;
-import org.teiid.query.validator.AbstractValidationVisitor;
-import org.teiid.query.validator.ValidationVisitor;
-import org.teiid.query.validator.Validator;
-import org.teiid.query.validator.ValidatorFailure;
-import org.teiid.query.validator.ValidatorReport;
-
-
-/**
- * Server side representation of the RequestMessage. Knows how to process itself.
- */
-public class Request implements SecurityFunctionEvaluator {
-
- // init state
- protected RequestMessage requestMsg;
- private String vdbName;
- private int vdbVersion;
- private BufferManager bufferManager;
- private ProcessorDataManager processorDataManager;
- private TransactionService transactionService;
- private TempTableStore tempTableStore;
- protected IDGenerator idGenerator = new IDGenerator();
- DQPWorkContext workContext;
- RequestID requestId;
-
- // acquired state
- protected CapabilitiesFinder capabilitiesFinder;
- protected QueryMetadataInterface metadata;
- private Set<String> multiSourceModels;
-
- // internal results
- protected boolean addedLimit;
- protected ProcessorPlan processPlan;
- // external results
- protected AnalysisRecord analysisRecord;
- protected CommandContext context;
- protected QueryProcessor processor;
-
- protected TransactionContext transactionContext;
- protected ConnectorManagerRepository connectorManagerRepo;
-
- protected Command userCommand;
- protected boolean returnsUpdateCount;
- private TempTableStore globalTables;
- private SessionAwareCache<PreparedPlan> planCache;
- private boolean resultSetCacheEnabled = true;
- private int userRequestConcurrency;
- private AuthorizationValidator authorizationValidator;
-
- void initialize(RequestMessage requestMsg,
- BufferManager bufferManager,
- ProcessorDataManager processorDataManager,
- TransactionService transactionService,
- TempTableStore tempTableStore,
- DQPWorkContext workContext,
- SessionAwareCache<PreparedPlan> planCache) {
-
- this.requestMsg = requestMsg;
- this.vdbName = workContext.getVdbName();
- this.vdbVersion = workContext.getVdbVersion();
- this.bufferManager = bufferManager;
- 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);
- this.planCache = planCache;
- }
-
- void setMetadata(CapabilitiesFinder capabilitiesFinder, QueryMetadataInterface metadata, Set multiSourceModels) {
- this.capabilitiesFinder = capabilitiesFinder;
- this.metadata = metadata;
- this.multiSourceModels = multiSourceModels;
- }
-
- public void setResultSetCacheEnabled(boolean resultSetCacheEnabled) {
- this.resultSetCacheEnabled = resultSetCacheEnabled;
- }
-
- public void setAuthorizationValidator(
- AuthorizationValidator authorizationValidator) {
- this.authorizationValidator = authorizationValidator;
- }
-
- /**
- * if the metadata has not been supplied via setMetadata, this method will create the appropriate state
- *
- * @throws TeiidComponentException
- */
- protected void initMetadata() throws TeiidComponentException {
- if (this.metadata != null) {
- return;
- }
- // Prepare dependencies for running the optimizer
- this.capabilitiesFinder = new CachedFinder(this.connectorManagerRepo, workContext.getVDB());
- this.capabilitiesFinder = new TempCapabilitiesFinder(this.capabilitiesFinder);
-
- VDBMetaData vdbMetadata = workContext.getVDB();
- metadata = vdbMetadata.getAttachment(QueryMetadataInterface.class);
- globalTables = vdbMetadata.getAttachment(TempTableStore.class);
-
- if (metadata == null) {
- throw new TeiidComponentException(QueryPlugin.Util.getString("DQPCore.Unable_to_load_metadata_for_VDB_name__{0},_version__{1}", this.vdbName, this.vdbVersion)); //$NON-NLS-1$
- }
-
- // Check for multi-source models and further wrap the metadata interface
- Set<String> multiSourceModelList = workContext.getVDB().getMultiSourceModelNames();
- if(multiSourceModelList != null && multiSourceModelList.size() > 0) {
- this.multiSourceModels = multiSourceModelList;
- this.metadata = new MultiSourceMetadataWrapper(this.metadata, this.multiSourceModels);
- }
-
- TempMetadataAdapter tma = new TempMetadataAdapter(metadata, this.tempTableStore.getMetadataStore());
- tma.setSession(true);
- this.metadata = tma;
- }
-
- protected void createCommandContext() throws QueryValidatorException {
- boolean returnsResultSet = userCommand.returnsResultSet();
- this.returnsUpdateCount = !(userCommand 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$
- }
-
- // Create command context, used in rewriting, planning, and processing
- // Identifies a "group" of requests on a per-connection basis to allow later
- // cleanup of all resources in the group on connection shutdown
- String groupName = workContext.getSessionId();
-
- RequestID reqID = workContext.getRequestID(this.requestMsg.getExecutionId());
-
- Properties props = new Properties();
- props.setProperty(ContextProperties.SESSION_ID, workContext.getSessionId());
-
- this.context =
- new CommandContext(
- reqID,
- groupName,
- workContext.getUserName(),
- requestMsg.getExecutionPayload(),
- workContext.getVdbName(),
- workContext.getVdbVersion(),
- props,
- this.requestMsg.getShowPlan() != ShowPlan.OFF);
- this.context.setProcessorBatchSize(bufferManager.getProcessorBatchSize());
- this.context.setConnectorBatchSize(bufferManager.getConnectorBatchSize());
- this.context.setGlobalTableStore(this.globalTables);
- if (multiSourceModels != null) {
- MultiSourcePlanToProcessConverter modifier = new MultiSourcePlanToProcessConverter(
- metadata, idGenerator, analysisRecord, capabilitiesFinder,
- multiSourceModels, workContext, context);
- context.setPlanToProcessConverter(modifier);
- }
-
- context.setSecurityFunctionEvaluator(this);
- context.setTempTableStore(tempTableStore);
- context.setQueryProcessorFactory(new QueryProcessorFactoryImpl(this.bufferManager, this.processorDataManager, this.capabilitiesFinder, idGenerator, metadata));
- context.setMetadata(this.metadata);
- context.setBufferManager(this.bufferManager);
- context.setPreparedPlanCache(planCache);
- context.setResultSetCacheEnabled(this.resultSetCacheEnabled);
- context.setUserRequestSourceConcurrency(this.userRequestConcurrency);
- context.setSubject(workContext.getSubject());
- }
-
- @Override
- public boolean hasRole(String roleType, String roleName)
- throws TeiidComponentException {
- if (!DATA_ROLE.equalsIgnoreCase(roleType)) {
- return false;
- }
- return authorizationValidator.hasRole(roleName, workContext);
- }
-
- public void setUserRequestConcurrency(int userRequestConcurrency) {
- this.userRequestConcurrency = userRequestConcurrency;
- }
-
- protected void checkReferences(List<Reference> references) throws QueryValidatorException {
- referenceCheck(references);
- }
-
- static void referenceCheck(List<Reference> references) throws QueryValidatorException {
- if (references != null && !references.isEmpty()) {
- throw new QueryValidatorException(QueryPlugin.Util.getString("Request.Invalid_character_in_query")); //$NON-NLS-1$
- }
- }
-
- protected void resolveCommand(Command command) throws QueryResolverException, TeiidComponentException {
- //ensure that the user command is distinct from the processing command
- //rewrite and planning may alter options, symbols, etc.
- QueryResolver.resolveCommand(command, metadata);
-
- this.userCommand = (Command)command.clone();
- }
-
- private void validateQuery(Command command)
- throws QueryValidatorException, TeiidComponentException {
-
- // Create generic sql validation visitor
- AbstractValidationVisitor visitor = new ValidationVisitor();
- validateWithVisitor(visitor, metadata, command);
- }
-
- private Command parseCommand() throws QueryParserException {
- String[] commands = requestMsg.getCommands();
- ParseInfo parseInfo = createParseInfo(this.requestMsg);
- if (requestMsg.isPreparedStatement() || requestMsg.isCallableStatement() || !requestMsg.isBatchedUpdate()) {
- String commandStr = commands[0];
- return QueryParser.getQueryParser().parseCommand(commandStr, parseInfo);
- }
- List<Command> parsedCommands = new ArrayList<Command>(commands.length);
- for (int i = 0; i < commands.length; i++) {
- String updateCommand = commands[i];
- parsedCommands.add(QueryParser.getQueryParser().parseCommand(updateCommand, parseInfo));
- }
- return new BatchedUpdateCommand(parsedCommands);
- }
-
- public static ParseInfo createParseInfo(RequestMessage requestMsg) {
- ParseInfo parseInfo = new ParseInfo();
- parseInfo.ansiQuotedIdentifiers = requestMsg.isAnsiQuotedIdentifiers();
- return parseInfo;
- }
-
- public static void validateWithVisitor(
- AbstractValidationVisitor visitor,
- QueryMetadataInterface metadata,
- Command command)
- throws QueryValidatorException, TeiidComponentException {
-
- // Validate with visitor
- ValidatorReport report = Validator.validate(command, metadata, visitor);
- if (report.hasItems()) {
- ValidatorFailure firstFailure = report.getItems().iterator().next();
- throw new QueryValidatorException(firstFailure.getMessage());
- }
- }
-
- private void createProcessor() throws TeiidComponentException {
-
- TransactionContext tc = transactionService.getOrCreateTransactionContext(workContext.getSessionId());
-
- Assertion.assertTrue(tc.getTransactionType() != TransactionContext.Scope.REQUEST, "Transaction already associated with request."); //$NON-NLS-1$
-
- // If local or global transaction is not started.
- if (tc.getTransactionType() == Scope.NONE) {
-
- boolean startAutoWrapTxn = false;
-
- if(RequestMessage.TXN_WRAP_ON.equals(requestMsg.getTxnAutoWrapMode())){
- startAutoWrapTxn = true;
- } else if (RequestMessage.TXN_WRAP_DETECT.equals(requestMsg.getTxnAutoWrapMode())){
- boolean transactionalRead = requestMsg.getTransactionIsolation() == Connection.TRANSACTION_REPEATABLE_READ
- || requestMsg.getTransactionIsolation() == Connection.TRANSACTION_SERIALIZABLE;
- startAutoWrapTxn = processPlan.requiresTransaction(transactionalRead);
- }
-
- if (startAutoWrapTxn) {
- try {
- tc = transactionService.begin(tc);
- } catch (XATransactionException err) {
- throw new TeiidComponentException(err);
- }
- }
- }
-
- this.transactionContext = tc;
- this.processor = new QueryProcessor(processPlan, context, bufferManager, processorDataManager);
- }
-
- /**
- * state side effects:
- * creates the analysis record
- * creates the command context
- * sets the pre-rewrite command on the request
- * adds a limit clause if the row limit is specified
- * sets the processor plan
- *
- * @throws TeiidComponentException
- * @throws TeiidProcessingException
- */
- protected void generatePlan() throws TeiidComponentException, TeiidProcessingException {
- Command command = parseCommand();
-
- List<Reference> references = ReferenceCollectorVisitor.getReferences(command);
-
- checkReferences(references);
-
- 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()) {
- this.context.setDeterminismLevel(Determinism.SESSION_DETERMINISTIC);
- break;
- }
- }
-
- validateQuery(command);
-
- command = QueryRewriter.rewrite(command, metadata, context);
-
- /*
- * Adds a row limit to a query if Statement.setMaxRows has been called and the command
- * doesn't already have a limit clause.
- */
- if (requestMsg.getRowLimit() > 0 && command instanceof QueryCommand) {
- QueryCommand query = (QueryCommand)command;
- if (query.getLimit() == null) {
- query.setLimit(new Limit(null, new Constant(new Integer(requestMsg.getRowLimit()), DataTypeManager.DefaultDataClasses.INTEGER)));
- this.addedLimit = true;
- }
- }
-
- try {
- // If using multi-source models, insert a proxy to simplify the supported capabilities. This is
- // done OUTSIDE the cache (wrapped around the cache) intentionally to avoid caching the simplified
- // capabilities which may be different for the same model in a different VDB used by this same DQP.
- CapabilitiesFinder finder = this.capabilitiesFinder;
- if(this.multiSourceModels != null) {
- finder = new MultiSourceCapabilitiesFinder(finder, this.multiSourceModels);
- }
-
- boolean debug = analysisRecord.recordDebug();
- if(debug) {
- analysisRecord.println("\n============================================================================"); //$NON-NLS-1$
- analysisRecord.println("USER COMMAND:\n" + command); //$NON-NLS-1$
- }
- // Run the optimizer
- try {
- processPlan = QueryOptimizer.optimizePlan(command, metadata, idGenerator, finder, analysisRecord, context);
- } finally {
- String debugLog = analysisRecord.getDebugLog();
- if(debugLog != null && debugLog.length() > 0) {
- LogManager.log(requestMsg.getShowPlan()==ShowPlan.DEBUG?MessageLevel.INFO:MessageLevel.TRACE, LogConstants.CTX_QUERY_PLANNER, debugLog);
- }
- if (analysisRecord.recordAnnotations() && analysisRecord.getAnnotations() != null && !analysisRecord.getAnnotations().isEmpty()) {
- LogManager.logDetail(LogConstants.CTX_QUERY_PLANNER, analysisRecord.getAnnotations());
- }
- }
- LogManager.logDetail(LogConstants.CTX_DQP, new Object[] { QueryPlugin.Util.getString("BasicInterceptor.ProcessTree_for__4"), requestId, processPlan }); //$NON-NLS-1$
- } catch (QueryMetadataException e) {
- throw new QueryPlannerException(e, QueryPlugin.Util.getString("DQPCore.Unknown_query_metadata_exception_while_registering_query__{0}.", requestId)); //$NON-NLS-1$
- }
- }
-
- public void processRequest()
- throws TeiidComponentException, TeiidProcessingException {
-
- LogManager.logDetail(LogConstants.CTX_DQP, this.requestId, "executing", this.requestMsg.isPreparedStatement()?"prepared":"", this.requestMsg.getCommandString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- initMetadata();
-
- generatePlan();
-
- postProcessXML();
-
- createProcessor();
- }
-
- private void postProcessXML() {
- if (requestMsg.getXMLFormat() != null && processPlan instanceof XMLPlan) {
- ((XMLPlan)processPlan).setXMLFormat(requestMsg.getXMLFormat());
- }
- this.context.setValidateXML(requestMsg.getValidationMode());
- }
-
- protected void validateAccess(Command command) throws QueryValidatorException, TeiidComponentException {
- this.authorizationValidator.validate(command, metadata, workContext);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,471 @@
+/*
+ * 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 java.sql.Connection;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+
+import org.teiid.adminapi.impl.VDBMetaData;
+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.api.exception.query.QueryValidatorException;
+import org.teiid.client.RequestMessage;
+import org.teiid.client.RequestMessage.ResultsMode;
+import org.teiid.client.RequestMessage.ShowPlan;
+import org.teiid.client.xa.XATransactionException;
+import org.teiid.common.buffer.BufferManager;
+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;
+import org.teiid.dqp.internal.process.multisource.MultiSourceCapabilitiesFinder;
+import org.teiid.dqp.internal.process.multisource.MultiSourceMetadataWrapper;
+import org.teiid.dqp.internal.process.multisource.MultiSourcePlanToProcessConverter;
+import org.teiid.dqp.message.RequestID;
+import org.teiid.dqp.service.TransactionContext;
+import org.teiid.dqp.service.TransactionService;
+import org.teiid.dqp.service.TransactionContext.Scope;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+import org.teiid.metadata.FunctionMethod.Determinism;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.eval.SecurityFunctionEvaluator;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempCapabilitiesFinder;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.optimizer.QueryOptimizer;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.parser.ParseInfo;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.QueryProcessor;
+import org.teiid.query.processor.xml.XMLPlan;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.lang.BatchedUpdateCommand;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.Limit;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.visitor.GroupCollectorVisitor;
+import org.teiid.query.sql.visitor.ReferenceCollectorVisitor;
+import org.teiid.query.tempdata.TempTableStore;
+import org.teiid.query.util.CommandContext;
+import org.teiid.query.util.ContextProperties;
+import org.teiid.query.validator.AbstractValidationVisitor;
+import org.teiid.query.validator.ValidationVisitor;
+import org.teiid.query.validator.Validator;
+import org.teiid.query.validator.ValidatorFailure;
+import org.teiid.query.validator.ValidatorReport;
+
+
+/**
+ * Server side representation of the RequestMessage. Knows how to process itself.
+ */
+public class Request implements SecurityFunctionEvaluator {
+
+ // init state
+ protected RequestMessage requestMsg;
+ private String vdbName;
+ private int vdbVersion;
+ private BufferManager bufferManager;
+ private ProcessorDataManager processorDataManager;
+ private TransactionService transactionService;
+ private TempTableStore tempTableStore;
+ protected IDGenerator idGenerator = new IDGenerator();
+ DQPWorkContext workContext;
+ RequestID requestId;
+
+ // acquired state
+ protected CapabilitiesFinder capabilitiesFinder;
+ protected QueryMetadataInterface metadata;
+ private Set<String> multiSourceModels;
+
+ // internal results
+ protected boolean addedLimit;
+ protected ProcessorPlan processPlan;
+ // external results
+ protected AnalysisRecord analysisRecord;
+ protected CommandContext context;
+ protected QueryProcessor processor;
+
+ protected TransactionContext transactionContext;
+ protected ConnectorManagerRepository connectorManagerRepo;
+
+ protected Command userCommand;
+ protected boolean returnsUpdateCount;
+ private TempTableStore globalTables;
+ private SessionAwareCache<PreparedPlan> planCache;
+ private boolean resultSetCacheEnabled = true;
+ private int userRequestConcurrency;
+ private AuthorizationValidator authorizationValidator;
+
+ void initialize(RequestMessage requestMsg,
+ BufferManager bufferManager,
+ ProcessorDataManager processorDataManager,
+ TransactionService transactionService,
+ TempTableStore tempTableStore,
+ DQPWorkContext workContext,
+ SessionAwareCache<PreparedPlan> planCache) {
+
+ this.requestMsg = requestMsg;
+ this.vdbName = workContext.getVdbName();
+ this.vdbVersion = workContext.getVdbVersion();
+ this.bufferManager = bufferManager;
+ 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);
+ this.planCache = planCache;
+ }
+
+ void setMetadata(CapabilitiesFinder capabilitiesFinder, QueryMetadataInterface metadata, Set multiSourceModels) {
+ this.capabilitiesFinder = capabilitiesFinder;
+ this.metadata = metadata;
+ this.multiSourceModels = multiSourceModels;
+ }
+
+ public void setResultSetCacheEnabled(boolean resultSetCacheEnabled) {
+ this.resultSetCacheEnabled = resultSetCacheEnabled;
+ }
+
+ public void setAuthorizationValidator(
+ AuthorizationValidator authorizationValidator) {
+ this.authorizationValidator = authorizationValidator;
+ }
+
+ /**
+ * if the metadata has not been supplied via setMetadata, this method will create the appropriate state
+ *
+ * @throws TeiidComponentException
+ */
+ protected void initMetadata() throws TeiidComponentException {
+ if (this.metadata != null) {
+ return;
+ }
+ // Prepare dependencies for running the optimizer
+ this.capabilitiesFinder = new CachedFinder(this.connectorManagerRepo, workContext.getVDB());
+ this.capabilitiesFinder = new TempCapabilitiesFinder(this.capabilitiesFinder);
+
+ VDBMetaData vdbMetadata = workContext.getVDB();
+ metadata = vdbMetadata.getAttachment(QueryMetadataInterface.class);
+ globalTables = vdbMetadata.getAttachment(TempTableStore.class);
+
+ if (metadata == null) {
+ throw new TeiidComponentException(QueryPlugin.Util.getString("DQPCore.Unable_to_load_metadata_for_VDB_name__{0},_version__{1}", this.vdbName, this.vdbVersion)); //$NON-NLS-1$
+ }
+
+ // Check for multi-source models and further wrap the metadata interface
+ Set<String> multiSourceModelList = workContext.getVDB().getMultiSourceModelNames();
+ if(multiSourceModelList != null && multiSourceModelList.size() > 0) {
+ this.multiSourceModels = multiSourceModelList;
+ this.metadata = new MultiSourceMetadataWrapper(this.metadata, this.multiSourceModels);
+ }
+
+ TempMetadataAdapter tma = new TempMetadataAdapter(metadata, this.tempTableStore.getMetadataStore());
+ tma.setSession(true);
+ this.metadata = tma;
+ }
+
+ 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$
+ }
+
+ // Create command context, used in rewriting, planning, and processing
+ // Identifies a "group" of requests on a per-connection basis to allow later
+ // cleanup of all resources in the group on connection shutdown
+ String groupName = workContext.getSessionId();
+
+ RequestID reqID = workContext.getRequestID(this.requestMsg.getExecutionId());
+
+ Properties props = new Properties();
+ props.setProperty(ContextProperties.SESSION_ID, workContext.getSessionId());
+
+ this.context =
+ new CommandContext(
+ reqID,
+ groupName,
+ workContext.getUserName(),
+ requestMsg.getExecutionPayload(),
+ workContext.getVdbName(),
+ workContext.getVdbVersion(),
+ props,
+ this.requestMsg.getShowPlan() != ShowPlan.OFF);
+ this.context.setProcessorBatchSize(bufferManager.getProcessorBatchSize());
+ this.context.setConnectorBatchSize(bufferManager.getConnectorBatchSize());
+ this.context.setGlobalTableStore(this.globalTables);
+ if (multiSourceModels != null) {
+ MultiSourcePlanToProcessConverter modifier = new MultiSourcePlanToProcessConverter(
+ metadata, idGenerator, analysisRecord, capabilitiesFinder,
+ multiSourceModels, workContext, context);
+ context.setPlanToProcessConverter(modifier);
+ }
+
+ context.setSecurityFunctionEvaluator(this);
+ context.setTempTableStore(tempTableStore);
+ context.setQueryProcessorFactory(new QueryProcessorFactoryImpl(this.bufferManager, this.processorDataManager, this.capabilitiesFinder, idGenerator, metadata));
+ context.setMetadata(this.metadata);
+ context.setBufferManager(this.bufferManager);
+ context.setPreparedPlanCache(planCache);
+ context.setResultSetCacheEnabled(this.resultSetCacheEnabled);
+ context.setUserRequestSourceConcurrency(this.userRequestConcurrency);
+ context.setSubject(workContext.getSubject());
+ this.context.setSession(workContext.getSession());
+ this.context.setRequestId(this.requestId);
+ }
+
+ @Override
+ public boolean hasRole(String roleType, String roleName)
+ throws TeiidComponentException {
+ if (!DATA_ROLE.equalsIgnoreCase(roleType)) {
+ return false;
+ }
+ return authorizationValidator.hasRole(roleName, workContext);
+ }
+
+ public void setUserRequestConcurrency(int userRequestConcurrency) {
+ this.userRequestConcurrency = userRequestConcurrency;
+ }
+
+ protected void checkReferences(List<Reference> references) throws QueryValidatorException {
+ referenceCheck(references);
+ }
+
+ static void referenceCheck(List<Reference> references) throws QueryValidatorException {
+ if (references != null && !references.isEmpty()) {
+ throw new QueryValidatorException(QueryPlugin.Util.getString("Request.Invalid_character_in_query")); //$NON-NLS-1$
+ }
+ }
+
+ protected void resolveCommand(Command command) throws QueryResolverException, TeiidComponentException {
+ //ensure that the user command is distinct from the processing command
+ //rewrite and planning may alter options, symbols, etc.
+ QueryResolver.resolveCommand(command, metadata);
+
+ this.userCommand = (Command)command.clone();
+ }
+
+ private void validateQuery(Command command)
+ throws QueryValidatorException, TeiidComponentException {
+
+ // Create generic sql validation visitor
+ AbstractValidationVisitor visitor = new ValidationVisitor();
+ validateWithVisitor(visitor, metadata, command);
+ }
+
+ private Command parseCommand() throws QueryParserException {
+ String[] commands = requestMsg.getCommands();
+ ParseInfo parseInfo = createParseInfo(this.requestMsg);
+ if (requestMsg.isPreparedStatement() || requestMsg.isCallableStatement() || !requestMsg.isBatchedUpdate()) {
+ String commandStr = commands[0];
+ return QueryParser.getQueryParser().parseCommand(commandStr, parseInfo);
+ }
+ List<Command> parsedCommands = new ArrayList<Command>(commands.length);
+ for (int i = 0; i < commands.length; i++) {
+ String updateCommand = commands[i];
+ parsedCommands.add(QueryParser.getQueryParser().parseCommand(updateCommand, parseInfo));
+ }
+ return new BatchedUpdateCommand(parsedCommands);
+ }
+
+ public static ParseInfo createParseInfo(RequestMessage requestMsg) {
+ ParseInfo parseInfo = new ParseInfo();
+ parseInfo.ansiQuotedIdentifiers = requestMsg.isAnsiQuotedIdentifiers();
+ return parseInfo;
+ }
+
+ public static void validateWithVisitor(
+ AbstractValidationVisitor visitor,
+ QueryMetadataInterface metadata,
+ Command command)
+ throws QueryValidatorException, TeiidComponentException {
+
+ // Validate with visitor
+ ValidatorReport report = Validator.validate(command, metadata, visitor);
+ if (report.hasItems()) {
+ ValidatorFailure firstFailure = report.getItems().iterator().next();
+ throw new QueryValidatorException(firstFailure.getMessage());
+ }
+ }
+
+ private void createProcessor() throws TeiidComponentException {
+
+ TransactionContext tc = transactionService.getOrCreateTransactionContext(workContext.getSessionId());
+
+ Assertion.assertTrue(tc.getTransactionType() != TransactionContext.Scope.REQUEST, "Transaction already associated with request."); //$NON-NLS-1$
+
+ // If local or global transaction is not started.
+ if (tc.getTransactionType() == Scope.NONE) {
+
+ boolean startAutoWrapTxn = false;
+
+ if(RequestMessage.TXN_WRAP_ON.equals(requestMsg.getTxnAutoWrapMode())){
+ startAutoWrapTxn = true;
+ } else if (RequestMessage.TXN_WRAP_DETECT.equals(requestMsg.getTxnAutoWrapMode())){
+ boolean transactionalRead = requestMsg.getTransactionIsolation() == Connection.TRANSACTION_REPEATABLE_READ
+ || requestMsg.getTransactionIsolation() == Connection.TRANSACTION_SERIALIZABLE;
+ startAutoWrapTxn = processPlan.requiresTransaction(transactionalRead);
+ }
+
+ if (startAutoWrapTxn) {
+ try {
+ tc = transactionService.begin(tc);
+ } catch (XATransactionException err) {
+ throw new TeiidComponentException(err);
+ }
+ }
+ }
+
+ this.transactionContext = tc;
+ this.processor = new QueryProcessor(processPlan, context, bufferManager, processorDataManager);
+ }
+
+ /**
+ * state side effects:
+ * creates the analysis record
+ * creates the command context
+ * sets the pre-rewrite command on the request
+ * adds a limit clause if the row limit is specified
+ * sets the processor plan
+ *
+ * @throws TeiidComponentException
+ * @throws TeiidProcessingException
+ */
+ protected void generatePlan() throws TeiidComponentException, TeiidProcessingException {
+ Command command = parseCommand();
+
+ List<Reference> references = ReferenceCollectorVisitor.getReferences(command);
+
+ checkReferences(references);
+
+ this.analysisRecord = new AnalysisRecord(requestMsg.getShowPlan() != ShowPlan.OFF, requestMsg.getShowPlan() == ShowPlan.DEBUG);
+
+ resolveCommand(command);
+
+ validateAccess(userCommand);
+
+ Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(command, true);
+ for (GroupSymbol groupSymbol : groups) {
+ if (groupSymbol.isTempTable()) {
+ this.context.setDeterminismLevel(Determinism.SESSION_DETERMINISTIC);
+ break;
+ }
+ }
+
+ validateQuery(command);
+
+ command = QueryRewriter.rewrite(command, metadata, context);
+
+ /*
+ * Adds a row limit to a query if Statement.setMaxRows has been called and the command
+ * doesn't already have a limit clause.
+ */
+ if (requestMsg.getRowLimit() > 0 && command instanceof QueryCommand) {
+ QueryCommand query = (QueryCommand)command;
+ if (query.getLimit() == null) {
+ query.setLimit(new Limit(null, new Constant(new Integer(requestMsg.getRowLimit()), DataTypeManager.DefaultDataClasses.INTEGER)));
+ this.addedLimit = true;
+ }
+ }
+
+ try {
+ // If using multi-source models, insert a proxy to simplify the supported capabilities. This is
+ // done OUTSIDE the cache (wrapped around the cache) intentionally to avoid caching the simplified
+ // capabilities which may be different for the same model in a different VDB used by this same DQP.
+ CapabilitiesFinder finder = this.capabilitiesFinder;
+ if(this.multiSourceModels != null) {
+ finder = new MultiSourceCapabilitiesFinder(finder, this.multiSourceModels);
+ }
+
+ boolean debug = analysisRecord.recordDebug();
+ if(debug) {
+ analysisRecord.println("\n============================================================================"); //$NON-NLS-1$
+ analysisRecord.println("USER COMMAND:\n" + command); //$NON-NLS-1$
+ }
+ // Run the optimizer
+ try {
+ processPlan = QueryOptimizer.optimizePlan(command, metadata, idGenerator, finder, analysisRecord, context);
+ } finally {
+ String debugLog = analysisRecord.getDebugLog();
+ if(debugLog != null && debugLog.length() > 0) {
+ LogManager.log(requestMsg.getShowPlan()==ShowPlan.DEBUG?MessageLevel.INFO:MessageLevel.TRACE, LogConstants.CTX_QUERY_PLANNER, debugLog);
+ }
+ if (analysisRecord.recordAnnotations() && analysisRecord.getAnnotations() != null && !analysisRecord.getAnnotations().isEmpty()) {
+ LogManager.logDetail(LogConstants.CTX_QUERY_PLANNER, analysisRecord.getAnnotations());
+ }
+ }
+ LogManager.logDetail(LogConstants.CTX_DQP, new Object[] { QueryPlugin.Util.getString("BasicInterceptor.ProcessTree_for__4"), requestId, processPlan }); //$NON-NLS-1$
+ } catch (QueryMetadataException e) {
+ throw new QueryPlannerException(e, QueryPlugin.Util.getString("DQPCore.Unknown_query_metadata_exception_while_registering_query__{0}.", requestId)); //$NON-NLS-1$
+ }
+ }
+
+ public void processRequest()
+ throws TeiidComponentException, TeiidProcessingException {
+
+ LogManager.logDetail(LogConstants.CTX_DQP, this.requestId, "executing", this.requestMsg.isPreparedStatement()?"prepared":"", this.requestMsg.getCommandString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ initMetadata();
+
+ generatePlan();
+
+ postProcessXML();
+
+ createProcessor();
+ }
+
+ private void postProcessXML() {
+ if (requestMsg.getXMLFormat() != null && processPlan instanceof XMLPlan) {
+ ((XMLPlan)processPlan).setXMLFormat(requestMsg.getXMLFormat());
+ }
+ this.context.setValidateXML(requestMsg.getValidationMode());
+ }
+
+ protected void validateAccess(Command command) throws QueryValidatorException, TeiidComponentException {
+ createCommandContext(command);
+ this.authorizationValidator.validate(command, metadata, workContext, context);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,861 +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 java.sql.ResultSet;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.teiid.client.RequestMessage;
-import org.teiid.client.ResultsMessage;
-import org.teiid.client.SourceWarning;
-import org.teiid.client.RequestMessage.ShowPlan;
-import org.teiid.client.lob.LobChunk;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.client.util.ResultsReceiver;
-import org.teiid.client.xa.XATransactionException;
-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.dqp.internal.process.DQPCore.CompletionListener;
-import org.teiid.dqp.internal.process.DQPCore.FutureWork;
-import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
-import org.teiid.dqp.internal.process.ThreadReuseExecutor.PrioritizedRunnable;
-import org.teiid.dqp.message.AtomicRequestID;
-import org.teiid.dqp.message.RequestID;
-import org.teiid.dqp.service.TransactionContext;
-import org.teiid.dqp.service.TransactionService;
-import org.teiid.dqp.service.TransactionContext.Scope;
-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.FunctionMethod.Determinism;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.parser.ParseInfo;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.BatchCollector;
-import org.teiid.query.processor.QueryProcessor;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-
-public class RequestWorkItem extends AbstractWorkItem implements PrioritizedRunnable {
-
- private final class WorkWrapper<T> implements
- DQPCore.CompletionListener<T> {
-
- boolean submitted;
- FutureWork<T> work;
-
- public WorkWrapper(FutureWork<T> work) {
- this.work = work;
- }
-
- @Override
- public void onCompletion(FutureWork<T> future) {
- WorkWrapper<?> nextWork = null;
- synchronized (queue) {
- if (!submitted) {
- return;
- }
- nextWork = queue.pollFirst();
- if (nextWork == null) {
- totalThreads--;
- } else {
- nextWork.submitted = true;
- }
- }
- if (nextWork != null) {
- dqpCore.addWork(nextWork.work);
- }
- }
- }
-
- private enum ProcessingState {NEW, PROCESSING, CLOSE}
- private ProcessingState state = ProcessingState.NEW;
-
- private enum TransactionState {NONE, ACTIVE, DONE}
- private TransactionState transactionState = TransactionState.NONE;
-
- private int totalThreads;
- private LinkedList<WorkWrapper<?>> queue = new LinkedList<WorkWrapper<?>>();
-
- /*
- * Obtained at construction time
- */
- protected final DQPCore dqpCore;
- final RequestMessage requestMsg;
- final RequestID requestID;
- private Request request; //provides the processing plan, held on a temporary basis
- private final int processorTimeslice;
- private CacheID cid;
- private final TransactionService transactionService;
- private final DQPWorkContext dqpWorkContext;
- boolean active;
-
- /*
- * obtained during new
- */
- private volatile QueryProcessor processor;
- private BatchCollector collector;
- private Command originalCommand;
- private AnalysisRecord analysisRecord;
- private TransactionContext transactionContext;
- TupleBuffer resultsBuffer;
- private boolean returnsUpdateCount;
-
- /*
- * maintained during processing
- */
- private Throwable processingException;
- private Map<AtomicRequestID, DataTierTupleSource> connectorInfo = new ConcurrentHashMap<AtomicRequestID, DataTierTupleSource>(4);
- // This exception contains details of all the atomic requests that failed when query is run in partial results mode.
- private List<TeiidException> warnings = new LinkedList<TeiidException>();
- private volatile boolean doneProducingBatches;
- private volatile boolean isClosed;
- private volatile boolean isCanceled;
- private volatile boolean closeRequested;
-
- //results request
- private ResultsReceiver<ResultsMessage> resultsReceiver;
- private int begin;
- private int end;
- private TupleBatch savedBatch;
- private Map<Integer, LobWorkItem> lobStreams = new ConcurrentHashMap<Integer, LobWorkItem>(4);
-
- /**The time when command begins processing on the server.*/
- private long processingTimestamp = System.currentTimeMillis();
-
- 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();
- this.transactionService = dqpCore.getTransactionService();
- this.dqpCore = dqpCore;
- this.request = request;
- this.dqpWorkContext = workContext;
- this.requestResults(1, requestMsg.getFetchSize(), receiver);
- }
-
- private boolean isForwardOnly() {
- return this.cid == null && requestMsg.getCursorType() == ResultSet.TYPE_FORWARD_ONLY;
- }
-
- /**
- * Ask for results.
- * @param beginRow
- * @param endRow
- */
- synchronized void requestResults(int beginRow, int endRow, ResultsReceiver<ResultsMessage> receiver) {
- if (this.resultsReceiver != null) {
- throw new IllegalStateException("Results already requested"); //$NON-NLS-1$\
- }
- this.resultsReceiver = receiver;
- this.begin = beginRow;
- this.end = endRow;
- }
-
- @Override
- protected boolean isDoneProcessing() {
- return isClosed;
- }
-
- @Override
- protected void resumeProcessing() {
- if (doneProducingBatches && !closeRequested && !isCanceled) {
- this.run(); // just run in the IO thread
- } else {
- dqpCore.addWork(this);
- }
- }
-
- @Override
- protected void interrupted(InterruptedException e) {
- try {
- this.requestCancel();
- } catch (TeiidComponentException e1) {
- throw new TeiidRuntimeException(e1);
- }
- super.interrupted(e);
- }
-
- @Override
- protected void process() {
- LogManager.logDetail(LogConstants.CTX_DQP, "Request Thread", requestID, "with state", state); //$NON-NLS-1$ //$NON-NLS-2$
- try {
- if (this.state == ProcessingState.NEW) {
- state = ProcessingState.PROCESSING;
- processNew();
- if (isCanceled) {
- this.processingException = new TeiidProcessingException(QueryPlugin.Util.getString("QueryProcessor.request_cancelled", this.requestID)); //$NON-NLS-1$
- state = ProcessingState.CLOSE;
- }
- }
-
- resume();
-
- if (this.state == ProcessingState.PROCESSING) {
- processMore();
- if (this.closeRequested) {
- this.state = ProcessingState.CLOSE;
- }
- }
- } catch (BlockedException e) {
- LogManager.logDetail(LogConstants.CTX_DQP, "Request Thread", requestID, "- processor blocked"); //$NON-NLS-1$ //$NON-NLS-2$
- } catch (QueryProcessor.ExpiredTimeSliceException e) {
- LogManager.logDetail(LogConstants.CTX_DQP, "Request Thread", requestID, "- time slice expired"); //$NON-NLS-1$ //$NON-NLS-2$
- this.moreWork();
- } catch (Throwable e) {
- LogManager.logDetail(LogConstants.CTX_DQP, e, "Request Thread", requestID, "- error occurred"); //$NON-NLS-1$ //$NON-NLS-2$
-
- if (!isCanceled()) {
- dqpCore.logMMCommand(this, Event.ERROR, null);
- //Case 5558: Differentiate between system level errors and
- //processing errors. Only log system level errors as errors,
- //log the processing errors as warnings only
- if(e instanceof TeiidProcessingException) {
- Throwable cause = e;
- while (cause.getCause() != null && cause.getCause() != cause) {
- cause = cause.getCause();
- }
- StackTraceElement[] elems = cause.getStackTrace();
- Object elem = null;
- if (elems.length > 0) {
- elem = cause.getStackTrace()[0];
- } else {
- elem = cause.getMessage();
- }
- LogManager.logWarning(LogConstants.CTX_DQP, QueryPlugin.Util.getString("ProcessWorker.processing_error", e.getMessage(), requestID, e.getClass().getName(), elem)); //$NON-NLS-1$
- }else {
- LogManager.logError(LogConstants.CTX_DQP, e, QueryPlugin.Util.getString("ProcessWorker.error", requestID)); //$NON-NLS-1$
- }
- }
-
- this.processingException = e;
- this.state = ProcessingState.CLOSE;
- } finally {
- if (this.state == ProcessingState.CLOSE && !isClosed) {
- attemptClose();
- } else if (isClosed) {
- /*
- * since there may be a client waiting notify them of a problem
- */
- if (this.processingException == null) {
- this.processingException = new IllegalStateException("Request is already closed"); //$NON-NLS-1$
- }
- sendError();
- }
- suspend();
- }
- }
-
- private void resume() throws XATransactionException {
- if (this.transactionState == TransactionState.ACTIVE && this.transactionContext.getTransaction() != null) {
- this.transactionService.resume(this.transactionContext);
- }
- }
-
- 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$
- }
- }
-
- protected void processMore() throws BlockedException, TeiidException {
- if (!doneProducingBatches) {
- this.processor.getContext().setTimeSliceEnd(System.currentTimeMillis() + this.processorTimeslice);
- sendResultsIfNeeded(null);
- this.resultsBuffer = collector.collectTuples();
- if (!doneProducingBatches) {
- doneProducingBatches();
- addToCache();
- }
- }
- if (this.transactionState == TransactionState.ACTIVE) {
- /*
- * TEIID-14 if we are done producing batches, then proactively close transactional
- * executions even ones that were intentionally kept alive. this may
- * break the read of a lob from a transactional source under a transaction
- * if the source does not support holding the clob open after commit
- */
- for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
- if (connectorRequest.isTransactional()) {
- connectorRequest.fullyCloseSource();
- }
- }
- this.transactionState = TransactionState.DONE;
- if (transactionContext.getTransactionType() == TransactionContext.Scope.REQUEST) {
- this.transactionService.commit(transactionContext);
- } else {
- suspend();
- }
- }
- sendResultsIfNeeded(null);
- }
-
- /**
- * Client close is currently implemented as asynch.
- * Any errors that occur will not make it to the client, instead we just log them here.
- */
- protected void attemptClose() {
- int rowcount = -1;
- if (this.resultsBuffer != null) {
- if (this.processor != null) {
- this.processor.closeProcessing();
-
- if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
- LogManager.logDetail(LogConstants.CTX_DQP, "Removing tuplesource for the request " + requestID); //$NON-NLS-1$
- }
- rowcount = resultsBuffer.getRowCount();
- if (this.cid == null || !this.doneProducingBatches) {
- resultsBuffer.remove();
- } else {
- try {
- this.resultsBuffer.persistLobs();
- } catch (TeiidComponentException e) {
- LogManager.logDetail(LogConstants.CTX_DQP, QueryPlugin.Util.getString("failed_to_cache")); //$NON-NLS-1$
- }
- }
-
- for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
- connectorRequest.fullyCloseSource();
- }
- }
-
- this.resultsBuffer = null;
-
- for (LobWorkItem lobWorkItem : this.lobStreams.values()) {
- lobWorkItem.close();
- }
- }
-
- if (this.transactionState == TransactionState.ACTIVE) {
- this.transactionState = TransactionState.DONE;
- if (transactionContext.getTransactionType() == TransactionContext.Scope.REQUEST) {
- try {
- this.transactionService.rollback(transactionContext);
- } catch (XATransactionException e1) {
- LogManager.logWarning(LogConstants.CTX_DQP, e1, QueryPlugin.Util.getString("ProcessWorker.failed_rollback")); //$NON-NLS-1$
- }
- } else {
- suspend();
- }
- }
-
- isClosed = true;
-
- dqpCore.removeRequest(this);
-
- if (this.processingException != null) {
- sendError();
- } else {
- dqpCore.logMMCommand(this, Event.END, rowcount);
- }
- }
-
- protected void processNew() throws TeiidProcessingException, TeiidComponentException {
- SessionAwareCache<CachedResults> rsCache = dqpCore.getRsCache();
-
- boolean cachable = false;
- CacheID cacheId = null;
- boolean canUseCached = (requestMsg.useResultSetCache() ||
- QueryParser.getQueryParser().parseCacheHint(requestMsg.getCommandString()) != null);
-
- if (rsCache != null) {
- if (!canUseCached) {
- LogManager.logDetail(LogConstants.CTX_DQP, requestID, "No cache directive"); //$NON-NLS-1$
- } else {
- ParseInfo pi = Request.createParseInfo(requestMsg);
- cacheId = new CacheID(this.dqpWorkContext, pi, requestMsg.getCommandString());
- cachable = cacheId.setParameters(requestMsg.getParameterValues());
- if (cachable) {
- 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);
- this.doneProducingBatches();
- return;
- }
- } else {
- LogManager.logDetail(LogConstants.CTX_DQP, requestID, "Parameters are not serializable - cache cannot be used for", cacheId); //$NON-NLS-1$
- }
- }
- }
- request.processRequest();
- originalCommand = request.userCommand;
- if (cachable && (requestMsg.useResultSetCache() || originalCommand.getCacheHint() != null) && rsCache != null && originalCommand.areResultsCachable()) {
- this.cid = cacheId;
- //turn on the collection of data objects used
- request.processor.getContext().setDataObjects(new HashSet<Object>(4));
- }
- processor = request.processor;
- collector = new BatchCollector(processor, processor.getBufferManager(), this.request.context, isForwardOnly()) {
- protected void flushBatchDirect(TupleBatch batch, boolean add) throws TeiidComponentException,TeiidProcessingException {
- resultsBuffer = getTupleBuffer();
- boolean added = false;
- if (cid != null) {
- super.flushBatchDirect(batch, add);
- added = true;
- }
- if (batch.getTerminationFlag()) {
- 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;
- }
- }
- }
- };
- this.resultsBuffer = collector.getTupleBuffer();
- if (this.resultsBuffer == null) {
- //This is just a dummy result it will get replaced by collector source
- resultsBuffer = this.processor.getBufferManager().createTupleBuffer(this.originalCommand.getProjectedSymbols(), this.request.context.getConnectionID(), TupleSourceType.FINAL);
- }
- analysisRecord = request.analysisRecord;
- analysisRecord.setQueryPlan(processor.getProcessorPlan().getDescriptionProperties());
- transactionContext = request.transactionContext;
- if (this.transactionContext != null && this.transactionContext.getTransactionType() != Scope.NONE) {
- this.transactionState = TransactionState.ACTIVE;
- }
- if (requestMsg.isNoExec()) {
- doneProducingBatches();
- resultsBuffer.close();
- this.cid = null;
- }
- this.returnsUpdateCount = request.returnsUpdateCount;
- request = null;
- }
-
- private void addToCache() {
- if (!doneProducingBatches || cid == null) {
- return;
- }
- 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$
- resultsBuffer.setPrefersMemory(originalCommand.getCacheHint().getPrefersMemory());
- if (originalCommand.getCacheHint().getDeterminism() != null) {
- determinismLevel = originalCommand.getCacheHint().getDeterminism();
- LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Cache hint modified the query determinism from ",processor.getContext().getDeterminismLevel(), " to ", determinismLevel }); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- if (determinismLevel.compareTo(Determinism.SESSION_DETERMINISTIC) <= 0) {
- LogManager.logInfo(LogConstants.CTX_DQP, QueryPlugin.Util.getString("RequestWorkItem.cache_nondeterministic", originalCommand)); //$NON-NLS-1$
- }
- dqpCore.getRsCache().put(cid, determinismLevel, cr, originalCommand.getCacheHint() != null?originalCommand.getCacheHint().getTtl():null);
- }
-
- /**
- * Send results if they have been requested. This should only be called from the processing thread.
- */
- protected boolean sendResultsIfNeeded(TupleBatch batch) throws TeiidComponentException {
- ResultsMessage response = null;
- ResultsReceiver<ResultsMessage> receiver = null;
- boolean result = true;
- synchronized (this) {
- if (this.resultsReceiver == null
- || (this.begin > (batch != null?batch.getEndRow():this.resultsBuffer.getRowCount()) && !doneProducingBatches)
- || (this.transactionState == TransactionState.ACTIVE)) {
- return result;
- }
-
- if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
- LogManager.logDetail(LogConstants.CTX_DQP, "[RequestWorkItem.sendResultsIfNeeded] requestID:", requestID, "resultsID:", this.resultsBuffer, "done:", doneProducingBatches ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- //TODO: support fetching more than 1 batch
- boolean fromBuffer = false;
- if (batch == null || !(batch.containsRow(this.begin) || (batch.getTerminationFlag() && batch.getEndRow() <= this.begin))) {
- if (savedBatch != null && savedBatch.containsRow(this.begin)) {
- batch = savedBatch;
- } else {
- batch = resultsBuffer.getBatch(begin);
- }
- savedBatch = null;
- fromBuffer = true;
- }
- int count = this.end - this.begin + 1;
- if (batch.getRowCount() > count) {
- int beginRow = Math.min(this.begin, batch.getEndRow() - count + 1);
- int endRow = Math.min(beginRow + count - 1, batch.getEndRow());
- boolean last = false;
- if (endRow == batch.getEndRow()) {
- last = batch.getTerminationFlag();
- } else if (fromBuffer && isForwardOnly()) {
- savedBatch = batch;
- }
- List<List<?>> memoryRows = batch.getTuples();
- batch = new TupleBatch(beginRow, memoryRows.subList(beginRow - batch.getBeginRow(), endRow - batch.getBeginRow() + 1));
- batch.setTerminationFlag(last);
- } else if (!fromBuffer){
- result = !isForwardOnly();
- }
- int finalRowCount = this.resultsBuffer.isFinal()?this.resultsBuffer.getRowCount():(batch.getTerminationFlag()?batch.getEndRow():-1);
-
- response = createResultsMessage(batch.getAllTuples(), this.originalCommand.getProjectedSymbols());
- response.setFirstRow(batch.getBeginRow());
- response.setLastRow(batch.getEndRow());
- response.setUpdateResult(this.returnsUpdateCount);
- // set final row
- response.setFinalRow(finalRowCount);
-
- // send any warnings with the response object
- List<Throwable> responseWarnings = new ArrayList<Throwable>();
- if (this.processor != null) {
- List<Exception> currentWarnings = processor.getAndClearWarnings();
- if (currentWarnings != null) {
- responseWarnings.addAll(currentWarnings);
- }
- }
- synchronized (warnings) {
- responseWarnings.addAll(this.warnings);
- this.warnings.clear();
- }
- response.setWarnings(responseWarnings);
-
- // If it is stored procedure, set parameters
- if (originalCommand instanceof StoredProcedure) {
- StoredProcedure proc = (StoredProcedure)originalCommand;
- if (proc.returnParameters()) {
- response.setParameters(getParameterInfo(proc));
- }
- }
- /*
- * mark the results sent at this point.
- * communication exceptions will be treated as non-recoverable
- */
- receiver = this.resultsReceiver;
- this.resultsReceiver = null;
- }
- receiver.receiveResults(response);
- return result;
- }
-
- public ResultsMessage createResultsMessage(List[] batch, List columnSymbols) {
- String[] columnNames = new String[columnSymbols.size()];
- String[] dataTypes = new String[columnSymbols.size()];
-
- for(int i=0; i<columnSymbols.size(); i++) {
- SingleElementSymbol symbol = (SingleElementSymbol) columnSymbols.get(i);
- columnNames[i] = SingleElementSymbol.getShortName(symbol.getOutputName());
- dataTypes[i] = DataTypeManager.getDataTypeName(symbol.getType());
- }
- ResultsMessage result = new ResultsMessage(requestMsg, batch, columnNames, dataTypes);
- setAnalysisRecords(result);
- return result;
- }
-
- private void setAnalysisRecords(ResultsMessage response) {
- if(analysisRecord != null) {
- if (requestMsg.getShowPlan() != ShowPlan.OFF) {
- if (processor != null) {
- analysisRecord.setQueryPlan(processor.getProcessorPlan().getDescriptionProperties());
- }
- response.setPlanDescription(analysisRecord.getQueryPlan());
- response.setAnnotations(analysisRecord.getAnnotations());
- }
- if (requestMsg.getShowPlan() == ShowPlan.DEBUG) {
- response.setDebugLog(analysisRecord.getDebugLog());
- }
- }
- }
-
- private void sendError() {
- ResultsReceiver<ResultsMessage> receiver = null;
- synchronized (this) {
- receiver = this.resultsReceiver;
- this.resultsReceiver = null;
- if (receiver == null) {
- LogManager.logDetail(LogConstants.CTX_DQP, processingException, "Unable to send error to client as results were already sent.", requestID); //$NON-NLS-1$
- return;
- }
- }
- LogManager.logDetail(LogConstants.CTX_DQP, processingException, "Sending error to client", requestID); //$NON-NLS-1$
- ResultsMessage response = new ResultsMessage(requestMsg);
- response.setException(processingException);
- setAnalysisRecords(response);
- receiver.receiveResults(response);
- }
-
- @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>();
-
- for (SPParameter param : procedure.getParameters()) {
- ParameterInfo info = new ParameterInfo(param.getParameterType(), param.getResultSetColumns().size());
- paramInfos.add(info);
- }
-
- return paramInfos;
- }
-
- public void processLobChunkRequest(String id, int streamRequestId, ResultsReceiver<LobChunk> chunckReceiver) {
- LobWorkItem workItem = null;
- synchronized (lobStreams) {
- workItem = this.lobStreams.get(new Integer(streamRequestId));
- if (workItem == null) {
- workItem = new LobWorkItem(this, dqpCore, id, streamRequestId);
- lobStreams.put(new Integer(streamRequestId), workItem);
- }
- }
- workItem.setResultsReceiver(chunckReceiver);
- if (this.dqpWorkContext.useCallingThread()) {
- workItem.run();
- } else {
- dqpCore.addWork(workItem);
- }
- }
-
- public void removeLobStream(int streamRequestId) {
- this.lobStreams.remove(new Integer(streamRequestId));
- }
-
- public boolean requestCancel() throws TeiidComponentException {
- synchronized (this) {
- if (this.isCanceled || this.closeRequested) {
- return false;
- }
- this.isCanceled = true;
- }
- if (this.processor != null) {
- this.processor.requestCanceled();
- }
-
- // Cancel Connector atomic requests
- try {
- for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
- connectorRequest.cancelRequest();
- }
- } finally {
- try {
- if (transactionService != null) {
- try {
- transactionService.cancelTransactions(requestID.getConnectionID(), true);
- } catch (XATransactionException err) {
- throw new TeiidComponentException(err);
- }
- }
- } finally {
- this.moreWork();
- }
- }
- return true;
- }
-
- public boolean requestAtomicRequestCancel(AtomicRequestID ari) throws TeiidComponentException {
- // in the case that this does not support partial results; cancel
- // the original processor request.
- if(!requestMsg.supportsPartialResults()) {
- return requestCancel();
- }
-
- DataTierTupleSource connectorRequest = this.connectorInfo.get(ari);
- if (connectorRequest != null) {
- connectorRequest.cancelRequest();
- return true;
- }
-
- LogManager.logDetail(LogConstants.CTX_DQP, "Connector request not found. AtomicRequestID=", ari); //$NON-NLS-1$
- return false;
- }
-
- public void requestClose() throws TeiidComponentException {
- synchronized (this) {
- if (this.state == ProcessingState.CLOSE || this.closeRequested) {
- if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
- LogManager.logDetail(LogConstants.CTX_DQP, "Request already closing" + requestID); //$NON-NLS-1$
- }
- return;
- }
- }
- this.closeRequested = true;
- if (!this.doneProducingBatches) {
- this.requestCancel(); //pending work should be canceled for fastest clean up
- }
- this.moreWork();
- }
-
- public void requestMore(int batchFirst, int batchLast, ResultsReceiver<ResultsMessage> receiver) {
- this.requestResults(batchFirst, batchLast, receiver);
- this.moreWork();
- }
-
- public void closeAtomicRequest(AtomicRequestID atomicRequestId) {
- connectorInfo.remove(atomicRequestId);
- LogManager.logTrace(LogConstants.CTX_DQP, new Object[] {"closed atomic-request:", atomicRequestId}); //$NON-NLS-1$
- }
-
- public void addConnectorRequest(AtomicRequestID atomicRequestId, DataTierTupleSource connInfo) {
- connectorInfo.put(atomicRequestId, connInfo);
- }
-
- /**
- * <p>This method add information to the warning on the work item for the given
- * <code>RequestID</code>. This method is called from <code>DataTierManager</code></p>
- */
- public void addSourceFailureDetails(SourceWarning details) {
- synchronized (warnings) {
- this.warnings.add(details);
- }
- }
-
- boolean isCanceled() {
- return isCanceled;
- }
-
- Command getOriginalCommand() throws TeiidProcessingException {
- if (this.originalCommand == null) {
- if (this.processingException != null) {
- throw new TeiidProcessingException(this.processingException);
- }
- throw new IllegalStateException("Original command is not available"); //$NON-NLS-1$
- }
- return this.originalCommand;
- }
-
- void setOriginalCommand(Command originalCommand) {
- this.originalCommand = originalCommand;
- }
-
- TransactionContext getTransactionContext() {
- return transactionContext;
- }
-
-
- Collection<DataTierTupleSource> getConnectorRequests() {
- return new LinkedList<DataTierTupleSource>(this.connectorInfo.values());
- }
-
- DataTierTupleSource getConnectorRequest(AtomicRequestID id) {
- return this.connectorInfo.get(id);
- }
-
- public List<TeiidException> getWarnings() {
- return warnings;
- }
-
- @Override
- public String toString() {
- return this.requestID.toString();
- }
-
- public DQPWorkContext getDqpWorkContext() {
- return dqpWorkContext;
- }
-
- public long getProcessingTimestamp() {
- return processingTimestamp;
- }
-
- @Override
- public void release() {
- try {
- requestCancel();
- } catch (TeiidComponentException e) {
- LogManager.logWarning(LogConstants.CTX_DQP, e, "Failed to cancel " + requestID); //$NON-NLS-1$
- }
- }
-
- private void doneProducingBatches() {
- this.doneProducingBatches = true;
- dqpCore.finishProcessing(this);
- }
-
- @Override
- public int getPriority() {
- return (closeRequested || isCanceled) ? 0 : 1000;
- }
-
- @Override
- public long getCreationTime() {
- return processingTimestamp;
- }
-
- <T> FutureWork<T> addHighPriorityWork(Callable<T> callable) {
- FutureWork<T> work = new FutureWork<T>(callable, PrioritizedRunnable.NO_WAIT_PRIORITY);
- dqpCore.addWork(work);
- return work;
- }
-
- <T> FutureWork<T> addWork(Callable<T> callable, CompletionListener<T> listener, int priority) {
- FutureWork<T> work = new FutureWork<T>(callable, priority);
- WorkWrapper<T> wl = new WorkWrapper<T>(work);
- work.addCompletionListener(wl);
- work.addCompletionListener(listener);
- synchronized (queue) {
- if (totalThreads < dqpCore.getUserRequestSourceConcurrency()) {
- dqpCore.addWork(work);
- totalThreads++;
- wl.submitted = true;
- } else {
- queue.add(wl);
- LogManager.logDetail(LogConstants.CTX_DQP, this.requestID, " reached max source concurrency of ", dqpCore.getUserRequestSourceConcurrency()); //$NON-NLS-1$
- }
- }
- return work;
- }
-
- void scheduleWork(Runnable r, int priority, long delay) {
- dqpCore.scheduleWork(r, priority, delay);
- }
-
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java (from rev 3218, trunk/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,861 @@
+/*
+ * 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 java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.teiid.client.RequestMessage;
+import org.teiid.client.ResultsMessage;
+import org.teiid.client.SourceWarning;
+import org.teiid.client.RequestMessage.ShowPlan;
+import org.teiid.client.lob.LobChunk;
+import org.teiid.client.metadata.ParameterInfo;
+import org.teiid.client.util.ResultsReceiver;
+import org.teiid.client.xa.XATransactionException;
+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.dqp.internal.process.DQPCore.CompletionListener;
+import org.teiid.dqp.internal.process.DQPCore.FutureWork;
+import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
+import org.teiid.dqp.internal.process.ThreadReuseExecutor.PrioritizedRunnable;
+import org.teiid.dqp.message.AtomicRequestID;
+import org.teiid.dqp.message.RequestID;
+import org.teiid.dqp.service.TransactionContext;
+import org.teiid.dqp.service.TransactionService;
+import org.teiid.dqp.service.TransactionContext.Scope;
+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.FunctionMethod.Determinism;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.parser.ParseInfo;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.BatchCollector;
+import org.teiid.query.processor.QueryProcessor;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+
+public class RequestWorkItem extends AbstractWorkItem implements PrioritizedRunnable {
+
+ private final class WorkWrapper<T> implements
+ DQPCore.CompletionListener<T> {
+
+ boolean submitted;
+ FutureWork<T> work;
+
+ public WorkWrapper(FutureWork<T> work) {
+ this.work = work;
+ }
+
+ @Override
+ public void onCompletion(FutureWork<T> future) {
+ WorkWrapper<?> nextWork = null;
+ synchronized (queue) {
+ if (!submitted) {
+ return;
+ }
+ nextWork = queue.pollFirst();
+ if (nextWork == null) {
+ totalThreads--;
+ } else {
+ nextWork.submitted = true;
+ }
+ }
+ if (nextWork != null) {
+ dqpCore.addWork(nextWork.work);
+ }
+ }
+ }
+
+ private enum ProcessingState {NEW, PROCESSING, CLOSE}
+ private ProcessingState state = ProcessingState.NEW;
+
+ private enum TransactionState {NONE, ACTIVE, DONE}
+ private TransactionState transactionState = TransactionState.NONE;
+
+ private int totalThreads;
+ private LinkedList<WorkWrapper<?>> queue = new LinkedList<WorkWrapper<?>>();
+
+ /*
+ * Obtained at construction time
+ */
+ protected final DQPCore dqpCore;
+ final RequestMessage requestMsg;
+ final RequestID requestID;
+ private Request request; //provides the processing plan, held on a temporary basis
+ private final int processorTimeslice;
+ private CacheID cid;
+ private final TransactionService transactionService;
+ private final DQPWorkContext dqpWorkContext;
+ boolean active;
+
+ /*
+ * obtained during new
+ */
+ private volatile QueryProcessor processor;
+ private BatchCollector collector;
+ private Command originalCommand;
+ private AnalysisRecord analysisRecord;
+ private TransactionContext transactionContext;
+ TupleBuffer resultsBuffer;
+ private boolean returnsUpdateCount;
+
+ /*
+ * maintained during processing
+ */
+ private Throwable processingException;
+ private Map<AtomicRequestID, DataTierTupleSource> connectorInfo = new ConcurrentHashMap<AtomicRequestID, DataTierTupleSource>(4);
+ // This exception contains details of all the atomic requests that failed when query is run in partial results mode.
+ private List<TeiidException> warnings = new LinkedList<TeiidException>();
+ private volatile boolean doneProducingBatches;
+ private volatile boolean isClosed;
+ private volatile boolean isCanceled;
+ private volatile boolean closeRequested;
+
+ //results request
+ private ResultsReceiver<ResultsMessage> resultsReceiver;
+ private int begin;
+ private int end;
+ private TupleBatch savedBatch;
+ private Map<Integer, LobWorkItem> lobStreams = new ConcurrentHashMap<Integer, LobWorkItem>(4);
+
+ /**The time when command begins processing on the server.*/
+ private long processingTimestamp = System.currentTimeMillis();
+
+ public RequestWorkItem(DQPCore dqpCore, RequestMessage requestMsg, Request request, ResultsReceiver<ResultsMessage> receiver, RequestID requestID, DQPWorkContext workContext) {
+ super(workContext.useCallingThread() || requestMsg.isSync() ? Thread.currentThread() : null);
+ this.requestMsg = requestMsg;
+ this.requestID = requestID;
+ this.processorTimeslice = dqpCore.getProcessorTimeSlice();
+ this.transactionService = dqpCore.getTransactionService();
+ this.dqpCore = dqpCore;
+ this.request = request;
+ this.dqpWorkContext = workContext;
+ this.requestResults(1, requestMsg.getFetchSize(), receiver);
+ }
+
+ private boolean isForwardOnly() {
+ return this.cid == null && requestMsg.getCursorType() == ResultSet.TYPE_FORWARD_ONLY;
+ }
+
+ /**
+ * Ask for results.
+ * @param beginRow
+ * @param endRow
+ */
+ synchronized void requestResults(int beginRow, int endRow, ResultsReceiver<ResultsMessage> receiver) {
+ if (this.resultsReceiver != null) {
+ throw new IllegalStateException("Results already requested"); //$NON-NLS-1$\
+ }
+ this.resultsReceiver = receiver;
+ this.begin = beginRow;
+ this.end = endRow;
+ }
+
+ @Override
+ protected boolean isDoneProcessing() {
+ return isClosed;
+ }
+
+ @Override
+ protected void resumeProcessing() {
+ if (doneProducingBatches && !closeRequested && !isCanceled) {
+ this.run(); // just run in the IO thread
+ } else {
+ dqpCore.addWork(this);
+ }
+ }
+
+ @Override
+ protected void interrupted(InterruptedException e) {
+ try {
+ this.requestCancel();
+ } catch (TeiidComponentException e1) {
+ throw new TeiidRuntimeException(e1);
+ }
+ super.interrupted(e);
+ }
+
+ @Override
+ protected void process() {
+ LogManager.logDetail(LogConstants.CTX_DQP, "Request Thread", requestID, "with state", state); //$NON-NLS-1$ //$NON-NLS-2$
+ try {
+ if (this.state == ProcessingState.NEW) {
+ state = ProcessingState.PROCESSING;
+ processNew();
+ if (isCanceled) {
+ this.processingException = new TeiidProcessingException(QueryPlugin.Util.getString("QueryProcessor.request_cancelled", this.requestID)); //$NON-NLS-1$
+ state = ProcessingState.CLOSE;
+ }
+ }
+
+ resume();
+
+ if (this.state == ProcessingState.PROCESSING) {
+ processMore();
+ if (this.closeRequested) {
+ this.state = ProcessingState.CLOSE;
+ }
+ }
+ } catch (BlockedException e) {
+ LogManager.logDetail(LogConstants.CTX_DQP, "Request Thread", requestID, "- processor blocked"); //$NON-NLS-1$ //$NON-NLS-2$
+ } catch (QueryProcessor.ExpiredTimeSliceException e) {
+ LogManager.logDetail(LogConstants.CTX_DQP, "Request Thread", requestID, "- time slice expired"); //$NON-NLS-1$ //$NON-NLS-2$
+ this.moreWork();
+ } catch (Throwable e) {
+ LogManager.logDetail(LogConstants.CTX_DQP, e, "Request Thread", requestID, "- error occurred"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ if (!isCanceled()) {
+ dqpCore.logMMCommand(this, Event.ERROR, null);
+ //Case 5558: Differentiate between system level errors and
+ //processing errors. Only log system level errors as errors,
+ //log the processing errors as warnings only
+ if(e instanceof TeiidProcessingException) {
+ Throwable cause = e;
+ while (cause.getCause() != null && cause.getCause() != cause) {
+ cause = cause.getCause();
+ }
+ StackTraceElement[] elems = cause.getStackTrace();
+ Object elem = null;
+ if (elems.length > 0) {
+ elem = cause.getStackTrace()[0];
+ } else {
+ elem = cause.getMessage();
+ }
+ LogManager.logWarning(LogConstants.CTX_DQP, QueryPlugin.Util.getString("ProcessWorker.processing_error", e.getMessage(), requestID, e.getClass().getName(), elem)); //$NON-NLS-1$
+ }else {
+ LogManager.logError(LogConstants.CTX_DQP, e, QueryPlugin.Util.getString("ProcessWorker.error", requestID)); //$NON-NLS-1$
+ }
+ }
+
+ this.processingException = e;
+ this.state = ProcessingState.CLOSE;
+ } finally {
+ if (this.state == ProcessingState.CLOSE && !isClosed) {
+ attemptClose();
+ } else if (isClosed) {
+ /*
+ * since there may be a client waiting notify them of a problem
+ */
+ if (this.processingException == null) {
+ this.processingException = new IllegalStateException("Request is already closed"); //$NON-NLS-1$
+ }
+ sendError();
+ }
+ suspend();
+ }
+ }
+
+ private void resume() throws XATransactionException {
+ if (this.transactionState == TransactionState.ACTIVE && this.transactionContext.getTransaction() != null) {
+ this.transactionService.resume(this.transactionContext);
+ }
+ }
+
+ 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$
+ }
+ }
+
+ protected void processMore() throws BlockedException, TeiidException {
+ if (!doneProducingBatches) {
+ this.processor.getContext().setTimeSliceEnd(System.currentTimeMillis() + this.processorTimeslice);
+ sendResultsIfNeeded(null);
+ this.resultsBuffer = collector.collectTuples();
+ if (!doneProducingBatches) {
+ doneProducingBatches();
+ addToCache();
+ }
+ }
+ if (this.transactionState == TransactionState.ACTIVE) {
+ /*
+ * TEIID-14 if we are done producing batches, then proactively close transactional
+ * executions even ones that were intentionally kept alive. this may
+ * break the read of a lob from a transactional source under a transaction
+ * if the source does not support holding the clob open after commit
+ */
+ for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
+ if (connectorRequest.isTransactional()) {
+ connectorRequest.fullyCloseSource();
+ }
+ }
+ this.transactionState = TransactionState.DONE;
+ if (transactionContext.getTransactionType() == TransactionContext.Scope.REQUEST) {
+ this.transactionService.commit(transactionContext);
+ } else {
+ suspend();
+ }
+ }
+ sendResultsIfNeeded(null);
+ }
+
+ /**
+ * Client close is currently implemented as asynch.
+ * Any errors that occur will not make it to the client, instead we just log them here.
+ */
+ protected void attemptClose() {
+ int rowcount = -1;
+ if (this.resultsBuffer != null) {
+ if (this.processor != null) {
+ this.processor.closeProcessing();
+
+ if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+ LogManager.logDetail(LogConstants.CTX_DQP, "Removing tuplesource for the request " + requestID); //$NON-NLS-1$
+ }
+ rowcount = resultsBuffer.getRowCount();
+ if (this.cid == null || !this.doneProducingBatches) {
+ resultsBuffer.remove();
+ } else {
+ try {
+ this.resultsBuffer.persistLobs();
+ } catch (TeiidComponentException e) {
+ LogManager.logDetail(LogConstants.CTX_DQP, QueryPlugin.Util.getString("failed_to_cache")); //$NON-NLS-1$
+ }
+ }
+
+ for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
+ connectorRequest.fullyCloseSource();
+ }
+ }
+
+ this.resultsBuffer = null;
+
+ for (LobWorkItem lobWorkItem : this.lobStreams.values()) {
+ lobWorkItem.close();
+ }
+ }
+
+ if (this.transactionState == TransactionState.ACTIVE) {
+ this.transactionState = TransactionState.DONE;
+ if (transactionContext.getTransactionType() == TransactionContext.Scope.REQUEST) {
+ try {
+ this.transactionService.rollback(transactionContext);
+ } catch (XATransactionException e1) {
+ LogManager.logWarning(LogConstants.CTX_DQP, e1, QueryPlugin.Util.getString("ProcessWorker.failed_rollback")); //$NON-NLS-1$
+ }
+ } else {
+ suspend();
+ }
+ }
+
+ isClosed = true;
+
+ dqpCore.removeRequest(this);
+
+ if (this.processingException != null) {
+ sendError();
+ } else {
+ dqpCore.logMMCommand(this, Event.END, rowcount);
+ }
+ }
+
+ protected void processNew() throws TeiidProcessingException, TeiidComponentException {
+ SessionAwareCache<CachedResults> rsCache = dqpCore.getRsCache();
+
+ boolean cachable = false;
+ CacheID cacheId = null;
+ boolean canUseCached = (requestMsg.useResultSetCache() ||
+ QueryParser.getQueryParser().parseCacheHint(requestMsg.getCommandString()) != null);
+
+ if (rsCache != null) {
+ if (!canUseCached) {
+ LogManager.logDetail(LogConstants.CTX_DQP, requestID, "No cache directive"); //$NON-NLS-1$
+ } else {
+ ParseInfo pi = Request.createParseInfo(requestMsg);
+ cacheId = new CacheID(this.dqpWorkContext, pi, requestMsg.getCommandString());
+ cachable = cacheId.setParameters(requestMsg.getParameterValues());
+ if (cachable) {
+ 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);
+ this.doneProducingBatches();
+ return;
+ }
+ } else {
+ LogManager.logDetail(LogConstants.CTX_DQP, requestID, "Parameters are not serializable - cache cannot be used for", cacheId); //$NON-NLS-1$
+ }
+ }
+ }
+ request.processRequest();
+ originalCommand = request.userCommand;
+ if (cachable && (requestMsg.useResultSetCache() || originalCommand.getCacheHint() != null) && rsCache != null && originalCommand.areResultsCachable()) {
+ this.cid = cacheId;
+ //turn on the collection of data objects used
+ request.processor.getContext().setDataObjects(new HashSet<Object>(4));
+ }
+ processor = request.processor;
+ collector = new BatchCollector(processor, processor.getBufferManager(), this.request.context, isForwardOnly()) {
+ protected void flushBatchDirect(TupleBatch batch, boolean add) throws TeiidComponentException,TeiidProcessingException {
+ resultsBuffer = getTupleBuffer();
+ boolean added = false;
+ if (cid != null) {
+ super.flushBatchDirect(batch, add);
+ added = true;
+ }
+ if (batch.getTerminationFlag()) {
+ 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.block(requestID, "Blocking due to full results buffer."); //$NON-NLS-1$
+ }
+ }
+ }
+ };
+ this.resultsBuffer = collector.getTupleBuffer();
+ if (this.resultsBuffer == null) {
+ //This is just a dummy result it will get replaced by collector source
+ resultsBuffer = this.processor.getBufferManager().createTupleBuffer(this.originalCommand.getProjectedSymbols(), this.request.context.getConnectionID(), TupleSourceType.FINAL);
+ }
+ analysisRecord = request.analysisRecord;
+ analysisRecord.setQueryPlan(processor.getProcessorPlan().getDescriptionProperties());
+ transactionContext = request.transactionContext;
+ if (this.transactionContext != null && this.transactionContext.getTransactionType() != Scope.NONE) {
+ this.transactionState = TransactionState.ACTIVE;
+ }
+ if (requestMsg.isNoExec()) {
+ doneProducingBatches();
+ resultsBuffer.close();
+ this.cid = null;
+ }
+ this.returnsUpdateCount = request.returnsUpdateCount;
+ request = null;
+ }
+
+ private void addToCache() {
+ if (!doneProducingBatches || cid == null) {
+ return;
+ }
+ 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$
+ resultsBuffer.setPrefersMemory(originalCommand.getCacheHint().getPrefersMemory());
+ if (originalCommand.getCacheHint().getDeterminism() != null) {
+ determinismLevel = originalCommand.getCacheHint().getDeterminism();
+ LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Cache hint modified the query determinism from ",processor.getContext().getDeterminismLevel(), " to ", determinismLevel }); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ if (determinismLevel.compareTo(Determinism.SESSION_DETERMINISTIC) <= 0) {
+ LogManager.logInfo(LogConstants.CTX_DQP, QueryPlugin.Util.getString("RequestWorkItem.cache_nondeterministic", originalCommand)); //$NON-NLS-1$
+ }
+ dqpCore.getRsCache().put(cid, determinismLevel, cr, originalCommand.getCacheHint() != null?originalCommand.getCacheHint().getTtl():null);
+ }
+
+ /**
+ * Send results if they have been requested. This should only be called from the processing thread.
+ */
+ protected boolean sendResultsIfNeeded(TupleBatch batch) throws TeiidComponentException {
+ ResultsMessage response = null;
+ ResultsReceiver<ResultsMessage> receiver = null;
+ boolean result = true;
+ synchronized (this) {
+ if (this.resultsReceiver == null
+ || (this.begin > (batch != null?batch.getEndRow():this.resultsBuffer.getRowCount()) && !doneProducingBatches)
+ || (this.transactionState == TransactionState.ACTIVE)) {
+ return result;
+ }
+
+ if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+ LogManager.logDetail(LogConstants.CTX_DQP, "[RequestWorkItem.sendResultsIfNeeded] requestID:", requestID, "resultsID:", this.resultsBuffer, "done:", doneProducingBatches ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ //TODO: support fetching more than 1 batch
+ boolean fromBuffer = false;
+ if (batch == null || !(batch.containsRow(this.begin) || (batch.getTerminationFlag() && batch.getEndRow() <= this.begin))) {
+ if (savedBatch != null && savedBatch.containsRow(this.begin)) {
+ batch = savedBatch;
+ } else {
+ batch = resultsBuffer.getBatch(begin);
+ }
+ savedBatch = null;
+ fromBuffer = true;
+ }
+ int count = this.end - this.begin + 1;
+ if (batch.getRowCount() > count) {
+ int beginRow = Math.min(this.begin, batch.getEndRow() - count + 1);
+ int endRow = Math.min(beginRow + count - 1, batch.getEndRow());
+ boolean last = false;
+ if (endRow == batch.getEndRow()) {
+ last = batch.getTerminationFlag();
+ } else if (fromBuffer && isForwardOnly()) {
+ savedBatch = batch;
+ }
+ List<List<?>> memoryRows = batch.getTuples();
+ batch = new TupleBatch(beginRow, memoryRows.subList(beginRow - batch.getBeginRow(), endRow - batch.getBeginRow() + 1));
+ batch.setTerminationFlag(last);
+ } else if (!fromBuffer){
+ result = !isForwardOnly();
+ }
+ int finalRowCount = this.resultsBuffer.isFinal()?this.resultsBuffer.getRowCount():(batch.getTerminationFlag()?batch.getEndRow():-1);
+
+ response = createResultsMessage(batch.getAllTuples(), this.originalCommand.getProjectedSymbols());
+ response.setFirstRow(batch.getBeginRow());
+ response.setLastRow(batch.getEndRow());
+ response.setUpdateResult(this.returnsUpdateCount);
+ // set final row
+ response.setFinalRow(finalRowCount);
+
+ // send any warnings with the response object
+ List<Throwable> responseWarnings = new ArrayList<Throwable>();
+ if (this.processor != null) {
+ List<Exception> currentWarnings = processor.getAndClearWarnings();
+ if (currentWarnings != null) {
+ responseWarnings.addAll(currentWarnings);
+ }
+ }
+ synchronized (warnings) {
+ responseWarnings.addAll(this.warnings);
+ this.warnings.clear();
+ }
+ response.setWarnings(responseWarnings);
+
+ // If it is stored procedure, set parameters
+ if (originalCommand instanceof StoredProcedure) {
+ StoredProcedure proc = (StoredProcedure)originalCommand;
+ if (proc.returnParameters()) {
+ response.setParameters(getParameterInfo(proc));
+ }
+ }
+ /*
+ * mark the results sent at this point.
+ * communication exceptions will be treated as non-recoverable
+ */
+ receiver = this.resultsReceiver;
+ this.resultsReceiver = null;
+ }
+ receiver.receiveResults(response);
+ return result;
+ }
+
+ public ResultsMessage createResultsMessage(List[] batch, List columnSymbols) {
+ String[] columnNames = new String[columnSymbols.size()];
+ String[] dataTypes = new String[columnSymbols.size()];
+
+ for(int i=0; i<columnSymbols.size(); i++) {
+ SingleElementSymbol symbol = (SingleElementSymbol) columnSymbols.get(i);
+ columnNames[i] = SingleElementSymbol.getShortName(symbol.getOutputName());
+ dataTypes[i] = DataTypeManager.getDataTypeName(symbol.getType());
+ }
+ ResultsMessage result = new ResultsMessage(requestMsg, batch, columnNames, dataTypes);
+ setAnalysisRecords(result);
+ return result;
+ }
+
+ private void setAnalysisRecords(ResultsMessage response) {
+ if(analysisRecord != null) {
+ if (requestMsg.getShowPlan() != ShowPlan.OFF) {
+ if (processor != null) {
+ analysisRecord.setQueryPlan(processor.getProcessorPlan().getDescriptionProperties());
+ }
+ response.setPlanDescription(analysisRecord.getQueryPlan());
+ response.setAnnotations(analysisRecord.getAnnotations());
+ }
+ if (requestMsg.getShowPlan() == ShowPlan.DEBUG) {
+ response.setDebugLog(analysisRecord.getDebugLog());
+ }
+ }
+ }
+
+ private void sendError() {
+ ResultsReceiver<ResultsMessage> receiver = null;
+ synchronized (this) {
+ receiver = this.resultsReceiver;
+ this.resultsReceiver = null;
+ if (receiver == null) {
+ LogManager.logDetail(LogConstants.CTX_DQP, processingException, "Unable to send error to client as results were already sent.", requestID); //$NON-NLS-1$
+ return;
+ }
+ }
+ LogManager.logDetail(LogConstants.CTX_DQP, processingException, "Sending error to client", requestID); //$NON-NLS-1$
+ ResultsMessage response = new ResultsMessage(requestMsg);
+ response.setException(processingException);
+ setAnalysisRecords(response);
+ receiver.receiveResults(response);
+ }
+
+ @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>();
+
+ for (SPParameter param : procedure.getParameters()) {
+ ParameterInfo info = new ParameterInfo(param.getParameterType(), param.getResultSetColumns().size());
+ paramInfos.add(info);
+ }
+
+ return paramInfos;
+ }
+
+ public void processLobChunkRequest(String id, int streamRequestId, ResultsReceiver<LobChunk> chunckReceiver) {
+ LobWorkItem workItem = null;
+ synchronized (lobStreams) {
+ workItem = this.lobStreams.get(new Integer(streamRequestId));
+ if (workItem == null) {
+ workItem = new LobWorkItem(this, dqpCore, id, streamRequestId);
+ lobStreams.put(new Integer(streamRequestId), workItem);
+ }
+ }
+ workItem.setResultsReceiver(chunckReceiver);
+ if (this.dqpWorkContext.useCallingThread()) {
+ workItem.run();
+ } else {
+ dqpCore.addWork(workItem);
+ }
+ }
+
+ public void removeLobStream(int streamRequestId) {
+ this.lobStreams.remove(new Integer(streamRequestId));
+ }
+
+ public boolean requestCancel() throws TeiidComponentException {
+ synchronized (this) {
+ if (this.isCanceled || this.closeRequested) {
+ return false;
+ }
+ this.isCanceled = true;
+ }
+ if (this.processor != null) {
+ this.processor.requestCanceled();
+ }
+
+ // Cancel Connector atomic requests
+ try {
+ for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
+ connectorRequest.cancelRequest();
+ }
+ } finally {
+ try {
+ if (transactionService != null) {
+ try {
+ transactionService.cancelTransactions(requestID.getConnectionID(), true);
+ } catch (XATransactionException err) {
+ throw new TeiidComponentException(err);
+ }
+ }
+ } finally {
+ this.moreWork();
+ }
+ }
+ return true;
+ }
+
+ public boolean requestAtomicRequestCancel(AtomicRequestID ari) throws TeiidComponentException {
+ // in the case that this does not support partial results; cancel
+ // the original processor request.
+ if(!requestMsg.supportsPartialResults()) {
+ return requestCancel();
+ }
+
+ DataTierTupleSource connectorRequest = this.connectorInfo.get(ari);
+ if (connectorRequest != null) {
+ connectorRequest.cancelRequest();
+ return true;
+ }
+
+ LogManager.logDetail(LogConstants.CTX_DQP, "Connector request not found. AtomicRequestID=", ari); //$NON-NLS-1$
+ return false;
+ }
+
+ public void requestClose() throws TeiidComponentException {
+ synchronized (this) {
+ if (this.state == ProcessingState.CLOSE || this.closeRequested) {
+ if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+ LogManager.logDetail(LogConstants.CTX_DQP, "Request already closing" + requestID); //$NON-NLS-1$
+ }
+ return;
+ }
+ }
+ this.closeRequested = true;
+ if (!this.doneProducingBatches) {
+ this.requestCancel(); //pending work should be canceled for fastest clean up
+ }
+ this.moreWork();
+ }
+
+ public void requestMore(int batchFirst, int batchLast, ResultsReceiver<ResultsMessage> receiver) {
+ this.requestResults(batchFirst, batchLast, receiver);
+ this.moreWork();
+ }
+
+ public void closeAtomicRequest(AtomicRequestID atomicRequestId) {
+ connectorInfo.remove(atomicRequestId);
+ LogManager.logTrace(LogConstants.CTX_DQP, new Object[] {"closed atomic-request:", atomicRequestId}); //$NON-NLS-1$
+ }
+
+ public void addConnectorRequest(AtomicRequestID atomicRequestId, DataTierTupleSource connInfo) {
+ connectorInfo.put(atomicRequestId, connInfo);
+ }
+
+ /**
+ * <p>This method add information to the warning on the work item for the given
+ * <code>RequestID</code>. This method is called from <code>DataTierManager</code></p>
+ */
+ public void addSourceFailureDetails(SourceWarning details) {
+ synchronized (warnings) {
+ this.warnings.add(details);
+ }
+ }
+
+ boolean isCanceled() {
+ return isCanceled;
+ }
+
+ Command getOriginalCommand() throws TeiidProcessingException {
+ if (this.originalCommand == null) {
+ if (this.processingException != null) {
+ throw new TeiidProcessingException(this.processingException);
+ }
+ throw new IllegalStateException("Original command is not available"); //$NON-NLS-1$
+ }
+ return this.originalCommand;
+ }
+
+ void setOriginalCommand(Command originalCommand) {
+ this.originalCommand = originalCommand;
+ }
+
+ TransactionContext getTransactionContext() {
+ return transactionContext;
+ }
+
+
+ Collection<DataTierTupleSource> getConnectorRequests() {
+ return new LinkedList<DataTierTupleSource>(this.connectorInfo.values());
+ }
+
+ DataTierTupleSource getConnectorRequest(AtomicRequestID id) {
+ return this.connectorInfo.get(id);
+ }
+
+ public List<TeiidException> getWarnings() {
+ return warnings;
+ }
+
+ @Override
+ public String toString() {
+ return this.requestID.toString();
+ }
+
+ public DQPWorkContext getDqpWorkContext() {
+ return dqpWorkContext;
+ }
+
+ public long getProcessingTimestamp() {
+ return processingTimestamp;
+ }
+
+ @Override
+ public void release() {
+ try {
+ requestCancel();
+ } catch (TeiidComponentException e) {
+ LogManager.logWarning(LogConstants.CTX_DQP, e, "Failed to cancel " + requestID); //$NON-NLS-1$
+ }
+ }
+
+ private void doneProducingBatches() {
+ this.doneProducingBatches = true;
+ dqpCore.finishProcessing(this);
+ }
+
+ @Override
+ public int getPriority() {
+ return (closeRequested || isCanceled) ? 0 : 1000;
+ }
+
+ @Override
+ public long getCreationTime() {
+ return processingTimestamp;
+ }
+
+ <T> FutureWork<T> addHighPriorityWork(Callable<T> callable) {
+ FutureWork<T> work = new FutureWork<T>(callable, PrioritizedRunnable.NO_WAIT_PRIORITY);
+ dqpCore.addWork(work);
+ return work;
+ }
+
+ <T> FutureWork<T> addWork(Callable<T> callable, CompletionListener<T> listener, int priority) {
+ FutureWork<T> work = new FutureWork<T>(callable, priority);
+ WorkWrapper<T> wl = new WorkWrapper<T>(work);
+ work.addCompletionListener(wl);
+ work.addCompletionListener(listener);
+ synchronized (queue) {
+ if (totalThreads < dqpCore.getUserRequestSourceConcurrency()) {
+ dqpCore.addWork(work);
+ totalThreads++;
+ wl.submitted = true;
+ } else {
+ queue.add(wl);
+ LogManager.logDetail(LogConstants.CTX_DQP, this.requestID, " reached max source concurrency of ", dqpCore.getUserRequestSourceConcurrency()); //$NON-NLS-1$
+ }
+ }
+ return work;
+ }
+
+ void scheduleWork(Runnable r, int priority, long delay) {
+ dqpCore.scheduleWork(r, priority, delay);
+ }
+
+}
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/eval/Evaluator.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1020 +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.eval;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.SQLException;
-import java.sql.SQLXML;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.regex.PatternSyntaxException;
-
-import net.sf.saxon.trans.XPathException;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.FunctionExecutionException;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.core.ComponentNotFoundException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.BlobType;
-import org.teiid.core.types.ClobImpl;
-import org.teiid.core.types.ClobType;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.types.InputStreamFactory;
-import org.teiid.core.types.SQLXMLImpl;
-import org.teiid.core.types.Sequencable;
-import org.teiid.core.types.Streamable;
-import org.teiid.core.types.TransformationException;
-import org.teiid.core.types.XMLType;
-import org.teiid.core.types.XMLType.Type;
-import org.teiid.core.types.basic.StringToSQLXMLTransform;
-import org.teiid.core.util.EquivalenceUtil;
-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.processor.ProcessorDataManager;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.lang.AbstractSetCriteria;
-import org.teiid.query.sql.lang.CollectionValueIterator;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.DependentSetCriteria;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.ExpressionCriteria;
-import org.teiid.query.sql.lang.IsNullCriteria;
-import org.teiid.query.sql.lang.MatchCriteria;
-import org.teiid.query.sql.lang.NotCriteria;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SubqueryCompareCriteria;
-import org.teiid.query.sql.lang.SubqueryContainer;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-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.ContextReference;
-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.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.SingleElementSymbol;
-import org.teiid.query.sql.symbol.TextLine;
-import org.teiid.query.sql.symbol.XMLElement;
-import org.teiid.query.sql.symbol.XMLForest;
-import org.teiid.query.sql.symbol.XMLNamespaces;
-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.XMLNamespaces.NamespaceItem;
-import org.teiid.query.sql.util.ValueIterator;
-import org.teiid.query.sql.util.ValueIteratorSource;
-import org.teiid.query.util.CommandContext;
-import org.teiid.query.xquery.saxon.SaxonXQueryExpression;
-import org.teiid.query.xquery.saxon.SaxonXQueryExpression.Result;
-import org.teiid.translator.WSConnection.Util;
-
-public class Evaluator {
-
- private final class SequenceReader extends Reader {
- private LinkedList<Reader> readers;
- private Reader current = null;
-
- public SequenceReader(LinkedList<Reader> readers) {
- this.readers = readers;
- }
-
- @Override
- public void close() throws IOException {
- for (Reader reader : readers) {
- try {
- reader.close();
- } catch (IOException e) {
-
- }
- }
- }
-
- @Override
- public int read(char[] cbuf, int off, int len)
- throws IOException {
- if (current == null && !readers.isEmpty()) {
- current = readers.removeFirst();
- }
- if (current == null) {
- return -1;
- }
- int read = current.read(cbuf, off, len);
- if (read == -1) {
- current.close();
- current = null;
- read = 0;
- }
- if (read < len) {
- int nextRead = read(cbuf, off + read, len - read);
- if (nextRead > 0) {
- read += nextRead;
- }
- }
- return read;
- }
- }
-
- public static class NameValuePair<T> {
- public String name;
- public T value;
-
- public NameValuePair(String name, T value) {
- this.name = name;
- this.value = value;
- }
- }
-
- 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$
-
- private Map elements;
-
- protected ProcessorDataManager dataMgr;
- protected CommandContext context;
-
- public static boolean evaluate(Criteria criteria) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
- return new Evaluator(Collections.emptyMap(), null, null).evaluate(criteria, Collections.emptyList());
- }
-
- public static Object evaluate(Expression expression) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
- return new Evaluator(Collections.emptyMap(), null, null).evaluate(expression, Collections.emptyList());
- }
-
- public Evaluator(Map elements, ProcessorDataManager dataMgr, CommandContext context) {
- this.context = context;
- this.dataMgr = dataMgr;
- this.elements = elements;
- }
-
- public void initialize(CommandContext context, ProcessorDataManager dataMgr) {
- this.context = context;
- this.dataMgr = dataMgr;
- }
-
- public boolean evaluate(Criteria criteria, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
- return Boolean.TRUE.equals(evaluateTVL(criteria, tuple));
- }
-
- public Boolean evaluateTVL(Criteria criteria, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
- if(criteria instanceof CompoundCriteria) {
- return evaluate((CompoundCriteria)criteria, tuple);
- } else if(criteria instanceof NotCriteria) {
- return evaluate((NotCriteria)criteria, tuple);
- } else if(criteria instanceof CompareCriteria) {
- return evaluate((CompareCriteria)criteria, tuple);
- } else if(criteria instanceof MatchCriteria) {
- return evaluate((MatchCriteria)criteria, tuple);
- } else if(criteria instanceof AbstractSetCriteria) {
- return evaluate((AbstractSetCriteria)criteria, tuple);
- } else if(criteria instanceof IsNullCriteria) {
- return Boolean.valueOf(evaluate((IsNullCriteria)criteria, tuple));
- } else if(criteria instanceof SubqueryCompareCriteria) {
- return evaluate((SubqueryCompareCriteria)criteria, tuple);
- } else if(criteria instanceof ExistsCriteria) {
- return Boolean.valueOf(evaluate((ExistsCriteria)criteria, tuple));
- } else if (criteria instanceof ExpressionCriteria) {
- return (Boolean)evaluate(((ExpressionCriteria)criteria).getExpression(), tuple);
- } else {
- throw new ExpressionEvaluationException("ERR.015.006.0010", QueryPlugin.Util.getString("ERR.015.006.0010", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- public Boolean evaluate(CompoundCriteria criteria, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
- List subCrits = criteria.getCriteria();
- Iterator subCritIter = subCrits.iterator();
-
- boolean and = criteria.getOperator() == CompoundCriteria.AND;
- Boolean result = and?Boolean.TRUE:Boolean.FALSE;
- while(subCritIter.hasNext()) {
- Criteria subCrit = (Criteria) subCritIter.next();
- Boolean value = evaluateTVL(subCrit, tuple);
- if (value == null) {
- result = null;
- } else if (!value.booleanValue()) {
- if (and) {
- return Boolean.FALSE;
- }
- } else if (!and) {
- return Boolean.TRUE;
- }
- }
- return result;
- }
-
- public Boolean evaluate(NotCriteria criteria, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
- Criteria subCrit = criteria.getCriteria();
- Boolean result = evaluateTVL(subCrit, tuple);
- if (result == null) {
- return null;
- }
- if (result.booleanValue()) {
- return Boolean.FALSE;
- }
- return Boolean.TRUE;
- }
-
- public Boolean evaluate(CompareCriteria criteria, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
- // Evaluate left expression
- Object leftValue = null;
- try {
- leftValue = evaluate(criteria.getLeftExpression(), tuple);
- } catch(ExpressionEvaluationException e) {
- throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[] {"left", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- // Shortcut if null
- if(leftValue == null) {
- return null;
- }
-
- // Evaluate right expression
- Object rightValue = null;
- try {
- rightValue = evaluate(criteria.getRightExpression(), tuple);
- } catch(ExpressionEvaluationException e) {
- throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[]{"right", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- // Shortcut if null
- if(rightValue == null) {
- return null;
- }
-
- // Compare two non-null values using specified operator
- return compare(criteria, leftValue, rightValue);
- }
-
- public static Boolean compare(CompareCriteria criteria, Object leftValue,
- Object rightValue) throws ExpressionEvaluationException {
- switch(criteria.getOperator()) {
- case CompareCriteria.EQ:
- return Boolean.valueOf(compareValues(leftValue, rightValue) == 0);
- case CompareCriteria.NE:
- return Boolean.valueOf(compareValues(leftValue, rightValue) != 0);
- case CompareCriteria.LT:
- return Boolean.valueOf((compareValues(leftValue, rightValue) < 0));
- case CompareCriteria.LE:
- return Boolean.valueOf((compareValues(leftValue, rightValue) <= 0));
- case CompareCriteria.GT:
- return Boolean.valueOf((compareValues(leftValue, rightValue) > 0));
- case CompareCriteria.GE:
- return Boolean.valueOf((compareValues(leftValue, rightValue) >= 0));
- default:
- throw new ExpressionEvaluationException("ERR.015.006.0012", QueryPlugin.Util.getString("ERR.015.006.0012", criteria.getOperator())); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- private static final int compareValues(Object leftValue, Object rightValue) {
- assert leftValue instanceof Comparable<?>;
- assert rightValue instanceof Comparable<?>;
- if (leftValue == rightValue) {
- return 0;
- }
- return ((Comparable<Object>)leftValue).compareTo(rightValue);
- }
-
- public Boolean evaluate(MatchCriteria criteria, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
- boolean result = false;
- // Evaluate left expression
- Object value = null;
- try {
- value = evaluate(criteria.getLeftExpression(), tuple);
- } catch(ExpressionEvaluationException e) {
- throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[]{"left", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- // Shortcut if null
- if(value == null) {
- return null;
- }
-
- CharSequence leftValue = null;
-
- if (value instanceof CharSequence) {
- leftValue = (CharSequence)value;
- } else {
- try {
- leftValue = ((Sequencable)value).getCharSequence();
- } catch (SQLException err) {
- throw new ExpressionEvaluationException(err, err.getMessage());
- }
- }
-
- // Evaluate right expression
- String rightValue = null;
- try {
- rightValue = (String) evaluate(criteria.getRightExpression(), tuple);
- } catch(ExpressionEvaluationException e) {
- throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[]{"right", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- // Shortcut if null
- if(rightValue == null) {
- return null;
- }
-
- result = match(rightValue, criteria.getEscapeChar(), leftValue);
-
- return Boolean.valueOf(result ^ criteria.isNegated());
- }
-
- private boolean match(String pattern, char escape, CharSequence search)
- throws ExpressionEvaluationException {
-
- StringBuffer rePattern = LIKE_TO_REGEX.translate(pattern, escape);
-
- // 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$
- }
- }
-
- private Boolean evaluate(AbstractSetCriteria criteria, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
- // Evaluate expression
- Object leftValue = null;
- try {
- leftValue = evaluate(criteria.getExpression(), tuple);
- } catch(ExpressionEvaluationException e) {
- throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // Shortcut if null
- if(leftValue == null) {
- return null;
- }
- Boolean result = Boolean.FALSE;
-
- ValueIterator valueIter = null;
- if (criteria instanceof SetCriteria) {
- SetCriteria set = (SetCriteria)criteria;
- if (set.isAllConstants()) {
- boolean exists = set.getValues().contains(new Constant(leftValue, criteria.getExpression().getType()));
- if (!exists) {
- if (set.getValues().contains(Constant.NULL_CONSTANT)) {
- return null;
- }
- return criteria.isNegated();
- }
- return !criteria.isNegated();
- }
- valueIter = new CollectionValueIterator(((SetCriteria)criteria).getValues());
- } else if (criteria instanceof DependentSetCriteria){
- ContextReference ref = (ContextReference)criteria;
- ValueIteratorSource vis = (ValueIteratorSource)getContext(criteria).getVariableContext().getGlobalValue(ref.getContextSymbol());
- Set<Object> values;
- try {
- values = vis.getCachedSet(ref.getValueExpression());
- } catch (TeiidProcessingException e) {
- throw new ExpressionEvaluationException(e, e.getMessage());
- }
- if (values != null) {
- return values.contains(leftValue);
- }
- //there are too many values to justify a linear search or holding
- //them in memory
- return true;
- } else if (criteria instanceof SubquerySetCriteria) {
- try {
- valueIter = evaluateSubquery((SubquerySetCriteria)criteria, tuple);
- } catch (TeiidProcessingException e) {
- throw new ExpressionEvaluationException(e, e.getMessage());
- }
- } else {
- throw new AssertionError("unknown set criteria type"); //$NON-NLS-1$
- }
- while(valueIter.hasNext()) {
- Object possibleValue = valueIter.next();
- Object value = null;
- if(possibleValue instanceof Expression) {
- try {
- value = evaluate((Expression) possibleValue, tuple);
- } catch(ExpressionEvaluationException e) {
- throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", possibleValue)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } else {
- value = possibleValue;
- }
-
- if(value != null) {
- if(compareValues(leftValue, value) == 0) {
- return Boolean.valueOf(!criteria.isNegated());
- } // else try next value
- } else {
- result = null;
- }
- }
-
- if (result == null) {
- return null;
- }
-
- return Boolean.valueOf(criteria.isNegated());
- }
-
- public boolean evaluate(IsNullCriteria criteria, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
- // Evaluate expression
- Object value = null;
- try {
- value = evaluate(criteria.getExpression(), tuple);
- } catch(ExpressionEvaluationException e) {
- throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return (value == null ^ criteria.isNegated());
- }
-
- private Boolean evaluate(SubqueryCompareCriteria criteria, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
- // Evaluate expression
- Object leftValue = null;
- try {
- leftValue = evaluate(criteria.getLeftExpression(), tuple);
- } catch(ExpressionEvaluationException e) {
- throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // Shortcut if null
- if(leftValue == null) {
- return null;
- }
-
- // Need to be careful to initialize this variable carefully for the case
- // where valueIterator has no values, and the block below is not entered.
- // If there are no rows, and ALL is the predicate quantifier, the result
- // should be true. If SOME is the predicate quantifier, or no quantifier
- // is used, the result should be false.
- Boolean result = Boolean.FALSE;
- if (criteria.getPredicateQuantifier() == SubqueryCompareCriteria.ALL){
- result = Boolean.TRUE;
- }
-
- ValueIterator valueIter;
- try {
- valueIter = evaluateSubquery(criteria, tuple);
- } catch (TeiidProcessingException e) {
- throw new ExpressionEvaluationException(e, e.getMessage());
- }
- while(valueIter.hasNext()) {
- Object value = valueIter.next();
-
- if(value != null) {
- int compare = compareValues(leftValue, value);
- // Compare two non-null values using specified operator
- switch(criteria.getOperator()) {
- case SubqueryCompareCriteria.EQ:
- result = Boolean.valueOf(compare == 0);
- break;
- case SubqueryCompareCriteria.NE:
- result = Boolean.valueOf(compare != 0);
- break;
- case SubqueryCompareCriteria.LT:
- result = Boolean.valueOf(compare < 0);
- break;
- case SubqueryCompareCriteria.LE:
- result = Boolean.valueOf(compare <= 0);
- break;
- case SubqueryCompareCriteria.GT:
- result = Boolean.valueOf(compare > 0);
- break;
- case SubqueryCompareCriteria.GE:
- result = Boolean.valueOf(compare >= 0);
- break;
- default:
- throw new ExpressionEvaluationException("ERR.015.006.0012", QueryPlugin.Util.getString("ERR.015.006.0012", criteria.getOperator())); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- switch(criteria.getPredicateQuantifier()) {
- case SubqueryCompareCriteria.ALL:
- if (Boolean.FALSE.equals(result)){
- return Boolean.FALSE;
- }
- break;
- case SubqueryCompareCriteria.SOME:
- if (Boolean.TRUE.equals(result)){
- return Boolean.TRUE;
- }
- break;
- default:
- throw new ExpressionEvaluationException("ERR.015.006.0057", QueryPlugin.Util.getString("ERR.015.006.0057", criteria.getPredicateQuantifier())); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- } else { // value is null
- result = null;
- }
-
-
- } //end value iteration
-
- return result;
- }
-
- public boolean evaluate(ExistsCriteria criteria, List<?> tuple)
- throws BlockedException, TeiidComponentException, ExpressionEvaluationException {
-
- ValueIterator valueIter;
- try {
- valueIter = evaluateSubquery(criteria, tuple);
- } catch (TeiidProcessingException e) {
- throw new ExpressionEvaluationException(e, e.getMessage());
- }
- if(valueIter.hasNext()) {
- return !criteria.isNegated();
- }
- return criteria.isNegated();
- }
-
- public Object evaluate(Expression expression, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
- try {
- return internalEvaluate(expression, tuple);
- } catch (ExpressionEvaluationException e) {
- throw new ExpressionEvaluationException(e, QueryPlugin.Util.getString("ExpressionEvaluator.Eval_failed", new Object[] {expression, e.getMessage()})); //$NON-NLS-1$
- }
- }
-
- private Object internalEvaluate(Expression expression, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
- if(expression instanceof SingleElementSymbol) {
- if (elements != null) {
- // Try to evaluate by lookup in the elements map (may work for both ElementSymbol and ExpressionSymbol
- Integer index = (Integer) elements.get(expression);
- if(index != null) {
- return tuple.get(index.intValue());
- }
- }
-
- // Otherwise this should be an ExpressionSymbol and we just need to dive in and evaluate the expression itself
- if (expression instanceof ExpressionSymbol && !(expression instanceof AggregateSymbol)) {
- ExpressionSymbol exprSyb = (ExpressionSymbol) expression;
- Expression expr = exprSyb.getExpression();
- return internalEvaluate(expr, tuple);
- }
-
- return getContext(expression).getFromContext(expression);
- }
- if(expression instanceof Constant) {
- return ((Constant) expression).getValue();
- } else if(expression instanceof Function) {
- return evaluate((Function) expression, tuple);
- } else if(expression instanceof CaseExpression) {
- return evaluate((CaseExpression) expression, tuple);
- } else if(expression instanceof SearchedCaseExpression) {
- return evaluate((SearchedCaseExpression) expression, tuple);
- } else if(expression instanceof Reference) {
- Reference ref = (Reference)expression;
- if (ref.isPositional() && ref.getExpression() == null) {
- return getContext(ref).getVariableContext().getGlobalValue(ref.getContextSymbol());
- }
- return internalEvaluate(ref.getExpression(), tuple);
- } else if(expression instanceof Criteria) {
- return evaluate((Criteria) expression, tuple);
- } else if(expression instanceof ScalarSubquery) {
- return evaluate((ScalarSubquery) expression, tuple);
- } else if (expression instanceof Criteria) {
- return evaluate((Criteria)expression, tuple);
- } else if (expression instanceof TextLine){
- return evaluateTextLine(tuple, (TextLine)expression);
- } else if (expression instanceof XMLElement){
- return evaluateXMLElement(tuple, (XMLElement)expression);
- } else if (expression instanceof XMLForest){
- return evaluateXMLForest(tuple, (XMLForest)expression);
- } else if (expression instanceof XMLSerialize){
- return evaluateXMLSerialize(tuple, (XMLSerialize)expression);
- } else if (expression instanceof XMLQuery) {
- return evaluateXMLQuery(tuple, (XMLQuery)expression);
- } else if (expression instanceof QueryString) {
- return evaluateQueryString(tuple, (QueryString)expression);
- } else if (expression instanceof XMLParse){
- return evaluateXMLParse(tuple, (XMLParse)expression);
- } else {
- throw new TeiidComponentException("ERR.015.006.0016", QueryPlugin.Util.getString("ERR.015.006.0016", expression.getClass().getName())); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- private Object evaluateXMLParse(List<?> tuple, final XMLParse xp) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
- Object value = internalEvaluate(xp.getExpression(), tuple);
- if (value == null) {
- return null;
- }
- XMLType.Type type = Type.DOCUMENT;
- SQLXMLImpl result = null;
- try {
- if (value instanceof String) {
- String string = (String)value;
- result = new SQLXMLImpl(string);
- result.setEncoding(Streamable.ENCODING);
- if (!xp.isWellFormed()) {
- Reader r = new StringReader(string);
- type = validate(xp, r);
- }
- } else {
- InputStreamFactory isf = null;
- Streamable<?> s = (Streamable<?>)value;
- isf = getInputStreamFactory(s);
- result = new SQLXMLImpl(isf);
- if (!xp.isWellFormed()) {
- Reader r = result.getCharacterStream();
- type = validate(xp, r);
- }
- }
- } catch (TransformationException e) {
- throw new ExpressionEvaluationException(e, e.getMessage());
- } catch (SQLException e) {
- throw new ExpressionEvaluationException(e, e.getMessage());
- }
- if (!xp.isDocument()) {
- type = Type.CONTENT;
- }
- XMLType xml = new XMLType(result);
- xml.setType(type);
- return xml;
- }
-
- //TODO: determine when wrapping is not needed
- public static InputStreamFactory getInputStreamFactory(Streamable<?> s) {
- if (s instanceof ClobType) {
- return new InputStreamFactory.ClobInputStreamFactory((Clob)s.getReference());
- } else if (s instanceof BlobType){
- return new InputStreamFactory.BlobInputStreamFactory((Blob)s.getReference());
- }
- return new InputStreamFactory.SQLXMLInputStreamFactory((SQLXML)s.getReference());
- }
-
- private Type validate(final XMLParse xp, Reader r)
- throws TransformationException {
- if (!xp.isDocument()) {
- LinkedList<Reader> readers = new LinkedList<Reader>();
- readers.add(new StringReader("<r>")); //$NON-NLS-1$
- readers.add(r);
- readers.add(new StringReader("</r>")); //$NON-NLS-1$
- r = new SequenceReader(readers);
- }
- return StringToSQLXMLTransform.isXml(r);
- }
-
- //TODO: exception if length is too long?
- private Object evaluateQueryString(List<?> tuple, QueryString queryString)
- throws ExpressionEvaluationException, BlockedException,
- TeiidComponentException {
- Evaluator.NameValuePair<Object>[] pairs = getNameValuePairs(tuple, queryString.getArgs(), false);
- String path = (String)internalEvaluate(queryString.getPath(), tuple);
- if (path == null) {
- path = ""; //$NON-NLS-1$
- }
- boolean appendedAny = false;
- StringBuilder result = new StringBuilder();
- for (Evaluator.NameValuePair<Object> nameValuePair : pairs) {
- if (nameValuePair.value == null) {
- continue;
- }
- if (appendedAny) {
- result.append('&');
- }
- appendedAny = true;
- result.append(Util.httpURLEncode(nameValuePair.name)).append('=').append(Util.httpURLEncode((String)nameValuePair.value));
- }
- if (!appendedAny) {
- return path;
- }
- result.insert(0, '?');
- result.insert(0, path);
- return result.toString();
- }
-
- private Object evaluateXMLQuery(List<?> tuple, XMLQuery xmlQuery)
- throws BlockedException, TeiidComponentException,
- FunctionExecutionException {
- boolean emptyOnEmpty = true;
- if (xmlQuery.getEmptyOnEmpty() != null) {
- emptyOnEmpty = xmlQuery.getEmptyOnEmpty();
- }
- Result result = null;
- try {
- result = evaluateXQuery(xmlQuery.getXQueryExpression(), xmlQuery.getPassing(), tuple);
- 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$
- } catch (XPathException e) {
- throw new FunctionExecutionException(e, QueryPlugin.Util.getString("Evaluator.xmlquery", e.getMessage())); //$NON-NLS-1$
- } finally {
- if (result != null) {
- result.close();
- }
- }
- }
-
- private Object evaluateXMLSerialize(List<?> tuple, XMLSerialize xs)
- throws ExpressionEvaluationException, BlockedException,
- TeiidComponentException, FunctionExecutionException {
- XMLType value = (XMLType) internalEvaluate(xs.getExpression(), tuple);
- if (value == null) {
- return null;
- }
- try {
- if (xs.isDocument() == null || !xs.isDocument()) {
- return serialize(xs, value);
- }
- if (value.getType() == Type.UNKNOWN) {
- Type type = StringToSQLXMLTransform.isXml(value.getCharacterStream());
- value.setType(type);
- }
- if (value.getType() == Type.DOCUMENT || value.getType() == Type.ELEMENT) {
- return serialize(xs, value);
- }
- } catch (SQLException e) {
- throw new FunctionExecutionException(e, e.getMessage());
- } catch (TransformationException e) {
- throw new FunctionExecutionException(e, e.getMessage());
- }
- throw new FunctionExecutionException(QueryPlugin.Util.getString("Evaluator.xmlserialize")); //$NON-NLS-1$
- }
-
- private Object serialize(XMLSerialize xs, XMLType value) throws TransformationException {
- if (xs.getType() == DataTypeManager.DefaultDataClasses.STRING) {
- return DataTypeManager.transformValue(value, xs.getType());
- }
- InputStreamFactory isf = getInputStreamFactory(value);
- return new ClobType(new ClobImpl(isf, -1));
- }
-
- private Object evaluateTextLine(List<?> tuple, TextLine function) throws ExpressionEvaluationException, BlockedException, TeiidComponentException, FunctionExecutionException {
- List<DerivedColumn> args = function.getExpressions();
- Evaluator.NameValuePair<Object>[] nameValuePairs = getNameValuePairs(tuple, args, true);
-
- try {
- return TextLine.evaluate(Arrays.asList(nameValuePairs), new TextLine.ValueExtractor<NameValuePair<Object>>() {
- public Object getValue(NameValuePair<Object> t) {
- return t.value;
- }
- }, function.getDelimiter(), function.getQuote());
- } catch (TransformationException e) {
- throw new ExpressionEvaluationException(e, e.getMessage());
- }
- }
-
- private Object evaluateXMLForest(List<?> tuple, XMLForest function)
- throws ExpressionEvaluationException, BlockedException,
- TeiidComponentException, FunctionExecutionException {
- List<DerivedColumn> args = function.getArgs();
- Evaluator.NameValuePair<Object>[] nameValuePairs = getNameValuePairs(tuple, args, true);
-
- try {
- return XMLSystemFunctions.xmlForest(context, namespaces(function.getNamespaces()), nameValuePairs);
- } catch (TeiidProcessingException e) {
- throw new FunctionExecutionException(e, e.getMessage());
- }
- }
-
- private Object evaluateXMLElement(List<?> tuple, XMLElement function)
- throws ExpressionEvaluationException, BlockedException,
- TeiidComponentException, FunctionExecutionException {
- List<Expression> content = function.getContent();
- List<Object> values = new ArrayList<Object>(content.size());
- for (Expression exp : content) {
- values.add(internalEvaluate(exp, tuple));
- }
- try {
- Evaluator.NameValuePair<Object>[] attributes = null;
- if (function.getAttributes() != null) {
- attributes = getNameValuePairs(tuple, function.getAttributes().getArgs(), true);
- }
- return XMLSystemFunctions.xmlElement(context, function.getName(), namespaces(function.getNamespaces()), attributes, values);
- } catch (TeiidProcessingException e) {
- throw new FunctionExecutionException(e, e.getMessage());
- }
- }
-
- public Result evaluateXQuery(SaxonXQueryExpression xquery, List<DerivedColumn> cols, List<?> tuple)
- throws BlockedException, TeiidComponentException, TeiidProcessingException {
- HashMap<String, Object> parameters = new HashMap<String, Object>();
- Object contextItem = null;
- for (DerivedColumn passing : cols) {
- Object value = this.evaluate(passing.getExpression(), tuple);
- if (passing.getAlias() == null) {
- contextItem = value;
- } else {
- parameters.put(passing.getAlias(), value);
- }
- }
- return xquery.evaluateXQuery(contextItem, parameters);
- }
-
- private Evaluator.NameValuePair<Object>[] getNameValuePairs(List<?> tuple, List<DerivedColumn> args, boolean xmlNames)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
- Evaluator.NameValuePair<Object>[] nameValuePairs = new Evaluator.NameValuePair[args.size()];
- for (int i = 0; i < args.size(); i++) {
- DerivedColumn symbol = args.get(i);
- String name = symbol.getAlias();
- Expression ex = symbol.getExpression();
- if (name == null && ex instanceof ElementSymbol) {
- name = ((ElementSymbol)ex).getShortName();
- if (xmlNames) {
- name = XMLSystemFunctions.escapeName(name, true);
- }
- }
- nameValuePairs[i] = new Evaluator.NameValuePair<Object>(name, internalEvaluate(ex, tuple));
- }
- return nameValuePairs;
- }
-
- private Evaluator.NameValuePair<String>[] namespaces(XMLNamespaces namespaces) {
- if (namespaces == null) {
- return null;
- }
- List<NamespaceItem> args = namespaces.getNamespaceItems();
- Evaluator.NameValuePair<String>[] nameValuePairs = new Evaluator.NameValuePair[args.size()];
- for(int i=0; i < args.size(); i++) {
- NamespaceItem item = args.get(i);
- nameValuePairs[i] = new Evaluator.NameValuePair<String>(item.getPrefix(), item.getUri());
- }
- return nameValuePairs;
- }
-
- private Object evaluate(CaseExpression expr, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
- Object exprVal = internalEvaluate(expr.getExpression(), tuple);
- for (int i = 0; i < expr.getWhenCount(); i++) {
- if (EquivalenceUtil.areEqual(exprVal, internalEvaluate(expr.getWhenExpression(i), tuple))) {
- return internalEvaluate(expr.getThenExpression(i), tuple);
- }
- }
- if (expr.getElseExpression() != null) {
- return internalEvaluate(expr.getElseExpression(), tuple);
- }
- return null;
- }
-
- private Object evaluate(SearchedCaseExpression expr, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
- for (int i = 0; i < expr.getWhenCount(); i++) {
- try {
- if (evaluate(expr.getWhenCriteria(i), tuple)) {
- return internalEvaluate(expr.getThenExpression(i), tuple);
- }
- } catch (ExpressionEvaluationException e) {
- throw new ExpressionEvaluationException(e, "ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", "CASE", expr.getWhenCriteria(i))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- }
- if (expr.getElseExpression() != null) {
- return internalEvaluate(expr.getElseExpression(), tuple);
- }
- return null;
- }
-
- private Object evaluate(Function function, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
- // Get function based on resolved function info
- FunctionDescriptor fd = function.getFunctionDescriptor();
-
- // Evaluate args
- Expression[] args = function.getArgs();
- Object[] values = null;
- int start = 0;
-
- if (fd.requiresContext()) {
- values = new Object[args.length+1];
- values[0] = context;
- start = 1;
- }
- else {
- values = new Object[args.length];
- }
-
- for(int i=0; i < args.length; i++) {
- values[i+start] = internalEvaluate(args[i], tuple);
- }
-
- // Check for function we can't evaluate
- if(fd.getPushdown() == PushDown.MUST_PUSHDOWN) {
- throw new TeiidComponentException(QueryPlugin.Util.getString("ExpressionEvaluator.Must_push", fd.getName())); //$NON-NLS-1$
- }
-
- // Check for special lookup function
- if(fd.getName().equalsIgnoreCase(FunctionLibrary.LOOKUP)) {
- if(dataMgr == null) {
- throw new ComponentNotFoundException("ERR.015.006.0055", QueryPlugin.Util.getString("ERR.015.006.0055")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- String codeTableName = (String) values[0];
- String returnElementName = (String) values[1];
- String keyElementName = (String) values[2];
-
- try {
- return dataMgr.lookupCodeValue(context, codeTableName, returnElementName, keyElementName, values[3]);
- } catch (TeiidProcessingException e) {
- throw new ExpressionEvaluationException(e, e.getMessage());
- }
- }
-
- // Execute function
- Object result = fd.invokeFunction(values);
- return result;
- }
-
- private Object evaluate(ScalarSubquery scalarSubquery, List<?> tuple)
- throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
- Object result = null;
- ValueIterator valueIter;
- try {
- valueIter = evaluateSubquery(scalarSubquery, tuple);
- } catch (TeiidProcessingException e) {
- throw new ExpressionEvaluationException(e, e.getMessage());
- }
- if(valueIter.hasNext()) {
- result = valueIter.next();
- if(valueIter.hasNext()) {
- // The subquery should be scalar, but has produced
- // more than one result value - this is an exception case
- throw new ExpressionEvaluationException("ERR.015.006.0058", QueryPlugin.Util.getString("ERR.015.006.0058", scalarSubquery.getCommand())); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- return result;
- }
-
- protected ValueIterator evaluateSubquery(SubqueryContainer container, List<?> tuple)
- throws TeiidProcessingException, BlockedException, TeiidComponentException {
- throw new UnsupportedOperationException("Subquery evaluation not possible with a base Evaluator"); //$NON-NLS-1$
- }
-
- private CommandContext getContext(LanguageObject expression) throws TeiidComponentException {
- if (context == null) {
- throw new TeiidComponentException("ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", expression, "No value was available")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return context;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/eval/Evaluator.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1023 @@
+/*
+ * 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.eval;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+
+import net.sf.saxon.trans.XPathException;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.FunctionExecutionException;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.core.ComponentNotFoundException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.BlobType;
+import org.teiid.core.types.ClobImpl;
+import org.teiid.core.types.ClobType;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.InputStreamFactory;
+import org.teiid.core.types.SQLXMLImpl;
+import org.teiid.core.types.Sequencable;
+import org.teiid.core.types.Streamable;
+import org.teiid.core.types.TransformationException;
+import org.teiid.core.types.XMLType;
+import org.teiid.core.types.XMLType.Type;
+import org.teiid.core.types.basic.StringToSQLXMLTransform;
+import org.teiid.core.util.EquivalenceUtil;
+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.processor.ProcessorDataManager;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.lang.AbstractSetCriteria;
+import org.teiid.query.sql.lang.CollectionValueIterator;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.DependentSetCriteria;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.ExpressionCriteria;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.MatchCriteria;
+import org.teiid.query.sql.lang.NotCriteria;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SubqueryCompareCriteria;
+import org.teiid.query.sql.lang.SubqueryContainer;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+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.ContextReference;
+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.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.SingleElementSymbol;
+import org.teiid.query.sql.symbol.TextLine;
+import org.teiid.query.sql.symbol.XMLElement;
+import org.teiid.query.sql.symbol.XMLForest;
+import org.teiid.query.sql.symbol.XMLNamespaces;
+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.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.SaxonXQueryExpression.Result;
+import org.teiid.translator.WSConnection.Util;
+
+public class Evaluator {
+
+ private final class SequenceReader extends Reader {
+ private LinkedList<Reader> readers;
+ private Reader current = null;
+
+ public SequenceReader(LinkedList<Reader> readers) {
+ this.readers = readers;
+ }
+
+ @Override
+ public void close() throws IOException {
+ for (Reader reader : readers) {
+ try {
+ reader.close();
+ } catch (IOException e) {
+
+ }
+ }
+ }
+
+ @Override
+ public int read(char[] cbuf, int off, int len)
+ throws IOException {
+ if (current == null && !readers.isEmpty()) {
+ current = readers.removeFirst();
+ }
+ if (current == null) {
+ return -1;
+ }
+ int read = current.read(cbuf, off, len);
+ if (read == -1) {
+ current.close();
+ current = null;
+ read = 0;
+ }
+ if (read < len) {
+ int nextRead = read(cbuf, off + read, len - read);
+ if (nextRead > 0) {
+ read += nextRead;
+ }
+ }
+ return read;
+ }
+ }
+
+ public static class NameValuePair<T> {
+ public String name;
+ public T value;
+
+ public NameValuePair(String name, T value) {
+ this.name = name;
+ this.value = value;
+ }
+ }
+
+ 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$
+
+ private Map elements;
+
+ protected ProcessorDataManager dataMgr;
+ protected CommandContext context;
+
+ public static boolean evaluate(Criteria criteria) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+ return new Evaluator(Collections.emptyMap(), null, null).evaluate(criteria, Collections.emptyList());
+ }
+
+ public static Object evaluate(Expression expression) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+ return new Evaluator(Collections.emptyMap(), null, null).evaluate(expression, Collections.emptyList());
+ }
+
+ public Evaluator(Map elements, ProcessorDataManager dataMgr, CommandContext context) {
+ this.context = context;
+ this.dataMgr = dataMgr;
+ this.elements = elements;
+ }
+
+ public void initialize(CommandContext context, ProcessorDataManager dataMgr) {
+ this.context = context;
+ this.dataMgr = dataMgr;
+ }
+
+ public boolean evaluate(Criteria criteria, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+ return Boolean.TRUE.equals(evaluateTVL(criteria, tuple));
+ }
+
+ public Boolean evaluateTVL(Criteria criteria, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+ if(criteria instanceof CompoundCriteria) {
+ return evaluate((CompoundCriteria)criteria, tuple);
+ } else if(criteria instanceof NotCriteria) {
+ return evaluate((NotCriteria)criteria, tuple);
+ } else if(criteria instanceof CompareCriteria) {
+ return evaluate((CompareCriteria)criteria, tuple);
+ } else if(criteria instanceof MatchCriteria) {
+ return evaluate((MatchCriteria)criteria, tuple);
+ } else if(criteria instanceof AbstractSetCriteria) {
+ return evaluate((AbstractSetCriteria)criteria, tuple);
+ } else if(criteria instanceof IsNullCriteria) {
+ return Boolean.valueOf(evaluate((IsNullCriteria)criteria, tuple));
+ } else if(criteria instanceof SubqueryCompareCriteria) {
+ return evaluate((SubqueryCompareCriteria)criteria, tuple);
+ } else if(criteria instanceof ExistsCriteria) {
+ return Boolean.valueOf(evaluate((ExistsCriteria)criteria, tuple));
+ } else if (criteria instanceof ExpressionCriteria) {
+ return (Boolean)evaluate(((ExpressionCriteria)criteria).getExpression(), tuple);
+ } else {
+ throw new ExpressionEvaluationException("ERR.015.006.0010", QueryPlugin.Util.getString("ERR.015.006.0010", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ public Boolean evaluate(CompoundCriteria criteria, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+ List subCrits = criteria.getCriteria();
+ Iterator subCritIter = subCrits.iterator();
+
+ boolean and = criteria.getOperator() == CompoundCriteria.AND;
+ Boolean result = and?Boolean.TRUE:Boolean.FALSE;
+ while(subCritIter.hasNext()) {
+ Criteria subCrit = (Criteria) subCritIter.next();
+ Boolean value = evaluateTVL(subCrit, tuple);
+ if (value == null) {
+ result = null;
+ } else if (!value.booleanValue()) {
+ if (and) {
+ return Boolean.FALSE;
+ }
+ } else if (!and) {
+ return Boolean.TRUE;
+ }
+ }
+ return result;
+ }
+
+ public Boolean evaluate(NotCriteria criteria, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+ Criteria subCrit = criteria.getCriteria();
+ Boolean result = evaluateTVL(subCrit, tuple);
+ if (result == null) {
+ return null;
+ }
+ if (result.booleanValue()) {
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ public Boolean evaluate(CompareCriteria criteria, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+ // Evaluate left expression
+ Object leftValue = null;
+ try {
+ leftValue = evaluate(criteria.getLeftExpression(), tuple);
+ } catch(ExpressionEvaluationException e) {
+ throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[] {"left", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ // Shortcut if null
+ if(leftValue == null) {
+ return null;
+ }
+
+ // Evaluate right expression
+ Object rightValue = null;
+ try {
+ rightValue = evaluate(criteria.getRightExpression(), tuple);
+ } catch(ExpressionEvaluationException e) {
+ throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[]{"right", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ // Shortcut if null
+ if(rightValue == null) {
+ return null;
+ }
+
+ // Compare two non-null values using specified operator
+ return compare(criteria, leftValue, rightValue);
+ }
+
+ public static Boolean compare(CompareCriteria criteria, Object leftValue,
+ Object rightValue) throws ExpressionEvaluationException {
+ switch(criteria.getOperator()) {
+ case CompareCriteria.EQ:
+ return Boolean.valueOf(compareValues(leftValue, rightValue) == 0);
+ case CompareCriteria.NE:
+ return Boolean.valueOf(compareValues(leftValue, rightValue) != 0);
+ case CompareCriteria.LT:
+ return Boolean.valueOf((compareValues(leftValue, rightValue) < 0));
+ case CompareCriteria.LE:
+ return Boolean.valueOf((compareValues(leftValue, rightValue) <= 0));
+ case CompareCriteria.GT:
+ return Boolean.valueOf((compareValues(leftValue, rightValue) > 0));
+ case CompareCriteria.GE:
+ return Boolean.valueOf((compareValues(leftValue, rightValue) >= 0));
+ default:
+ throw new ExpressionEvaluationException("ERR.015.006.0012", QueryPlugin.Util.getString("ERR.015.006.0012", criteria.getOperator())); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ private static final int compareValues(Object leftValue, Object rightValue) {
+ assert leftValue instanceof Comparable<?>;
+ assert rightValue instanceof Comparable<?>;
+ if (leftValue == rightValue) {
+ return 0;
+ }
+ return ((Comparable<Object>)leftValue).compareTo(rightValue);
+ }
+
+ public Boolean evaluate(MatchCriteria criteria, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+ boolean result = false;
+ // Evaluate left expression
+ Object value = null;
+ try {
+ value = evaluate(criteria.getLeftExpression(), tuple);
+ } catch(ExpressionEvaluationException e) {
+ throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[]{"left", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ // Shortcut if null
+ if(value == null) {
+ return null;
+ }
+
+ CharSequence leftValue = null;
+
+ if (value instanceof CharSequence) {
+ leftValue = (CharSequence)value;
+ } else {
+ try {
+ leftValue = ((Sequencable)value).getCharSequence();
+ } catch (SQLException err) {
+ throw new ExpressionEvaluationException(err, err.getMessage());
+ }
+ }
+
+ // Evaluate right expression
+ String rightValue = null;
+ try {
+ rightValue = (String) evaluate(criteria.getRightExpression(), tuple);
+ } catch(ExpressionEvaluationException e) {
+ throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[]{"right", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ // Shortcut if null
+ if(rightValue == null) {
+ return null;
+ }
+
+ result = match(rightValue, criteria.getEscapeChar(), leftValue);
+
+ return Boolean.valueOf(result ^ criteria.isNegated());
+ }
+
+ private boolean match(String pattern, char escape, CharSequence search)
+ throws ExpressionEvaluationException {
+
+ StringBuffer rePattern = LIKE_TO_REGEX.translate(pattern, escape);
+
+ // 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$
+ }
+ }
+
+ private Boolean evaluate(AbstractSetCriteria criteria, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+ // Evaluate expression
+ Object leftValue = null;
+ try {
+ leftValue = evaluate(criteria.getExpression(), tuple);
+ } catch(ExpressionEvaluationException e) {
+ throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // Shortcut if null
+ if(leftValue == null) {
+ return null;
+ }
+ Boolean result = Boolean.FALSE;
+
+ ValueIterator valueIter = null;
+ if (criteria instanceof SetCriteria) {
+ SetCriteria set = (SetCriteria)criteria;
+ if (set.isAllConstants()) {
+ boolean exists = set.getValues().contains(new Constant(leftValue, criteria.getExpression().getType()));
+ if (!exists) {
+ if (set.getValues().contains(Constant.NULL_CONSTANT)) {
+ return null;
+ }
+ return criteria.isNegated();
+ }
+ return !criteria.isNegated();
+ }
+ valueIter = new CollectionValueIterator(((SetCriteria)criteria).getValues());
+ } else if (criteria instanceof DependentSetCriteria){
+ ContextReference ref = (ContextReference)criteria;
+ VariableContext vc = getContext(criteria).getVariableContext();
+ ValueIteratorSource vis = (ValueIteratorSource)vc.getGlobalValue(ref.getContextSymbol());
+ Set<Object> values;
+ try {
+ values = vis.getCachedSet(ref.getValueExpression());
+ } catch (TeiidProcessingException e) {
+ throw new ExpressionEvaluationException(e, e.getMessage());
+ }
+ 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;
+ } else if (criteria instanceof SubquerySetCriteria) {
+ try {
+ valueIter = evaluateSubquery((SubquerySetCriteria)criteria, tuple);
+ } catch (TeiidProcessingException e) {
+ throw new ExpressionEvaluationException(e, e.getMessage());
+ }
+ } else {
+ throw new AssertionError("unknown set criteria type"); //$NON-NLS-1$
+ }
+ while(valueIter.hasNext()) {
+ Object possibleValue = valueIter.next();
+ Object value = null;
+ if(possibleValue instanceof Expression) {
+ try {
+ value = evaluate((Expression) possibleValue, tuple);
+ } catch(ExpressionEvaluationException e) {
+ throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", possibleValue)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ } else {
+ value = possibleValue;
+ }
+
+ if(value != null) {
+ if(compareValues(leftValue, value) == 0) {
+ return Boolean.valueOf(!criteria.isNegated());
+ } // else try next value
+ } else {
+ result = null;
+ }
+ }
+
+ if (result == null) {
+ return null;
+ }
+
+ return Boolean.valueOf(criteria.isNegated());
+ }
+
+ public boolean evaluate(IsNullCriteria criteria, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+ // Evaluate expression
+ Object value = null;
+ try {
+ value = evaluate(criteria.getExpression(), tuple);
+ } catch(ExpressionEvaluationException e) {
+ throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ return (value == null ^ criteria.isNegated());
+ }
+
+ private Boolean evaluate(SubqueryCompareCriteria criteria, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+ // Evaluate expression
+ Object leftValue = null;
+ try {
+ leftValue = evaluate(criteria.getLeftExpression(), tuple);
+ } catch(ExpressionEvaluationException e) {
+ throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // Shortcut if null
+ if(leftValue == null) {
+ return null;
+ }
+
+ // Need to be careful to initialize this variable carefully for the case
+ // where valueIterator has no values, and the block below is not entered.
+ // If there are no rows, and ALL is the predicate quantifier, the result
+ // should be true. If SOME is the predicate quantifier, or no quantifier
+ // is used, the result should be false.
+ Boolean result = Boolean.FALSE;
+ if (criteria.getPredicateQuantifier() == SubqueryCompareCriteria.ALL){
+ result = Boolean.TRUE;
+ }
+
+ ValueIterator valueIter;
+ try {
+ valueIter = evaluateSubquery(criteria, tuple);
+ } catch (TeiidProcessingException e) {
+ throw new ExpressionEvaluationException(e, e.getMessage());
+ }
+ while(valueIter.hasNext()) {
+ Object value = valueIter.next();
+
+ if(value != null) {
+ int compare = compareValues(leftValue, value);
+ // Compare two non-null values using specified operator
+ switch(criteria.getOperator()) {
+ case SubqueryCompareCriteria.EQ:
+ result = Boolean.valueOf(compare == 0);
+ break;
+ case SubqueryCompareCriteria.NE:
+ result = Boolean.valueOf(compare != 0);
+ break;
+ case SubqueryCompareCriteria.LT:
+ result = Boolean.valueOf(compare < 0);
+ break;
+ case SubqueryCompareCriteria.LE:
+ result = Boolean.valueOf(compare <= 0);
+ break;
+ case SubqueryCompareCriteria.GT:
+ result = Boolean.valueOf(compare > 0);
+ break;
+ case SubqueryCompareCriteria.GE:
+ result = Boolean.valueOf(compare >= 0);
+ break;
+ default:
+ throw new ExpressionEvaluationException("ERR.015.006.0012", QueryPlugin.Util.getString("ERR.015.006.0012", criteria.getOperator())); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ switch(criteria.getPredicateQuantifier()) {
+ case SubqueryCompareCriteria.ALL:
+ if (Boolean.FALSE.equals(result)){
+ return Boolean.FALSE;
+ }
+ break;
+ case SubqueryCompareCriteria.SOME:
+ if (Boolean.TRUE.equals(result)){
+ return Boolean.TRUE;
+ }
+ break;
+ default:
+ throw new ExpressionEvaluationException("ERR.015.006.0057", QueryPlugin.Util.getString("ERR.015.006.0057", criteria.getPredicateQuantifier())); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ } else { // value is null
+ result = null;
+ }
+
+
+ } //end value iteration
+
+ return result;
+ }
+
+ public boolean evaluate(ExistsCriteria criteria, List<?> tuple)
+ throws BlockedException, TeiidComponentException, ExpressionEvaluationException {
+
+ ValueIterator valueIter;
+ try {
+ valueIter = evaluateSubquery(criteria, tuple);
+ } catch (TeiidProcessingException e) {
+ throw new ExpressionEvaluationException(e, e.getMessage());
+ }
+ if(valueIter.hasNext()) {
+ return !criteria.isNegated();
+ }
+ return criteria.isNegated();
+ }
+
+ public Object evaluate(Expression expression, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+ try {
+ return internalEvaluate(expression, tuple);
+ } catch (ExpressionEvaluationException e) {
+ throw new ExpressionEvaluationException(e, QueryPlugin.Util.getString("ExpressionEvaluator.Eval_failed", new Object[] {expression, e.getMessage()})); //$NON-NLS-1$
+ }
+ }
+
+ private Object internalEvaluate(Expression expression, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+ if(expression instanceof SingleElementSymbol) {
+ if (elements != null) {
+ // Try to evaluate by lookup in the elements map (may work for both ElementSymbol and ExpressionSymbol
+ Integer index = (Integer) elements.get(expression);
+ if(index != null) {
+ return tuple.get(index.intValue());
+ }
+ }
+
+ // Otherwise this should be an ExpressionSymbol and we just need to dive in and evaluate the expression itself
+ if (expression instanceof ExpressionSymbol && !(expression instanceof AggregateSymbol)) {
+ ExpressionSymbol exprSyb = (ExpressionSymbol) expression;
+ Expression expr = exprSyb.getExpression();
+ return internalEvaluate(expr, tuple);
+ }
+
+ return getContext(expression).getFromContext(expression);
+ }
+ if(expression instanceof Constant) {
+ return ((Constant) expression).getValue();
+ } else if(expression instanceof Function) {
+ return evaluate((Function) expression, tuple);
+ } else if(expression instanceof CaseExpression) {
+ return evaluate((CaseExpression) expression, tuple);
+ } else if(expression instanceof SearchedCaseExpression) {
+ return evaluate((SearchedCaseExpression) expression, tuple);
+ } else if(expression instanceof Reference) {
+ Reference ref = (Reference)expression;
+ if (ref.isPositional() && ref.getExpression() == null) {
+ return getContext(ref).getVariableContext().getGlobalValue(ref.getContextSymbol());
+ }
+ return internalEvaluate(ref.getExpression(), tuple);
+ } else if(expression instanceof Criteria) {
+ return evaluate((Criteria) expression, tuple);
+ } else if(expression instanceof ScalarSubquery) {
+ return evaluate((ScalarSubquery) expression, tuple);
+ } else if (expression instanceof Criteria) {
+ return evaluate((Criteria)expression, tuple);
+ } else if (expression instanceof TextLine){
+ return evaluateTextLine(tuple, (TextLine)expression);
+ } else if (expression instanceof XMLElement){
+ return evaluateXMLElement(tuple, (XMLElement)expression);
+ } else if (expression instanceof XMLForest){
+ return evaluateXMLForest(tuple, (XMLForest)expression);
+ } else if (expression instanceof XMLSerialize){
+ return evaluateXMLSerialize(tuple, (XMLSerialize)expression);
+ } else if (expression instanceof XMLQuery) {
+ return evaluateXMLQuery(tuple, (XMLQuery)expression);
+ } else if (expression instanceof QueryString) {
+ return evaluateQueryString(tuple, (QueryString)expression);
+ } else if (expression instanceof XMLParse){
+ return evaluateXMLParse(tuple, (XMLParse)expression);
+ } else {
+ throw new TeiidComponentException("ERR.015.006.0016", QueryPlugin.Util.getString("ERR.015.006.0016", expression.getClass().getName())); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ private Object evaluateXMLParse(List<?> tuple, final XMLParse xp) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+ Object value = internalEvaluate(xp.getExpression(), tuple);
+ if (value == null) {
+ return null;
+ }
+ XMLType.Type type = Type.DOCUMENT;
+ SQLXMLImpl result = null;
+ try {
+ if (value instanceof String) {
+ String string = (String)value;
+ result = new SQLXMLImpl(string);
+ result.setEncoding(Streamable.ENCODING);
+ if (!xp.isWellFormed()) {
+ Reader r = new StringReader(string);
+ type = validate(xp, r);
+ }
+ } else {
+ InputStreamFactory isf = null;
+ Streamable<?> s = (Streamable<?>)value;
+ isf = getInputStreamFactory(s);
+ result = new SQLXMLImpl(isf);
+ if (!xp.isWellFormed()) {
+ Reader r = result.getCharacterStream();
+ type = validate(xp, r);
+ }
+ }
+ } catch (TransformationException e) {
+ throw new ExpressionEvaluationException(e, e.getMessage());
+ } catch (SQLException e) {
+ throw new ExpressionEvaluationException(e, e.getMessage());
+ }
+ if (!xp.isDocument()) {
+ type = Type.CONTENT;
+ }
+ XMLType xml = new XMLType(result);
+ xml.setType(type);
+ return xml;
+ }
+
+ //TODO: determine when wrapping is not needed
+ public static InputStreamFactory getInputStreamFactory(Streamable<?> s) {
+ if (s instanceof ClobType) {
+ return new InputStreamFactory.ClobInputStreamFactory((Clob)s.getReference());
+ } else if (s instanceof BlobType){
+ return new InputStreamFactory.BlobInputStreamFactory((Blob)s.getReference());
+ }
+ return new InputStreamFactory.SQLXMLInputStreamFactory((SQLXML)s.getReference());
+ }
+
+ private Type validate(final XMLParse xp, Reader r)
+ throws TransformationException {
+ if (!xp.isDocument()) {
+ LinkedList<Reader> readers = new LinkedList<Reader>();
+ readers.add(new StringReader("<r>")); //$NON-NLS-1$
+ readers.add(r);
+ readers.add(new StringReader("</r>")); //$NON-NLS-1$
+ r = new SequenceReader(readers);
+ }
+ return StringToSQLXMLTransform.isXml(r);
+ }
+
+ //TODO: exception if length is too long?
+ private Object evaluateQueryString(List<?> tuple, QueryString queryString)
+ throws ExpressionEvaluationException, BlockedException,
+ TeiidComponentException {
+ Evaluator.NameValuePair<Object>[] pairs = getNameValuePairs(tuple, queryString.getArgs(), false);
+ String path = (String)internalEvaluate(queryString.getPath(), tuple);
+ if (path == null) {
+ path = ""; //$NON-NLS-1$
+ }
+ boolean appendedAny = false;
+ StringBuilder result = new StringBuilder();
+ for (Evaluator.NameValuePair<Object> nameValuePair : pairs) {
+ if (nameValuePair.value == null) {
+ continue;
+ }
+ if (appendedAny) {
+ result.append('&');
+ }
+ appendedAny = true;
+ result.append(Util.httpURLEncode(nameValuePair.name)).append('=').append(Util.httpURLEncode((String)nameValuePair.value));
+ }
+ if (!appendedAny) {
+ return path;
+ }
+ result.insert(0, '?');
+ result.insert(0, path);
+ return result.toString();
+ }
+
+ private Object evaluateXMLQuery(List<?> tuple, XMLQuery xmlQuery)
+ throws BlockedException, TeiidComponentException,
+ FunctionExecutionException {
+ boolean emptyOnEmpty = true;
+ if (xmlQuery.getEmptyOnEmpty() != null) {
+ emptyOnEmpty = xmlQuery.getEmptyOnEmpty();
+ }
+ Result result = null;
+ try {
+ result = evaluateXQuery(xmlQuery.getXQueryExpression(), xmlQuery.getPassing(), tuple);
+ 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$
+ } catch (XPathException e) {
+ throw new FunctionExecutionException(e, QueryPlugin.Util.getString("Evaluator.xmlquery", e.getMessage())); //$NON-NLS-1$
+ } finally {
+ if (result != null) {
+ result.close();
+ }
+ }
+ }
+
+ private Object evaluateXMLSerialize(List<?> tuple, XMLSerialize xs)
+ throws ExpressionEvaluationException, BlockedException,
+ TeiidComponentException, FunctionExecutionException {
+ XMLType value = (XMLType) internalEvaluate(xs.getExpression(), tuple);
+ if (value == null) {
+ return null;
+ }
+ try {
+ if (xs.isDocument() == null || !xs.isDocument()) {
+ return serialize(xs, value);
+ }
+ if (value.getType() == Type.UNKNOWN) {
+ Type type = StringToSQLXMLTransform.isXml(value.getCharacterStream());
+ value.setType(type);
+ }
+ if (value.getType() == Type.DOCUMENT || value.getType() == Type.ELEMENT) {
+ return serialize(xs, value);
+ }
+ } catch (SQLException e) {
+ throw new FunctionExecutionException(e, e.getMessage());
+ } catch (TransformationException e) {
+ throw new FunctionExecutionException(e, e.getMessage());
+ }
+ throw new FunctionExecutionException(QueryPlugin.Util.getString("Evaluator.xmlserialize")); //$NON-NLS-1$
+ }
+
+ private Object serialize(XMLSerialize xs, XMLType value) throws TransformationException {
+ if (xs.getType() == DataTypeManager.DefaultDataClasses.STRING) {
+ return DataTypeManager.transformValue(value, xs.getType());
+ }
+ InputStreamFactory isf = getInputStreamFactory(value);
+ return new ClobType(new ClobImpl(isf, -1));
+ }
+
+ private Object evaluateTextLine(List<?> tuple, TextLine function) throws ExpressionEvaluationException, BlockedException, TeiidComponentException, FunctionExecutionException {
+ List<DerivedColumn> args = function.getExpressions();
+ Evaluator.NameValuePair<Object>[] nameValuePairs = getNameValuePairs(tuple, args, true);
+
+ try {
+ return TextLine.evaluate(Arrays.asList(nameValuePairs), new TextLine.ValueExtractor<NameValuePair<Object>>() {
+ public Object getValue(NameValuePair<Object> t) {
+ return t.value;
+ }
+ }, function.getDelimiter(), function.getQuote());
+ } catch (TransformationException e) {
+ throw new ExpressionEvaluationException(e, e.getMessage());
+ }
+ }
+
+ private Object evaluateXMLForest(List<?> tuple, XMLForest function)
+ throws ExpressionEvaluationException, BlockedException,
+ TeiidComponentException, FunctionExecutionException {
+ List<DerivedColumn> args = function.getArgs();
+ Evaluator.NameValuePair<Object>[] nameValuePairs = getNameValuePairs(tuple, args, true);
+
+ try {
+ return XMLSystemFunctions.xmlForest(context, namespaces(function.getNamespaces()), nameValuePairs);
+ } catch (TeiidProcessingException e) {
+ throw new FunctionExecutionException(e, e.getMessage());
+ }
+ }
+
+ private Object evaluateXMLElement(List<?> tuple, XMLElement function)
+ throws ExpressionEvaluationException, BlockedException,
+ TeiidComponentException, FunctionExecutionException {
+ List<Expression> content = function.getContent();
+ List<Object> values = new ArrayList<Object>(content.size());
+ for (Expression exp : content) {
+ values.add(internalEvaluate(exp, tuple));
+ }
+ try {
+ Evaluator.NameValuePair<Object>[] attributes = null;
+ if (function.getAttributes() != null) {
+ attributes = getNameValuePairs(tuple, function.getAttributes().getArgs(), true);
+ }
+ return XMLSystemFunctions.xmlElement(context, function.getName(), namespaces(function.getNamespaces()), attributes, values);
+ } catch (TeiidProcessingException e) {
+ throw new FunctionExecutionException(e, e.getMessage());
+ }
+ }
+
+ public Result evaluateXQuery(SaxonXQueryExpression xquery, List<DerivedColumn> cols, List<?> tuple)
+ throws BlockedException, TeiidComponentException, TeiidProcessingException {
+ HashMap<String, Object> parameters = new HashMap<String, Object>();
+ Object contextItem = null;
+ for (DerivedColumn passing : cols) {
+ Object value = this.evaluate(passing.getExpression(), tuple);
+ if (passing.getAlias() == null) {
+ contextItem = value;
+ } else {
+ parameters.put(passing.getAlias(), value);
+ }
+ }
+ return xquery.evaluateXQuery(contextItem, parameters);
+ }
+
+ private Evaluator.NameValuePair<Object>[] getNameValuePairs(List<?> tuple, List<DerivedColumn> args, boolean xmlNames)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+ Evaluator.NameValuePair<Object>[] nameValuePairs = new Evaluator.NameValuePair[args.size()];
+ for (int i = 0; i < args.size(); i++) {
+ DerivedColumn symbol = args.get(i);
+ String name = symbol.getAlias();
+ Expression ex = symbol.getExpression();
+ if (name == null && ex instanceof ElementSymbol) {
+ name = ((ElementSymbol)ex).getShortName();
+ if (xmlNames) {
+ name = XMLSystemFunctions.escapeName(name, true);
+ }
+ }
+ nameValuePairs[i] = new Evaluator.NameValuePair<Object>(name, internalEvaluate(ex, tuple));
+ }
+ return nameValuePairs;
+ }
+
+ private Evaluator.NameValuePair<String>[] namespaces(XMLNamespaces namespaces) {
+ if (namespaces == null) {
+ return null;
+ }
+ List<NamespaceItem> args = namespaces.getNamespaceItems();
+ Evaluator.NameValuePair<String>[] nameValuePairs = new Evaluator.NameValuePair[args.size()];
+ for(int i=0; i < args.size(); i++) {
+ NamespaceItem item = args.get(i);
+ nameValuePairs[i] = new Evaluator.NameValuePair<String>(item.getPrefix(), item.getUri());
+ }
+ return nameValuePairs;
+ }
+
+ private Object evaluate(CaseExpression expr, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+ Object exprVal = internalEvaluate(expr.getExpression(), tuple);
+ for (int i = 0; i < expr.getWhenCount(); i++) {
+ if (EquivalenceUtil.areEqual(exprVal, internalEvaluate(expr.getWhenExpression(i), tuple))) {
+ return internalEvaluate(expr.getThenExpression(i), tuple);
+ }
+ }
+ if (expr.getElseExpression() != null) {
+ return internalEvaluate(expr.getElseExpression(), tuple);
+ }
+ return null;
+ }
+
+ private Object evaluate(SearchedCaseExpression expr, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+ for (int i = 0; i < expr.getWhenCount(); i++) {
+ try {
+ if (evaluate(expr.getWhenCriteria(i), tuple)) {
+ return internalEvaluate(expr.getThenExpression(i), tuple);
+ }
+ } catch (ExpressionEvaluationException e) {
+ throw new ExpressionEvaluationException(e, "ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", "CASE", expr.getWhenCriteria(i))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ }
+ if (expr.getElseExpression() != null) {
+ return internalEvaluate(expr.getElseExpression(), tuple);
+ }
+ return null;
+ }
+
+ private Object evaluate(Function function, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+ // Get function based on resolved function info
+ FunctionDescriptor fd = function.getFunctionDescriptor();
+
+ // Evaluate args
+ Expression[] args = function.getArgs();
+ Object[] values = null;
+ int start = 0;
+
+ if (fd.requiresContext()) {
+ values = new Object[args.length+1];
+ values[0] = context;
+ start = 1;
+ }
+ else {
+ values = new Object[args.length];
+ }
+
+ for(int i=0; i < args.length; i++) {
+ values[i+start] = internalEvaluate(args[i], tuple);
+ }
+
+ // Check for function we can't evaluate
+ if(fd.getPushdown() == PushDown.MUST_PUSHDOWN) {
+ throw new TeiidComponentException(QueryPlugin.Util.getString("ExpressionEvaluator.Must_push", fd.getName())); //$NON-NLS-1$
+ }
+
+ // Check for special lookup function
+ if(fd.getName().equalsIgnoreCase(FunctionLibrary.LOOKUP)) {
+ if(dataMgr == null) {
+ throw new ComponentNotFoundException("ERR.015.006.0055", QueryPlugin.Util.getString("ERR.015.006.0055")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ String codeTableName = (String) values[0];
+ String returnElementName = (String) values[1];
+ String keyElementName = (String) values[2];
+
+ try {
+ return dataMgr.lookupCodeValue(context, codeTableName, returnElementName, keyElementName, values[3]);
+ } catch (TeiidProcessingException e) {
+ throw new ExpressionEvaluationException(e, e.getMessage());
+ }
+ }
+
+ // Execute function
+ Object result = fd.invokeFunction(values);
+ return result;
+ }
+
+ private Object evaluate(ScalarSubquery scalarSubquery, List<?> tuple)
+ throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+ Object result = null;
+ ValueIterator valueIter;
+ try {
+ valueIter = evaluateSubquery(scalarSubquery, tuple);
+ } catch (TeiidProcessingException e) {
+ throw new ExpressionEvaluationException(e, e.getMessage());
+ }
+ if(valueIter.hasNext()) {
+ result = valueIter.next();
+ if(valueIter.hasNext()) {
+ // The subquery should be scalar, but has produced
+ // more than one result value - this is an exception case
+ throw new ExpressionEvaluationException("ERR.015.006.0058", QueryPlugin.Util.getString("ERR.015.006.0058", scalarSubquery.getCommand())); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+ return result;
+ }
+
+ protected ValueIterator evaluateSubquery(SubqueryContainer container, List<?> tuple)
+ throws TeiidProcessingException, BlockedException, TeiidComponentException {
+ throw new UnsupportedOperationException("Subquery evaluation not possible with a base Evaluator"); //$NON-NLS-1$
+ }
+
+ private CommandContext getContext(LanguageObject expression) throws TeiidComponentException {
+ if (context == null) {
+ throw new TeiidComponentException("ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", expression, "No value was available")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ return context;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingAttribute.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingAttribute.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingAttribute.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,191 +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.mapping.xml;
-
-import org.teiid.query.sql.symbol.ElementSymbol;
-
-
-/**
- * A Mapping node which denotes a attribuite 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;
-
- public MappingAttribute(String name) {
- this(name, MappingNodeConstants.NO_NAMESPACE);
- }
-
- public MappingAttribute(String name, String nameInSource) {
- this(name, MappingNodeConstants.NO_NAMESPACE);
- setNameInSource(nameInSource);
- }
-
- public MappingAttribute(String name, Namespace namespace) {
- setProperty(MappingNodeConstants.Properties.NAME, name);
- setProperty(MappingNodeConstants.Properties.NODE_TYPE, MappingNodeConstants.ATTRIBUTE);
-
- this.namespace = namespace;
- if (namespace != MappingNodeConstants.NO_NAMESPACE) {
- setProperty(MappingNodeConstants.Properties.NAMESPACE_PREFIX, namespace.getPrefix());
- }
- }
-
- public void acceptVisitor(MappingVisitor visitor) {
- visitor.visit(this);
- }
-
- public MappingElement getParentNode() {
- return (MappingElement)getParent();
- }
-
- public Namespace getNamespace() {
- return this.namespace;
- }
-
- public void setNameInSource(String srcName) {
- if (srcName != null) {
- setProperty(MappingNodeConstants.Properties.ELEMENT_NAME, srcName);
- }
- }
-
- public void setDefaultValue(String value) {
- if (value != null) {
- setProperty(MappingNodeConstants.Properties.DEFAULT_VALUE, value);
- }
- }
-
- public void setValue(String value) {
- if (value != null) {
- setProperty(MappingNodeConstants.Properties.FIXED_VALUE, value);
- }
- }
-
- public void setOptional(boolean optional) {
- setProperty(MappingNodeConstants.Properties.IS_OPTIONAL, Boolean.valueOf(optional));
- }
-
- public void setNormalizeText(String normalize) {
- if (normalize != null) {
- setProperty(MappingNodeConstants.Properties.NORMALIZE_TEXT, normalize);
- }
- }
-
- public void setAlwaysInclude(boolean include) {
- setProperty(MappingNodeConstants.Properties.ALWAYS_INCLUDE, Boolean.valueOf(include));
- }
-
- /**
- * @see org.teiid.query.mapping.xml.MappingNode#getPathName()
- */
- public String getPathName() {
- return "@" + super.getPathName(); //$NON-NLS-1$
- }
-
- public String getCanonicalName() {
- return getFullyQualifiedName().toUpperCase();
- }
-
- /**
- * Namespace prefix
- * @return
- */
- public String getNamespacePrefix() {
- return (String)getProperty(MappingNodeConstants.Properties.NAMESPACE_PREFIX);
- }
-
- public String getNameInSource() {
- return (String)getProperty(MappingNodeConstants.Properties.ELEMENT_NAME);
- }
-
- public String getDefaultValue() {
- return (String)getProperty(MappingNodeConstants.Properties.DEFAULT_VALUE);
- }
-
- public String getValue() {
- return (String)getProperty(MappingNodeConstants.Properties.FIXED_VALUE);
- }
-
- public boolean isOptional() {
- Boolean optional = (Boolean)getProperty(MappingNodeConstants.Properties.IS_OPTIONAL);
- if (optional != null) {
- return optional.booleanValue();
- }
- return false;
- }
-
- public String getNormalizeText() {
- String text = (String)getProperty(MappingNodeConstants.Properties.NORMALIZE_TEXT);
- if (text == null) {
- text = MappingNodeConstants.Defaults.DEFAULT_NORMALIZE_TEXT;
- }
- return text;
- }
-
- public boolean isAlwaysInclude() {
- Boolean include = (Boolean)getProperty(MappingNodeConstants.Properties.ALWAYS_INCLUDE);
- if (include != null) {
- return include.booleanValue();
- }
- return false;
- }
-
- public String getSource() {
- return (String) getProperty(MappingNodeConstants.Properties.RESULT_SET_NAME);
- }
-
- public void setElementSymbol(ElementSymbol symbol) {
- this.symbol = symbol;
- }
-
- public ElementSymbol getElementSymbol() {
- return this.symbol;
- }
-
- /**
- * @see org.teiid.query.mapping.xml.MappingNode#getSourceNode()
- */
- public MappingSourceNode getSourceNode() {
- String nameInSource = getNameInSource();
- if (nameInSource != null) {
- String source = nameInSource.substring(0, nameInSource.lastIndexOf('.'));
- MappingBaseNode parent = getParentNode();
- while(parent != null) {
- if (parent instanceof MappingSourceNode) {
- MappingSourceNode sourceNode = (MappingSourceNode)parent;
- if (sourceNode.getResultName().equalsIgnoreCase(source)) {
- return sourceNode;
- }
- }
- parent = parent.getParentNode();
- }
- }
- return super.getSourceNode();
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingAttribute.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingAttribute.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingAttribute.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingAttribute.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,188 @@
+/*
+ * 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.mapping.xml;
+
+import org.teiid.query.sql.symbol.ElementSymbol;
+
+
+/**
+ * A Mapping node which denotes a attribute node.
+ */
+public class MappingAttribute extends MappingNode {
+ // Element symbol in the resultset source
+ ElementSymbol symbol;
+
+ // namespace of the attribute
+ Namespace namespace;
+
+ public MappingAttribute(String name) {
+ this(name, MappingNodeConstants.NO_NAMESPACE);
+ }
+
+ public MappingAttribute(String name, String nameInSource) {
+ this(name, MappingNodeConstants.NO_NAMESPACE);
+ setNameInSource(nameInSource);
+ }
+
+ public MappingAttribute(String name, Namespace namespace) {
+ setProperty(MappingNodeConstants.Properties.NAME, name);
+ setProperty(MappingNodeConstants.Properties.NODE_TYPE, MappingNodeConstants.ATTRIBUTE);
+
+ this.namespace = namespace;
+ if (namespace != MappingNodeConstants.NO_NAMESPACE) {
+ setProperty(MappingNodeConstants.Properties.NAMESPACE_PREFIX, namespace.getPrefix());
+ }
+ }
+
+ public void acceptVisitor(MappingVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ public MappingElement getParentNode() {
+ return (MappingElement)getParent();
+ }
+
+ public Namespace getNamespace() {
+ return this.namespace;
+ }
+
+ public void setNameInSource(String srcName) {
+ if (srcName != null) {
+ setProperty(MappingNodeConstants.Properties.ELEMENT_NAME, srcName);
+ }
+ }
+
+ public void setDefaultValue(String value) {
+ if (value != null) {
+ setProperty(MappingNodeConstants.Properties.DEFAULT_VALUE, value);
+ }
+ }
+
+ public void setValue(String value) {
+ if (value != null) {
+ setProperty(MappingNodeConstants.Properties.FIXED_VALUE, value);
+ }
+ }
+
+ public void setOptional(boolean optional) {
+ setProperty(MappingNodeConstants.Properties.IS_OPTIONAL, Boolean.valueOf(optional));
+ }
+
+ public void setNormalizeText(String normalize) {
+ if (normalize != null) {
+ setProperty(MappingNodeConstants.Properties.NORMALIZE_TEXT, normalize);
+ }
+ }
+
+ public void setAlwaysInclude(boolean include) {
+ setProperty(MappingNodeConstants.Properties.ALWAYS_INCLUDE, Boolean.valueOf(include));
+ }
+
+ /**
+ * @see org.teiid.query.mapping.xml.MappingNode#getPathName()
+ */
+ public String getPathName() {
+ return "@" + super.getPathName(); //$NON-NLS-1$
+ }
+
+ public String getCanonicalName() {
+ return getFullyQualifiedName().toUpperCase();
+ }
+
+ /**
+ * Namespace prefix
+ * @return
+ */
+ public String getNamespacePrefix() {
+ return (String)getProperty(MappingNodeConstants.Properties.NAMESPACE_PREFIX);
+ }
+
+ public String getNameInSource() {
+ return (String)getProperty(MappingNodeConstants.Properties.ELEMENT_NAME);
+ }
+
+ public String getDefaultValue() {
+ return (String)getProperty(MappingNodeConstants.Properties.DEFAULT_VALUE);
+ }
+
+ public String getValue() {
+ return (String)getProperty(MappingNodeConstants.Properties.FIXED_VALUE);
+ }
+
+ public boolean isOptional() {
+ Boolean optional = (Boolean)getProperty(MappingNodeConstants.Properties.IS_OPTIONAL);
+ if (optional != null) {
+ return optional.booleanValue();
+ }
+ return false;
+ }
+
+ public String getNormalizeText() {
+ String text = (String)getProperty(MappingNodeConstants.Properties.NORMALIZE_TEXT);
+ if (text == null) {
+ text = MappingNodeConstants.Defaults.DEFAULT_NORMALIZE_TEXT;
+ }
+ return text;
+ }
+
+ public boolean isAlwaysInclude() {
+ Boolean include = (Boolean)getProperty(MappingNodeConstants.Properties.ALWAYS_INCLUDE);
+ if (include != null) {
+ return include.booleanValue();
+ }
+ return false;
+ }
+
+ public String getSource() {
+ return (String) getProperty(MappingNodeConstants.Properties.RESULT_SET_NAME);
+ }
+
+ public void setElementSymbol(ElementSymbol symbol) {
+ this.symbol = symbol;
+ }
+
+ public ElementSymbol getElementSymbol() {
+ return this.symbol;
+ }
+
+ /**
+ * @see org.teiid.query.mapping.xml.MappingNode#getSourceNode()
+ */
+ public MappingSourceNode getSourceNode() {
+ String nameInSource = getNameInSource();
+ if (nameInSource != null) {
+ String source = nameInSource.substring(0, nameInSource.lastIndexOf('.'));
+ MappingBaseNode parent = getParentNode();
+ while(parent != null) {
+ if (parent instanceof MappingSourceNode) {
+ MappingSourceNode sourceNode = (MappingSourceNode)parent;
+ if (sourceNode.getResultName().equalsIgnoreCase(source)) {
+ return sourceNode;
+ }
+ }
+ parent = parent.getParentNode();
+ }
+ }
+ return super.getSourceNode();
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingBaseNode.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingBaseNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingBaseNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,233 +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.mapping.xml;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.query.QueryPlugin;
-
-
-
-/**
- * This is base class to define all nodes except the attribute. However, this quite not
- * enough to define a Element node. Specially designed for sequence, choice and all node
- * types
- */
-public abstract class MappingBaseNode extends MappingNode {
- // An ID on the recursive parent as to who the recursive child node is?
- String recursionId;
-
- protected MappingBaseNode() {
- // implicit constructor
- }
-
- public MappingBaseNode setMinOccurrs(int cardinality) {
- setProperty(MappingNodeConstants.Properties.CARDINALITY_MIN_BOUND, new Integer(cardinality));
- return this;
- }
-
- public MappingBaseNode setMaxOccurrs(int cardinality) {
- setProperty(MappingNodeConstants.Properties.CARDINALITY_MAX_BOUND, new Integer(cardinality));
- return this;
- }
-
- public MappingBaseNode setSource(String source) {
- if (source != null) {
- setProperty(MappingNodeConstants.Properties.RESULT_SET_NAME, source);
- }
- else {
- removeProperty(MappingNodeConstants.Properties.RESULT_SET_NAME);
- }
- return this;
- }
-
- public String getSource() {
- return (String)getProperty(MappingNodeConstants.Properties.RESULT_SET_NAME);
- }
-
- public MappingElement addChildElement(MappingElement elem) {
- if (elem.isRecursive()) {
- MappingRecursiveElement recursiveElement = (MappingRecursiveElement)elem;
- MappingBaseNode recursiveRoot = getRecursiveRootNode(recursiveElement);
- recursiveRoot.setRootRecursiveNode(true, recursiveElement.getMappingClass().toUpperCase());
- addChild(elem);
- }
- else {
- addChild(elem);
- }
- return elem;
- }
-
- private MappingBaseNode getRecursiveRootNode(MappingRecursiveElement elem) {
- if (hasSource(elem.getMappingClass())) {
- return this;
- }
- MappingBaseNode parent = this.getParentNode();
- if (parent != null) {
- return parent.getRecursiveRootNode(elem);
- }
- throw new TeiidRuntimeException(QueryPlugin.Util.getString("invalid_recurive_node", elem)); //$NON-NLS-1$
- }
-
- /**
- * Any node with its parent node of Source Node, is like property on node itself,
- * as all the source nodes will have atmost one child.
- * @param source
- * @return
- */
- private boolean hasSource(String source) {
- return source.equals(getSource());
- }
-
- public MappingChoiceNode addChoiceNode(MappingChoiceNode elem) {
- addChild(elem);
- return elem;
- }
-
- public MappingSequenceNode addSequenceNode(MappingSequenceNode elem) {
- addChild(elem);
- return elem;
- }
-
- public MappingAllNode addAllNode(MappingAllNode elem) {
- addChild(elem);
- return elem;
- }
-
- public MappingSourceNode addSourceNode(MappingSourceNode elem) {
- addChild(elem);
- return elem;
- }
-
- public MappingCriteriaNode addCriteriaNode(MappingCriteriaNode node) {
- addChild(node);
- return node;
- }
-
- public MappingBaseNode getParentNode() {
- if (getParent() instanceof MappingBaseNode) {
- return (MappingBaseNode)getParent();
- }
- return null;
- }
-
- public String getName() {
- // if we decide to give the choice/seq/all nodes names then
- // we need to change the logic in the "getFullName()"
- return null;
- }
-
- public String getCanonicalName() {
- return getFullyQualifiedName().toUpperCase();
- }
-
- public void removeChildNode(MappingBaseNode toRemove) {
- getChildren().remove(toRemove);
- }
-
- public int getMinOccurence() {
- Integer occur = (Integer)getProperty(MappingNodeConstants.Properties.CARDINALITY_MIN_BOUND);
- if (occur != null) {
- return occur.intValue();
- }
- return 1;
- }
-
- public int getMaxOccurence() {
- Integer occur = (Integer)getProperty(MappingNodeConstants.Properties.CARDINALITY_MAX_BOUND);
- if (occur != null) {
- return occur.intValue();
- }
- return 1;
- }
-
- /**
- * specify the element is a recursive root
- * @param root
- */
- void setRootRecursiveNode(boolean root, String recursionId) {
- setProperty(MappingNodeConstants.Properties.IS_RECURSIVE_ROOT, Boolean.valueOf(root));
- this.recursionId = recursionId;
- }
-
- public String getRecursionId() {
- return this.recursionId;
- }
-
- public boolean isRootRecursiveNode() {
- return Boolean.TRUE.equals(getProperty(MappingNodeConstants.Properties.IS_RECURSIVE_ROOT));
- }
-
- /**
- * Get the document node of this node.
- * @return
- */
- public MappingDocument getDocument() {
- if (isDocumentNode()) {
- return (MappingDocument)this;
- }
- return getParentNode().getDocument();
- }
-
- public boolean isDocumentNode() {
- return false;
- }
-
- /**
- * A tag root node is the first visual node (Element to be specific) in the document tree
- * which is the root element in the output xml document.
- * @return true if
- */
- public boolean isTagRoot() {
- return false;
- }
-
- public List getStagingTables() {
- return (List)getProperty(MappingNodeConstants.Properties.TEMP_GROUP_NAMES);
- }
-
- public void setStagingTables(List tables) {
- if (tables != null) {
- setProperty(MappingNodeConstants.Properties.TEMP_GROUP_NAMES, tables);
- }
- else {
- removeProperty(MappingNodeConstants.Properties.TEMP_GROUP_NAMES);
- }
- }
-
- public void addStagingTable(String tablename) {
- if (tablename == null) {
- return;
- }
- List tables = getStagingTables();
- if (tables == null || tables == Collections.EMPTY_LIST) {
- tables = new ArrayList();
- }
- tables.add(tablename);
- setProperty(MappingNodeConstants.Properties.TEMP_GROUP_NAMES, tables);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingBaseNode.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingBaseNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingBaseNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingBaseNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,232 @@
+/*
+ * 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.mapping.xml;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.query.QueryPlugin;
+
+
+
+/**
+ * This is base class to define all nodes except the attribute. However, this quite not
+ * enough to define a Element node. Specially designed for sequence, choice and all node
+ * types
+ */
+public abstract class MappingBaseNode extends MappingNode {
+ // An ID on the recursive parent as to who the recursive child node is?
+ String recursionId;
+
+ protected MappingBaseNode() {
+ // implicit constructor
+ }
+
+ public MappingBaseNode setMinOccurrs(int cardinality) {
+ setProperty(MappingNodeConstants.Properties.CARDINALITY_MIN_BOUND, new Integer(cardinality));
+ return this;
+ }
+
+ public MappingBaseNode setMaxOccurrs(int cardinality) {
+ setProperty(MappingNodeConstants.Properties.CARDINALITY_MAX_BOUND, new Integer(cardinality));
+ return this;
+ }
+
+ public MappingBaseNode setSource(String source) {
+ if (source != null) {
+ setProperty(MappingNodeConstants.Properties.RESULT_SET_NAME, source);
+ }
+ else {
+ removeProperty(MappingNodeConstants.Properties.RESULT_SET_NAME);
+ }
+ return this;
+ }
+
+ public String getSource() {
+ return (String)getProperty(MappingNodeConstants.Properties.RESULT_SET_NAME);
+ }
+
+ public MappingElement addChildElement(MappingElement elem) {
+ if (elem.isRecursive()) {
+ MappingRecursiveElement recursiveElement = (MappingRecursiveElement)elem;
+ MappingBaseNode recursiveRoot = getRecursiveRootNode(recursiveElement);
+ recursiveRoot.setRootRecursiveNode(true, recursiveElement.getMappingClass().toUpperCase());
+ addChild(elem);
+ }
+ else {
+ addChild(elem);
+ }
+ return elem;
+ }
+
+ private MappingBaseNode getRecursiveRootNode(MappingRecursiveElement elem) {
+ if (hasSource(elem.getMappingClass())) {
+ return this;
+ }
+ MappingBaseNode parent = this.getParentNode();
+ if (parent != null) {
+ return parent.getRecursiveRootNode(elem);
+ }
+ throw new TeiidRuntimeException(QueryPlugin.Util.getString("invalid_recurive_node", elem)); //$NON-NLS-1$
+ }
+
+ /**
+ * Any node with its parent node of Source Node, is like property on node itself,
+ * as all the source nodes will have atmost one child.
+ * @param source
+ * @return
+ */
+ private boolean hasSource(String source) {
+ return source.equals(getSource());
+ }
+
+ public MappingChoiceNode addChoiceNode(MappingChoiceNode elem) {
+ addChild(elem);
+ return elem;
+ }
+
+ public MappingSequenceNode addSequenceNode(MappingSequenceNode elem) {
+ addChild(elem);
+ return elem;
+ }
+
+ public MappingAllNode addAllNode(MappingAllNode elem) {
+ addChild(elem);
+ return elem;
+ }
+
+ public MappingSourceNode addSourceNode(MappingSourceNode elem) {
+ addChild(elem);
+ return elem;
+ }
+
+ public MappingCriteriaNode addCriteriaNode(MappingCriteriaNode node) {
+ addChild(node);
+ return node;
+ }
+
+ public MappingBaseNode getParentNode() {
+ if (getParent() instanceof MappingBaseNode) {
+ return (MappingBaseNode)getParent();
+ }
+ return null;
+ }
+
+ public String getName() {
+ // if we decide to give the choice/seq/all nodes names then
+ // we need to change the logic in the "getFullName()"
+ return null;
+ }
+
+ public String getCanonicalName() {
+ return getFullyQualifiedName().toUpperCase();
+ }
+
+ public void removeChildNode(MappingBaseNode toRemove) {
+ getChildren().remove(toRemove);
+ }
+
+ public int getMinOccurence() {
+ Integer occur = (Integer)getProperty(MappingNodeConstants.Properties.CARDINALITY_MIN_BOUND);
+ if (occur != null) {
+ return occur.intValue();
+ }
+ return 1;
+ }
+
+ public int getMaxOccurence() {
+ Integer occur = (Integer)getProperty(MappingNodeConstants.Properties.CARDINALITY_MAX_BOUND);
+ if (occur != null) {
+ return occur.intValue();
+ }
+ return 1;
+ }
+
+ /**
+ * specify the element is a recursive root
+ * @param root
+ */
+ void setRootRecursiveNode(boolean root, String recursionId) {
+ setProperty(MappingNodeConstants.Properties.IS_RECURSIVE_ROOT, Boolean.valueOf(root));
+ this.recursionId = recursionId;
+ }
+
+ public String getRecursionId() {
+ return this.recursionId;
+ }
+
+ public boolean isRootRecursiveNode() {
+ return Boolean.TRUE.equals(getProperty(MappingNodeConstants.Properties.IS_RECURSIVE_ROOT));
+ }
+
+ /**
+ * Get the document node of this node.
+ * @return
+ */
+ public MappingDocument getDocument() {
+ if (isDocumentNode()) {
+ return (MappingDocument)this;
+ }
+ return getParentNode().getDocument();
+ }
+
+ public boolean isDocumentNode() {
+ return false;
+ }
+
+ /**
+ * A tag root node is the first visual node (Element to be specific) in the document tree
+ * which is the root element in the output xml document.
+ * @return true if
+ */
+ public boolean isTagRoot() {
+ return false;
+ }
+
+ public List<String> getStagingTables() {
+ return (List<String>)getProperty(MappingNodeConstants.Properties.TEMP_GROUP_NAMES);
+ }
+
+ public void setStagingTables(List<String> tables) {
+ if (tables != null) {
+ setProperty(MappingNodeConstants.Properties.TEMP_GROUP_NAMES, tables);
+ }
+ else {
+ removeProperty(MappingNodeConstants.Properties.TEMP_GROUP_NAMES);
+ }
+ }
+
+ public void addStagingTable(String tablename) {
+ if (tablename == null) {
+ return;
+ }
+ List<String> tables = getStagingTables();
+ if (tables == null || tables.isEmpty()) {
+ tables = new ArrayList<String>();
+ }
+ tables.add(tablename);
+ setProperty(MappingNodeConstants.Properties.TEMP_GROUP_NAMES, tables);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingCriteriaNode.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingCriteriaNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingCriteriaNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,113 +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.mapping.xml;
-
-import java.util.List;
-
-import org.teiid.query.sql.lang.Criteria;
-
-
-
-/**
- * Represents a Criteria Node under a Choice Node, which defines the criteria
- * on the selection of child elements.
- */
-public class MappingCriteriaNode extends MappingBaseNode{
- boolean defalt;
- List criteriaGroups;
- Criteria criteriaNode;
-
- public MappingCriteriaNode(String criteria, boolean defalt) {
- setCriteria(criteria);
- setAsDefault(defalt);
- setProperty(MappingNodeConstants.Properties.NODE_TYPE, MappingNodeConstants.CRITERIA);
- }
-
- public MappingCriteriaNode() {
- setAsDefault(true);
- setProperty(MappingNodeConstants.Properties.NODE_TYPE, MappingNodeConstants.CRITERIA);
- }
-
- public void acceptVisitor(MappingVisitor visitor) {
- visitor.visit(this);
- }
-
- public MappingCriteriaNode setCriteria(String criteria) {
- if (criteria != null && criteria.length() > 0) {
- criteria = criteria.trim();
- setProperty(MappingNodeConstants.Properties.CRITERIA, criteria);
- }
- return this;
- }
-
- public MappingCriteriaNode setAsDefault(boolean defalt) {
- this.defalt = defalt;
- setProperty(MappingNodeConstants.Properties.IS_DEFAULT_CHOICE, Boolean.valueOf(defalt));
- return this;
- }
-
- public boolean isDefault() {
- return this.defalt;
- }
-
- public String getCriteria(){
- return (String) getProperty(MappingNodeConstants.Properties.CRITERIA);
- }
-
- /**
- * This is parsed and resolved criteria node based on the criteria string. This is set by
- * ValidateMappedCriteriaVisitor class during pre planning.
- * @param node
- */
- public void setCriteriaNode(Criteria node) {
- this.criteriaNode = node;
- }
-
- public Criteria getCriteriaNode() {
- 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()
- */
- public boolean isExcluded() {
- return false;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingCriteriaNode.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingCriteriaNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingCriteriaNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingCriteriaNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,93 @@
+/*
+ * 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.mapping.xml;
+
+import org.teiid.query.sql.lang.Criteria;
+
+
+
+/**
+ * Represents a Criteria Node under a Choice Node, which defines the criteria
+ * on the selection of child elements.
+ */
+public class MappingCriteriaNode extends MappingBaseNode{
+ boolean defalt;
+ Criteria criteriaNode;
+
+ public MappingCriteriaNode(String criteria, boolean defalt) {
+ setCriteria(criteria);
+ setAsDefault(defalt);
+ setProperty(MappingNodeConstants.Properties.NODE_TYPE, MappingNodeConstants.CRITERIA);
+ }
+
+ public MappingCriteriaNode() {
+ setAsDefault(true);
+ setProperty(MappingNodeConstants.Properties.NODE_TYPE, MappingNodeConstants.CRITERIA);
+ }
+
+ public void acceptVisitor(MappingVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ public MappingCriteriaNode setCriteria(String criteria) {
+ if (criteria != null && criteria.length() > 0) {
+ criteria = criteria.trim();
+ setProperty(MappingNodeConstants.Properties.CRITERIA, criteria);
+ }
+ return this;
+ }
+
+ public MappingCriteriaNode setAsDefault(boolean defalt) {
+ this.defalt = defalt;
+ setProperty(MappingNodeConstants.Properties.IS_DEFAULT_CHOICE, Boolean.valueOf(defalt));
+ return this;
+ }
+
+ public boolean isDefault() {
+ return this.defalt;
+ }
+
+ public String getCriteria(){
+ return (String) getProperty(MappingNodeConstants.Properties.CRITERIA);
+ }
+
+ /**
+ * This is parsed and resolved criteria node based on the criteria string. This is set by
+ * ValidateMappedCriteriaVisitor class during pre planning.
+ * @param node
+ */
+ public void setCriteriaNode(Criteria node) {
+ this.criteriaNode = node;
+ }
+
+ public Criteria getCriteriaNode() {
+ return this.criteriaNode;
+ }
+
+ /**
+ * @see org.teiid.query.mapping.xml.MappingNode#isExcluded()
+ */
+ public boolean isExcluded() {
+ return false;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingDocument.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingDocument.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingDocument.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,185 +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.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;
-
-
-
-/**
- * A Mapping Node document object.
- */
-public class MappingDocument extends MappingBaseNode {
-
- MappingBaseNode root;
- boolean formatted;
- String encoding;
- String name;
-
- public MappingDocument(boolean formatted) {
- this(MappingNodeConstants.Defaults.DEFAULT_DOCUMENT_ENCODING, formatted);
- }
-
- public MappingDocument(String encoding, boolean formatted) {
- if (encoding == null) {
- encoding = MappingNodeConstants.Defaults.DEFAULT_DOCUMENT_ENCODING;
- }
- setDocumentEncoding(encoding);
- setFormatted(formatted);
- }
-
- public void acceptVisitor(MappingVisitor visitor) {
- visitor.visit(this);
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getFullyQualifiedName() {
- return name;
- }
-
- public String getCanonicalName() {
- return name.toUpperCase();
- }
-
- public MappingBaseNode getRootNode() {
- return root;
- }
-
- /**
- * A tag root is the first visual node on the document. A document can contain a "source" node
- * at root, but what ever is the first maping element that is the tag root.
- * @return
- */
- public MappingElement getTagRootElement() {
- if (this.root instanceof MappingSourceNode) {
- return (MappingElement)this.root.getNodeChildren().get(0);
- }
- return (MappingElement)this.root;
- }
-
- void setRoot(MappingBaseNode root) {
- if (root != null) {
- this.root = root;
- this.getChildren().clear();
- this.addChild(root);
- }
- }
-
- public String getDocumentEncoding() {
- return this.encoding;
- }
-
- public boolean isFormatted() {
- return this.formatted;
- }
-
- public boolean isDocumentNode() {
- return true;
- }
-
- public void setDocumentEncoding(String encoding) {
- this.encoding = encoding;
- setProperty(MappingNodeConstants.Properties.DOCUMENT_ENCODING, this.encoding);
- }
-
- public void setFormatted(boolean formatted) {
- this.formatted = formatted;
- setProperty(MappingNodeConstants.Properties.FORMATTED_DOCUMENT, Boolean.valueOf(this.formatted));
- }
-
- /**
- * Make sure the cardinality is set correctly
- */
- private void fixCardinality(MappingElement root) {
- root.setMaxOccurrs(1);
- root.setMinOccurrs(1);
- }
-
- public MappingAllNode addAllNode(MappingAllNode elem) {
- throw new TeiidRuntimeException(QueryPlugin.Util.getString("WrongTypeChild")); //$NON-NLS-1$
- }
-
- public MappingChoiceNode addChoiceNode(MappingChoiceNode elem) {
- throw new TeiidRuntimeException(QueryPlugin.Util.getString("WrongTypeChild")); //$NON-NLS-1$
- }
-
- public MappingSequenceNode addSequenceNode(MappingSequenceNode elem) {
- throw new TeiidRuntimeException(QueryPlugin.Util.getString("WrongTypeChild")); //$NON-NLS-1$
- }
-
- public MappingElement addChildElement(MappingElement elem) {
- if (elem == null) {
- throw new TeiidRuntimeException(QueryPlugin.Util.getString("root_cannotbe_null")); //$NON-NLS-1$
- }
- fixCardinality(elem);
- setRoot(elem);
- return elem;
- }
-
- public MappingSourceNode addSourceNode(MappingSourceNode elem) {
- if (elem == null) {
- throw new TeiidRuntimeException(QueryPlugin.Util.getString("root_cannotbe_null")); //$NON-NLS-1$
- }
- setRoot(elem);
- return elem;
- }
-
- /**
- * @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);
- }
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingDocument.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingDocument.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingDocument.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingDocument.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,164 @@
+/*
+ * 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.mapping.xml;
+
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.query.QueryPlugin;
+
+
+
+/**
+ * A Mapping Node document object.
+ */
+public class MappingDocument extends MappingBaseNode {
+
+ MappingBaseNode root;
+ boolean formatted;
+ String encoding;
+ String name;
+
+ public MappingDocument(boolean formatted) {
+ this(MappingNodeConstants.Defaults.DEFAULT_DOCUMENT_ENCODING, formatted);
+ }
+
+ public MappingDocument(String encoding, boolean formatted) {
+ if (encoding == null) {
+ encoding = MappingNodeConstants.Defaults.DEFAULT_DOCUMENT_ENCODING;
+ }
+ setDocumentEncoding(encoding);
+ setFormatted(formatted);
+ }
+
+ public void acceptVisitor(MappingVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getFullyQualifiedName() {
+ return name;
+ }
+
+ public String getCanonicalName() {
+ return name.toUpperCase();
+ }
+
+ public MappingBaseNode getRootNode() {
+ return root;
+ }
+
+ /**
+ * A tag root is the first visual node on the document. A document can contain a "source" node
+ * at root, but what ever is the first maping element that is the tag root.
+ * @return
+ */
+ public MappingElement getTagRootElement() {
+ if (this.root instanceof MappingSourceNode) {
+ return (MappingElement)this.root.getNodeChildren().get(0);
+ }
+ return (MappingElement)this.root;
+ }
+
+ void setRoot(MappingBaseNode root) {
+ if (root != null) {
+ this.root = root;
+ this.getChildren().clear();
+ this.addChild(root);
+ }
+ }
+
+ public String getDocumentEncoding() {
+ return this.encoding;
+ }
+
+ public boolean isFormatted() {
+ return this.formatted;
+ }
+
+ public boolean isDocumentNode() {
+ return true;
+ }
+
+ public void setDocumentEncoding(String encoding) {
+ this.encoding = encoding;
+ setProperty(MappingNodeConstants.Properties.DOCUMENT_ENCODING, this.encoding);
+ }
+
+ public void setFormatted(boolean formatted) {
+ this.formatted = formatted;
+ setProperty(MappingNodeConstants.Properties.FORMATTED_DOCUMENT, Boolean.valueOf(this.formatted));
+ }
+
+ /**
+ * Make sure the cardinality is set correctly
+ */
+ private void fixCardinality(MappingElement root) {
+ root.setMaxOccurrs(1);
+ root.setMinOccurrs(1);
+ }
+
+ public MappingAllNode addAllNode(MappingAllNode elem) {
+ throw new TeiidRuntimeException(QueryPlugin.Util.getString("WrongTypeChild")); //$NON-NLS-1$
+ }
+
+ public MappingChoiceNode addChoiceNode(MappingChoiceNode elem) {
+ throw new TeiidRuntimeException(QueryPlugin.Util.getString("WrongTypeChild")); //$NON-NLS-1$
+ }
+
+ public MappingSequenceNode addSequenceNode(MappingSequenceNode elem) {
+ throw new TeiidRuntimeException(QueryPlugin.Util.getString("WrongTypeChild")); //$NON-NLS-1$
+ }
+
+ public MappingElement addChildElement(MappingElement elem) {
+ if (elem == null) {
+ throw new TeiidRuntimeException(QueryPlugin.Util.getString("root_cannotbe_null")); //$NON-NLS-1$
+ }
+ fixCardinality(elem);
+ setRoot(elem);
+ return elem;
+ }
+
+ public MappingSourceNode addSourceNode(MappingSourceNode elem) {
+ if (elem == null) {
+ throw new TeiidRuntimeException(QueryPlugin.Util.getString("root_cannotbe_null")); //$NON-NLS-1$
+ }
+ setRoot(elem);
+ return elem;
+ }
+
+ /**
+ * @see org.teiid.query.mapping.xml.MappingNode#clone()
+ */
+ public MappingDocument clone() {
+ MappingDocument clone = (MappingDocument) super.clone();
+ clone.root = (MappingBaseNode) clone.getChildren().iterator().next();
+ return clone;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingElement.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingElement.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingElement.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,342 +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.mapping.xml;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-
-import org.teiid.query.sql.symbol.ElementSymbol;
-
-
-
-/**
- * A Mapping Node which defines a Element in XML Schema Mapping document
- */
-public class MappingElement extends MappingBaseNode {
-
- // 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) {
- this(name, MappingNodeConstants.NO_NAMESPACE);
- }
-
- public MappingElement(String name, String nameInSource) {
- this(name, MappingNodeConstants.NO_NAMESPACE);
- setNameInSource(nameInSource);
- }
-
- public MappingElement(String name, Namespace namespace) {
- setProperty(MappingNodeConstants.Properties.NAME, name);
- setProperty(MappingNodeConstants.Properties.NODE_TYPE, MappingNodeConstants.ELEMENT);
-
- this.namespace = namespace;
- if (namespace != MappingNodeConstants.NO_NAMESPACE) {
- setProperty(MappingNodeConstants.Properties.NAMESPACE_PREFIX, namespace.getPrefix());
- }
- }
-
- public void acceptVisitor(MappingVisitor visitor) {
- visitor.visit(this);
- }
-
- public Namespace getNamespace() {
- return this.namespace;
- }
-
- public MappingElement setNameInSource(String srcName) {
- if (srcName != null) {
- setProperty(MappingNodeConstants.Properties.ELEMENT_NAME, srcName);
- }
- return this;
- }
-
- public MappingElement setNillable(boolean nil) {
- setProperty(MappingNodeConstants.Properties.IS_NILLABLE, Boolean.valueOf(nil));
- return this;
- }
-
- public MappingElement setDefaultValue(String value) {
- if (value != null) {
- setProperty(MappingNodeConstants.Properties.DEFAULT_VALUE, value);
- }
- return this;
- }
-
- public MappingElement setValue(String value) {
- if (value != null) {
- setProperty(MappingNodeConstants.Properties.FIXED_VALUE, value);
- }
- return this;
- }
-
- public MappingElement setOptional(boolean optional) {
- setProperty(MappingNodeConstants.Properties.IS_OPTIONAL, Boolean.valueOf(optional));
- return this;
- }
-
- public MappingElement setNormalizeText(String normalize) {
- if (normalize != null) {
- setProperty(MappingNodeConstants.Properties.NORMALIZE_TEXT, normalize);
- }
- return this;
- }
-
- public MappingElement setType(String type) {
- if (type != null) {
- setProperty(MappingNodeConstants.Properties.BUILT_IN_TYPE, type);
- }
- return this;
- }
-
- public MappingElement setAlwaysInclude(boolean include) {
- setProperty(MappingNodeConstants.Properties.ALWAYS_INCLUDE, Boolean.valueOf(include));
- return this;
- }
-
- /**
- * Adds a comment node to the current element and returns the added
- * child node
- */
- public MappingCommentNode addCommentNode(MappingCommentNode elem) {
- addChild(elem);
- return elem;
- }
-
- /**
- * Adds the attribute node to the current node and returns the current node
- */
- public MappingElement addAttribute(MappingAttribute attr) {
- addChild(attr);
- return this;
- }
-
- /**
- * Adds a sibiling node to the current node and returns the added sibiling node;
- * @param elem
- */
- public MappingElement addSibilingElement(MappingElement elem) {
- getParent().addChild(elem);
- return elem;
- }
-
- /**
- * Remove attribute node from element
- * @param toRemove
- */
- public void removeAttribute(MappingAttribute toRemove) {
- List children = getChildren();
- for (final Iterator i = children.iterator(); i.hasNext();) {
- if (i.next() == toRemove) {
- i.remove();
- break;
- }
- } // for
- }
-
- /**
- * Declare the namespaces on the element.
- */
- public void setNamespaces(Namespace[] spaces) {
- if (spaces != null && spaces.length > 0) {
- Properties props = new Properties();
- for (int i = 0; i < spaces.length; i++) {
- props.put(spaces[i].getPrefix(), spaces[i].getUri());
- }
- setProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS, props);
- }
- }
-
- public void addNamespace(Namespace space) {
- if (space != null) {
- Properties props = (Properties)getProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS);
- if (props == null) {
- props = new Properties();
- }
- props.put(space.getPrefix(), space.getUri());
- setProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS, props);
- }
- }
-
- /**
- * Get all the attributes on this Node
- * @return empty list if not found any attributes
- */
- public List getAttributes() {
- return getChildren(MappingNodeConstants.ATTRIBUTE);
- }
-
- public boolean hasAttributes() {
- List attr = getAttributes();
- return (attr != null && !attr.isEmpty());
- }
-
- /**
- * true if this element is recursive element; false otherwise
- */
- public boolean isRecursive() {
- return false;
- }
-
- /**
- * Name of the node
- * @return
- */
- public String getName() {
- return (String)getProperty(MappingNodeConstants.Properties.NAME);
- }
-
- /**
- * Namespace prefix
- * @return
- */
- public String getNamespacePrefix() {
- return (String)getProperty(MappingNodeConstants.Properties.NAMESPACE_PREFIX);
- }
-
- /**
- * Namespaces to be decalred
- * @return
- */
- public Namespace[] getNamespaces() {
- ArrayList list = new ArrayList();
- Properties props = (Properties)getProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS);
- if (props != null && !props.isEmpty()) {
- for(Iterator i = props.keySet().iterator(); i.hasNext();) {
- String key = (String)i.next();
- String value = props.getProperty(key);
- list.add(new Namespace(key, value));
- }
- }
- return (Namespace[]) list.toArray(new Namespace[list.size()]);
- }
-
- public Properties getNamespacesAsProperties() {
- Properties props = (Properties)getProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS);
- if (props == null) {
- props = new Properties();
- }
- return props;
- }
-
- public String getNameInSource() {
- return (String)getProperty(MappingNodeConstants.Properties.ELEMENT_NAME);
- }
-
- public boolean isNillable() {
- Boolean nillable = (Boolean)getProperty(MappingNodeConstants.Properties.IS_NILLABLE);
- if (nillable != null) {
- return nillable.booleanValue();
- }
- return false;
- }
-
- public String getDefaultValue() {
- return (String)getProperty(MappingNodeConstants.Properties.DEFAULT_VALUE);
- }
-
- public String getValue() {
- return (String)getProperty(MappingNodeConstants.Properties.FIXED_VALUE);
- }
-
- public boolean isOptional() {
- Boolean optional = (Boolean)getProperty(MappingNodeConstants.Properties.IS_OPTIONAL);
- if (optional != null) {
- return optional.booleanValue();
- }
- return false;
- }
-
- public String getNormalizeText() {
- String text = (String)getProperty(MappingNodeConstants.Properties.NORMALIZE_TEXT);
- if (text == null) {
- text = MappingNodeConstants.Defaults.DEFAULT_NORMALIZE_TEXT;
- }
- return text;
- }
-
- public String getType() {
- return (String)getProperty(MappingNodeConstants.Properties.BUILT_IN_TYPE);
- }
-
- public boolean isAlwaysInclude() {
- Boolean include = (Boolean)getProperty(MappingNodeConstants.Properties.ALWAYS_INCLUDE);
- if (include != null) {
- return include.booleanValue();
- }
- return true;
- }
-
- /**
- * @see org.teiid.query.mapping.xml.MappingBaseNode#isTagRoot()
- */
- public boolean isTagRoot() {
- MappingBaseNode parent = getParentNode();
- while (parent != null) {
- if (parent instanceof MappingElement) {
- return false;
- }
- parent = parent.getParentNode();
- }
- return true;
- }
-
- public void setElementSymbol(ElementSymbol symbol) {
- this.symbol = symbol;
- }
-
- public ElementSymbol getElementSymbol() {
- return this.symbol;
- }
-
- /**
- * @see org.teiid.query.mapping.xml.MappingNode#getSourceNode()
- */
- public MappingSourceNode getSourceNode() {
- String nameInSource = getNameInSource();
- if (nameInSource != null) {
- String source = nameInSource.substring(0, nameInSource.lastIndexOf('.'));
- MappingBaseNode parent = getParentNode();
- while(parent != null) {
- if (parent instanceof MappingSourceNode) {
- MappingSourceNode sourceNode = (MappingSourceNode)parent;
- if (sourceNode.getResultName().equalsIgnoreCase(source)) {
- return sourceNode;
- }
- }
- parent = parent.getParentNode();
- }
- }
- return super.getSourceNode();
- }
-}
-
-
-
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingElement.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingElement.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingElement.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingElement.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,339 @@
+/*
+ * 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.mapping.xml;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+
+import org.teiid.query.sql.symbol.ElementSymbol;
+
+
+
+/**
+ * A Mapping Node which defines a Element in XML Schema Mapping document
+ */
+public class MappingElement extends MappingBaseNode {
+
+ // Element symbol in the resultset source
+ ElementSymbol symbol;
+
+ Namespace namespace;
+
+ public MappingElement(String name) {
+ this(name, MappingNodeConstants.NO_NAMESPACE);
+ }
+
+ public MappingElement(String name, String nameInSource) {
+ this(name, MappingNodeConstants.NO_NAMESPACE);
+ setNameInSource(nameInSource);
+ }
+
+ public MappingElement(String name, Namespace namespace) {
+ setProperty(MappingNodeConstants.Properties.NAME, name);
+ setProperty(MappingNodeConstants.Properties.NODE_TYPE, MappingNodeConstants.ELEMENT);
+
+ this.namespace = namespace;
+ if (namespace != MappingNodeConstants.NO_NAMESPACE) {
+ setProperty(MappingNodeConstants.Properties.NAMESPACE_PREFIX, namespace.getPrefix());
+ }
+ }
+
+ public void acceptVisitor(MappingVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ public Namespace getNamespace() {
+ return this.namespace;
+ }
+
+ public MappingElement setNameInSource(String srcName) {
+ if (srcName != null) {
+ setProperty(MappingNodeConstants.Properties.ELEMENT_NAME, srcName);
+ }
+ return this;
+ }
+
+ public MappingElement setNillable(boolean nil) {
+ setProperty(MappingNodeConstants.Properties.IS_NILLABLE, Boolean.valueOf(nil));
+ return this;
+ }
+
+ public MappingElement setDefaultValue(String value) {
+ if (value != null) {
+ setProperty(MappingNodeConstants.Properties.DEFAULT_VALUE, value);
+ }
+ return this;
+ }
+
+ public MappingElement setValue(String value) {
+ if (value != null) {
+ setProperty(MappingNodeConstants.Properties.FIXED_VALUE, value);
+ }
+ return this;
+ }
+
+ public MappingElement setOptional(boolean optional) {
+ setProperty(MappingNodeConstants.Properties.IS_OPTIONAL, Boolean.valueOf(optional));
+ return this;
+ }
+
+ public MappingElement setNormalizeText(String normalize) {
+ if (normalize != null) {
+ setProperty(MappingNodeConstants.Properties.NORMALIZE_TEXT, normalize);
+ }
+ return this;
+ }
+
+ public MappingElement setType(String type) {
+ if (type != null) {
+ setProperty(MappingNodeConstants.Properties.BUILT_IN_TYPE, type);
+ }
+ return this;
+ }
+
+ public MappingElement setAlwaysInclude(boolean include) {
+ setProperty(MappingNodeConstants.Properties.ALWAYS_INCLUDE, Boolean.valueOf(include));
+ return this;
+ }
+
+ /**
+ * Adds a comment node to the current element and returns the added
+ * child node
+ */
+ public MappingCommentNode addCommentNode(MappingCommentNode elem) {
+ addChild(elem);
+ return elem;
+ }
+
+ /**
+ * Adds the attribute node to the current node and returns the current node
+ */
+ public MappingElement addAttribute(MappingAttribute attr) {
+ addChild(attr);
+ return this;
+ }
+
+ /**
+ * Adds a sibiling node to the current node and returns the added sibiling node;
+ * @param elem
+ */
+ public MappingElement addSibilingElement(MappingElement elem) {
+ getParent().addChild(elem);
+ return elem;
+ }
+
+ /**
+ * Remove attribute node from element
+ * @param toRemove
+ */
+ public void removeAttribute(MappingAttribute toRemove) {
+ List children = getChildren();
+ for (final Iterator i = children.iterator(); i.hasNext();) {
+ if (i.next() == toRemove) {
+ i.remove();
+ break;
+ }
+ } // for
+ }
+
+ /**
+ * Declare the namespaces on the element.
+ */
+ public void setNamespaces(Namespace[] spaces) {
+ if (spaces != null && spaces.length > 0) {
+ Properties props = new Properties();
+ for (int i = 0; i < spaces.length; i++) {
+ props.put(spaces[i].getPrefix(), spaces[i].getUri());
+ }
+ setProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS, props);
+ }
+ }
+
+ public void addNamespace(Namespace space) {
+ if (space != null) {
+ Properties props = (Properties)getProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS);
+ if (props == null) {
+ props = new Properties();
+ }
+ props.put(space.getPrefix(), space.getUri());
+ setProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS, props);
+ }
+ }
+
+ /**
+ * Get all the attributes on this Node
+ * @return empty list if not found any attributes
+ */
+ public List getAttributes() {
+ return getChildren(MappingNodeConstants.ATTRIBUTE);
+ }
+
+ public boolean hasAttributes() {
+ List attr = getAttributes();
+ return (attr != null && !attr.isEmpty());
+ }
+
+ /**
+ * true if this element is recursive element; false otherwise
+ */
+ public boolean isRecursive() {
+ return false;
+ }
+
+ /**
+ * Name of the node
+ * @return
+ */
+ public String getName() {
+ return (String)getProperty(MappingNodeConstants.Properties.NAME);
+ }
+
+ /**
+ * Namespace prefix
+ * @return
+ */
+ public String getNamespacePrefix() {
+ return (String)getProperty(MappingNodeConstants.Properties.NAMESPACE_PREFIX);
+ }
+
+ /**
+ * Namespaces to be decalred
+ * @return
+ */
+ public Namespace[] getNamespaces() {
+ ArrayList list = new ArrayList();
+ Properties props = (Properties)getProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS);
+ if (props != null && !props.isEmpty()) {
+ for(Iterator i = props.keySet().iterator(); i.hasNext();) {
+ String key = (String)i.next();
+ String value = props.getProperty(key);
+ list.add(new Namespace(key, value));
+ }
+ }
+ return (Namespace[]) list.toArray(new Namespace[list.size()]);
+ }
+
+ public Properties getNamespacesAsProperties() {
+ Properties props = (Properties)getProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS);
+ if (props == null) {
+ props = new Properties();
+ }
+ return props;
+ }
+
+ public String getNameInSource() {
+ return (String)getProperty(MappingNodeConstants.Properties.ELEMENT_NAME);
+ }
+
+ public boolean isNillable() {
+ Boolean nillable = (Boolean)getProperty(MappingNodeConstants.Properties.IS_NILLABLE);
+ if (nillable != null) {
+ return nillable.booleanValue();
+ }
+ return false;
+ }
+
+ public String getDefaultValue() {
+ return (String)getProperty(MappingNodeConstants.Properties.DEFAULT_VALUE);
+ }
+
+ public String getValue() {
+ return (String)getProperty(MappingNodeConstants.Properties.FIXED_VALUE);
+ }
+
+ public boolean isOptional() {
+ Boolean optional = (Boolean)getProperty(MappingNodeConstants.Properties.IS_OPTIONAL);
+ if (optional != null) {
+ return optional.booleanValue();
+ }
+ return false;
+ }
+
+ public String getNormalizeText() {
+ String text = (String)getProperty(MappingNodeConstants.Properties.NORMALIZE_TEXT);
+ if (text == null) {
+ text = MappingNodeConstants.Defaults.DEFAULT_NORMALIZE_TEXT;
+ }
+ return text;
+ }
+
+ public String getType() {
+ return (String)getProperty(MappingNodeConstants.Properties.BUILT_IN_TYPE);
+ }
+
+ public boolean isAlwaysInclude() {
+ Boolean include = (Boolean)getProperty(MappingNodeConstants.Properties.ALWAYS_INCLUDE);
+ if (include != null) {
+ return include.booleanValue();
+ }
+ return true;
+ }
+
+ /**
+ * @see org.teiid.query.mapping.xml.MappingBaseNode#isTagRoot()
+ */
+ public boolean isTagRoot() {
+ MappingBaseNode parent = getParentNode();
+ while (parent != null) {
+ if (parent instanceof MappingElement) {
+ return false;
+ }
+ parent = parent.getParentNode();
+ }
+ return true;
+ }
+
+ public void setElementSymbol(ElementSymbol symbol) {
+ this.symbol = symbol;
+ }
+
+ public ElementSymbol getElementSymbol() {
+ return this.symbol;
+ }
+
+ /**
+ * @see org.teiid.query.mapping.xml.MappingNode#getSourceNode()
+ */
+ public MappingSourceNode getSourceNode() {
+ String nameInSource = getNameInSource();
+ if (nameInSource != null) {
+ String source = nameInSource.substring(0, nameInSource.lastIndexOf('.'));
+ MappingBaseNode parent = getParentNode();
+ while(parent != null) {
+ if (parent instanceof MappingSourceNode) {
+ MappingSourceNode sourceNode = (MappingSourceNode)parent;
+ if (sourceNode.getResultName().equalsIgnoreCase(source)) {
+ return sourceNode;
+ }
+ }
+ parent = parent.getParentNode();
+ }
+ }
+ return super.getSourceNode();
+ }
+}
+
+
+
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNode.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,480 +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.mapping.xml;
-
-import java.io.PrintStream;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.sql.symbol.ElementSymbol;
-
-
-/**
- * There will be a mapping node
- * for every entity (element or attribute) in a target XML document.
- * @see MappingNodeConstants
- */
-public abstract class MappingNode implements Cloneable, Serializable {
-
- /** 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();
-
- /** node properties, as defined in NodeConstants.Properties. */
- private Map nodeProperties;
-
- /** default constructor */
- public MappingNode(){
- }
-
- /**
- * Get the parent of this node.
- */
- public MappingNode getParent() {
- return this.parent;
- }
-
- public static MappingNode findNode(MappingNode root, String partialName) {
- String canonicalName = root.getName();
-
- if (canonicalName != null) {
- //@ is optional, so we need to check for it only with attributes
- if (partialName.startsWith("@")) { //$NON-NLS-1$
- canonicalName = "@" + canonicalName; //$NON-NLS-1$
- }
-
- canonicalName = canonicalName.toUpperCase();
-
- boolean abort = true;
-
- if (partialName.startsWith(canonicalName)) {
- if (partialName.length() > canonicalName.length() + 1 && partialName.charAt(canonicalName.length()) == ElementSymbol.SEPARATOR.toCharArray()[0]) {
- partialName = partialName.substring(canonicalName.length() + 1);
- abort = false;
- } else if (partialName.length() == canonicalName.length()) {
- return root;
- }
- }
-
- if (abort) {
- return null;
- }
- }
-
- for (Iterator i = root.getChildren().iterator(); i.hasNext();) {
- MappingNode child = (MappingNode)i.next();
- MappingNode found = findNode(child, partialName);
- if (found != null) {
- return found;
- }
- }
-
- return null;
- }
-
- /**
- * 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 ) {
- this.parent = parent;
- }
-
- /**
- * Get the children contained by this node, or an empty List
- * @return children; if no children, return empty List (never null)
- */
- public List getChildren(){
- return this.children;
- }
-
- /**
- * 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();
- while ( iter.hasNext() ) {
- MappingNode node = (MappingNode)iter.next();
- if ( node.getProperty(MappingNodeConstants.Properties.NODE_TYPE).equals(type) ) {
- subset.add( node );
- }
- }
- return subset;
- }
-
- public List getNodeChildren() {
- List subset = new ArrayList();
- Iterator iter = children.iterator();
- while ( iter.hasNext() ) {
- MappingNode node = (MappingNode)iter.next();
- if ( !node.getProperty(MappingNodeConstants.Properties.NODE_TYPE).equals(MappingNodeConstants.ATTRIBUTE) ) {
- subset.add( node );
- }
- }
- return subset;
- }
-
- /**
- * Add a child mapping node to this one.
- * @param MappingNode to add as a child of this node
- * @return the added node, with parent set to this node
- */
- public MappingNode addChild( MappingNode node ) {
- this.children.add( node );
- node.setParent(this);
- return node;
- }
-
- /**
- * Retrieve one of the Object values, keyed off the
- * Integer property keys defined in
- * {@link MappingNodeConstants.Properties}
- * @param propertyID Integer property key
- * @return Object value
- */
- public Object getProperty(Integer propertyID) {
- Object value = null;
- if(nodeProperties != null) {
- value = nodeProperties.get(propertyID);
- }
- if (value == null){
- value = MappingNodeConstants.Defaults.DEFAULT_VALUES.get(propertyID);
- }
- return value;
- }
-
- /**
- * Sets one of the Object values, keyed off the
- * Integer property keys defined in
- * {@link MappingNodeConstants.Properties}
- * @param propertyID Integer property key
- * @param value Object property value
- */
- void setProperty(Integer 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
- 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
- props.put(propertyID, value);
- } else {
- // The value is equal to the default, so because we didn't set it
- // we have to make sure to remove any existing value ...
- props.remove(propertyID);
- }
- }
- }
-
- void removeProperty(Integer propertyID) {
- getNodeProperties().remove(propertyID);
- }
-
- /**
- * Returns the actual local properties object, instantiates if necessary.
- * The Map returned is the basis for equality for a MappingNode.
- * <b>Note:</b> Use {@link #getProperties} unless absolutely necessary.
- * @return the actual properties (not including defaults) stored at this
- * object.
- * @see #getProperties
- */
- public Map getNodeProperties(){
- if(nodeProperties == null) {
- nodeProperties = new HashMap();
- }
- return nodeProperties;
- }
-
-
- /**
- * <p>Gets the fully qualified name of this node, this is obtained by concatenating
- * the nodes name to the parents qualified name with a delimiter in between them.</p>
- * @return The fully qualified name of this node.
- */
- public String getFullyQualifiedName() {
- String myName = getPathName();
- String parentName = (getParent() == null) ? "" : getParent().getFullyQualifiedName(); //$NON-NLS-1$
-
- if(myName == null || myName.equals("")) { //$NON-NLS-1$
- return parentName;
- } else if(parentName == null || parentName.equals("")) { //$NON-NLS-1$
- return myName;
- } else {
- return parentName + MappingNodeConstants.PATH_DELIM + myName;
- }
- }
-
- public String getName() {
- return (String) this.getProperty(MappingNodeConstants.Properties.NAME);
- }
-
- public String getPathName() {
- return getName();
- }
-
- // =========================================================================
- // OVERRIDE Object METHODS
- // =========================================================================
-
- /**
- * Compare the symbol based ONLY on properties (including name), NOT on
- * parent node and children nodes (or lack thereof).
- * @param obj Other object
- * @return True if other obj is a MappingNode (or subclass) and properties
- * are equal
- */
- public boolean equals(Object obj) {
- if(obj == this) {
- return true;
- }
-
- if(obj != null && obj instanceof MappingNode) {
- return ((MappingNode)obj).getNodeProperties().equals(getNodeProperties());
- }
- return false;
- }
-
- /**
- * Return a hash code for this symbol.
- * @return Hash code
- */
- public int hashCode() {
- return this.getNodeProperties().hashCode();
- }
-
- /**
- * Returns a string representation of an instance of this class.
- */
- public String toString() {
- Object name = getProperty(MappingNodeConstants.Properties.NAME);
- Object criteria = getProperty(MappingNodeConstants.Properties.CRITERIA);
- Object prefix = getProperty(MappingNodeConstants.Properties.NAMESPACE_PREFIX);
- Object defaultValue = getProperty(MappingNodeConstants.Properties.DEFAULT_VALUE);
- Object fixedValue = getProperty(MappingNodeConstants.Properties.FIXED_VALUE);
- Object namespaces = getProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS);
-
- return "[" + getProperty(MappingNodeConstants.Properties.NODE_TYPE) + "]" //$NON-NLS-1$ //$NON-NLS-2$
- + " name='" + ((prefix != null) ? prefix + ":" : "") + ((name != null) ? name : "") + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- //+ " path='" + ((name != null) ? getSchemaPath() : "undefined") + "'"
- + ((defaultValue != null) ? " default='" + defaultValue + "'" : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- + ((fixedValue != null) ? " fixed='" + fixedValue + "'" : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- + " minOccurs=" + getProperty(MappingNodeConstants.Properties.CARDINALITY_MIN_BOUND) //$NON-NLS-1$
- + " maxOccurs=" + getProperty(MappingNodeConstants.Properties.CARDINALITY_MAX_BOUND) //$NON-NLS-1$
- + ((criteria != null) ? (" constraint=\"" + criteria + "\"") : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- + ((namespaces != null) ? (" namespaces=\"" + namespaces + "\"") : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
-
- /**
- * Prints the whole tree of MappingNodes to the provided PrintStream.
- */
- public static void printMappingNodeTree(MappingNode root, PrintStream output){
- output.print(toStringNodeTree(root));
- }
-
- public static String toStringNodeTree(MappingNode root){
- StringBuffer str = new StringBuffer();
- buildTreeString(root, str, 0);
- return str.toString();
- }
-
- // Define a single tab
- private static final String TAB = " "; //$NON-NLS-1$
-
- private static void buildTreeString(MappingNode node, StringBuffer str, int tabLevel){
- setTab(str, tabLevel++);
- str.append(node.toString());
- str.append(node.getNodeProperties());
- str.append("\n"); //$NON-NLS-1$
-
- Iterator i = node.getChildren().iterator();
- while (i.hasNext()){
- buildTreeString((MappingNode)i.next(), str, tabLevel);
- }
- }
-
- private static void setTab(StringBuffer str, int tabStop) {
- for(int i=0; i<tabStop; i++) {
- str.append(TAB);
- }
- }
-
- /**
- * Starting at a point in a mapping document and traversing either upward toward the root or
- * downward (depth or breadth first), this method finds and returns
- * the first MappingNode instance that has the indicated property key and value. A <code>null</code>
- * can be passed in for the value parameter, indicating the first node should be returned which has
- * <i>any</i> non-null value for the property key.
- * @param propertyKey any of the properties defined in {@link MappingNodeConstants.Properties}
- * @param value an Object value that is checked for. <code>null</code> can be passed in, indicating
- * the first node with any non-null value for that property should be returned
- * @param node a MappingNode in a mapping document - this is the beginning point of the search
- * @param searchDirection indicates whether to search upward or downward (depth or breadth first) from the
- * node parameter; use either {@link MappingNodeConstants#SEARCH_UP},
- * {@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) {
- return findFirstNodeWithPropertyValue(propertyKey, value, false, node, searchDirection);
- }
-
- /**
- * Starting at a point in a mapping document and traversing either upward toward the root or
- * downward (depth or breadth first), this method finds and returns
- * the first MappingNode instance that has the indicated property key and value. A <code>null</code>
- * can be passed in for the value parameter, indicating the first node should be returned which has
- * <i>any</i> non-null value for the property key.
- * @param propertyKey any of the properties defined in {@link MappingNodeConstants.Properties}
- * for which the value is of type String
- * @param value an Object value that is checked for. <code>null</code> can be passed in, indicating
- * the first node with any non-null value for that property should be returned
- * @param node a MappingNode in a mapping document - this is the beginning point of the search
- * @param searchDirection indicates whether to search upward or downward (depth or breadth first) from the
- * node parameter; use either {@link MappingNodeConstants#SEARCH_UP},
- * {@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) {
- return findFirstNodeWithPropertyValue(propertyKey, value, true, node, searchDirection);
- }
-
- private static MappingNode findFirstNodeWithPropertyValue(Integer propertyKey, Object value, boolean isStringValue, MappingNode node, int searchDirection) {
-
- if (node == null || propertyKey == null){
- return null;
- }
- if (searchDirection == MappingNodeConstants.SEARCH_UP){
- return traverseUpForFirstNodeWithPropertyString(propertyKey, value, isStringValue, node);
- } else if (searchDirection == MappingNodeConstants.SEARCH_DOWN){
- return traverseDownForFirstNodeWithPropertyString(propertyKey, value, isStringValue, node, false);
- } else if (searchDirection == MappingNodeConstants.SEARCH_DOWN_BREADTH_FIRST){
- // Check root node first
- if (checkThisNodeForPropertyValue(propertyKey, value, isStringValue, node)){
- return node;
- }
- return traverseDownForFirstNodeWithPropertyString(propertyKey, value, isStringValue, node, true);
- } else {
- throw new IllegalArgumentException(QueryPlugin.Util.getString("ERR.015.002.0009", searchDirection )); //$NON-NLS-1$
- }
- }
-
- private static MappingNode traverseDownForFirstNodeWithPropertyString(Integer propertyKey, Object value, boolean isStringValue, MappingNode node, boolean breadthFirst) {
- if (breadthFirst) {
- Iterator children = node.getChildren().iterator();
- while (children.hasNext()){
- MappingNode child = (MappingNode)children.next();
- if (checkThisNodeForPropertyValue(propertyKey, value, isStringValue, child)){
- return child;
- }
- }
- } else {
- if (checkThisNodeForPropertyValue(propertyKey, value, isStringValue, node)){
- return node;
- }
- }
-
- Iterator children = node.getChildren().iterator();
- while (children.hasNext()){
- MappingNode child = (MappingNode)children.next();
-
- //recursive call to this method
- MappingNode result = traverseDownForFirstNodeWithPropertyString(propertyKey, value, isStringValue, child, breadthFirst);
- if (result != null){
- return result;
- }
- }
-
- return null;
- }
-
- private static boolean checkThisNodeForPropertyValue(Integer propertyKey, Object value, boolean isStringValue, MappingNode node) {
- Object thisValue = node.getProperty(propertyKey);
- if (thisValue != null){
- if (value == null){
- return true;
- }
- if (isStringValue && ((String)thisValue).equalsIgnoreCase((String)value)) {
- return true;
- }
- if (thisValue.equals(value)) {
- return true;
- }
- }
- return false;
- }
-
- private static MappingNode traverseUpForFirstNodeWithPropertyString(Integer propertyKey, Object value, boolean isStringValue, MappingNode node) {
- while (node != null){
- if (checkThisNodeForPropertyValue(propertyKey, value, isStringValue, node)){
- return node;
- }
- node = node.getParent();
- }
- return null;
- }
-
- public MappingNode setExclude(boolean exclude) {
- setProperty(MappingNodeConstants.Properties.IS_EXCLUDED, Boolean.valueOf(exclude));
- return this;
- }
-
- public boolean isExcluded() {
- Boolean exclude = (Boolean)getProperty(MappingNodeConstants.Properties.IS_EXCLUDED);
- if (exclude != null) {
- return exclude.booleanValue();
- }
- return false;
- }
-
- public abstract void acceptVisitor(MappingVisitor visitor);
-
- /**
- * Get the source node for this Mapping Node; note that only mapping elements and
- * mapping attributes have the source nodes; that too ones with specified with
- * NameInSource specified attribute.
- *
- * If not find nearest one looking up the tree.
- * @return
- */
- public MappingSourceNode getSourceNode() {
- if (getParent() != null) {
- return getParent().getSourceNode();
- }
- return null;
- }
-
- public String getNameInSource() {
- return null;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNode.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,501 @@
+/*
+ * 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.mapping.xml;
+
+import java.io.PrintStream;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+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;
+
+
+/**
+ * There will be a mapping node
+ * for every entity (element or attribute) in a target XML document.
+ * @see MappingNodeConstants
+ */
+public abstract class MappingNode implements Cloneable, Serializable {
+
+ 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 List<MappingNode> children = new LinkedList<MappingNode>();
+
+ /** node properties, as defined in NodeConstants.Properties. */
+ private Map<MappingNodeConstants.Properties, Object> nodeProperties;
+
+ /** default constructor */
+ public MappingNode(){
+ }
+
+ /**
+ * Get the parent of this node.
+ */
+ public MappingNode getParent() {
+ return this.parent;
+ }
+
+ public static MappingNode findNode(MappingNode root, String partialName) {
+ String canonicalName = root.getName();
+
+ if (canonicalName != null) {
+ //@ is optional, so we need to check for it only with attributes
+ if (partialName.startsWith("@")) { //$NON-NLS-1$
+ canonicalName = "@" + canonicalName; //$NON-NLS-1$
+ }
+
+ canonicalName = canonicalName.toUpperCase();
+
+ boolean abort = true;
+
+ if (partialName.startsWith(canonicalName)) {
+ if (partialName.length() > canonicalName.length() + 1 && partialName.charAt(canonicalName.length()) == ElementSymbol.SEPARATOR.toCharArray()[0]) {
+ partialName = partialName.substring(canonicalName.length() + 1);
+ abort = false;
+ } else if (partialName.length() == canonicalName.length()) {
+ return root;
+ }
+ }
+
+ if (abort) {
+ return null;
+ }
+ }
+
+ for (Iterator<MappingNode> i = root.getChildren().iterator(); i.hasNext();) {
+ MappingNode child = i.next();
+ MappingNode found = findNode(child, partialName);
+ if (found != null) {
+ return found;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Set the parent of this node. This method is restricted, as
+ * it should be called only when {@link #addChild adding a child node}
+ */
+ void setParent( MappingNode parent ) {
+ this.parent = parent;
+ }
+
+ /**
+ * Get the children contained by this node, or an empty List
+ * @return children; if no children, return empty List (never null)
+ */
+ public List<MappingNode> getChildren(){
+ return this.children;
+ }
+
+ /**
+ * 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<MappingNode> getChildren( String type ) {
+ List<MappingNode> subset = new ArrayList<MappingNode>();
+ Iterator<MappingNode> iter = children.iterator();
+ while ( iter.hasNext() ) {
+ MappingNode node = iter.next();
+ if ( node.getProperty(MappingNodeConstants.Properties.NODE_TYPE).equals(type) ) {
+ subset.add( node );
+ }
+ }
+ return subset;
+ }
+
+ public List<MappingNode> getNodeChildren() {
+ List<MappingNode> subset = new ArrayList<MappingNode>();
+ Iterator<MappingNode> iter = children.iterator();
+ while ( iter.hasNext() ) {
+ MappingNode node = iter.next();
+ if ( !node.getProperty(MappingNodeConstants.Properties.NODE_TYPE).equals(MappingNodeConstants.ATTRIBUTE) ) {
+ subset.add( node );
+ }
+ }
+ return subset;
+ }
+
+ /**
+ * Add a child mapping node to this one.
+ * @param MappingNode to add as a child of this node
+ * @return the added node, with parent set to this node
+ */
+ public MappingNode addChild( MappingNode node ) {
+ this.children.add( node );
+ node.setParent(this);
+ return node;
+ }
+
+ /**
+ * Retrieve one of the Object values, keyed off the
+ * Integer property keys defined in
+ * {@link MappingNodeConstants.Properties}
+ * @param propertyID Integer property key
+ * @return Object value
+ */
+ public Object getProperty(MappingNodeConstants.Properties propertyID) {
+ Object value = null;
+ if(nodeProperties != null) {
+ value = nodeProperties.get(propertyID);
+ }
+ if (value == null){
+ value = MappingNodeConstants.Defaults.DEFAULT_VALUES.get(propertyID);
+ }
+ return value;
+ }
+
+ /**
+ * Sets one of the Object values, keyed off the
+ * Integer property keys defined in
+ * {@link MappingNodeConstants.Properties}
+ * @param propertyID Integer property key
+ * @param value Object property 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<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
+ props.put(propertyID, value);
+ } else {
+ // The value is equal to the default, so because we didn't set it
+ // we have to make sure to remove any existing value ...
+ props.remove(propertyID);
+ }
+ }
+ }
+
+ void removeProperty(MappingNodeConstants.Properties propertyID) {
+ getNodeProperties().remove(propertyID);
+ }
+
+ /**
+ * Returns the actual local properties object, instantiates if necessary.
+ * The Map returned is the basis for equality for a MappingNode.
+ * <b>Note:</b> Use {@link #getProperties} unless absolutely necessary.
+ * @return the actual properties (not including defaults) stored at this
+ * object.
+ * @see #getProperties
+ */
+ public Map<MappingNodeConstants.Properties, Object> getNodeProperties(){
+ if(nodeProperties == null) {
+ nodeProperties = new HashMap<MappingNodeConstants.Properties, Object>();
+ }
+ return nodeProperties;
+ }
+
+
+ /**
+ * <p>Gets the fully qualified name of this node, this is obtained by concatenating
+ * the nodes name to the parents qualified name with a delimiter in between them.</p>
+ * @return The fully qualified name of this node.
+ */
+ public String getFullyQualifiedName() {
+ String myName = getPathName();
+ String parentName = (getParent() == null) ? "" : getParent().getFullyQualifiedName(); //$NON-NLS-1$
+
+ if(myName == null || myName.equals("")) { //$NON-NLS-1$
+ return parentName;
+ } else if(parentName == null || parentName.equals("")) { //$NON-NLS-1$
+ return myName;
+ } else {
+ return parentName + MappingNodeConstants.PATH_DELIM + myName;
+ }
+ }
+
+ public String getName() {
+ return (String) this.getProperty(MappingNodeConstants.Properties.NAME);
+ }
+
+ public String getPathName() {
+ return getName();
+ }
+
+ // =========================================================================
+ // OVERRIDE Object METHODS
+ // =========================================================================
+
+ /**
+ * Compare the symbol based ONLY on properties (including name), NOT on
+ * parent node and children nodes (or lack thereof).
+ * @param obj Other object
+ * @return True if other obj is a MappingNode (or subclass) and properties
+ * are equal
+ */
+ public boolean equals(Object obj) {
+ if(obj == this) {
+ return true;
+ }
+
+ if(obj != null && obj instanceof MappingNode) {
+ return ((MappingNode)obj).getNodeProperties().equals(getNodeProperties());
+ }
+ return false;
+ }
+
+ /**
+ * Return a hash code for this symbol.
+ * @return Hash code
+ */
+ public int hashCode() {
+ return this.getNodeProperties().hashCode();
+ }
+
+ /**
+ * Returns a string representation of an instance of this class.
+ */
+ public String toString() {
+ Object name = getProperty(MappingNodeConstants.Properties.NAME);
+ Object criteria = getProperty(MappingNodeConstants.Properties.CRITERIA);
+ Object prefix = getProperty(MappingNodeConstants.Properties.NAMESPACE_PREFIX);
+ Object defaultValue = getProperty(MappingNodeConstants.Properties.DEFAULT_VALUE);
+ Object fixedValue = getProperty(MappingNodeConstants.Properties.FIXED_VALUE);
+ Object namespaces = getProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS);
+
+ return "[" + getProperty(MappingNodeConstants.Properties.NODE_TYPE) + "]" //$NON-NLS-1$ //$NON-NLS-2$
+ + " name='" + ((prefix != null) ? prefix + ":" : "") + ((name != null) ? name : "") + "'" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ //+ " path='" + ((name != null) ? getSchemaPath() : "undefined") + "'"
+ + ((defaultValue != null) ? " default='" + defaultValue + "'" : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ + ((fixedValue != null) ? " fixed='" + fixedValue + "'" : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ + " minOccurs=" + getProperty(MappingNodeConstants.Properties.CARDINALITY_MIN_BOUND) //$NON-NLS-1$
+ + " maxOccurs=" + getProperty(MappingNodeConstants.Properties.CARDINALITY_MAX_BOUND) //$NON-NLS-1$
+ + ((criteria != null) ? (" constraint=\"" + criteria + "\"") : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ + ((namespaces != null) ? (" namespaces=\"" + namespaces + "\"") : ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+
+ /**
+ * Prints the whole tree of MappingNodes to the provided PrintStream.
+ */
+ public static void printMappingNodeTree(MappingNode root, PrintStream output){
+ output.print(toStringNodeTree(root));
+ }
+
+ public static String toStringNodeTree(MappingNode root){
+ StringBuffer str = new StringBuffer();
+ buildTreeString(root, str, 0);
+ return str.toString();
+ }
+
+ // Define a single tab
+ private static final String TAB = " "; //$NON-NLS-1$
+
+ private static void buildTreeString(MappingNode node, StringBuffer str, int tabLevel){
+ setTab(str, tabLevel++);
+ str.append(node.toString());
+ str.append(node.getNodeProperties());
+ str.append("\n"); //$NON-NLS-1$
+
+ Iterator<MappingNode> i = node.getChildren().iterator();
+ while (i.hasNext()){
+ buildTreeString(i.next(), str, tabLevel);
+ }
+ }
+
+ private static void setTab(StringBuffer str, int tabStop) {
+ for(int i=0; i<tabStop; i++) {
+ str.append(TAB);
+ }
+ }
+
+ /**
+ * Starting at a point in a mapping document and traversing either upward toward the root or
+ * downward (depth or breadth first), this method finds and returns
+ * the first MappingNode instance that has the indicated property key and value. A <code>null</code>
+ * can be passed in for the value parameter, indicating the first node should be returned which has
+ * <i>any</i> non-null value for the property key.
+ * @param propertyKey any of the properties defined in {@link MappingNodeConstants.Properties}
+ * @param value an Object value that is checked for. <code>null</code> can be passed in, indicating
+ * the first node with any non-null value for that property should be returned
+ * @param node a MappingNode in a mapping document - this is the beginning point of the search
+ * @param searchDirection indicates whether to search upward or downward (depth or breadth first) from the
+ * node parameter; use either {@link MappingNodeConstants#SEARCH_UP},
+ * {@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(MappingNodeConstants.Properties propertyKey, Object value, MappingNode node, int searchDirection) {
+ return findFirstNodeWithPropertyValue(propertyKey, value, false, node, searchDirection);
+ }
+
+ /**
+ * Starting at a point in a mapping document and traversing either upward toward the root or
+ * downward (depth or breadth first), this method finds and returns
+ * the first MappingNode instance that has the indicated property key and value. A <code>null</code>
+ * can be passed in for the value parameter, indicating the first node should be returned which has
+ * <i>any</i> non-null value for the property key.
+ * @param propertyKey any of the properties defined in {@link MappingNodeConstants.Properties}
+ * for which the value is of type String
+ * @param value an Object value that is checked for. <code>null</code> can be passed in, indicating
+ * the first node with any non-null value for that property should be returned
+ * @param node a MappingNode in a mapping document - this is the beginning point of the search
+ * @param searchDirection indicates whether to search upward or downward (depth or breadth first) from the
+ * node parameter; use either {@link MappingNodeConstants#SEARCH_UP},
+ * {@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(MappingNodeConstants.Properties propertyKey, String value, MappingNode node, int searchDirection) {
+ return findFirstNodeWithPropertyValue(propertyKey, value, true, node, searchDirection);
+ }
+
+ private static MappingNode findFirstNodeWithPropertyValue(MappingNodeConstants.Properties propertyKey, Object value, boolean isStringValue, MappingNode node, int searchDirection) {
+
+ if (node == null || propertyKey == null){
+ return null;
+ }
+ if (searchDirection == MappingNodeConstants.SEARCH_UP){
+ return traverseUpForFirstNodeWithPropertyString(propertyKey, value, isStringValue, node);
+ } else if (searchDirection == MappingNodeConstants.SEARCH_DOWN){
+ return traverseDownForFirstNodeWithPropertyString(propertyKey, value, isStringValue, node, false);
+ } else if (searchDirection == MappingNodeConstants.SEARCH_DOWN_BREADTH_FIRST){
+ // Check root node first
+ if (checkThisNodeForPropertyValue(propertyKey, value, isStringValue, node)){
+ return node;
+ }
+ return traverseDownForFirstNodeWithPropertyString(propertyKey, value, isStringValue, node, true);
+ } else {
+ throw new IllegalArgumentException(QueryPlugin.Util.getString("ERR.015.002.0009", searchDirection )); //$NON-NLS-1$
+ }
+ }
+
+ private static MappingNode traverseDownForFirstNodeWithPropertyString(MappingNodeConstants.Properties propertyKey, Object value, boolean isStringValue, MappingNode node, boolean breadthFirst) {
+ if (breadthFirst) {
+ Iterator<MappingNode> children = node.getChildren().iterator();
+ while (children.hasNext()){
+ MappingNode child = children.next();
+ if (checkThisNodeForPropertyValue(propertyKey, value, isStringValue, child)){
+ return child;
+ }
+ }
+ } else {
+ if (checkThisNodeForPropertyValue(propertyKey, value, isStringValue, node)){
+ return node;
+ }
+ }
+
+ Iterator<MappingNode> children = node.getChildren().iterator();
+ while (children.hasNext()){
+ MappingNode child = children.next();
+
+ //recursive call to this method
+ MappingNode result = traverseDownForFirstNodeWithPropertyString(propertyKey, value, isStringValue, child, breadthFirst);
+ if (result != null){
+ return result;
+ }
+ }
+
+ return null;
+ }
+
+ private static boolean checkThisNodeForPropertyValue(MappingNodeConstants.Properties propertyKey, Object value, boolean isStringValue, MappingNode node) {
+ Object thisValue = node.getProperty(propertyKey);
+ if (thisValue != null){
+ if (value == null){
+ return true;
+ }
+ if (isStringValue && ((String)thisValue).equalsIgnoreCase((String)value)) {
+ return true;
+ }
+ if (thisValue.equals(value)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static MappingNode traverseUpForFirstNodeWithPropertyString(MappingNodeConstants.Properties propertyKey, Object value, boolean isStringValue, MappingNode node) {
+ while (node != null){
+ if (checkThisNodeForPropertyValue(propertyKey, value, isStringValue, node)){
+ return node;
+ }
+ node = node.getParent();
+ }
+ return null;
+ }
+
+ public MappingNode setExclude(boolean exclude) {
+ setProperty(MappingNodeConstants.Properties.IS_EXCLUDED, Boolean.valueOf(exclude));
+ return this;
+ }
+
+ public boolean isExcluded() {
+ Boolean exclude = (Boolean)getProperty(MappingNodeConstants.Properties.IS_EXCLUDED);
+ if (exclude != null) {
+ return exclude.booleanValue();
+ }
+ return false;
+ }
+
+ public abstract void acceptVisitor(MappingVisitor visitor);
+
+ /**
+ * Get the source node for this Mapping Node; note that only mapping elements and
+ * mapping attributes have the source nodes; that too ones with specified with
+ * NameInSource specified attribute.
+ *
+ * If not find nearest one looking up the tree.
+ * @return
+ */
+ public MappingSourceNode getSourceNode() {
+ if (getParent() != null) {
+ return getParent().getSourceNode();
+ }
+ return null;
+ }
+
+ 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;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNodeConstants.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingNodeConstants.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNodeConstants.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,719 +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.mapping.xml;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Constants, property names, and property default values for
- * a {@link MappingNode}.
- */
-public final class MappingNodeConstants {
-
- // Can't instantiate
- private MappingNodeConstants() { }
-
- // =========================================================================
- // CONSTANTS
- // =========================================================================
-
- /**
- * Indicates a search of a mapping document should be upward. See
- * {@link MappingNode#findFirstNodeWithProperty}
- */
- public static final int SEARCH_UP = 2;
-
- /**
- * Indicates a search of a mapping document should be downward, DEPTH FIRST. See
- * {@link MappingNode#findFirstNodeWithProperty}
- */
- public static final int SEARCH_DOWN = 3; // DEPTH FIRST
-
- /**
- * Indicates a search of a mapping document should be downward, BREADTH FIRST. See
- * {@link MappingNode#findFirstNodeWithProperty}
- */
- public static final int SEARCH_DOWN_BREADTH_FIRST = 4; //BREADTH FIRST
-
- /** Constant for children returned by non-complex nodes (never have children). */
- static final List NO_CHILDREN = Collections.EMPTY_LIST;
-
- /** Schema node path delimeter. */
- public static final String PATH_DELIM = "."; //$NON-NLS-1$
-
- /** The value used to indicate an unbounded maximum cardinality */
- public static final Integer CARDINALITY_UNBOUNDED = new Integer(-1);
-
- public static final String CARDINALITY_UNBOUNDED_STRING = "unbounded"; //$NON-NLS-1$
-
- /** Constant defining a target node type of "attribute". */
- public static final String ATTRIBUTE = "attribute"; //$NON-NLS-1$
-
- /** Constant defining a target node type of "element". */
- public static final String ELEMENT = "element"; //$NON-NLS-1$
-
- /** Constant defining a target node type of "comment". */
- public static final String COMMENT = "comment"; //$NON-NLS-1$
-
- /** Constant defining a target node type of "sequence". */
- public static final String SEQUENCE = "sequence"; //$NON-NLS-1$
-
- /** Constant defining a target node type of "choice". */
- public static final String CHOICE = "choice"; //$NON-NLS-1$
-
- /** Constant defining a target node type of "All". */
- public static final String ALL = "all"; //$NON-NLS-1$
-
- /** Constant defining a target node type of "Criteria". */
- public static final String CRITERIA = "criteria"; //$NON-NLS-1$
-
- /** Constant defining a target node type of "source". */
- public static final String SOURCE = "source"; //$NON-NLS-1$
-
-
- /**
- * Defines a default namespace holder for the nodes with out any
- * namespace declarations.
- */
- public static final Namespace NO_NAMESPACE = new Namespace("", ""); //$NON-NLS-1$ //$NON-NLS-2$
-
- /**
- * This constant is merely used as a placeholder in the declaration of a
- * default namespace in an XML doc instance. A default namespace has no
- * prefix associated with it, so the String used here is a forbidden XML
- * character that could never be used as a real namespace prefix.
- */
- public static final String DEFAULT_NAMESPACE_PREFIX = ""; //$NON-NLS-1$
-
- /**
- * Prefix of the XML Schema namespace for instances - needed to make
- * use of the "nil" attribute defined in that namespace, for
- * nillable nodes
- * @see #INSTANCES_NAMESPACE
- */
- public static final String INSTANCES_NAMESPACE_PREFIX = "xsi"; //$NON-NLS-1$
-
- /**
- * The XML Schema namespace for instances - needed to make
- * use of the "nil" attribute defined in that namespace, for
- * nillable nodes
- * @see #INSTANCES_NAMESPACE_PREFIX
- */
- public static final String INSTANCES_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance"; //$NON-NLS-1$
-
- public static final String NAMESPACE_DECLARATION_ATTRIBUTE_NAMESPACE = "xmlns"; //$NON-NLS-1$
-
- /**
- * PRESERVE -No normalization is done, the value is not changed.
- * REPLACE - All occurrences of tab, line feed and carriage return are replaced with space
- * COLLAPSE - After the processing implied by replace, contiguous sequences of space are
- * collapsed to a single space, and leading and trailing spaces are removed.
- */
- public static final String NORMALIZE_TEXT_PRESERVE = "preserve"; //$NON-NLS-1$
- public static final String NORMALIZE_TEXT_REPLACE = "replace"; //$NON-NLS-1$
- public static final String NORMALIZE_TEXT_COLLAPSE = "collapse"; //$NON-NLS-1$
-
- /**
- * Default built-in type = no type info, which is an empty string
- */
- public static final String NO_TYPE = ""; //$NON-NLS-1$
-
- // =========================================================================
- // PROPERTIES
- // =========================================================================
-
- /**
- * Property names for type-specific node properties. Values will be of
- * type String unless otherwise specified.
- */
- public static final class Properties {
- private Properties() { }
-
- /** The basic name of this node. Will be the element or attribute tag name. */
- public static final Integer NAME = new Integer(0);
-
- /**
- * 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);
-
- /**
- * <p>This property allows for one or more namespace declarations
- * (a namespace prefix and a namespace uri) at a given node. The
- * object value should be a java.util.Properties object, where each
- * key is a String prefix and each value is the namespace String
- * uri. The prefix may then be referenced by other nodes via
- * the {@link #NAMESPACE_PREFIX} property.</p>
- *
- * <p>One common example would be the XML Schema namespace for
- * instances. In this case, the common convention is to use
- * "xsi" for the prefix, and the uri is
- * "http://www.w3.org/2001/XMLSchema-instance". This is commonly
- * declared at the root node of the document instance. Then, elsewhere,
- * a node may for example use the "nil" attribute from that namespace:
- *
- * <pre><shipDate xsi:nil="true"/></pre>
- * </p>
- */
- public static final Integer NAMESPACE_DECLARATIONS = new Integer(2);
-
- /**
- * 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
-
- /**
- * <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);
-
- /**
- * <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);
-
- /**
- * 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);
-
- /**
- * This property represents a default value for an XML node
- */
- public static final Integer DEFAULT_VALUE = new Integer(8);
-
- /**
- * This property represents a fixed value for an XML node
- */
- public static final Integer FIXED_VALUE = new Integer(11);
-
- /**
- * <p>Value will be of type Boolean. Indicates that the node is nillable,
- * i.e. may have a child attribute <code>xsi:nil="true"</code>,
- * where xsi indicates the W3C namespace for instances. This explicitly
- * 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
- * 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);
-
- /**
- * <p>This node will be completely ignored, not output, not
- * processed</p>
- * <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);
-
-
- /** The name of the result being returned by this node */
- public static final Integer RESULT_SET_NAME = new Integer(20);
-
- /**
- * The name(s) of the temporary group(s) to be materialized at this
- * document node.
- * <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);
-
- /** The symbol from a result set that maps to this node. */
- public static final Integer ELEMENT_NAME = new Integer(30);
-
- /** The temporary property to mark whether this node should be included. */
- public static final Integer IS_INCLUDED = new Integer(15);
-
- /**
- * The text for a comment.
- */
- public static final Integer COMMENT_TEXT = new Integer(16);
-
- /**
- * Indicates that the element or attribute is to be considered optional,
- * even if it has a fixed or default value - it should be removed from the
- * result doc if it doesn't have child content or doesn't receive character
- * content from the underlying data store. See defect 12077
- * <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);
-
- /**
- * <p>Indicates the level of text normalization that will be applied
- * to the text content for a given element or attribute. </p>
- * <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);
-
- /**
- * Specifies the design-time base built-in type for the virtual document node.
- * This property is <strong>optional</strong> and may not exist, particularly for
- * legacy XML virtual docs or for nodes that are not mapped to data. This information
- * 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);
-
- // ========================================================================
- // CHOICE NODE RELATED PROPERTIES
- // ========================================================================
-
- /**
- * <p>This property of a <i>single child</i> of a choice node marks that
- * child as representing the default choice of the choice node.</p>
- * <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);
-
- /**
- * <p>This property of a choice node indicates that, by
- * default (if none of the choices evaluate to true), an
- * exception will be thrown. The order in which this
- * will be considered: first, check that a child node
- * is marked as the {@link #IS_DEFAULT_CHOICE default choice};
- * if not, then check this property. If it is true, throw
- * an exception, if false, do nothing.</p>
- * <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);
-
- // ========================================================================
- // RECURSI0N RELATED PROPERTIES
- // ========================================================================
-
- /**
- * 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}</p>
- */
- public static final Integer IS_RECURSIVE = new Integer(59);
-
- /**
- * The criteria of a node representing the root of a recursive
- * XML fragment. The criteria should specify under what circumstances the
- * recursion should terminate. i.e. "resultSetName.employeeName = 'Jones'"
- * @see #RECURSION_LIMIT
- */
- public static final Integer RECURSION_CRITERIA = new Integer(50);
-
- /**
- * The recursion limit of a recursive XML fragment - if the
- * {@link #RECURSION_CRITERIA} does not terminate the recursion before
- * the limit is reached, the recursion will be terminated after this
- * many iterations. This is to prevent runaway recursion.
- * <p>Type: <code>java.lang.Integer</code></p>
- * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_RECURSION_LIMIT}</p>
- * @see #EXCEPTION_ON_RECURSION_LIMIT
- */
- public static final Integer RECURSION_LIMIT = new Integer(51);
-
- /**
- * If recursion is terminated due to the safeguard {@link #RECURSION_LIMIT} being
- * reached, this property controls whether an exception will be thrown or not.
- * <p>Type: <code>java.lang.Boolean</code></p>
- * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_EXCEPTION_ON_RECURSION_LIMIT}</p>
- * @see #RECURSION_CRITERIA
- * @see #RECURSION_LIMIT
- */
- public static final Integer EXCEPTION_ON_RECURSION_LIMIT = new Integer(52);
-
- /**
- * This property should be set on each document node at which a recursive
- * mapping class is anchored. The value of this property should be the
- * String name of the ancestor mapping class which is rooted at the
- * recursive root node (i.e. the root of the recursive fragment of the
- * document).
- * <p>Type: <code>java.lang.String</code></p>
- */
- public static final Integer RECURSION_ROOT_MAPPING_CLASS = new Integer(53);
-
- /**
- * 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);
-
- // ==================================================================================
- // DOCUMENT PROPERTIES (read from root node only, applicable to document as a whole)
- // ==================================================================================
-
- /**
- * <p>The encoding format of the document. This property only needs to be
- * 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);
-
- /**
- * <p>Indicates whether the document will be outputted as a compressed
- * String, or in readable form, with line breaks or indenting. This
- * property only needs to be set at the root MappingNode
- * of the document.</p>
- * <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);
-
- /**
- * 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);
-
- /**
- * In the case of the recursive mapping element nodes, the source nodes
- * may be different, in that case the original result set name
- * (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);
-
- /**
- * 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);
- }
-
- // =========================================================================
- // XML DOCUMENT TAGS
- // =========================================================================
-
- /**
- * These are the String values to be used for XML document tags.
- * They map to one of the property keys defined in {@link Properties},
- * With the exceptions of the namespace ones:
- * {@link #NAMESPACE_DECLARATION} and child tags.
- * @see getPropertyString
- * @see getPropertyInteger
- */
- public static final class Tags {
- private Tags() { }
-
- public static final String MAPPING_ROOT_NAME = "xmlMapping"; //$NON-NLS-1$
- public static final String MAPPING_NODE_NAME = "mappingNode"; //$NON-NLS-1$
-
- public static final String NAME = "name"; //$NON-NLS-1$
- public static final String NAMESPACE_PREFIX = "namespace"; //$NON-NLS-1$
- /**
- * The wrapper tag around a single namespace declaration
- */
- public static final String NAMESPACE_DECLARATION = "namespaceDeclaration"; //$NON-NLS-1$
- /**
- * The attribute, child of the namespace declaration element,
- * which specifies the prefix of a namespace declaration
- */
- public static final String NAMESPACE_DECLARATION_PREFIX = "prefix"; //$NON-NLS-1$
- /**
- * The attribute, child of the namespace declaration element,
- * which specifies the uri of a namespace declaration
- */
- public static final String NAMESPACE_DECLARATION_URI = "uri"; //$NON-NLS-1$
- public static final String NODE_TYPE = "nodeType"; //$NON-NLS-1$
- public static final String CARDINALITY_MIN_BOUND = "minOccurs"; //$NON-NLS-1$
- public static final String CARDINALITY_MAX_BOUND = "maxOccurs"; //$NON-NLS-1$
- public static final String CRITERIA = "criteria"; //$NON-NLS-1$
- public static final String DEFAULT_VALUE = "default"; //$NON-NLS-1$
- public static final String FIXED_VALUE = "fixed"; //$NON-NLS-1$
- public static final String RESULT_SET_NAME = "source"; //$NON-NLS-1$
- //public static final String ALIAS_RESULT_SET_NAME="aliasSource";//$NON-NLS-1$
- /**
- * specifies a single temp group name - this tag has
- * multiplicity of zero or more
- */
- public static final String TEMP_GROUP_NAME = "tempGroup"; //$NON-NLS-1$
- public static final String ELEMENT_NAME = "symbol"; //$NON-NLS-1$
- public static final String COMMENT_TEXT = "comment"; //$NON-NLS-1$
- public static final String IS_OPTIONAL = "optional"; //$NON-NLS-1$
- public static final String IS_NILLABLE = "isNillable"; //$NON-NLS-1$
- public static final String IS_EXCLUDED = "isExcluded"; //$NON-NLS-1$
- public static final String IS_DEFAULT_CHOICE = "isDefaultChoice"; //$NON-NLS-1$
- public static final String EXCEPTION_ON_DEFAULT = "exceptionOnDefault"; //$NON-NLS-1$
- public static final String DOCUMENT_ENCODING = "documentEncoding"; //$NON-NLS-1$
- public static final String NORMALIZE_TEXT = "textNormalization"; //$NON-NLS-1$
- public static final String BUILT_IN_TYPE = "builtInType"; //$NON-NLS-1$
- public static final String FORMATTED_DOCUMENT = "formattedDocument"; //$NON-NLS-1$
- public static final String IS_RECURSIVE = "isRecursive"; //$NON-NLS-1$
- public static final String RECURSION_CRITERIA = "recursionCriteria"; //$NON-NLS-1$
- public static final String RECURSION_LIMIT = "recursionLimit"; //$NON-NLS-1$
- public static final String RECURSION_LIMIT_EXCEPTION = "recursionLimitException"; //$NON-NLS-1$
- public static final String RECURSION_ROOT_MAPPING_CLASS = "recursionRootMappingClass"; //$NON-NLS-1$
- public static final String ALWAYS_INCLUDE = "includeAlways"; //$NON-NLS-1$
- /**
- * The List of the tags, defined in this Class, which are
- * child elements of a {@link #MAPPING_NODE_NAME mapping node}
- * tag. They are in a fixed order, so that the
- * {@link MappingOutputter} can output documents in a consistent
- * manner. Some tags are left out that the MappingOutputter
- * handles separately.
- */
- static final List OUTPUTTER_PROPERTY_TAGS;
-
- // Initialize static variables...
- static {
- List temp = Arrays.asList( new String[]{
- MappingNodeConstants.Tags.NAME,
- MappingNodeConstants.Tags.NODE_TYPE,
- MappingNodeConstants.Tags.NAMESPACE_PREFIX,
- MappingNodeConstants.Tags.DOCUMENT_ENCODING,
- MappingNodeConstants.Tags.FORMATTED_DOCUMENT,
- MappingNodeConstants.Tags.CRITERIA,
- MappingNodeConstants.Tags.DEFAULT_VALUE,
- MappingNodeConstants.Tags.FIXED_VALUE,
- MappingNodeConstants.Tags.CARDINALITY_MIN_BOUND,
- MappingNodeConstants.Tags.CARDINALITY_MAX_BOUND,
- MappingNodeConstants.Tags.RESULT_SET_NAME,
- MappingNodeConstants.Tags.TEMP_GROUP_NAME,
- MappingNodeConstants.Tags.ELEMENT_NAME,
- MappingNodeConstants.Tags.COMMENT_TEXT,
- MappingNodeConstants.Tags.IS_OPTIONAL,
- MappingNodeConstants.Tags.IS_NILLABLE,
- MappingNodeConstants.Tags.IS_EXCLUDED,
- MappingNodeConstants.Tags.IS_DEFAULT_CHOICE,
- MappingNodeConstants.Tags.EXCEPTION_ON_DEFAULT,
- MappingNodeConstants.Tags.IS_RECURSIVE,
- MappingNodeConstants.Tags.RECURSION_CRITERIA,
- MappingNodeConstants.Tags.RECURSION_LIMIT,
- MappingNodeConstants.Tags.RECURSION_LIMIT_EXCEPTION,
- MappingNodeConstants.Tags.RECURSION_ROOT_MAPPING_CLASS,
- MappingNodeConstants.Tags.NORMALIZE_TEXT,
- MappingNodeConstants.Tags.ALWAYS_INCLUDE,
- MappingNodeConstants.Tags.BUILT_IN_TYPE
- } );
- OUTPUTTER_PROPERTY_TAGS = Collections.unmodifiableList(temp);
- }
- }
-
-
- /**
- * Convert a property String into one of the Integer property keys
- * defined in {@link Properties}
- * @param property String representation of property
- * @return one of the properties defined in the
- * {@link Properties} inner class
- * @throw IllegalArgumentException if parameter isn't for one of the properties
- * defined in {@link Properties}
- * @see getPropertyString
- */
- public static final Integer getPropertyInteger(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;
- else if (property.equals(Tags.CARDINALITY_MIN_BOUND)) return Properties.CARDINALITY_MIN_BOUND;
- else if (property.equals(Tags.CARDINALITY_MAX_BOUND)) return Properties.CARDINALITY_MAX_BOUND;
- else if (property.equals(Tags.CRITERIA)) return Properties.CRITERIA;
- else if (property.equals(Tags.DEFAULT_VALUE)) return Properties.DEFAULT_VALUE;
- else if (property.equals(Tags.FIXED_VALUE)) return Properties.FIXED_VALUE;
- else if (property.equals(Tags.RESULT_SET_NAME)) return Properties.RESULT_SET_NAME;
- //else if (property.equals(Tags.ALIAS_RESULT_SET_NAME)) return Properties.ALIAS_RESULT_SET_NAME;
- else if (property.equals(Tags.TEMP_GROUP_NAME)) return Properties.TEMP_GROUP_NAMES;
- else if (property.equals(Tags.ELEMENT_NAME)) return Properties.ELEMENT_NAME;
- else if (property.equals(Tags.COMMENT_TEXT)) return Properties.COMMENT_TEXT;
- else if (property.equals(Tags.IS_OPTIONAL)) return Properties.IS_OPTIONAL;
- else if (property.equals(Tags.IS_NILLABLE)) return Properties.IS_NILLABLE;
- else if (property.equals(Tags.IS_EXCLUDED)) return Properties.IS_EXCLUDED;
- else if (property.equals(Tags.IS_DEFAULT_CHOICE)) return Properties.IS_DEFAULT_CHOICE;
- else if (property.equals(Tags.EXCEPTION_ON_DEFAULT)) return Properties.EXCEPTION_ON_DEFAULT;
- else if (property.equals(Tags.DOCUMENT_ENCODING)) return Properties.DOCUMENT_ENCODING;
- else if (property.equals(Tags.FORMATTED_DOCUMENT)) return Properties.FORMATTED_DOCUMENT;
- else if (property.equals(Tags.IS_RECURSIVE)) return Properties.IS_RECURSIVE;
- else if (property.equals(Tags.RECURSION_CRITERIA)) return Properties.RECURSION_CRITERIA;
- else if (property.equals(Tags.RECURSION_LIMIT)) return Properties.RECURSION_LIMIT;
- else if (property.equals(Tags.RECURSION_LIMIT_EXCEPTION)) return Properties.EXCEPTION_ON_RECURSION_LIMIT;
- else if (property.equals(Tags.RECURSION_ROOT_MAPPING_CLASS)) return Properties.RECURSION_ROOT_MAPPING_CLASS;
- else if (property.equals(Tags.NORMALIZE_TEXT)) return Properties.NORMALIZE_TEXT;
- else if (property.equals(Tags.BUILT_IN_TYPE)) return Properties.BUILT_IN_TYPE;
- else if (property.equals(Tags.ALWAYS_INCLUDE)) return Properties.ALWAYS_INCLUDE;
- else {
- throw new IllegalArgumentException("Unknown property ("+property+")"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- /**
- * Convert a property Integer into a String (suitable for an XML tag).
- * @param property one of the properties defined in the
- * {@link Properties} inner class
- * @return String representation of property
- * @throw IllegalArgumentException if parameter isn't one of the properties
- * defined in {@link Properties}
- * @see getPropertyInteger
- */
- public static final String getPropertyString(Integer property){
- if(property.equals(Properties.NAME)) return Tags.NAME;
- else if (property.equals(Properties.NAMESPACE_PREFIX)) return Tags.NAMESPACE_PREFIX;
- else if (property.equals(Properties.NODE_TYPE)) return Tags.NODE_TYPE;
- else if (property.equals(Properties.CARDINALITY_MIN_BOUND)) return Tags.CARDINALITY_MIN_BOUND;
- else if (property.equals(Properties.CARDINALITY_MAX_BOUND)) return Tags.CARDINALITY_MAX_BOUND;
- else if (property.equals(Properties.CRITERIA)) return Tags.CRITERIA;
- else if (property.equals(Properties.DEFAULT_VALUE)) return Tags.DEFAULT_VALUE;
- else if (property.equals(Properties.FIXED_VALUE)) return Tags.FIXED_VALUE;
- else if (property.equals(Properties.RESULT_SET_NAME)) return Tags.RESULT_SET_NAME;
- else if (property.equals(Properties.TEMP_GROUP_NAMES)) return Tags.TEMP_GROUP_NAME;
- else if (property.equals(Properties.ELEMENT_NAME)) return Tags.ELEMENT_NAME;
- else if (property.equals(Properties.COMMENT_TEXT)) return Tags.COMMENT_TEXT;
- else if (property.equals(Properties.IS_OPTIONAL)) return Tags.IS_OPTIONAL;
- else if (property.equals(Properties.IS_NILLABLE)) return Tags.IS_NILLABLE;
- else if (property.equals(Properties.IS_EXCLUDED)) return Tags.IS_EXCLUDED;
- else if (property.equals(Properties.IS_DEFAULT_CHOICE)) return Tags.IS_DEFAULT_CHOICE;
- else if (property.equals(Properties.EXCEPTION_ON_DEFAULT)) return Tags.EXCEPTION_ON_DEFAULT;
- else if (property.equals(Properties.DOCUMENT_ENCODING)) return Tags.DOCUMENT_ENCODING;
- else if (property.equals(Properties.FORMATTED_DOCUMENT)) return Tags.FORMATTED_DOCUMENT;
- else if (property.equals(Properties.IS_RECURSIVE)) return Tags.IS_RECURSIVE;
- else if (property.equals(Properties.RECURSION_CRITERIA)) return Tags.RECURSION_CRITERIA;
- else if (property.equals(Properties.RECURSION_LIMIT)) return Tags.RECURSION_LIMIT;
- else if (property.equals(Properties.EXCEPTION_ON_RECURSION_LIMIT)) return Tags.RECURSION_LIMIT_EXCEPTION;
- else if (property.equals(Properties.RECURSION_ROOT_MAPPING_CLASS)) return Tags.RECURSION_ROOT_MAPPING_CLASS;
- else if (property.equals(Properties.NORMALIZE_TEXT)) return Tags.NORMALIZE_TEXT;
- else if (property.equals(Properties.BUILT_IN_TYPE)) return Tags.BUILT_IN_TYPE;
- else if (property.equals(Properties.ALWAYS_INCLUDE)) return Tags.ALWAYS_INCLUDE;
- else {
- throw new IllegalArgumentException("Unknown property ("+property+")"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- // =========================================================================
- // DEFAULTS
- // =========================================================================
-
- /**
- * Default property values for node {@link MappingNodeConstants.Properties properties}
- */
- public static final class Defaults {
- private Defaults() { }
-
- /**
- * Default property values, keyed off the properties defined in
- * {@link MappingNodeConstants.Properties}. The {@link MappingNode} class will return
- * these values if none are defined, for each property.
- */
- public static final Map DEFAULT_VALUES;
-
- /** The default minimum bound of the cardinality of a node. */
- public static final Integer DEFAULT_CARDINALITY_MINIMUM_BOUND = new Integer(1);
-
- /** The default maximum bound of the cardinality of a node. */
- public static final Integer DEFAULT_CARDINALITY_MAXIMUM_BOUND = new Integer(1);
-
- /** The default output type of the node, if no value is specified */
- public static final String DEFAULT_NODE_TYPE = ELEMENT;
-
- /** The default value for {@link MappingNodeConstants.Properties#IS_NILLABLE} */
- public static final Boolean DEFAULT_IS_NILLABLE = Boolean.FALSE;
-
- /** The default value for {@link MappingNodeConstants.Properties#TEMP_GROUP_NAMES} */
- public static final Collection DEFAULT_TEMP_GROUP_NAMES = Collections.EMPTY_LIST;
-
- /** The default value for {@link MappingNodeConstants.Properties#IS_OPTIONAL} */
- public static final Boolean DEFAULT_IS_OPTIONAL = Boolean.FALSE;
-
- /** The default value for {@link MappingNodeConstants.Properties#NORMALIZE_TEXT} */
- public static final String DEFAULT_NORMALIZE_TEXT = NORMALIZE_TEXT_PRESERVE;
-
- /** The default value for {@link MappingNodeConstants.Properties#BUILT_IN_TYPE} */
- public static final String DEFAULT_BUILT_IN_TYPE = NO_TYPE;
-
- // ========================================================================
- // CHOICE RELATED DEFAULTS
- // ========================================================================
-
- /** The default value for {@link MappingNodeConstants.Properties#IS_NILLABLE} */
- public static final Boolean DEFAULT_IS_EXCLUDED = Boolean.FALSE;
-
- /** The default value for {@link MappingNodeConstants.Properties#IS_INCLUDED} */
- public static final Boolean DEFAULT_IS_INCLUDED = Boolean.FALSE;
-
- /** The default value for {@link MappingNodeConstants.Properties#IS_DEFAULT_CHOICE} */
- public static final Boolean DEFAULT_IS_DEFAULT_CHOICE = Boolean.FALSE;
-
- /** The default value for {@link MappingNodeConstants.Properties#EXCEPTION_ON_DEFAULT} */
- public static final Boolean DEFAULT_EXCEPTION_ON_DEFAULT = Boolean.FALSE;
-
- // ========================================================================
- // RECURSI0N RELATED DEFAULTS
- // ========================================================================
-
- /** The default value for {@link MappingNodeConstants.Properties#IS_RECURSIVE} */
- public static final Boolean DEFAULT_IS_RECURSIVE = Boolean.FALSE;
-
- /** The default value for {@link MappingNodeConstants.Properties#IS_RECURSIVE_ROOT} */
- public static final Boolean DEFAULT_IS_RECURSIVE_ROOT = Boolean.FALSE;
-
- /** The default value for {@link MappingNodeConstants.Properties#RECURSION_LIMIT} */
- public static final Integer DEFAULT_RECURSION_LIMIT = new Integer(10);
-
- /** The default value for {@link MappingNodeConstants.Properties#EXCEPTION_ON_RECURSION_LIMIT} */
- public static final Boolean DEFAULT_EXCEPTION_ON_RECURSION_LIMIT = Boolean.FALSE;
-
- // ========================================================================
- // DOCUMENT RELATED DEFAULTS
- // ========================================================================
-
- /** The default value for {@link MappingNodeConstants.Properties#DOCUMENT_ENCODING} */
- public static final String DEFAULT_DOCUMENT_ENCODING = "UTF-8"; //$NON-NLS-1$
-
- /** The default value for {@link MappingNodeConstants.Properties#FORMATTED_DOCUMENT} */
- public static final Boolean DEFAULT_FORMATTED_DOCUMENT = Boolean.FALSE;
-
- static{
- HashMap temp = new HashMap();
- 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);
- temp.put(Properties.IS_NILLABLE, DEFAULT_IS_NILLABLE);
- temp.put(Properties.TEMP_GROUP_NAMES, DEFAULT_TEMP_GROUP_NAMES);
- temp.put(Properties.IS_OPTIONAL, DEFAULT_IS_OPTIONAL);
- temp.put(Properties.IS_EXCLUDED, DEFAULT_IS_EXCLUDED);
- temp.put(Properties.IS_INCLUDED, DEFAULT_IS_INCLUDED);
- temp.put(Properties.IS_DEFAULT_CHOICE, DEFAULT_IS_DEFAULT_CHOICE);
- temp.put(Properties.EXCEPTION_ON_DEFAULT, DEFAULT_EXCEPTION_ON_DEFAULT);
- temp.put(Properties.IS_RECURSIVE, DEFAULT_IS_RECURSIVE);
- temp.put(Properties.IS_RECURSIVE_ROOT, DEFAULT_IS_RECURSIVE_ROOT);
- temp.put(Properties.RECURSION_LIMIT, DEFAULT_RECURSION_LIMIT);
- temp.put(Properties.EXCEPTION_ON_RECURSION_LIMIT, DEFAULT_EXCEPTION_ON_RECURSION_LIMIT);
- temp.put(Properties.DOCUMENT_ENCODING, DEFAULT_DOCUMENT_ENCODING);
- temp.put(Properties.FORMATTED_DOCUMENT, DEFAULT_FORMATTED_DOCUMENT);
- temp.put(Properties.NORMALIZE_TEXT, DEFAULT_NORMALIZE_TEXT);
- DEFAULT_VALUES = Collections.unmodifiableMap(temp);
- }
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNodeConstants.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingNodeConstants.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNodeConstants.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingNodeConstants.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,718 @@
+/*
+ * 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.mapping.xml;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Constants, property names, and property default values for
+ * a {@link MappingNode}.
+ */
+public final class MappingNodeConstants {
+
+ // Can't instantiate
+ private MappingNodeConstants() { }
+
+ // =========================================================================
+ // CONSTANTS
+ // =========================================================================
+
+ /**
+ * Indicates a search of a mapping document should be upward. See
+ * {@link MappingNode#findFirstNodeWithProperty}
+ */
+ public static final int SEARCH_UP = 2;
+
+ /**
+ * Indicates a search of a mapping document should be downward, DEPTH FIRST. See
+ * {@link MappingNode#findFirstNodeWithProperty}
+ */
+ public static final int SEARCH_DOWN = 3; // DEPTH FIRST
+
+ /**
+ * Indicates a search of a mapping document should be downward, BREADTH FIRST. See
+ * {@link MappingNode#findFirstNodeWithProperty}
+ */
+ public static final int SEARCH_DOWN_BREADTH_FIRST = 4; //BREADTH FIRST
+
+ /** Constant for children returned by non-complex nodes (never have children). */
+ static final List NO_CHILDREN = Collections.EMPTY_LIST;
+
+ /** Schema node path delimeter. */
+ public static final String PATH_DELIM = "."; //$NON-NLS-1$
+
+ /** The value used to indicate an unbounded maximum cardinality */
+ public static final Integer CARDINALITY_UNBOUNDED = new Integer(-1);
+
+ public static final String CARDINALITY_UNBOUNDED_STRING = "unbounded"; //$NON-NLS-1$
+
+ /** Constant defining a target node type of "attribute". */
+ public static final String ATTRIBUTE = "attribute"; //$NON-NLS-1$
+
+ /** Constant defining a target node type of "element". */
+ public static final String ELEMENT = "element"; //$NON-NLS-1$
+
+ /** Constant defining a target node type of "comment". */
+ public static final String COMMENT = "comment"; //$NON-NLS-1$
+
+ /** Constant defining a target node type of "sequence". */
+ public static final String SEQUENCE = "sequence"; //$NON-NLS-1$
+
+ /** Constant defining a target node type of "choice". */
+ public static final String CHOICE = "choice"; //$NON-NLS-1$
+
+ /** Constant defining a target node type of "All". */
+ public static final String ALL = "all"; //$NON-NLS-1$
+
+ /** Constant defining a target node type of "Criteria". */
+ public static final String CRITERIA = "criteria"; //$NON-NLS-1$
+
+ /** Constant defining a target node type of "source". */
+ public static final String SOURCE = "source"; //$NON-NLS-1$
+
+
+ /**
+ * Defines a default namespace holder for the nodes with out any
+ * namespace declarations.
+ */
+ public static final Namespace NO_NAMESPACE = new Namespace("", ""); //$NON-NLS-1$ //$NON-NLS-2$
+
+ /**
+ * This constant is merely used as a placeholder in the declaration of a
+ * default namespace in an XML doc instance. A default namespace has no
+ * prefix associated with it, so the String used here is a forbidden XML
+ * character that could never be used as a real namespace prefix.
+ */
+ public static final String DEFAULT_NAMESPACE_PREFIX = ""; //$NON-NLS-1$
+
+ /**
+ * Prefix of the XML Schema namespace for instances - needed to make
+ * use of the "nil" attribute defined in that namespace, for
+ * nillable nodes
+ * @see #INSTANCES_NAMESPACE
+ */
+ public static final String INSTANCES_NAMESPACE_PREFIX = "xsi"; //$NON-NLS-1$
+
+ /**
+ * The XML Schema namespace for instances - needed to make
+ * use of the "nil" attribute defined in that namespace, for
+ * nillable nodes
+ * @see #INSTANCES_NAMESPACE_PREFIX
+ */
+ public static final String INSTANCES_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance"; //$NON-NLS-1$
+
+ public static final String NAMESPACE_DECLARATION_ATTRIBUTE_NAMESPACE = "xmlns"; //$NON-NLS-1$
+
+ /**
+ * PRESERVE -No normalization is done, the value is not changed.
+ * REPLACE - All occurrences of tab, line feed and carriage return are replaced with space
+ * COLLAPSE - After the processing implied by replace, contiguous sequences of space are
+ * collapsed to a single space, and leading and trailing spaces are removed.
+ */
+ public static final String NORMALIZE_TEXT_PRESERVE = "preserve"; //$NON-NLS-1$
+ public static final String NORMALIZE_TEXT_REPLACE = "replace"; //$NON-NLS-1$
+ public static final String NORMALIZE_TEXT_COLLAPSE = "collapse"; //$NON-NLS-1$
+
+ /**
+ * Default built-in type = no type info, which is an empty string
+ */
+ public static final String NO_TYPE = ""; //$NON-NLS-1$
+
+ // =========================================================================
+ // PROPERTIES
+ // =========================================================================
+
+ /**
+ * Property names for type-specific node properties. Values will be of
+ * type String unless otherwise specified.
+ */
+ public enum Properties {
+
+ /** The basic name of this node. Will be the element or attribute tag name. */
+ 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.
+ */
+ NAMESPACE_PREFIX,
+
+ /**
+ * <p>This property allows for one or more namespace declarations
+ * (a namespace prefix and a namespace uri) at a given node. The
+ * object value should be a java.util.Properties object, where each
+ * key is a String prefix and each value is the namespace String
+ * uri. The prefix may then be referenced by other nodes via
+ * the {@link #NAMESPACE_PREFIX} property.</p>
+ *
+ * <p>One common example would be the XML Schema namespace for
+ * instances. In this case, the common convention is to use
+ * "xsi" for the prefix, and the uri is
+ * "http://www.w3.org/2001/XMLSchema-instance". This is commonly
+ * declared at the root node of the document instance. Then, elsewhere,
+ * a node may for example use the "nil" attribute from that namespace:
+ *
+ * <pre><shipDate xsi:nil="true"/></pre>
+ * </p>
+ */
+ NAMESPACE_DECLARATIONS,
+
+ /**
+ * The target node type. Can take on one of the values {@link #ATTRIBUTE}
+ * or {@link #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>
+ */
+ 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>
+ */
+ 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.
+ */
+ CRITERIA,
+
+ /**
+ * This property represents a default value for an XML node
+ */
+ DEFAULT_VALUE,
+
+ /**
+ * This property represents a fixed value for an XML node
+ */
+ FIXED_VALUE,
+
+ /**
+ * <p>Value will be of type Boolean. Indicates that the node is nillable,
+ * i.e. may have a child attribute <code>xsi:nil="true"</code>,
+ * where xsi indicates the W3C namespace for instances. This explicitly
+ * 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 #NODETYPE} property must have
+ * a value of {@link #ELEMENT}), although this constraint is not
+ * enforced anywhere in the MappingNode framework.</p>
+ */
+ IS_NILLABLE,
+
+ /**
+ * <p>This node will be completely ignored, not output, not
+ * processed</p>
+ * <p>Type: <code>java.lang.Boolean</code></p>
+ * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_IS_EXCLUDED}</p>
+ */
+ IS_EXCLUDED,
+
+
+ /** The name of the result being returned by this node */
+ RESULT_SET_NAME,
+
+ /**
+ * The name(s) of the temporary group(s) to be materialized at this
+ * document node.
+ * <p>Type: <code>java.util.List</code> of </code>java.lang.String</code>
+ * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_TEMP_GROUP_NAMES}</p>
+ */
+ TEMP_GROUP_NAMES,
+
+ /** The symbol from a result set that maps to this node. */
+ ELEMENT_NAME,
+
+ /** The temporary property to mark whether this node should be included. */
+ IS_INCLUDED,
+
+ /**
+ * The text for a comment.
+ */
+ COMMENT_TEXT,
+
+ /**
+ * Indicates that the element or attribute is to be considered optional,
+ * even if it has a fixed or default value - it should be removed from the
+ * result doc if it doesn't have child content or doesn't receive character
+ * content from the underlying data store. See defect 12077
+ * <p>Type: <code>java.lang.Boolean</code>
+ * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_IS_OPTIONAL}</p>
+ */
+ IS_OPTIONAL,
+
+ /**
+ * <p>Indicates the level of text normalization that will be applied
+ * to the text content for a given element or attribute. </p>
+ * <p>Type: <code>java.lang.String</code></p>
+ * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_NORMALIZE_TEXT}</p>
+ */
+ NORMALIZE_TEXT,
+
+ /**
+ * Specifies the design-time base built-in type for the virtual document node.
+ * This property is <strong>optional</strong> and may not exist, particularly for
+ * legacy XML virtual docs or for nodes that are not mapped to data. This information
+ * is used to determine special translations from the runtime value to the expected
+ * XML schema output value string.
+ */
+ BUILT_IN_TYPE,
+
+ // ========================================================================
+ // CHOICE NODE RELATED PROPERTIES
+ // ========================================================================
+
+ /**
+ * <p>This property of a <i>single child</i> of a choice node marks that
+ * child as representing the default choice of the choice node.</p>
+ * <p>Type: <code>java.lang.Boolean</code></p>
+ * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_IS_DEFAULT_CHOICE}</p>
+ */
+ IS_DEFAULT_CHOICE,
+
+ /**
+ * <p>This property of a choice node indicates that, by
+ * default (if none of the choices evaluate to true), an
+ * exception will be thrown. The order in which this
+ * will be considered: first, check that a child node
+ * is marked as the {@link #IS_DEFAULT_CHOICE default choice};
+ * if not, then check this property. If it is true, throw
+ * an exception, if false, do nothing.</p>
+ * <p>Type: <code>java.lang.Boolean</code></p>
+ * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_EXCEPTION_ON_DEFAULT}</p>
+ */
+ EXCEPTION_ON_DEFAULT,
+
+ // ========================================================================
+ // RECURSI0N RELATED PROPERTIES
+ // ========================================================================
+
+ /**
+ * 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}</p>
+ */
+ IS_RECURSIVE,
+
+ /**
+ * The criteria of a node representing the root of a recursive
+ * XML fragment. The criteria should specify under what circumstances the
+ * recursion should terminate. i.e. "resultSetName.employeeName = 'Jones'"
+ * @see #RECURSION_LIMIT
+ */
+ RECURSION_CRITERIA,
+
+ /**
+ * The recursion limit of a recursive XML fragment - if the
+ * {@link #RECURSION_CRITERIA} does not terminate the recursion before
+ * the limit is reached, the recursion will be terminated after this
+ * many iterations. This is to prevent runaway recursion.
+ * <p>Type: <code>java.lang.Integer</code></p>
+ * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_RECURSION_LIMIT}</p>
+ * @see #EXCEPTION_ON_RECURSION_LIMIT
+ */
+ RECURSION_LIMIT,
+
+ /**
+ * If recursion is terminated due to the safeguard {@link #RECURSION_LIMIT} being
+ * reached, this property controls whether an exception will be thrown or not.
+ * <p>Type: <code>java.lang.Boolean</code></p>
+ * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_EXCEPTION_ON_RECURSION_LIMIT}</p>
+ * @see #RECURSION_CRITERIA
+ * @see #RECURSION_LIMIT
+ */
+ EXCEPTION_ON_RECURSION_LIMIT,
+
+ /**
+ * This property should be set on each document node at which a recursive
+ * mapping class is anchored. The value of this property should be the
+ * String name of the ancestor mapping class which is rooted at the
+ * recursive root node (i.e. the root of the recursive fragment of the
+ * document).
+ * <p>Type: <code>java.lang.String</code></p>
+ */
+ 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>
+ */
+ IS_RECURSIVE_ROOT,
+
+ // ==================================================================================
+ // DOCUMENT PROPERTIES (read from root node only, applicable to document as a whole)
+ // ==================================================================================
+
+ /**
+ * <p>The encoding format of the document. This property only needs to be
+ * set at the root MappingNode of the document.</p>
+ * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_DOCUMENT_ENCODING}</p>
+ */
+ DOCUMENT_ENCODING,
+
+ /**
+ * <p>Indicates whether the document will be outputted as a compressed
+ * String, or in readable form, with line breaks or indenting. This
+ * property only needs to be set at the root MappingNode
+ * of the document.</p>
+ * <p>Type: <code>java.lang.Boolean</code></p>
+ * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_FORMATTED_DOCUMENT}</p>
+ */
+ 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.
+ */
+ ALWAYS_INCLUDE,
+
+ /**
+ * In the case of the recursive mapping element nodes, the source nodes
+ * may be different, in that case the original result set name
+ * (i.e. mapping class in recurive node) is alias to the source node which is
+ * above the recursive node.
+ */
+ ALIAS_RESULT_SET_NAME,
+
+ /**
+ * Result Set Info object which contains the query and the plan for
+ * the source node.
+ */
+ RESULT_SET_INFO,
+ }
+
+ // =========================================================================
+ // XML DOCUMENT TAGS
+ // =========================================================================
+
+ /**
+ * These are the String values to be used for XML document tags.
+ * They map to one of the property keys defined in {@link Properties},
+ * With the exceptions of the namespace ones:
+ * {@link #NAMESPACE_DECLARATION} and child tags.
+ * @see getPropertyString
+ * @see getPropertyInteger
+ */
+ public static final class Tags {
+ private Tags() { }
+
+ public static final String MAPPING_ROOT_NAME = "xmlMapping"; //$NON-NLS-1$
+ public static final String MAPPING_NODE_NAME = "mappingNode"; //$NON-NLS-1$
+
+ public static final String NAME = "name"; //$NON-NLS-1$
+ public static final String NAMESPACE_PREFIX = "namespace"; //$NON-NLS-1$
+ /**
+ * The wrapper tag around a single namespace declaration
+ */
+ public static final String NAMESPACE_DECLARATION = "namespaceDeclaration"; //$NON-NLS-1$
+ /**
+ * The attribute, child of the namespace declaration element,
+ * which specifies the prefix of a namespace declaration
+ */
+ public static final String NAMESPACE_DECLARATION_PREFIX = "prefix"; //$NON-NLS-1$
+ /**
+ * The attribute, child of the namespace declaration element,
+ * which specifies the uri of a namespace declaration
+ */
+ public static final String NAMESPACE_DECLARATION_URI = "uri"; //$NON-NLS-1$
+ public static final String NODE_TYPE = "nodeType"; //$NON-NLS-1$
+ public static final String CARDINALITY_MIN_BOUND = "minOccurs"; //$NON-NLS-1$
+ public static final String CARDINALITY_MAX_BOUND = "maxOccurs"; //$NON-NLS-1$
+ public static final String CRITERIA = "criteria"; //$NON-NLS-1$
+ public static final String DEFAULT_VALUE = "default"; //$NON-NLS-1$
+ public static final String FIXED_VALUE = "fixed"; //$NON-NLS-1$
+ public static final String RESULT_SET_NAME = "source"; //$NON-NLS-1$
+ //public static final String ALIAS_RESULT_SET_NAME="aliasSource";//$NON-NLS-1$
+ /**
+ * specifies a single temp group name - this tag has
+ * multiplicity of zero or more
+ */
+ public static final String TEMP_GROUP_NAME = "tempGroup"; //$NON-NLS-1$
+ public static final String ELEMENT_NAME = "symbol"; //$NON-NLS-1$
+ public static final String COMMENT_TEXT = "comment"; //$NON-NLS-1$
+ public static final String IS_OPTIONAL = "optional"; //$NON-NLS-1$
+ public static final String IS_NILLABLE = "isNillable"; //$NON-NLS-1$
+ public static final String IS_EXCLUDED = "isExcluded"; //$NON-NLS-1$
+ public static final String IS_DEFAULT_CHOICE = "isDefaultChoice"; //$NON-NLS-1$
+ public static final String EXCEPTION_ON_DEFAULT = "exceptionOnDefault"; //$NON-NLS-1$
+ public static final String DOCUMENT_ENCODING = "documentEncoding"; //$NON-NLS-1$
+ public static final String NORMALIZE_TEXT = "textNormalization"; //$NON-NLS-1$
+ public static final String BUILT_IN_TYPE = "builtInType"; //$NON-NLS-1$
+ public static final String FORMATTED_DOCUMENT = "formattedDocument"; //$NON-NLS-1$
+ public static final String IS_RECURSIVE = "isRecursive"; //$NON-NLS-1$
+ public static final String RECURSION_CRITERIA = "recursionCriteria"; //$NON-NLS-1$
+ public static final String RECURSION_LIMIT = "recursionLimit"; //$NON-NLS-1$
+ public static final String RECURSION_LIMIT_EXCEPTION = "recursionLimitException"; //$NON-NLS-1$
+ public static final String RECURSION_ROOT_MAPPING_CLASS = "recursionRootMappingClass"; //$NON-NLS-1$
+ public static final String ALWAYS_INCLUDE = "includeAlways"; //$NON-NLS-1$
+ /**
+ * The List of the tags, defined in this Class, which are
+ * child elements of a {@link #MAPPING_NODE_NAME mapping node}
+ * tag. They are in a fixed order, so that the
+ * {@link MappingOutputter} can output documents in a consistent
+ * manner. Some tags are left out that the MappingOutputter
+ * handles separately.
+ */
+ static final List<String> OUTPUTTER_PROPERTY_TAGS;
+
+ // Initialize static variables...
+ static {
+ List<String> temp = Arrays.asList( new String[]{
+ MappingNodeConstants.Tags.NAME,
+ MappingNodeConstants.Tags.NODE_TYPE,
+ MappingNodeConstants.Tags.NAMESPACE_PREFIX,
+ MappingNodeConstants.Tags.DOCUMENT_ENCODING,
+ MappingNodeConstants.Tags.FORMATTED_DOCUMENT,
+ MappingNodeConstants.Tags.CRITERIA,
+ MappingNodeConstants.Tags.DEFAULT_VALUE,
+ MappingNodeConstants.Tags.FIXED_VALUE,
+ MappingNodeConstants.Tags.CARDINALITY_MIN_BOUND,
+ MappingNodeConstants.Tags.CARDINALITY_MAX_BOUND,
+ MappingNodeConstants.Tags.RESULT_SET_NAME,
+ MappingNodeConstants.Tags.TEMP_GROUP_NAME,
+ MappingNodeConstants.Tags.ELEMENT_NAME,
+ MappingNodeConstants.Tags.COMMENT_TEXT,
+ MappingNodeConstants.Tags.IS_OPTIONAL,
+ MappingNodeConstants.Tags.IS_NILLABLE,
+ MappingNodeConstants.Tags.IS_EXCLUDED,
+ MappingNodeConstants.Tags.IS_DEFAULT_CHOICE,
+ MappingNodeConstants.Tags.EXCEPTION_ON_DEFAULT,
+ MappingNodeConstants.Tags.IS_RECURSIVE,
+ MappingNodeConstants.Tags.RECURSION_CRITERIA,
+ MappingNodeConstants.Tags.RECURSION_LIMIT,
+ MappingNodeConstants.Tags.RECURSION_LIMIT_EXCEPTION,
+ MappingNodeConstants.Tags.RECURSION_ROOT_MAPPING_CLASS,
+ MappingNodeConstants.Tags.NORMALIZE_TEXT,
+ MappingNodeConstants.Tags.ALWAYS_INCLUDE,
+ MappingNodeConstants.Tags.BUILT_IN_TYPE
+ } );
+ OUTPUTTER_PROPERTY_TAGS = Collections.unmodifiableList(temp);
+ }
+ }
+
+
+ /**
+ * Convert a property String into one of the Integer property keys
+ * defined in {@link Properties}
+ * @param property String representation of property
+ * @return one of the properties defined in the
+ * {@link Properties} inner class
+ * @throw IllegalArgumentException if parameter isn't for one of the properties
+ * defined in {@link Properties}
+ * @see getPropertyString
+ */
+ 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;
+ else if (property.equals(Tags.CARDINALITY_MIN_BOUND)) return Properties.CARDINALITY_MIN_BOUND;
+ else if (property.equals(Tags.CARDINALITY_MAX_BOUND)) return Properties.CARDINALITY_MAX_BOUND;
+ else if (property.equals(Tags.CRITERIA)) return Properties.CRITERIA;
+ else if (property.equals(Tags.DEFAULT_VALUE)) return Properties.DEFAULT_VALUE;
+ else if (property.equals(Tags.FIXED_VALUE)) return Properties.FIXED_VALUE;
+ else if (property.equals(Tags.RESULT_SET_NAME)) return Properties.RESULT_SET_NAME;
+ //else if (property.equals(Tags.ALIAS_RESULT_SET_NAME)) return Properties.ALIAS_RESULT_SET_NAME;
+ else if (property.equals(Tags.TEMP_GROUP_NAME)) return Properties.TEMP_GROUP_NAMES;
+ else if (property.equals(Tags.ELEMENT_NAME)) return Properties.ELEMENT_NAME;
+ else if (property.equals(Tags.COMMENT_TEXT)) return Properties.COMMENT_TEXT;
+ else if (property.equals(Tags.IS_OPTIONAL)) return Properties.IS_OPTIONAL;
+ else if (property.equals(Tags.IS_NILLABLE)) return Properties.IS_NILLABLE;
+ else if (property.equals(Tags.IS_EXCLUDED)) return Properties.IS_EXCLUDED;
+ else if (property.equals(Tags.IS_DEFAULT_CHOICE)) return Properties.IS_DEFAULT_CHOICE;
+ else if (property.equals(Tags.EXCEPTION_ON_DEFAULT)) return Properties.EXCEPTION_ON_DEFAULT;
+ else if (property.equals(Tags.DOCUMENT_ENCODING)) return Properties.DOCUMENT_ENCODING;
+ else if (property.equals(Tags.FORMATTED_DOCUMENT)) return Properties.FORMATTED_DOCUMENT;
+ else if (property.equals(Tags.IS_RECURSIVE)) return Properties.IS_RECURSIVE;
+ else if (property.equals(Tags.RECURSION_CRITERIA)) return Properties.RECURSION_CRITERIA;
+ else if (property.equals(Tags.RECURSION_LIMIT)) return Properties.RECURSION_LIMIT;
+ else if (property.equals(Tags.RECURSION_LIMIT_EXCEPTION)) return Properties.EXCEPTION_ON_RECURSION_LIMIT;
+ else if (property.equals(Tags.RECURSION_ROOT_MAPPING_CLASS)) return Properties.RECURSION_ROOT_MAPPING_CLASS;
+ else if (property.equals(Tags.NORMALIZE_TEXT)) return Properties.NORMALIZE_TEXT;
+ else if (property.equals(Tags.BUILT_IN_TYPE)) return Properties.BUILT_IN_TYPE;
+ else if (property.equals(Tags.ALWAYS_INCLUDE)) return Properties.ALWAYS_INCLUDE;
+ else {
+ throw new IllegalArgumentException("Unknown property ("+property+")"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ /**
+ * Convert a property Integer into a String (suitable for an XML tag).
+ * @param property one of the properties defined in the
+ * {@link Properties} inner class
+ * @return String representation of property
+ * @throw IllegalArgumentException if parameter isn't one of the properties
+ * defined in {@link Properties}
+ * @see getPropertyInteger
+ */
+ public static final String getPropertyString(Integer property){
+ if(property.equals(Properties.NAME)) return Tags.NAME;
+ else if (property.equals(Properties.NAMESPACE_PREFIX)) return Tags.NAMESPACE_PREFIX;
+ else if (property.equals(Properties.NODE_TYPE)) return Tags.NODE_TYPE;
+ else if (property.equals(Properties.CARDINALITY_MIN_BOUND)) return Tags.CARDINALITY_MIN_BOUND;
+ else if (property.equals(Properties.CARDINALITY_MAX_BOUND)) return Tags.CARDINALITY_MAX_BOUND;
+ else if (property.equals(Properties.CRITERIA)) return Tags.CRITERIA;
+ else if (property.equals(Properties.DEFAULT_VALUE)) return Tags.DEFAULT_VALUE;
+ else if (property.equals(Properties.FIXED_VALUE)) return Tags.FIXED_VALUE;
+ else if (property.equals(Properties.RESULT_SET_NAME)) return Tags.RESULT_SET_NAME;
+ else if (property.equals(Properties.TEMP_GROUP_NAMES)) return Tags.TEMP_GROUP_NAME;
+ else if (property.equals(Properties.ELEMENT_NAME)) return Tags.ELEMENT_NAME;
+ else if (property.equals(Properties.COMMENT_TEXT)) return Tags.COMMENT_TEXT;
+ else if (property.equals(Properties.IS_OPTIONAL)) return Tags.IS_OPTIONAL;
+ else if (property.equals(Properties.IS_NILLABLE)) return Tags.IS_NILLABLE;
+ else if (property.equals(Properties.IS_EXCLUDED)) return Tags.IS_EXCLUDED;
+ else if (property.equals(Properties.IS_DEFAULT_CHOICE)) return Tags.IS_DEFAULT_CHOICE;
+ else if (property.equals(Properties.EXCEPTION_ON_DEFAULT)) return Tags.EXCEPTION_ON_DEFAULT;
+ else if (property.equals(Properties.DOCUMENT_ENCODING)) return Tags.DOCUMENT_ENCODING;
+ else if (property.equals(Properties.FORMATTED_DOCUMENT)) return Tags.FORMATTED_DOCUMENT;
+ else if (property.equals(Properties.IS_RECURSIVE)) return Tags.IS_RECURSIVE;
+ else if (property.equals(Properties.RECURSION_CRITERIA)) return Tags.RECURSION_CRITERIA;
+ else if (property.equals(Properties.RECURSION_LIMIT)) return Tags.RECURSION_LIMIT;
+ else if (property.equals(Properties.EXCEPTION_ON_RECURSION_LIMIT)) return Tags.RECURSION_LIMIT_EXCEPTION;
+ else if (property.equals(Properties.RECURSION_ROOT_MAPPING_CLASS)) return Tags.RECURSION_ROOT_MAPPING_CLASS;
+ else if (property.equals(Properties.NORMALIZE_TEXT)) return Tags.NORMALIZE_TEXT;
+ else if (property.equals(Properties.BUILT_IN_TYPE)) return Tags.BUILT_IN_TYPE;
+ else if (property.equals(Properties.ALWAYS_INCLUDE)) return Tags.ALWAYS_INCLUDE;
+ else {
+ throw new IllegalArgumentException("Unknown property ("+property+")"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ // =========================================================================
+ // DEFAULTS
+ // =========================================================================
+
+ /**
+ * Default property values for node {@link MappingNodeConstants.Properties properties}
+ */
+ public static final class Defaults {
+ private Defaults() { }
+
+ /**
+ * Default property values, keyed off the properties defined in
+ * {@link MappingNodeConstants.Properties}. The {@link MappingNode} class will return
+ * these values if none are defined, for each property.
+ */
+ 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);
+
+ /** The default maximum bound of the cardinality of a node. */
+ public static final Integer DEFAULT_CARDINALITY_MAXIMUM_BOUND = new Integer(1);
+
+ /** The default output type of the node, if no value is specified */
+ public static final String DEFAULT_NODE_TYPE = ELEMENT;
+
+ /** The default value for {@link MappingNodeConstants.Properties#IS_NILLABLE} */
+ public static final Boolean DEFAULT_IS_NILLABLE = Boolean.FALSE;
+
+ /** The default value for {@link MappingNodeConstants.Properties#TEMP_GROUP_NAMES} */
+ public static final Collection DEFAULT_TEMP_GROUP_NAMES = Collections.EMPTY_LIST;
+
+ /** The default value for {@link MappingNodeConstants.Properties#IS_OPTIONAL} */
+ public static final Boolean DEFAULT_IS_OPTIONAL = Boolean.FALSE;
+
+ /** The default value for {@link MappingNodeConstants.Properties#NORMALIZE_TEXT} */
+ public static final String DEFAULT_NORMALIZE_TEXT = NORMALIZE_TEXT_PRESERVE;
+
+ /** The default value for {@link MappingNodeConstants.Properties#BUILT_IN_TYPE} */
+ public static final String DEFAULT_BUILT_IN_TYPE = NO_TYPE;
+
+ // ========================================================================
+ // CHOICE RELATED DEFAULTS
+ // ========================================================================
+
+ /** The default value for {@link MappingNodeConstants.Properties#IS_NILLABLE} */
+ public static final Boolean DEFAULT_IS_EXCLUDED = Boolean.FALSE;
+
+ /** The default value for {@link MappingNodeConstants.Properties#IS_INCLUDED} */
+ public static final Boolean DEFAULT_IS_INCLUDED = Boolean.FALSE;
+
+ /** The default value for {@link MappingNodeConstants.Properties#IS_DEFAULT_CHOICE} */
+ public static final Boolean DEFAULT_IS_DEFAULT_CHOICE = Boolean.FALSE;
+
+ /** The default value for {@link MappingNodeConstants.Properties#EXCEPTION_ON_DEFAULT} */
+ public static final Boolean DEFAULT_EXCEPTION_ON_DEFAULT = Boolean.FALSE;
+
+ // ========================================================================
+ // RECURSI0N RELATED DEFAULTS
+ // ========================================================================
+
+ /** The default value for {@link MappingNodeConstants.Properties#IS_RECURSIVE} */
+ public static final Boolean DEFAULT_IS_RECURSIVE = Boolean.FALSE;
+
+ /** The default value for {@link MappingNodeConstants.Properties#IS_RECURSIVE_ROOT} */
+ public static final Boolean DEFAULT_IS_RECURSIVE_ROOT = Boolean.FALSE;
+
+ /** The default value for {@link MappingNodeConstants.Properties#RECURSION_LIMIT} */
+ public static final Integer DEFAULT_RECURSION_LIMIT = new Integer(10);
+
+ /** The default value for {@link MappingNodeConstants.Properties#EXCEPTION_ON_RECURSION_LIMIT} */
+ public static final Boolean DEFAULT_EXCEPTION_ON_RECURSION_LIMIT = Boolean.FALSE;
+
+ // ========================================================================
+ // DOCUMENT RELATED DEFAULTS
+ // ========================================================================
+
+ /** The default value for {@link MappingNodeConstants.Properties#DOCUMENT_ENCODING} */
+ public static final String DEFAULT_DOCUMENT_ENCODING = "UTF-8"; //$NON-NLS-1$
+
+ /** The default value for {@link MappingNodeConstants.Properties#FORMATTED_DOCUMENT} */
+ public static final Boolean DEFAULT_FORMATTED_DOCUMENT = Boolean.FALSE;
+
+ static{
+ 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);
+ temp.put(Properties.IS_NILLABLE, DEFAULT_IS_NILLABLE);
+ temp.put(Properties.TEMP_GROUP_NAMES, DEFAULT_TEMP_GROUP_NAMES);
+ temp.put(Properties.IS_OPTIONAL, DEFAULT_IS_OPTIONAL);
+ temp.put(Properties.IS_EXCLUDED, DEFAULT_IS_EXCLUDED);
+ temp.put(Properties.IS_INCLUDED, DEFAULT_IS_INCLUDED);
+ temp.put(Properties.IS_DEFAULT_CHOICE, DEFAULT_IS_DEFAULT_CHOICE);
+ temp.put(Properties.EXCEPTION_ON_DEFAULT, DEFAULT_EXCEPTION_ON_DEFAULT);
+ temp.put(Properties.IS_RECURSIVE, DEFAULT_IS_RECURSIVE);
+ temp.put(Properties.IS_RECURSIVE_ROOT, DEFAULT_IS_RECURSIVE_ROOT);
+ temp.put(Properties.RECURSION_LIMIT, DEFAULT_RECURSION_LIMIT);
+ temp.put(Properties.EXCEPTION_ON_RECURSION_LIMIT, DEFAULT_EXCEPTION_ON_RECURSION_LIMIT);
+ temp.put(Properties.DOCUMENT_ENCODING, DEFAULT_DOCUMENT_ENCODING);
+ temp.put(Properties.FORMATTED_DOCUMENT, DEFAULT_FORMATTED_DOCUMENT);
+ temp.put(Properties.NORMALIZE_TEXT, DEFAULT_NORMALIZE_TEXT);
+ DEFAULT_VALUES = Collections.unmodifiableMap(temp);
+ }
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingOutputter.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingOutputter.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingOutputter.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,194 +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.mapping.xml;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Properties;
-
-import javax.xml.stream.XMLOutputFactory;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.XMLStreamWriter;
-
-import org.teiid.query.QueryPlugin;
-
-
-/**
- * <p>Outputs a mapping definition in XML format. The mapping definition is
- * held in object form in an instance of the <code>MappingDefinition</code>
- * class. This is transferred into an XML <code>Document</code> representation
- * and then written to a file. </p>
- *
- * @see MappingDefinition
- */
-public class MappingOutputter {
-
- private static final String ELEM_ROOT = MappingNodeConstants.Tags.MAPPING_ROOT_NAME;
- private static final String ELEM_NODE = MappingNodeConstants.Tags.MAPPING_NODE_NAME;
-
- XMLStreamWriter writer;
-
- /**
- * @param stream The output stream
- *
- * @throws IOException if there are problems writing to the file.
- */
- public void write(MappingDocument doc, PrintWriter stream) throws IOException {
- try {
- XMLOutputFactory xof = XMLOutputFactory.newInstance();
- writer = xof.createXMLStreamWriter(stream);
- writer.writeStartDocument("UTF-8", "1.0"); //$NON-NLS-1$ //$NON-NLS-2$
- writer.writeStartElement(ELEM_ROOT);
- writeElement(MappingNodeConstants.Tags.DOCUMENT_ENCODING, doc.getDocumentEncoding());
- writeElement(MappingNodeConstants.Tags.FORMATTED_DOCUMENT, Boolean.toString(doc.isFormatted()));
- loadNode(doc.getRootNode());
- writer.writeEndElement();
- writer.writeEndDocument();
- } catch (XMLStreamException e) {
- throw new IOException(e);
- }
- }
-
- void writeElement(String name, String content) throws XMLStreamException {
- writer.writeStartElement(name);
- writer.writeCharacters(content);
- writer.writeEndElement();
- }
-
- // =========================================================================
- // D O C U M E N T B U I L D I N G M E T H O D S
- // =========================================================================
-
- /**
- * <p>Load XML document from domain object. </p>
- * @throws XMLStreamException
- */
- void loadNode( MappingNode node ) throws XMLStreamException {
- writer.writeStartElement(ELEM_NODE);
-
- //namespace declarations have to be handled specially
- Properties namespaces = (Properties)node.getProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS);
- if (namespaces != null){
- addNamespaceDeclarations(namespaces);
- }
-
- // Only get the property values actually stored in the MappingNode, not
- // default values also
- Map properties = node.getNodeProperties();
-
- addElementProperties(properties );
-
- Iterator children = node.getChildren().iterator();
- while ( children.hasNext() ) {
- MappingNode child = (MappingNode)children.next();
- loadNode( child );
- }
- writer.writeEndElement();
- }
-
- private void addNamespaceDeclarations(Properties namespaces) throws XMLStreamException{
- Enumeration e = namespaces.propertyNames();
- while (e.hasMoreElements()){
- String prefix = (String)e.nextElement();
- String uri = namespaces.getProperty(prefix);
- writer.writeStartElement(MappingNodeConstants.Tags.NAMESPACE_DECLARATION);
- if (!prefix.equals(MappingNodeConstants.DEFAULT_NAMESPACE_PREFIX)){
- writeElement(MappingNodeConstants.Tags.NAMESPACE_DECLARATION_PREFIX, prefix);
- }
- writeElement(MappingNodeConstants.Tags.NAMESPACE_DECLARATION_URI, uri);
- writer.writeEndElement();
- }
- }
-
- /**
- * Add a set of properties to an XML node.
- * @throws XMLStreamException
- */
- void addElementProperties(Map properties ) throws XMLStreamException {
- Iterator propNames = MappingNodeConstants.Tags.OUTPUTTER_PROPERTY_TAGS.iterator();
- while ( propNames.hasNext() ) {
- String propName = (String)propNames.next();
- Integer propKey = MappingNodeConstants.getPropertyInteger(propName);
- if ( properties.containsKey(propKey) ) {
- Object value = properties.get(propKey);
- addElementProperty( propName, value );
- }
- }
- }
-
- /**
- * Add a single property to an XML node.
- * @throws XMLStreamException
- */
- void addElementProperty(String name, Object value ) throws XMLStreamException {
- if ( value == null ) {
- throw new IllegalArgumentException( QueryPlugin.Util.getString("ERR.015.002.0010", name) ); //$NON-NLS-1$
- }
- if (value instanceof Collection){
- Iterator i = ((Collection)value).iterator();
- while (i.hasNext()) {
- writeElement(name, getXMLText(i.next()));
- }
- } else {
- writeElement(name, getXMLText(value));
- }
- }
-
- // =========================================================================
- // U T I L I T Y M E T H O D S
- // =========================================================================
-
- /** Utility to return a string, accounting for null. */
- private String getXMLText( Object obj ) {
- if ( obj instanceof String ) {
- return getXMLText( (String)obj );
- } else if ( obj instanceof Integer ) {
- return getXMLText( (Integer)obj );
- } else if ( obj instanceof Boolean ) {
- return getXMLText( (Boolean)obj );
- } else {
- throw new IllegalArgumentException( QueryPlugin.Util.getString("ERR.015.002.0011", obj.getClass().getName() )); //$NON-NLS-1$
- }
- }
-
- /** Utility to return a string, accounting for null. */
- private String getXMLText( String str ) {
- return ( str != null ) ? str : ""; //$NON-NLS-1$
- }
-
- /** Utility to convert an integer to a string */
- private String getXMLText( Integer value ) {
- return value.toString();
- }
-
- /** Utility to convert a Boolean to a string */
- private String getXMLText( Boolean value ) {
- return value.toString();
- }
-
-} // END CLASS
-
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingOutputter.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingOutputter.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingOutputter.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingOutputter.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,194 @@
+/*
+ * 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.mapping.xml;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.teiid.query.QueryPlugin;
+
+
+/**
+ * <p>Outputs a mapping definition in XML format. The mapping definition is
+ * held in object form in an instance of the <code>MappingDefinition</code>
+ * class. This is transferred into an XML <code>Document</code> representation
+ * and then written to a file. </p>
+ *
+ * @see MappingDefinition
+ */
+public class MappingOutputter {
+
+ private static final String ELEM_ROOT = MappingNodeConstants.Tags.MAPPING_ROOT_NAME;
+ private static final String ELEM_NODE = MappingNodeConstants.Tags.MAPPING_NODE_NAME;
+
+ XMLStreamWriter writer;
+
+ /**
+ * @param stream The output stream
+ *
+ * @throws IOException if there are problems writing to the file.
+ */
+ public void write(MappingDocument doc, PrintWriter stream) throws IOException {
+ try {
+ XMLOutputFactory xof = XMLOutputFactory.newInstance();
+ writer = xof.createXMLStreamWriter(stream);
+ writer.writeStartDocument("UTF-8", "1.0"); //$NON-NLS-1$ //$NON-NLS-2$
+ writer.writeStartElement(ELEM_ROOT);
+ writeElement(MappingNodeConstants.Tags.DOCUMENT_ENCODING, doc.getDocumentEncoding());
+ writeElement(MappingNodeConstants.Tags.FORMATTED_DOCUMENT, Boolean.toString(doc.isFormatted()));
+ loadNode(doc.getRootNode());
+ writer.writeEndElement();
+ writer.writeEndDocument();
+ } catch (XMLStreamException e) {
+ throw new IOException(e);
+ }
+ }
+
+ void writeElement(String name, String content) throws XMLStreamException {
+ writer.writeStartElement(name);
+ writer.writeCharacters(content);
+ writer.writeEndElement();
+ }
+
+ // =========================================================================
+ // D O C U M E N T B U I L D I N G M E T H O D S
+ // =========================================================================
+
+ /**
+ * <p>Load XML document from domain object. </p>
+ * @throws XMLStreamException
+ */
+ void loadNode( MappingNode node ) throws XMLStreamException {
+ writer.writeStartElement(ELEM_NODE);
+
+ //namespace declarations have to be handled specially
+ Properties namespaces = (Properties)node.getProperty(MappingNodeConstants.Properties.NAMESPACE_DECLARATIONS);
+ if (namespaces != null){
+ addNamespaceDeclarations(namespaces);
+ }
+
+ // Only get the property values actually stored in the MappingNode, not
+ // default values also
+ Map properties = node.getNodeProperties();
+
+ addElementProperties(properties );
+
+ Iterator children = node.getChildren().iterator();
+ while ( children.hasNext() ) {
+ MappingNode child = (MappingNode)children.next();
+ loadNode( child );
+ }
+ writer.writeEndElement();
+ }
+
+ private void addNamespaceDeclarations(Properties namespaces) throws XMLStreamException{
+ Enumeration e = namespaces.propertyNames();
+ while (e.hasMoreElements()){
+ String prefix = (String)e.nextElement();
+ String uri = namespaces.getProperty(prefix);
+ writer.writeStartElement(MappingNodeConstants.Tags.NAMESPACE_DECLARATION);
+ if (!prefix.equals(MappingNodeConstants.DEFAULT_NAMESPACE_PREFIX)){
+ writeElement(MappingNodeConstants.Tags.NAMESPACE_DECLARATION_PREFIX, prefix);
+ }
+ writeElement(MappingNodeConstants.Tags.NAMESPACE_DECLARATION_URI, uri);
+ writer.writeEndElement();
+ }
+ }
+
+ /**
+ * Add a set of properties to an XML node.
+ * @throws XMLStreamException
+ */
+ void addElementProperties(Map properties ) throws XMLStreamException {
+ Iterator<String> propNames = MappingNodeConstants.Tags.OUTPUTTER_PROPERTY_TAGS.iterator();
+ while ( propNames.hasNext() ) {
+ String propName = propNames.next();
+ MappingNodeConstants.Properties propKey = MappingNodeConstants.getProperty(propName);
+ if ( properties.containsKey(propKey) ) {
+ Object value = properties.get(propKey);
+ addElementProperty( propName, value );
+ }
+ }
+ }
+
+ /**
+ * Add a single property to an XML node.
+ * @throws XMLStreamException
+ */
+ void addElementProperty(String name, Object value ) throws XMLStreamException {
+ if ( value == null ) {
+ throw new IllegalArgumentException( QueryPlugin.Util.getString("ERR.015.002.0010", name) ); //$NON-NLS-1$
+ }
+ if (value instanceof Collection){
+ Iterator i = ((Collection)value).iterator();
+ while (i.hasNext()) {
+ writeElement(name, getXMLText(i.next()));
+ }
+ } else {
+ writeElement(name, getXMLText(value));
+ }
+ }
+
+ // =========================================================================
+ // U T I L I T Y M E T H O D S
+ // =========================================================================
+
+ /** Utility to return a string, accounting for null. */
+ private String getXMLText( Object obj ) {
+ if ( obj instanceof String ) {
+ return getXMLText( (String)obj );
+ } else if ( obj instanceof Integer ) {
+ return getXMLText( (Integer)obj );
+ } else if ( obj instanceof Boolean ) {
+ return getXMLText( (Boolean)obj );
+ } else {
+ throw new IllegalArgumentException( QueryPlugin.Util.getString("ERR.015.002.0011", obj.getClass().getName() )); //$NON-NLS-1$
+ }
+ }
+
+ /** Utility to return a string, accounting for null. */
+ private String getXMLText( String str ) {
+ return ( str != null ) ? str : ""; //$NON-NLS-1$
+ }
+
+ /** Utility to convert an integer to a string */
+ private String getXMLText( Integer value ) {
+ return value.toString();
+ }
+
+ /** Utility to convert a Boolean to a string */
+ private String getXMLText( Boolean value ) {
+ return value.toString();
+ }
+
+} // END CLASS
+
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingRecursiveElement.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingRecursiveElement.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingRecursiveElement.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.query.mapping.xml;
-
-import java.util.List;
-
-import org.teiid.query.sql.lang.Criteria;
-
-
-
-/**
- * A element which specifies a recursive element inside and xml schema.
- * A recursive element is that embeds the self node type of elements
- * upto given depth limit.
- */
-public class MappingRecursiveElement extends MappingElement {
- List criteriaGroups;
- Criteria criteriaNode;
-
- public MappingRecursiveElement(String name, String mappingClass) {
- super(name);
- setProperty(MappingNodeConstants.Properties.IS_RECURSIVE, Boolean.TRUE);
- setProperty(MappingNodeConstants.Properties.RECURSION_ROOT_MAPPING_CLASS, mappingClass);
- }
-
- public MappingRecursiveElement(String name, Namespace namespace, String mappingClass) {
- super(name, namespace);
- setProperty(MappingNodeConstants.Properties.IS_RECURSIVE, Boolean.TRUE);
- setProperty(MappingNodeConstants.Properties.RECURSION_ROOT_MAPPING_CLASS, mappingClass);
- }
-
- public void acceptVisitor(MappingVisitor visitor) {
- visitor.visit(this);
- }
-
- /**
- * Is recursice
- * @see org.teiid.query.mapping.xml.MappingElement#isRecursive()
- */
- public boolean isRecursive() {
- return true;
- }
-
- /**
- * Sets the criteria on which the recurrsion must occur
- */
- public MappingRecursiveElement setCriteria(String criteria) {
- if (criteria != null && criteria.length() > 0) {
- criteria = criteria.trim();
- setProperty(MappingNodeConstants.Properties.RECURSION_CRITERIA, criteria);
- }
- return this;
- }
-
- /**
- * Sets limit on how deep the recurrsion is allowed to occur in result
- * document. If the execeptionOnBreach is set to true, if the limit rules are
- * violated then exception will be thrown, otherwise re-currsion will stop at
- * the depth specified.
- */
- public MappingRecursiveElement setRecursionLimit(int depth, boolean execeptionOnBreach) {
- setProperty(MappingNodeConstants.Properties.RECURSION_LIMIT, new Integer(depth));
- setProperty(MappingNodeConstants.Properties.EXCEPTION_ON_RECURSION_LIMIT, Boolean.valueOf(execeptionOnBreach));
- return this;
- }
-
- public String getMappingClass() {
- return (String) getProperty(MappingNodeConstants.Properties.RECURSION_ROOT_MAPPING_CLASS);
- }
-
- /**
- * Get the re-currsion criteria; not to be consufused with criteria on the MappingCriteria
- * element
- * @return
- */
- public String getCriteria(){
- return (String) getProperty(MappingNodeConstants.Properties.RECURSION_CRITERIA);
- }
-
- public int getRecursionLimit() {
- Integer limit = (Integer)getProperty(MappingNodeConstants.Properties.RECURSION_LIMIT);
- if (limit != null) {
- return limit.intValue();
- }
- return MappingNodeConstants.Defaults.DEFAULT_RECURSION_LIMIT.intValue();
- }
-
- public boolean throwExceptionOnRecurrsionLimit() {
- Boolean breached = (Boolean)getProperty(MappingNodeConstants.Properties.EXCEPTION_ON_RECURSION_LIMIT);
- if (breached != null) {
- return breached.booleanValue();
- }
- return MappingNodeConstants.Defaults.DEFAULT_EXCEPTION_ON_RECURSION_LIMIT.booleanValue();
- }
-
- /**
- * 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
- */
- public void setCriteriaNode(Criteria node) {
- this.criteriaNode = node;
- }
-
- public Criteria getCriteriaNode() {
- return this.criteriaNode;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingRecursiveElement.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingRecursiveElement.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingRecursiveElement.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingRecursiveElement.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,125 @@
+/*
+ * 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.mapping.xml;
+
+import org.teiid.query.sql.lang.Criteria;
+
+
+
+/**
+ * A element which specifies a recursive element inside and xml schema.
+ * A recursive element is that embeds the self node type of elements
+ * upto given depth limit.
+ */
+public class MappingRecursiveElement extends MappingElement {
+ Criteria criteriaNode;
+
+ public MappingRecursiveElement(String name, String mappingClass) {
+ super(name);
+ setProperty(MappingNodeConstants.Properties.IS_RECURSIVE, Boolean.TRUE);
+ setProperty(MappingNodeConstants.Properties.RECURSION_ROOT_MAPPING_CLASS, mappingClass);
+ }
+
+ public MappingRecursiveElement(String name, Namespace namespace, String mappingClass) {
+ super(name, namespace);
+ setProperty(MappingNodeConstants.Properties.IS_RECURSIVE, Boolean.TRUE);
+ setProperty(MappingNodeConstants.Properties.RECURSION_ROOT_MAPPING_CLASS, mappingClass);
+ }
+
+ public void acceptVisitor(MappingVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ /**
+ * Is recursice
+ * @see org.teiid.query.mapping.xml.MappingElement#isRecursive()
+ */
+ public boolean isRecursive() {
+ return true;
+ }
+
+ /**
+ * Sets the criteria on which the recurrsion must occur
+ */
+ public MappingRecursiveElement setCriteria(String criteria) {
+ if (criteria != null && criteria.length() > 0) {
+ criteria = criteria.trim();
+ setProperty(MappingNodeConstants.Properties.RECURSION_CRITERIA, criteria);
+ }
+ return this;
+ }
+
+ /**
+ * Sets limit on how deep the recurrsion is allowed to occur in result
+ * document. If the execeptionOnBreach is set to true, if the limit rules are
+ * violated then exception will be thrown, otherwise re-currsion will stop at
+ * the depth specified.
+ */
+ public MappingRecursiveElement setRecursionLimit(int depth, boolean execeptionOnBreach) {
+ setProperty(MappingNodeConstants.Properties.RECURSION_LIMIT, new Integer(depth));
+ setProperty(MappingNodeConstants.Properties.EXCEPTION_ON_RECURSION_LIMIT, Boolean.valueOf(execeptionOnBreach));
+ return this;
+ }
+
+ public String getMappingClass() {
+ return (String) getProperty(MappingNodeConstants.Properties.RECURSION_ROOT_MAPPING_CLASS);
+ }
+
+ /**
+ * Get the re-currsion criteria; not to be consufused with criteria on the MappingCriteria
+ * element
+ * @return
+ */
+ public String getCriteria(){
+ return (String) getProperty(MappingNodeConstants.Properties.RECURSION_CRITERIA);
+ }
+
+ public int getRecursionLimit() {
+ Integer limit = (Integer)getProperty(MappingNodeConstants.Properties.RECURSION_LIMIT);
+ if (limit != null) {
+ return limit.intValue();
+ }
+ return MappingNodeConstants.Defaults.DEFAULT_RECURSION_LIMIT.intValue();
+ }
+
+ public boolean throwExceptionOnRecurrsionLimit() {
+ Boolean breached = (Boolean)getProperty(MappingNodeConstants.Properties.EXCEPTION_ON_RECURSION_LIMIT);
+ if (breached != null) {
+ return breached.booleanValue();
+ }
+ return MappingNodeConstants.Defaults.DEFAULT_EXCEPTION_ON_RECURSION_LIMIT.booleanValue();
+ }
+
+ /**
+ * This is parsed and resolved criteria node based on the criteria string. This is set by
+ * ValidateMappedCriteriaVisitor class during pre planning.
+ * @param node
+ */
+ public void setCriteriaNode(Criteria node) {
+ this.criteriaNode = node;
+ }
+
+ public Criteria getCriteriaNode() {
+ return this.criteriaNode;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,107 +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.mapping.xml;
-
-import java.util.Iterator;
-import java.util.List;
-
-
-/**
- * A Visitor framework for navigating the Mapping Nodes
- */
-public class MappingVisitor {
- private boolean abort = false;
-
- protected void setAbort(boolean abort) {
- this.abort = abort;
- }
-
- protected boolean shouldAbort() {
- return abort;
- }
-
- public void visit(MappingNode node) {}
-
- public void visit(MappingDocument doc) {
- visit((MappingNode)doc);
- }
- public void visit(MappingElement element) {
- visit((MappingBaseNode)element);
- }
- public void visit(MappingAttribute attribute) {
- visit((MappingNode)attribute);
- }
- public void visit(MappingBaseNode baseNode) {
- visit((MappingNode)baseNode);
- }
- public void visit(MappingChoiceNode choice) {
- visit((MappingBaseNode)choice);
- }
- public void visit(MappingSequenceNode sequence) {
- visit((MappingBaseNode)sequence);
- }
- public void visit(MappingAllNode all) {
- visit((MappingBaseNode)all);
- }
- public void visit(MappingCommentNode comment) {
- visit((MappingNode)comment);
- }
- public void visit(MappingCriteriaNode node) {
- visit((MappingBaseNode)node);
- }
- public void visit(MappingRecursiveElement element) {
- visit((MappingElement)element);
- }
- public void visit(MappingSourceNode element) {
- visit((MappingBaseNode)element);
- }
- /**
- * @param element
- */
- protected void walkChildNodes(MappingNode element) {
-
- List children = element.getNodeChildren();
- for(Iterator i=children.iterator(); i.hasNext();) {
-
- if (shouldAbort()) {
- break;
- }
-
- MappingNode node = (MappingNode)i.next();
- node.acceptVisitor(this);
- }
- }
-
- /**
- * @param element
- */
- protected void walkAttributes(MappingElement element) {
- List attributes = element.getAttributes();
- for(Iterator i=attributes.iterator(); i.hasNext();) {
- if (shouldAbort()) {
- break;
- }
- visit((MappingAttribute)i.next());
- }
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingVisitor.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/mapping/xml/MappingVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/MappingVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,110 @@
+/*
+ * 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.mapping.xml;
+
+import java.util.Iterator;
+import java.util.List;
+
+
+/**
+ * A Visitor framework for navigating the Mapping Nodes
+ */
+public class MappingVisitor {
+ private boolean abort = false;
+
+ protected void setAbort(boolean abort) {
+ this.abort = abort;
+ }
+
+ protected boolean shouldAbort() {
+ return abort;
+ }
+
+ /**
+ * @param node
+ */
+ public void visit(MappingNode node) {}
+
+ public void visit(MappingDocument doc) {
+ visit((MappingNode)doc);
+ }
+ public void visit(MappingElement element) {
+ visit((MappingBaseNode)element);
+ }
+ public void visit(MappingAttribute attribute) {
+ visit((MappingNode)attribute);
+ }
+ public void visit(MappingBaseNode baseNode) {
+ visit((MappingNode)baseNode);
+ }
+ public void visit(MappingChoiceNode choice) {
+ visit((MappingBaseNode)choice);
+ }
+ public void visit(MappingSequenceNode sequence) {
+ visit((MappingBaseNode)sequence);
+ }
+ public void visit(MappingAllNode all) {
+ visit((MappingBaseNode)all);
+ }
+ public void visit(MappingCommentNode comment) {
+ visit((MappingNode)comment);
+ }
+ public void visit(MappingCriteriaNode node) {
+ visit((MappingBaseNode)node);
+ }
+ public void visit(MappingRecursiveElement element) {
+ visit((MappingElement)element);
+ }
+ public void visit(MappingSourceNode element) {
+ visit((MappingBaseNode)element);
+ }
+ /**
+ * @param element
+ */
+ protected void walkChildNodes(MappingNode element) {
+
+ List<MappingNode> children = element.getNodeChildren();
+ for(Iterator<MappingNode> i=children.iterator(); i.hasNext();) {
+
+ if (shouldAbort()) {
+ break;
+ }
+
+ MappingNode node = i.next();
+ node.acceptVisitor(this);
+ }
+ }
+
+ /**
+ * @param element
+ */
+ protected void walkAttributes(MappingElement element) {
+ List attributes = element.getAttributes();
+ for(Iterator i=attributes.iterator(); i.hasNext();) {
+ if (shouldAbort()) {
+ break;
+ }
+ visit((MappingAttribute)i.next());
+ }
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/ResultSetInfo.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/mapping/xml/ResultSetInfo.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/ResultSetInfo.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,204 +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.mapping.xml;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-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.OrderBy;
-import org.teiid.query.sql.symbol.ElementSymbol;
-
-
-/**
- * Represents a result set used in an XML query - this can be based on either a mapping class query
- * or a staging table. All info about the result set is stored in this object - some is only applicable
- * for certain kinds of result sets.
- */
-public class ResultSetInfo {
-
- private String resultSetName;
-
- // 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;
-
- // Row limit, may be null if no limit
- private int userRowLimit = -1;
-
- // whether or not to throw exception on row limit
- private boolean exceptionOnRowLimit = false;
-
- private OrderBy orderBy;
-
- private Criteria criteria;
-
- private Set criteriaResultSets = new HashSet();
-
- 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;
-
- public ResultSetInfo(String resultName) {
- this(resultName, false);
- }
-
- public ResultSetInfo(String resultName, boolean staged) {
- this.resultSetName = resultName;
- this.stagedResult = staged;
- }
-
- public String getResultSetName() {
- return this.resultSetName;
- }
-
- public Command getCommand() {
- return this.rsCommand;
- }
-
- public void setCommand(Command cmd) {
- this.rsCommand = cmd;
- }
-
- public ProcessorPlan getPlan() {
- return rsPlan;
- }
-
- public void setPlan(ProcessorPlan plan) {
- this.rsPlan = plan;
- }
-
- public int getUserRowLimit() {
- return userRowLimit;
- }
-
- public void setUserRowLimit(int limit, boolean throwException) {
- this.userRowLimit = limit;
- this.exceptionOnRowLimit = throwException;
- }
-
- public boolean exceptionOnRowlimit() {
- return exceptionOnRowLimit;
- }
-
- public Criteria getCriteria() {
- return this.criteria;
- }
-
- public void setCriteria(Criteria criteria) {
- this.criteria = criteria;
- }
-
- public OrderBy getOrderBy() {
- return this.orderBy;
- }
-
- public void setOrderBy(OrderBy orderBy) {
- this.orderBy = orderBy;
- }
-
- public Set getCriteriaResultSets() {
- return this.criteriaResultSets;
- }
-
- public void addToCriteriaResultSets(Set criteriaResultSets) {
- this.criteriaResultSets.addAll(criteriaResultSets);
- }
-
- public boolean isCriteriaRaised() {
- return this.criteriaRaised;
- }
-
- public void setCriteriaRaised(boolean criteriaRaised) {
- this.criteriaRaised = criteriaRaised;
- }
-
- public Object clone() {
- ResultSetInfo clone = new ResultSetInfo(this.resultSetName, this.stagedResult);
- 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;
- return clone;
- }
-
- public String toString() {
- return resultSetName + ", resultSetObject " + rsCommand; //$NON-NLS-1$
- }
-
- public boolean isJoinedWithParent() {
- return this.joinedWithParent;
- }
-
- public void setJoinedWithParent(boolean joinedWithParent) {
- this.joinedWithParent = joinedWithParent;
- }
-
- public boolean isJoinRoot() {
- return this.joinRoot;
- }
-
- public void setJoinRoot(boolean joinRoot) {
- this.joinRoot = joinRoot;
- }
-
- public int getMappingClassNumber() {
- return this.mappingClassNumber;
- }
-
- public void setMappingClassNumber(int mappingClassNumber) {
- this.mappingClassNumber = mappingClassNumber;
- }
-
- public ElementSymbol getMappingClassSymbol() {
- return this.mappingClassSymbol;
- }
-
- public void setMappingClassSymbol(ElementSymbol mappingClassSymbol) {
- this.mappingClassSymbol = mappingClassSymbol;
- }
-
- public boolean isStagedResult() {
- return this.stagedResult;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/ResultSetInfo.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/mapping/xml/ResultSetInfo.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/ResultSetInfo.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/mapping/xml/ResultSetInfo.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,179 @@
+/*
+ * 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.mapping.xml;
+
+import java.util.HashSet;
+import java.util.Set;
+
+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.OrderBy;
+import org.teiid.query.sql.symbol.ElementSymbol;
+
+
+/**
+ * Represents a result set used in an XML query - this can be based on either a mapping class query
+ * or a staging table. All info about the result set is stored in this object - some is only applicable
+ * for certain kinds of result sets.
+ */
+public class ResultSetInfo {
+
+ private String resultSetName;
+
+ // The result set command
+ private Command rsCommand;
+
+ // The processor plan output for the result set
+ private ProcessorPlan rsPlan;
+
+ // Row limit, may be null if no limit
+ private int userRowLimit = -1;
+
+ // whether or not to throw exception on row limit
+ private boolean exceptionOnRowLimit = false;
+
+ private OrderBy orderBy;
+
+ private Criteria criteria;
+
+ private Set<MappingSourceNode> criteriaResultSets = new HashSet<MappingSourceNode>();
+
+ private boolean criteriaRaised = false;
+
+ private boolean stagedResult = false;
+
+ //joined source node state
+ private int mappingClassNumber = 0;
+ private ElementSymbol mappingClassSymbol;
+
+ public ResultSetInfo(String resultName) {
+ this(resultName, false);
+ }
+
+ public ResultSetInfo(String resultName, boolean staged) {
+ this.resultSetName = resultName;
+ this.stagedResult = staged;
+ }
+
+ public String getResultSetName() {
+ return this.resultSetName;
+ }
+
+ public Command getCommand() {
+ return this.rsCommand;
+ }
+
+ public void setCommand(Command cmd) {
+ this.rsCommand = cmd;
+ }
+
+ public ProcessorPlan getPlan() {
+ return rsPlan;
+ }
+
+ public void setPlan(ProcessorPlan plan) {
+ this.rsPlan = plan;
+ }
+
+ public int getUserRowLimit() {
+ return userRowLimit;
+ }
+
+ public void setUserRowLimit(int limit, boolean throwException) {
+ this.userRowLimit = limit;
+ this.exceptionOnRowLimit = throwException;
+ }
+
+ public boolean exceptionOnRowlimit() {
+ return exceptionOnRowLimit;
+ }
+
+ public Criteria getCriteria() {
+ return this.criteria;
+ }
+
+ public void setCriteria(Criteria criteria) {
+ this.criteria = criteria;
+ }
+
+ public OrderBy getOrderBy() {
+ return this.orderBy;
+ }
+
+ public void setOrderBy(OrderBy orderBy) {
+ this.orderBy = orderBy;
+ }
+
+ public Set<MappingSourceNode> getCriteriaResultSets() {
+ return this.criteriaResultSets;
+ }
+
+ public void addToCriteriaResultSets(Set<MappingSourceNode> criteriaResultSets) {
+ this.criteriaResultSets.addAll(criteriaResultSets);
+ }
+
+ public boolean isCriteriaRaised() {
+ return this.criteriaRaised;
+ }
+
+ public void setCriteriaRaised(boolean criteriaRaised) {
+ this.criteriaRaised = criteriaRaised;
+ }
+
+ public Object clone() {
+ ResultSetInfo clone = new ResultSetInfo(this.resultSetName, this.stagedResult);
+ clone.rsPlan = this.rsPlan;
+ clone.userRowLimit = this.userRowLimit;
+ clone.exceptionOnRowLimit = this.exceptionOnRowLimit;
+ clone.rsCommand = (Command)this.rsCommand.clone();
+ clone.criteriaRaised = this.criteriaRaised;
+ clone.mappingClassNumber = this.mappingClassNumber;
+ clone.mappingClassSymbol = this.mappingClassSymbol;
+ return clone;
+ }
+
+ public String toString() {
+ return resultSetName + ", resultSetObject " + rsCommand; //$NON-NLS-1$
+ }
+
+ public int getMappingClassNumber() {
+ return this.mappingClassNumber;
+ }
+
+ public void setMappingClassNumber(int mappingClassNumber) {
+ this.mappingClassNumber = mappingClassNumber;
+ }
+
+ public ElementSymbol getMappingClassSymbol() {
+ return this.mappingClassSymbol;
+ }
+
+ public void setMappingClassSymbol(ElementSymbol mappingClassSymbol) {
+ this.mappingClassSymbol = mappingClassSymbol;
+ }
+
+ public boolean isStagedResult() {
+ return this.stagedResult;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/CompositeMetadataStore.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/metadata/CompositeMetadataStore.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/CompositeMetadataStore.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,161 +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.metadata;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.util.StringUtil;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.metadata.Procedure;
-import org.teiid.metadata.Schema;
-import org.teiid.metadata.Table;
-import org.teiid.metadata.Table.Type;
-
-
-/**
- * Aggregates the metadata from multiple stores.
- * IMPORTANT: All strings queries should be in upper case.
- */
-public class CompositeMetadataStore extends MetadataStore {
-
-
- public CompositeMetadataStore(MetadataStore metadataStore) {
- addMetadataStore(metadataStore);
- }
-
- public CompositeMetadataStore(List<MetadataStore> metadataStores) {
- for (MetadataStore metadataStore : metadataStores) {
- addMetadataStore(metadataStore);
- }
- }
-
- public void addMetadataStore(MetadataStore metadataStore) {
- this.schemas.putAll(metadataStore.getSchemas());
- this.datatypes.addAll(metadataStore.getDatatypes());
- }
-
- public Schema getSchema(String fullName)
- throws QueryMetadataException {
- Schema result = getSchemas().get(fullName);
- if (result == null) {
- throw new QueryMetadataException(fullName+TransformationMetadata.NOT_EXISTS_MESSAGE);
- }
- return result;
- }
-
- public Table findGroup(String fullName)
- throws QueryMetadataException {
- int index = fullName.indexOf(TransformationMetadata.DELIMITER_STRING);
- if (index == -1) {
- throw new QueryMetadataException(fullName+TransformationMetadata.NOT_EXISTS_MESSAGE);
- }
- String schema = fullName.substring(0, index);
- Table result = getSchema(schema).getTables().get(fullName.substring(index + 1));
- if (result == null) {
- throw new QueryMetadataException(fullName+TransformationMetadata.NOT_EXISTS_MESSAGE);
- }
- return result;
- }
-
- /**
- * TODO: this resolving mode allows partial matches of a full group name containing .
- * @param partialGroupName
- * @return
- */
- public Collection<Table> getGroupsForPartialName(String partialGroupName) {
- List<Table> result = new LinkedList<Table>();
- for (Schema schema : getSchemas().values()) {
- for (Table t : schema.getTables().values()) {
- String name = t.getName();
- if (matchesPartialName(partialGroupName, name, schema)) {
- result.add(t);
- }
- }
- }
- return result;
- }
-
- protected boolean matchesPartialName(String partialGroupName, String name, Schema schema) {
- if (!StringUtil.endsWithIgnoreCase(name, partialGroupName)) {
- return false;
- }
- int schemaMatch = partialGroupName.length() - name.length();
- if (schemaMatch > 0) {
- if (schemaMatch != schema.getName().length() + 1
- || !StringUtil.startsWithIgnoreCase(partialGroupName, schema.getName())
- || partialGroupName.charAt(schemaMatch + 1) != '.') {
- return false;
- }
- } else if (schemaMatch < 0 && name.charAt(-schemaMatch - 1) != '.') {
- return false;
- }
- return true;
- }
-
- public Collection<Procedure> getStoredProcedure(String name)
- throws TeiidComponentException, QueryMetadataException {
- List<Procedure> result = new LinkedList<Procedure>();
- int index = name.indexOf(TransformationMetadata.DELIMITER_STRING);
- if (index > -1) {
- String schema = name.substring(0, index);
- Procedure proc = getSchema(schema).getProcedures().get(name.substring(index + 1));
- if (proc != null) {
- result.add(proc);
- return result;
- }
- }
- //assume it's a partial name
- for (Schema schema : getSchemas().values()) {
- for (Procedure p : schema.getProcedures().values()) {
- if (matchesPartialName(name, p.getName(), schema)) {
- result.add(p);
- }
- }
- }
- if (result.isEmpty()) {
- throw new QueryMetadataException(name.substring(1)+TransformationMetadata.NOT_EXISTS_MESSAGE);
- }
- return result;
- }
-
- /*
- * The next method is a hold over from XML/UUID resolving and will perform poorly
- */
-
- public Collection<Table> getXMLTempGroups(Table tableRecord) {
- ArrayList<Table> results = new ArrayList<Table>();
- String namePrefix = tableRecord.getFullName() + TransformationMetadata.DELIMITER_STRING;
- for (Table table : tableRecord.getParent().getTables().values()) {
- if (table.getTableType() == Type.XmlStagingTable && table.getName().startsWith(namePrefix)) {
- results.add(table);
- }
- }
- return results;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/CompositeMetadataStore.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/metadata/CompositeMetadataStore.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/CompositeMetadataStore.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/CompositeMetadataStore.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,158 @@
+/*
+ * 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.metadata;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.util.StringUtil;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.metadata.Table.Type;
+
+
+/**
+ * Aggregates the metadata from multiple stores.
+ * IMPORTANT: All strings queries should be in upper case.
+ */
+public class CompositeMetadataStore extends MetadataStore {
+
+
+ public CompositeMetadataStore(MetadataStore metadataStore) {
+ addMetadataStore(metadataStore);
+ }
+
+ public CompositeMetadataStore(List<MetadataStore> metadataStores) {
+ for (MetadataStore metadataStore : metadataStores) {
+ addMetadataStore(metadataStore);
+ }
+ }
+
+ public void addMetadataStore(MetadataStore metadataStore) {
+ this.schemas.putAll(metadataStore.getSchemas());
+ this.datatypes.addAll(metadataStore.getDatatypes());
+ }
+
+ public Schema getSchema(String fullName)
+ throws QueryMetadataException {
+ Schema result = getSchemas().get(fullName);
+ if (result == null) {
+ throw new QueryMetadataException(fullName+TransformationMetadata.NOT_EXISTS_MESSAGE);
+ }
+ return result;
+ }
+
+ public Table findGroup(String fullName)
+ throws QueryMetadataException {
+ int index = fullName.indexOf(TransformationMetadata.DELIMITER_STRING);
+ if (index == -1) {
+ throw new QueryMetadataException(fullName+TransformationMetadata.NOT_EXISTS_MESSAGE);
+ }
+ String schema = fullName.substring(0, index);
+ Table result = getSchema(schema).getTables().get(fullName.substring(index + 1));
+ if (result == null) {
+ throw new QueryMetadataException(fullName+TransformationMetadata.NOT_EXISTS_MESSAGE);
+ }
+ return result;
+ }
+
+ /**
+ * TODO: this resolving mode allows partial matches of a full group name containing .
+ * @param partialGroupName
+ * @return
+ */
+ public Collection<Table> getGroupsForPartialName(String partialGroupName) {
+ List<Table> result = new LinkedList<Table>();
+ for (Schema schema : getSchemas().values()) {
+ for (Table t : schema.getTables().values()) {
+ String name = t.getName();
+ if (matchesPartialName(partialGroupName, name, schema)) {
+ result.add(t);
+ }
+ }
+ }
+ return result;
+ }
+
+ protected boolean matchesPartialName(String partialGroupName, String name, Schema schema) {
+ if (!StringUtil.endsWithIgnoreCase(name, partialGroupName)) {
+ return false;
+ }
+ int schemaMatch = partialGroupName.length() - name.length();
+ if (schemaMatch > 0) {
+ if (schemaMatch != schema.getName().length() + 1
+ || !StringUtil.startsWithIgnoreCase(partialGroupName, schema.getName())
+ || partialGroupName.charAt(schemaMatch + 1) != '.') {
+ return false;
+ }
+ } else if (schemaMatch < 0 && name.charAt(-schemaMatch - 1) != '.') {
+ return false;
+ }
+ return true;
+ }
+
+ public Collection<Procedure> getStoredProcedure(String name)
+ throws TeiidComponentException, QueryMetadataException {
+ List<Procedure> result = new LinkedList<Procedure>();
+ int index = name.indexOf(TransformationMetadata.DELIMITER_STRING);
+ if (index > -1) {
+ String schema = name.substring(0, index);
+ Procedure proc = getSchema(schema).getProcedures().get(name.substring(index + 1));
+ if (proc != null) {
+ result.add(proc);
+ return result;
+ }
+ }
+ //assume it's a partial name
+ for (Schema schema : getSchemas().values()) {
+ for (Procedure p : schema.getProcedures().values()) {
+ if (matchesPartialName(name, p.getName(), schema)) {
+ result.add(p);
+ }
+ }
+ }
+ return result;
+ }
+
+ /*
+ * The next method is a hold over from XML/UUID resolving and will perform poorly
+ */
+
+ public Collection<Table> getXMLTempGroups(Table tableRecord) {
+ ArrayList<Table> results = new ArrayList<Table>();
+ 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);
+ }
+ }
+ return results;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataAdapter.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/metadata/TempMetadataAdapter.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataAdapter.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,755 +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.metadata;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.mapping.xml.MappingNode;
-
-
-/**
- * <p>This is an adapter class, it contains another instance of
- * QueryMetadataInterface as well as a TempMetadataStore. It defers to
- * either one of these when appropriate.</p>
- *
- * <p>When a metadataID Object is requested for a group or element name, this
- * will first check the QueryMetadataInterface. If an ID wasn't found there,
- * it will then check the TempMetadataStore.</p>
- *
- * <p>For methods that take a metadataID arg, this class may check whether it
- * is a TempMetadataID or not and react accordingly.</p>
- */
-public class TempMetadataAdapter extends BasicQueryMetadataWrapper {
-
- private static final String SEPARATOR = "."; //$NON-NLS-1$
- public static final TempMetadataID TEMP_MODEL = new TempMetadataID("__TEMP__", Collections.EMPTY_LIST); //$NON-NLS-1$
-
- private TempMetadataStore tempStore;
- private Map materializationTables;
- private Map queryNodes;
- private boolean session;
-
- public TempMetadataAdapter(QueryMetadataInterface metadata, TempMetadataStore tempStore) {
- super(metadata);
- this.tempStore = tempStore;
- }
-
- public TempMetadataAdapter(QueryMetadataInterface metadata, TempMetadataStore tempStore, Map materializationTables, Map queryNodes) {
- super(metadata);
- this.tempStore = tempStore;
- this.materializationTables = materializationTables;
- this.queryNodes = queryNodes;
- }
-
- public boolean isSession() {
- return session;
- }
-
- public void setSession(boolean session) {
- this.session = session;
- }
-
- public QueryMetadataInterface getSessionMetadata() {
- if (isSession()) {
- TempMetadataAdapter tma = new TempMetadataAdapter(new BasicQueryMetadata(), this.tempStore);
- tma.session = true;
- return tma;
- }
- return this.actualMetadata.getSessionMetadata();
- }
-
- public QueryMetadataInterface getDesignTimeMetadata() {
- if (isSession()) {
- return this.actualMetadata.getDesignTimeMetadata();
- }
- return new TempMetadataAdapter(this.actualMetadata.getDesignTimeMetadata(), tempStore, materializationTables, queryNodes);
- }
-
- public TempMetadataStore getMetadataStore() {
- return this.tempStore;
- }
-
- public QueryMetadataInterface getMetadata() {
- return this.actualMetadata;
- }
-
- /**
- * Check metadata first, then check temp groups if not found
- */
- public Object getElementID(String elementName)
- throws TeiidComponentException, QueryMetadataException {
-
- Object tempID = null;
- try {
- tempID = this.actualMetadata.getElementID(elementName);
- } catch (QueryMetadataException e) {
- //ignore
- }
-
- if (tempID == null){
- tempID = this.tempStore.getTempElementID(elementName);
- }
-
- if(tempID != null) {
- return tempID;
- }
- Object[] params = new Object[]{elementName};
- String msg = QueryPlugin.Util.getString("TempMetadataAdapter.Element_____{0}_____not_found._1", params); //$NON-NLS-1$
- throw new QueryMetadataException(msg);
- }
-
- /**
- * Check metadata first, then check temp groups if not found
- */
- public Object getGroupID(String groupName)
- throws TeiidComponentException, QueryMetadataException {
-
- Object tempID = null;
- try {
- tempID = this.actualMetadata.getGroupID(groupName);
- } catch (QueryMetadataException e) {
- //ignore
- }
-
- if (tempID == null){
- tempID = this.tempStore.getTempGroupID(groupName);
- }
-
- if(tempID != null) {
- return tempID;
- }
- Object[] params = new Object[]{groupName};
- String msg = QueryPlugin.Util.getString("TempMetadataAdapter.Group_____{0}_____not_found._1", params); //$NON-NLS-1$
- throw new QueryMetadataException(msg);
- }
-
-
- public Object getModelID(Object groupOrElementID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(groupOrElementID instanceof TempMetadataID) {
- return TempMetadataAdapter.TEMP_MODEL;
- }
- return this.actualMetadata.getModelID(groupOrElementID);
- }
-
- // SPECIAL: Override for temp groups
- public String getFullName(Object metadataID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(metadataID instanceof TempMetadataID) {
- return ((TempMetadataID)metadataID).getID();
- }
- return this.actualMetadata.getFullName(metadataID);
- }
-
- @Override
- public String getName(Object metadataID) throws TeiidComponentException,
- QueryMetadataException {
- if(metadataID instanceof TempMetadataID) {
- TempMetadataID tid = (TempMetadataID)metadataID;
- return tid.getName();
- }
- return this.actualMetadata.getName(metadataID);
- }
-
- // SPECIAL: Override for temp groups
- public List getElementIDsInGroupID(Object groupID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(groupID instanceof TempMetadataID) {
- return new ArrayList(((TempMetadataID)groupID).getElements());
- }
- return this.actualMetadata.getElementIDsInGroupID(groupID);
- }
-
- // SPECIAL: Override for temp groups
- public Object getGroupIDForElementID(Object elementID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(elementID instanceof TempMetadataID) {
- String elementName = ((TempMetadataID)elementID).getID();
- String groupName = elementName.substring(0, elementName.lastIndexOf(SEPARATOR));
- return this.tempStore.getTempGroupID(groupName);
- }
- return this.actualMetadata.getGroupIDForElementID(elementID);
- }
-
- // SPECIAL: Override for temp groups
- public String getElementType(Object elementID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(elementID instanceof TempMetadataID) {
- TempMetadataID tempID = (TempMetadataID)elementID;
- if (tempID.getType() != null) {
- return DataTypeManager.getDataTypeName( tempID.getType() );
- }
- throw new AssertionError("No type set for element " + elementID); //$NON-NLS-1$
- }
- return this.actualMetadata.getElementType(elementID);
- }
-
- public Object getDefaultValue(Object elementID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(elementID instanceof TempMetadataID) {
- return null;
- }
- return this.actualMetadata.getDefaultValue(elementID);
- }
-
- public Object getMaximumValue(Object elementID) throws TeiidComponentException, QueryMetadataException {
- if (elementID instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)elementID;
- elementID = id.getOriginalMetadataID();
- if (elementID == null) {
- return null;
- }
- }
- return this.actualMetadata.getMaximumValue(elementID);
- }
-
- public Object getMinimumValue(Object elementID) throws TeiidComponentException, QueryMetadataException {
- if (elementID instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)elementID;
- elementID = id.getOriginalMetadataID();
- if (elementID == null) {
- return null;
- }
- }
- return this.actualMetadata.getMinimumValue(elementID);
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getDistinctValues(java.lang.Object)
- */
- public int getDistinctValues(Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof TempMetadataID) {
- return -1;
- }
- return this.actualMetadata.getDistinctValues(elementID);
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getNullValues(java.lang.Object)
- */
- public int getNullValues(Object elementID) throws TeiidComponentException, QueryMetadataException {
- if (elementID instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)elementID;
- elementID = id.getOriginalMetadataID();
- if (elementID == null) {
- return -1;
- }
- }
- return this.actualMetadata.getNullValues(elementID);
- }
-
- public QueryNode getVirtualPlan(Object groupID)
- throws TeiidComponentException, QueryMetadataException {
-
- if (this.queryNodes != null && this.queryNodes.containsKey(groupID)) {
- return (QueryNode)this.queryNodes.get(groupID);
- }
-
- if(groupID instanceof TempMetadataID && !(actualMetadata instanceof TempMetadataAdapter)) {
- return ((TempMetadataID)groupID).getQueryNode();
- }
- return this.actualMetadata.getVirtualPlan(groupID);
- }
-
- // SPECIAL: Override for temp groups
- public boolean isVirtualGroup(Object groupID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(groupID instanceof TempMetadataID) {
- return ((TempMetadataID)groupID).isVirtual();
- }
- return this.actualMetadata.isVirtualGroup(groupID);
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#hasMaterialization(java.lang.Object)
- * @since 4.2
- */
- public boolean hasMaterialization(Object groupID)
- throws TeiidComponentException, QueryMetadataException {
-
- // check if any dynamic materialization tables are defined
- if (this.materializationTables != null && this.materializationTables.containsKey(groupID)) {
- return true;
- }
-
- if(groupID instanceof TempMetadataID) {
- return false;
- }
-
- return this.actualMetadata.hasMaterialization(groupID);
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getMaterialization(java.lang.Object)
- * @since 4.2
- */
- public Object getMaterialization(Object groupID)
- throws TeiidComponentException, QueryMetadataException {
-
- // check if any dynamic materialization tables are defined
- if (this.materializationTables != null) {
- Object result = this.materializationTables.get(groupID);
- if (result != null) {
- return result;
- }
- }
-
- if(groupID instanceof TempMetadataID) {
- return null;
- }
-
- return this.actualMetadata.getMaterialization(groupID);
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getMaterializationStage(java.lang.Object)
- * @since 4.2
- */
- public Object getMaterializationStage(Object groupID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(groupID instanceof TempMetadataID) {
- return null;
- }
-
- // we do not care about the dynamic materialization tables here as they are loaded dynamically.
- return this.actualMetadata.getMaterializationStage(groupID);
- }
-
- public boolean isVirtualModel(Object modelID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(modelID.equals(TEMP_MODEL)) {
- return false;
- }
- return this.actualMetadata.isVirtualModel(modelID);
- }
-
- // --------------------- Implement OptimizerMetadata -------------------
-
- public boolean elementSupports(Object elementID, int supportConstant)
- throws TeiidComponentException, QueryMetadataException {
-
- if (elementID instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)elementID;
-
- switch(supportConstant) {
- case SupportConstants.Element.SEARCHABLE_LIKE: return true;
- case SupportConstants.Element.SEARCHABLE_COMPARE:return true;
- case SupportConstants.Element.SELECT: return true;
- case SupportConstants.Element.NULL: {
- if (id.isNotNull()) {
- return false;
- }
- if (id.isTempTable()) {
- return true;
- }
- break;
- }
- case SupportConstants.Element.AUTO_INCREMENT: return id.isAutoIncrement();
- case SupportConstants.Element.UPDATE: return id.isTempTable() || id.isUpdatable();
-
- }
-
- // If this is a temp table column or real metadata is unknown, return hard-coded values
- elementID = id.getOriginalMetadataID();
- if(elementID == null || id.isTempTable()) {
- switch(supportConstant) {
- case SupportConstants.Element.NULL: return true;
- case SupportConstants.Element.SIGNED: return true;
- }
-
- return false;
- }
- }
-
- return this.actualMetadata.elementSupports(elementID, supportConstant);
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getIndexesInGroup(java.lang.Object)
- */
- public Collection getIndexesInGroup(Object groupID)
- throws TeiidComponentException, QueryMetadataException {
- if(groupID instanceof TempMetadataID) {
- List<List<TempMetadataID>> result = ((TempMetadataID)groupID).getIndexes();
- if (result == null) {
- return Collections.emptyList();
- }
- return result;
- }
- return this.actualMetadata.getIndexesInGroup(groupID);
- }
-
- public Collection getUniqueKeysInGroup(Object groupID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(groupID instanceof TempMetadataID) {
- LinkedList<List<TempMetadataID>> result = new LinkedList<List<TempMetadataID>>();
- TempMetadataID id = (TempMetadataID)groupID;
- if (id.getPrimaryKey() != null) {
- result.add(id.getPrimaryKey());
- }
- if (id.getUniqueKeys() != null) {
- result.addAll(id.getUniqueKeys());
- }
- return result;
- }
- return this.actualMetadata.getUniqueKeysInGroup(groupID);
- }
-
- public Collection getForeignKeysInGroup(Object groupID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(groupID instanceof TempMetadataID) {
- return Collections.EMPTY_LIST;
- }
- return this.actualMetadata.getForeignKeysInGroup(groupID);
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getElementIDsInIndex(java.lang.Object)
- */
- public List getElementIDsInIndex(Object index)
- throws TeiidComponentException, QueryMetadataException {
- return this.actualMetadata.getElementIDsInIndex(index);
- }
-
- public List getElementIDsInKey(Object keyID)
- throws TeiidComponentException, QueryMetadataException {
-
- if (keyID instanceof List) {
- return (List)keyID;
- }
-
- return this.actualMetadata.getElementIDsInKey(keyID);
- }
-
- public boolean groupSupports(Object groupID, int groupConstant)
- throws TeiidComponentException, QueryMetadataException {
-
- if(groupID instanceof TempMetadataID){
- return true;
- }
-
- return this.actualMetadata.groupSupports(groupID, groupConstant);
- }
-
- public MappingNode getMappingNode(Object groupID)
- throws TeiidComponentException, QueryMetadataException {
-
- return this.actualMetadata.getMappingNode(groupID);
- }
-
- public boolean isXMLGroup(Object groupID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(groupID instanceof TempMetadataID) {
- return false;
- }
- return this.actualMetadata.isXMLGroup(groupID);
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getVirtualDatabaseName()
- */
- public String getVirtualDatabaseName()
- throws TeiidComponentException, QueryMetadataException {
-
- return this.actualMetadata.getVirtualDatabaseName();
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getAccessPatternsInGroup(Object)
- */
- public Collection getAccessPatternsInGroup(Object groupID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(groupID instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)groupID;
-
- return id.getAccessPatterns();
- }
- return this.actualMetadata.getAccessPatternsInGroup(groupID);
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getElementIDsInAccessPattern(Object)
- */
- public List getElementIDsInAccessPattern(Object accessPattern)
- throws TeiidComponentException, QueryMetadataException {
-
- if (accessPattern instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)accessPattern;
- if (id.getElements() != null) {
- return id.getElements();
- }
- return Collections.EMPTY_LIST;
- }
-
- return this.actualMetadata.getElementIDsInAccessPattern(accessPattern);
- }
-
- public Collection getXMLTempGroups(Object groupID)
- throws TeiidComponentException, QueryMetadataException{
-
- if(groupID instanceof TempMetadataID) {
- return Collections.EMPTY_SET;
- }
- return this.actualMetadata.getXMLTempGroups(groupID);
- }
-
- public int getCardinality(Object groupID)
- throws TeiidComponentException, QueryMetadataException{
-
- if(groupID instanceof TempMetadataID) {
- return ((TempMetadataID)groupID).getCardinality();
- }
- return this.actualMetadata.getCardinality(groupID);
- }
-
- public List getXMLSchemas(Object groupID) throws TeiidComponentException, QueryMetadataException {
- if(groupID instanceof TempMetadataID) {
- return Collections.EMPTY_LIST;
- }
- return this.actualMetadata.getXMLSchemas(groupID);
- }
-
- public Properties getExtensionProperties(Object metadataID)
- throws TeiidComponentException, QueryMetadataException {
-
- if(metadataID instanceof TempMetadataID) {
- return null;
- }
- return actualMetadata.getExtensionProperties(metadataID);
- }
-
- public int getElementLength(Object elementID) throws TeiidComponentException, QueryMetadataException {
- if (elementID instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)elementID;
- Object origElementID = id.getOriginalMetadataID();
- if (origElementID == null) {
- String type = getElementType(elementID);
- if(type.equals(DataTypeManager.DefaultDataTypes.STRING)) {
- return 255;
- }
- return 10;
- }
- elementID = origElementID;
- }
-
- return actualMetadata.getElementLength(elementID);
- }
-
- public int getPosition(Object elementID) throws TeiidComponentException, QueryMetadataException {
- if (elementID instanceof TempMetadataID) {
- return ((TempMetadataID)elementID).getPosition();
- }
- return actualMetadata.getPosition(elementID);
- }
-
- public int getPrecision(Object elementID) throws TeiidComponentException, QueryMetadataException {
- if (elementID instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)elementID;
- elementID = id.getOriginalMetadataID();
- if (elementID == null) {
- return 0;
- }
- }
- return actualMetadata.getPrecision(elementID);
- }
-
- public int getRadix(Object elementID) throws TeiidComponentException, QueryMetadataException {
- if (elementID instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)elementID;
- elementID = id.getOriginalMetadataID();
- if (elementID == null) {
- return 0;
- }
- }
- return actualMetadata.getRadix(elementID);
- }
-
- public int getScale(Object elementID) throws TeiidComponentException, QueryMetadataException {
- if (elementID instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)elementID;
- elementID = id.getOriginalMetadataID();
- if (elementID == null) {
- return 0;
- }
- }
- return actualMetadata.getScale(elementID);
- }
-
- /**
- * Get the native type name for the element.
- * @see org.teiid.query.metadata.QueryMetadataInterface#getNativeType(java.lang.Object)
- * @since 4.2
- */
- public String getNativeType(Object elementID) throws TeiidComponentException,
- QueryMetadataException {
- if (elementID instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)elementID;
- elementID = id.getOriginalMetadataID();
- if (elementID == null) {
- return ""; //$NON-NLS-1$
- }
- }
-
- return actualMetadata.getNativeType(elementID);
- }
-
- public boolean isProcedure(Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof TempMetadataID) {
- Object oid = ((TempMetadataID) elementID).getOriginalMetadataID();
- if (oid != null) {
- return actualMetadata.isProcedure(oid);
- }
- return false;
- }
-
- return actualMetadata.isProcedure(elementID);
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getModeledType(java.lang.Object)
- * @since 5.0
- */
- public String getModeledType(Object elementID) throws TeiidComponentException,
- QueryMetadataException {
-
- if (elementID instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)elementID;
- elementID = id.getOriginalMetadataID();
- if (elementID == null) {
- return null;
- }
- }
-
- return actualMetadata.getModeledType(elementID);
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getModeledBaseType(java.lang.Object)
- * @since 5.0
- */
- public String getModeledBaseType(Object elementID) throws TeiidComponentException,
- QueryMetadataException {
-
- if (elementID instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)elementID;
- elementID = id.getOriginalMetadataID();
- if (elementID == null) {
- return null;
- }
- }
-
- return actualMetadata.getModeledBaseType(elementID);
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getModeledPrimitiveType(java.lang.Object)
- * @since 5.0
- */
- public String getModeledPrimitiveType(Object elementID) throws TeiidComponentException,
- QueryMetadataException {
-
- if (elementID instanceof TempMetadataID) {
- TempMetadataID id = (TempMetadataID)elementID;
- elementID = id.getOriginalMetadataID();
- if (elementID == null) {
- return null;
- }
- }
-
- return actualMetadata.getModeledPrimitiveType(elementID);
- }
-
- public boolean isTemporaryTable(Object groupID) throws TeiidComponentException, QueryMetadataException {
- if(groupID instanceof TempMetadataID) {
- return ((TempMetadataID)groupID).isTempTable();
- }
- //return this.metadata.isTemporaryGroup(groupID);
- return false;
- }
-
- @Override
- public Object addToMetadataCache(Object metadataID, String key, Object value)
- throws TeiidComponentException, QueryMetadataException {
- if (metadataID instanceof TempMetadataID) {
- TempMetadataID tid = (TempMetadataID)metadataID;
- return tid.setProperty(key, value);
- }
-
- return this.actualMetadata.addToMetadataCache(metadataID, key, value);
- }
-
- @Override
- public Object getFromMetadataCache(Object metadataID, String key)
- throws TeiidComponentException, QueryMetadataException {
- if (metadataID instanceof TempMetadataID) {
- TempMetadataID tid = (TempMetadataID)metadataID;
- return tid.getProperty(key);
- }
-
- return this.actualMetadata.getFromMetadataCache(metadataID, key);
- }
-
- @Override
- public boolean isScalarGroup(Object groupID)
- throws TeiidComponentException, QueryMetadataException {
- if (groupID instanceof TempMetadataID) {
- TempMetadataID tid = (TempMetadataID)groupID;
- return tid.isScalarGroup();
- }
-
- return this.actualMetadata.isScalarGroup(groupID);
- }
-
- @Override
- public Object getPrimaryKey(Object metadataID) {
- if (metadataID instanceof TempMetadataID) {
- return ((TempMetadataID)metadataID).getPrimaryKey();
- }
- return this.actualMetadata.getPrimaryKey(metadataID);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataAdapter.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/metadata/TempMetadataAdapter.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataAdapter.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataAdapter.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,770 @@
+/*
+ * 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.metadata;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+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;
+
+
+/**
+ * <p>This is an adapter class, it contains another instance of
+ * QueryMetadataInterface as well as a TempMetadataStore. It defers to
+ * either one of these when appropriate.</p>
+ *
+ * <p>When a metadataID Object is requested for a group or element name, this
+ * will first check the QueryMetadataInterface. If an ID wasn't found there,
+ * it will then check the TempMetadataStore.</p>
+ *
+ * <p>For methods that take a metadataID arg, this class may check whether it
+ * is a TempMetadataID or not and react accordingly.</p>
+ */
+public class TempMetadataAdapter extends BasicQueryMetadataWrapper {
+
+ private static final String SEPARATOR = "."; //$NON-NLS-1$
+ public static final TempMetadataID TEMP_MODEL = new TempMetadataID("__TEMP__", Collections.EMPTY_LIST); //$NON-NLS-1$
+
+ private TempMetadataStore tempStore;
+ private Map materializationTables;
+ private Map queryNodes;
+ private boolean session;
+
+ public TempMetadataAdapter(QueryMetadataInterface metadata, TempMetadataStore tempStore) {
+ super(metadata);
+ this.tempStore = tempStore;
+ }
+
+ public TempMetadataAdapter(QueryMetadataInterface metadata, TempMetadataStore tempStore, Map materializationTables, Map queryNodes) {
+ super(metadata);
+ this.tempStore = tempStore;
+ this.materializationTables = materializationTables;
+ this.queryNodes = queryNodes;
+ }
+
+ public boolean isSession() {
+ return session;
+ }
+
+ public void setSession(boolean session) {
+ this.session = session;
+ }
+
+ public QueryMetadataInterface getSessionMetadata() {
+ if (isSession()) {
+ TempMetadataAdapter tma = new TempMetadataAdapter(new BasicQueryMetadata(), this.tempStore);
+ tma.session = true;
+ return tma;
+ }
+ return this.actualMetadata.getSessionMetadata();
+ }
+
+ public QueryMetadataInterface getDesignTimeMetadata() {
+ if (isSession()) {
+ return this.actualMetadata.getDesignTimeMetadata();
+ }
+ return new TempMetadataAdapter(this.actualMetadata.getDesignTimeMetadata(), tempStore, materializationTables, queryNodes);
+ }
+
+ public TempMetadataStore getMetadataStore() {
+ return this.tempStore;
+ }
+
+ public QueryMetadataInterface getMetadata() {
+ return this.actualMetadata;
+ }
+
+ /**
+ * Check metadata first, then check temp groups if not found
+ */
+ public Object getElementID(String elementName)
+ throws TeiidComponentException, QueryMetadataException {
+
+ Object tempID = null;
+ try {
+ tempID = this.actualMetadata.getElementID(elementName);
+ } catch (QueryMetadataException e) {
+ //ignore
+ }
+
+ if (tempID == null){
+ tempID = this.tempStore.getTempElementID(elementName);
+ }
+
+ if(tempID != null) {
+ return tempID;
+ }
+ Object[] params = new Object[]{elementName};
+ String msg = QueryPlugin.Util.getString("TempMetadataAdapter.Element_____{0}_____not_found._1", params); //$NON-NLS-1$
+ throw new QueryMetadataException(msg);
+ }
+
+ /**
+ * Check metadata first, then check temp groups if not found
+ */
+ public Object getGroupID(String groupName)
+ throws TeiidComponentException, QueryMetadataException {
+
+ Object tempID = null;
+ try {
+ tempID = this.actualMetadata.getGroupID(groupName);
+ } catch (QueryMetadataException e) {
+ //ignore
+ }
+
+ if (tempID == null){
+ tempID = this.tempStore.getTempGroupID(groupName);
+ }
+
+ if(tempID != null) {
+ return tempID;
+ }
+ Object[] params = new Object[]{groupName};
+ String msg = QueryPlugin.Util.getString("TempMetadataAdapter.Group_____{0}_____not_found._1", params); //$NON-NLS-1$
+ 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 {
+
+ if(groupOrElementID instanceof TempMetadataID) {
+ return TempMetadataAdapter.TEMP_MODEL;
+ }
+ return this.actualMetadata.getModelID(groupOrElementID);
+ }
+
+ // SPECIAL: Override for temp groups
+ public String getFullName(Object metadataID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(metadataID instanceof TempMetadataID) {
+ return ((TempMetadataID)metadataID).getID();
+ }
+ return this.actualMetadata.getFullName(metadataID);
+ }
+
+ @Override
+ public String getName(Object metadataID) throws TeiidComponentException,
+ QueryMetadataException {
+ if(metadataID instanceof TempMetadataID) {
+ TempMetadataID tid = (TempMetadataID)metadataID;
+ return tid.getName();
+ }
+ return this.actualMetadata.getName(metadataID);
+ }
+
+ // SPECIAL: Override for temp groups
+ public List getElementIDsInGroupID(Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(groupID instanceof TempMetadataID) {
+ return new ArrayList(((TempMetadataID)groupID).getElements());
+ }
+ return this.actualMetadata.getElementIDsInGroupID(groupID);
+ }
+
+ // SPECIAL: Override for temp groups
+ public Object getGroupIDForElementID(Object elementID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(elementID instanceof TempMetadataID) {
+ String elementName = ((TempMetadataID)elementID).getID();
+ String groupName = elementName.substring(0, elementName.lastIndexOf(SEPARATOR));
+ return this.tempStore.getTempGroupID(groupName);
+ }
+ return this.actualMetadata.getGroupIDForElementID(elementID);
+ }
+
+ // SPECIAL: Override for temp groups
+ public String getElementType(Object elementID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(elementID instanceof TempMetadataID) {
+ TempMetadataID tempID = (TempMetadataID)elementID;
+ if (tempID.getType() != null) {
+ return DataTypeManager.getDataTypeName( tempID.getType() );
+ }
+ throw new AssertionError("No type set for element " + elementID); //$NON-NLS-1$
+ }
+ return this.actualMetadata.getElementType(elementID);
+ }
+
+ public Object getDefaultValue(Object elementID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(elementID instanceof TempMetadataID) {
+ return null;
+ }
+ return this.actualMetadata.getDefaultValue(elementID);
+ }
+
+ public Object getMaximumValue(Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if (elementID instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)elementID;
+ elementID = id.getOriginalMetadataID();
+ if (elementID == null) {
+ return null;
+ }
+ }
+ return this.actualMetadata.getMaximumValue(elementID);
+ }
+
+ public Object getMinimumValue(Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if (elementID instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)elementID;
+ elementID = id.getOriginalMetadataID();
+ if (elementID == null) {
+ return null;
+ }
+ }
+ return this.actualMetadata.getMinimumValue(elementID);
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getDistinctValues(java.lang.Object)
+ */
+ public int getDistinctValues(Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof TempMetadataID) {
+ return -1;
+ }
+ return this.actualMetadata.getDistinctValues(elementID);
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getNullValues(java.lang.Object)
+ */
+ public int getNullValues(Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if (elementID instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)elementID;
+ elementID = id.getOriginalMetadataID();
+ if (elementID == null) {
+ return -1;
+ }
+ }
+ return this.actualMetadata.getNullValues(elementID);
+ }
+
+ public QueryNode getVirtualPlan(Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if (this.queryNodes != null && this.queryNodes.containsKey(groupID)) {
+ return (QueryNode)this.queryNodes.get(groupID);
+ }
+
+ if(groupID instanceof TempMetadataID && !(actualMetadata instanceof TempMetadataAdapter)) {
+ return ((TempMetadataID)groupID).getQueryNode();
+ }
+ return this.actualMetadata.getVirtualPlan(groupID);
+ }
+
+ // SPECIAL: Override for temp groups
+ public boolean isVirtualGroup(Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(groupID instanceof TempMetadataID) {
+ return ((TempMetadataID)groupID).isVirtual();
+ }
+ return this.actualMetadata.isVirtualGroup(groupID);
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#hasMaterialization(java.lang.Object)
+ * @since 4.2
+ */
+ public boolean hasMaterialization(Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ // check if any dynamic materialization tables are defined
+ if (this.materializationTables != null && this.materializationTables.containsKey(groupID)) {
+ return true;
+ }
+
+ if(groupID instanceof TempMetadataID) {
+ return false;
+ }
+
+ return this.actualMetadata.hasMaterialization(groupID);
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getMaterialization(java.lang.Object)
+ * @since 4.2
+ */
+ public Object getMaterialization(Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ // check if any dynamic materialization tables are defined
+ if (this.materializationTables != null) {
+ Object result = this.materializationTables.get(groupID);
+ if (result != null) {
+ return result;
+ }
+ }
+
+ if(groupID instanceof TempMetadataID) {
+ return null;
+ }
+
+ return this.actualMetadata.getMaterialization(groupID);
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getMaterializationStage(java.lang.Object)
+ * @since 4.2
+ */
+ public Object getMaterializationStage(Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(groupID instanceof TempMetadataID) {
+ return null;
+ }
+
+ // we do not care about the dynamic materialization tables here as they are loaded dynamically.
+ return this.actualMetadata.getMaterializationStage(groupID);
+ }
+
+ public boolean isVirtualModel(Object modelID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(modelID.equals(TEMP_MODEL)) {
+ return false;
+ }
+ return this.actualMetadata.isVirtualModel(modelID);
+ }
+
+ // --------------------- Implement OptimizerMetadata -------------------
+
+ public boolean elementSupports(Object elementID, int supportConstant)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if (elementID instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)elementID;
+
+ switch(supportConstant) {
+ case SupportConstants.Element.SEARCHABLE_LIKE: return true;
+ case SupportConstants.Element.SEARCHABLE_COMPARE:return true;
+ case SupportConstants.Element.SELECT: return true;
+ case SupportConstants.Element.NULL: {
+ if (id.isNotNull()) {
+ return false;
+ }
+ if (id.isTempTable()) {
+ return true;
+ }
+ break;
+ }
+ case SupportConstants.Element.AUTO_INCREMENT: return id.isAutoIncrement();
+ case SupportConstants.Element.UPDATE: return id.isTempTable() || id.isUpdatable();
+
+ }
+
+ // If this is a temp table column or real metadata is unknown, return hard-coded values
+ elementID = id.getOriginalMetadataID();
+ if(elementID == null || id.isTempTable()) {
+ switch(supportConstant) {
+ case SupportConstants.Element.NULL: return true;
+ case SupportConstants.Element.SIGNED: return true;
+ }
+
+ return false;
+ }
+ }
+
+ return this.actualMetadata.elementSupports(elementID, supportConstant);
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getIndexesInGroup(java.lang.Object)
+ */
+ public Collection getIndexesInGroup(Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+ if(groupID instanceof TempMetadataID) {
+ List<List<TempMetadataID>> result = ((TempMetadataID)groupID).getIndexes();
+ if (result == null) {
+ return Collections.emptyList();
+ }
+ return result;
+ }
+ return this.actualMetadata.getIndexesInGroup(groupID);
+ }
+
+ public Collection getUniqueKeysInGroup(Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(groupID instanceof TempMetadataID) {
+ LinkedList<List<TempMetadataID>> result = new LinkedList<List<TempMetadataID>>();
+ TempMetadataID id = (TempMetadataID)groupID;
+ if (id.getPrimaryKey() != null) {
+ result.add(id.getPrimaryKey());
+ }
+ if (id.getUniqueKeys() != null) {
+ result.addAll(id.getUniqueKeys());
+ }
+ return result;
+ }
+ return this.actualMetadata.getUniqueKeysInGroup(groupID);
+ }
+
+ public Collection getForeignKeysInGroup(Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(groupID instanceof TempMetadataID) {
+ return Collections.EMPTY_LIST;
+ }
+ return this.actualMetadata.getForeignKeysInGroup(groupID);
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getElementIDsInIndex(java.lang.Object)
+ */
+ public List getElementIDsInIndex(Object index)
+ throws TeiidComponentException, QueryMetadataException {
+ return this.actualMetadata.getElementIDsInIndex(index);
+ }
+
+ public List getElementIDsInKey(Object keyID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if (keyID instanceof List) {
+ return (List)keyID;
+ }
+
+ return this.actualMetadata.getElementIDsInKey(keyID);
+ }
+
+ public boolean groupSupports(Object groupID, int groupConstant)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(groupID instanceof TempMetadataID){
+ return true;
+ }
+
+ return this.actualMetadata.groupSupports(groupID, groupConstant);
+ }
+
+ public MappingNode getMappingNode(Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ return this.actualMetadata.getMappingNode(groupID);
+ }
+
+ public boolean isXMLGroup(Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(groupID instanceof TempMetadataID) {
+ return ((TempMetadataID)groupID).getMetadataType() == Type.XML;
+ }
+ return this.actualMetadata.isXMLGroup(groupID);
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getVirtualDatabaseName()
+ */
+ public String getVirtualDatabaseName()
+ throws TeiidComponentException, QueryMetadataException {
+
+ return this.actualMetadata.getVirtualDatabaseName();
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getAccessPatternsInGroup(Object)
+ */
+ public Collection getAccessPatternsInGroup(Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(groupID instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)groupID;
+
+ return id.getAccessPatterns();
+ }
+ return this.actualMetadata.getAccessPatternsInGroup(groupID);
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getElementIDsInAccessPattern(Object)
+ */
+ public List getElementIDsInAccessPattern(Object accessPattern)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if (accessPattern instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)accessPattern;
+ if (id.getElements() != null) {
+ return id.getElements();
+ }
+ return Collections.EMPTY_LIST;
+ }
+
+ return this.actualMetadata.getElementIDsInAccessPattern(accessPattern);
+ }
+
+ public Collection getXMLTempGroups(Object groupID)
+ throws TeiidComponentException, QueryMetadataException{
+
+ if(groupID instanceof TempMetadataID) {
+ return Collections.EMPTY_SET;
+ }
+ return this.actualMetadata.getXMLTempGroups(groupID);
+ }
+
+ public int getCardinality(Object groupID)
+ throws TeiidComponentException, QueryMetadataException{
+
+ if(groupID instanceof TempMetadataID) {
+ return ((TempMetadataID)groupID).getCardinality();
+ }
+ return this.actualMetadata.getCardinality(groupID);
+ }
+
+ public List getXMLSchemas(Object groupID) throws TeiidComponentException, QueryMetadataException {
+ if(groupID instanceof TempMetadataID) {
+ return Collections.EMPTY_LIST;
+ }
+ return this.actualMetadata.getXMLSchemas(groupID);
+ }
+
+ public Properties getExtensionProperties(Object metadataID)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(metadataID instanceof TempMetadataID) {
+ return null;
+ }
+ return actualMetadata.getExtensionProperties(metadataID);
+ }
+
+ public int getElementLength(Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if (elementID instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)elementID;
+ Object origElementID = id.getOriginalMetadataID();
+ if (origElementID == null) {
+ String type = getElementType(elementID);
+ if(type.equals(DataTypeManager.DefaultDataTypes.STRING)) {
+ return 255;
+ }
+ return 10;
+ }
+ elementID = origElementID;
+ }
+
+ return actualMetadata.getElementLength(elementID);
+ }
+
+ public int getPosition(Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if (elementID instanceof TempMetadataID) {
+ return ((TempMetadataID)elementID).getPosition();
+ }
+ return actualMetadata.getPosition(elementID);
+ }
+
+ public int getPrecision(Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if (elementID instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)elementID;
+ elementID = id.getOriginalMetadataID();
+ if (elementID == null) {
+ return 0;
+ }
+ }
+ return actualMetadata.getPrecision(elementID);
+ }
+
+ public int getRadix(Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if (elementID instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)elementID;
+ elementID = id.getOriginalMetadataID();
+ if (elementID == null) {
+ return 0;
+ }
+ }
+ return actualMetadata.getRadix(elementID);
+ }
+
+ public int getScale(Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if (elementID instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)elementID;
+ elementID = id.getOriginalMetadataID();
+ if (elementID == null) {
+ return 0;
+ }
+ }
+ return actualMetadata.getScale(elementID);
+ }
+
+ /**
+ * Get the native type name for the element.
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getNativeType(java.lang.Object)
+ * @since 4.2
+ */
+ public String getNativeType(Object elementID) throws TeiidComponentException,
+ QueryMetadataException {
+ if (elementID instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)elementID;
+ elementID = id.getOriginalMetadataID();
+ if (elementID == null) {
+ return ""; //$NON-NLS-1$
+ }
+ }
+
+ return actualMetadata.getNativeType(elementID);
+ }
+
+ public boolean isProcedure(Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof TempMetadataID) {
+ Object oid = ((TempMetadataID) elementID).getOriginalMetadataID();
+ if (oid != null) {
+ return actualMetadata.isProcedure(oid);
+ }
+ return false;
+ }
+
+ return actualMetadata.isProcedure(elementID);
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getModeledType(java.lang.Object)
+ * @since 5.0
+ */
+ public String getModeledType(Object elementID) throws TeiidComponentException,
+ QueryMetadataException {
+
+ if (elementID instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)elementID;
+ elementID = id.getOriginalMetadataID();
+ if (elementID == null) {
+ return null;
+ }
+ }
+
+ return actualMetadata.getModeledType(elementID);
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getModeledBaseType(java.lang.Object)
+ * @since 5.0
+ */
+ public String getModeledBaseType(Object elementID) throws TeiidComponentException,
+ QueryMetadataException {
+
+ if (elementID instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)elementID;
+ elementID = id.getOriginalMetadataID();
+ if (elementID == null) {
+ return null;
+ }
+ }
+
+ return actualMetadata.getModeledBaseType(elementID);
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getModeledPrimitiveType(java.lang.Object)
+ * @since 5.0
+ */
+ public String getModeledPrimitiveType(Object elementID) throws TeiidComponentException,
+ QueryMetadataException {
+
+ if (elementID instanceof TempMetadataID) {
+ TempMetadataID id = (TempMetadataID)elementID;
+ elementID = id.getOriginalMetadataID();
+ if (elementID == null) {
+ return null;
+ }
+ }
+
+ return actualMetadata.getModeledPrimitiveType(elementID);
+ }
+
+ public boolean isTemporaryTable(Object groupID) throws TeiidComponentException, QueryMetadataException {
+ if(groupID instanceof TempMetadataID) {
+ return ((TempMetadataID)groupID).isTempTable();
+ }
+ //return this.metadata.isTemporaryGroup(groupID);
+ return false;
+ }
+
+ @Override
+ public Object addToMetadataCache(Object metadataID, String key, Object value)
+ throws TeiidComponentException, QueryMetadataException {
+ if (metadataID instanceof TempMetadataID) {
+ TempMetadataID tid = (TempMetadataID)metadataID;
+ return tid.setProperty(key, value);
+ }
+
+ return this.actualMetadata.addToMetadataCache(metadataID, key, value);
+ }
+
+ @Override
+ public Object getFromMetadataCache(Object metadataID, String key)
+ throws TeiidComponentException, QueryMetadataException {
+ if (metadataID instanceof TempMetadataID) {
+ TempMetadataID tid = (TempMetadataID)metadataID;
+ return tid.getProperty(key);
+ }
+
+ return this.actualMetadata.getFromMetadataCache(metadataID, key);
+ }
+
+ @Override
+ public boolean isScalarGroup(Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+ if (groupID instanceof TempMetadataID) {
+ TempMetadataID tid = (TempMetadataID)groupID;
+ return tid.isScalarGroup();
+ }
+
+ return this.actualMetadata.isScalarGroup(groupID);
+ }
+
+ @Override
+ public Object getPrimaryKey(Object metadataID) {
+ if (metadataID instanceof TempMetadataID) {
+ return ((TempMetadataID)metadataID).getPrimaryKey();
+ }
+ return this.actualMetadata.getPrimaryKey(metadataID);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataID.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/metadata/TempMetadataID.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataID.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,415 +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.metadata;
-
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.teiid.core.util.LRUCache;
-import org.teiid.metadata.AbstractMetadataRecord.DataModifiable;
-import org.teiid.metadata.AbstractMetadataRecord.Modifiable;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.sql.lang.CacheHint;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-
-/**
- * This class represents a temporary metadata ID. A temporary metadata ID
- * does not exist in a real metadata source. Rather, it is used temporarily
- * in context of processing a single query. This metadata ID can be used to
- * represent either a group or an element depending on the constructor used.
- *
- * TODO: we should be using the real metadata objects, but internal and
- * designer legacy keep us on the temp framework
- */
-public class TempMetadataID implements Serializable, Modifiable, DataModifiable {
-
- private static final long serialVersionUID = -1879211827339120135L;
- private static final int LOCAL_CACHE_SIZE = 8;
-
- private static final int MOD_COUNT_FOR_COST_UPDATE = 8;
-
- public static class TableData {
- Collection<TempMetadataID> accessPatterns;
- List<TempMetadataID> elements;
- int cardinality = QueryMetadataInterface.UNKNOWN_CARDINALITY;
- List<TempMetadataID> primaryKey;
- QueryNode queryNode;
- LRUCache<Object, Object> localCache;
- CacheHint cacheHint;
- List<List<TempMetadataID>> keys;
- List<List<TempMetadataID>> indexes;
- long lastDataModification;
- long lastModified;
- int modCount;
-
- public long getLastDataModification() {
- return lastDataModification;
- }
-
- public void dataModified(int updateCount) {
- if (updateCount == 0) {
- return;
- }
- long ts = System.currentTimeMillis();
- modCount += updateCount;
- if (modCount > MOD_COUNT_FOR_COST_UPDATE) {
- this.lastModified = ts;
- modCount = 0;
- }
- this.lastDataModification = ts;
- }
-
- public long getLastModified() {
- return lastModified;
- }
-
- }
-
- private static TableData DUMMY_DATA = new TableData();
-
- public enum Type {
- VIRTUAL,
- TEMP,
- SCALAR
- }
-
- private String ID; // never null, upper cased fully-qualified string
- private String name;
- private Type metadataType = Type.VIRTUAL;
- private Object originalMetadataID;
-
- private TableData data;
-
- //Column metadata
- private int position;
- private Class<?> type; // type of this element, only for element
- private boolean autoIncrement;
- private boolean notNull;
- private boolean updatable;
-
- /**
- * Constructor for group form of metadata ID.
- * @param ID Fully-qualified, upper-case name of ID
- * @param elements List of TempMetadataID representing elements
- */
- public TempMetadataID(String ID, List<TempMetadataID> elements) {
- this(ID, elements, Type.VIRTUAL);
- }
-
- /**
- * Constructor for group form of metadata ID.
- * @param ID Fully-qualified, upper-case name of ID
- * @param elements List of TempMetadataID representing elements
- * @param isVirtual whether or not the group is a virtual group
- */
- public TempMetadataID(String ID, List<TempMetadataID> elements, Type type) {
- this.data = new TableData();
- this.ID = ID;
- this.data.elements = elements;
- int pos = 1;
- for (TempMetadataID tempMetadataID : elements) {
- tempMetadataID.setPosition(pos++);
- }
- this.name = ID;
- this.metadataType = type;
- }
-
- /**
- * Constructor for element form of metadata ID.
- * @param ID Fully-qualified, upper-case name of ID
- * @param type Type of elements List of TempMetadataID representing elements
- */
- public TempMetadataID(String ID, Class<?> type) {
- this.ID = ID;
- this.type = type;
- }
-
- /**
- * Constructor for element form of metadata ID with the underlying element.
- * @param ID Fully-qualified, upper-case name of ID
- * @param type Type of elements List of TempMetadataID representing elements
- * @param metadataID the orginal metadataID
- */
- public TempMetadataID(String ID, Class<?> type, Object metadataID) {
- this.ID = ID;
- this.type = type;
- this.originalMetadataID = metadataID;
- }
-
- @Override
- public long getLastDataModification() {
- return getTableData().getLastDataModification();
- }
-
- @Override
- public long getLastModified() {
- return getTableData().getLastModified();
- }
-
- /**
- * Get ID value
- * @return ID value
- */
- public String getID() {
- return this.ID;
- }
-
- /**
- * Get type - only valid for elements
- * @return Type for elements, null for groups
- */
- public Class<?> getType() {
- return this.type;
- }
-
- /**
- * Get elements - only valid for groups
- * @return List of TempMetadataID for groups, null for elements
- */
- public List<TempMetadataID> getElements() {
- return this.getTableData().elements;
- }
-
- /**
- * add a element to the temp table.
- * @param elem
- */
- protected void addElement(TempMetadataID elem) {
- if (this.getTableData().elements != null) {
- this.getTableData().elements.add(elem);
- elem.setPosition(this.getTableData().elements.size());
- }
- if (this.getTableData().localCache != null) {
- this.getTableData().localCache.clear();
- }
- }
-
- /**
- * Check whether this group is virtual
- * @return True if virtual
- */
- public boolean isVirtual() {
- return metadataType == Type.VIRTUAL;
- }
-
- /**
- * Whether it is a temporary table
- * @return
- * @since 5.5
- */
- public boolean isTempTable() {
- return this.metadataType == Type.TEMP;
- }
-
- /**
- * Return string representation of ID
- * @return String representation
- */
- public String toString() {
- return ID;
- }
-
- /**
- * Compare this temp metadata ID with another object.
- * @return True if obj is another TempMetadataID with same ID value
- */
- public boolean equals(Object obj) {
- if(this == obj) {
- return true;
- }
-
- if(!(obj instanceof TempMetadataID)) {
- return false;
- }
- return this.getID().equals( ((TempMetadataID) obj).getID());
- }
-
- /**
- * Return hash code
- * @return Hash code value for object
- */
- public int hashCode() {
- return this.ID.hashCode();
- }
-
- public void setOriginalMetadataID(Object metadataId) {
- this.originalMetadataID = metadataId;
- }
-
- /**
- * @return Returns the originalMetadataID.
- * @since 4.3
- */
- public Object getOriginalMetadataID() {
- return this.originalMetadataID;
- }
-
- public Collection<TempMetadataID> getAccessPatterns() {
- if (this.getTableData().accessPatterns == null) {
- return Collections.emptyList();
- }
- return this.getTableData().accessPatterns;
- }
-
- public void setAccessPatterns(Collection<TempMetadataID> accessPatterns) {
- this.getTableData().accessPatterns = accessPatterns;
- }
-
- public int getCardinality() {
- return this.getTableData().cardinality;
- }
-
- public void setCardinality(int cardinality) {
- this.getTableData().cardinality = cardinality;
- }
-
- public void setTempTable(boolean isTempTable) {
- if (isTempTable) {
- this.metadataType = Type.TEMP;
- } else {
- this.metadataType = Type.VIRTUAL;
- }
- }
-
- Object getProperty(Object key) {
- if (this.getTableData().localCache != null) {
- return this.getTableData().localCache.get(key);
- }
- return null;
- }
-
- Object setProperty(Object key, Object value) {
- if (this.getTableData().localCache == null) {
- this.getTableData().localCache = new LRUCache<Object, Object>(LOCAL_CACHE_SIZE);
- }
- return this.getTableData().localCache.put(key, value);
- }
-
- public boolean isScalarGroup() {
- return this.metadataType == Type.SCALAR;
- }
-
- public void setMetadataType(Type metadataType) {
- this.metadataType = metadataType;
- }
-
- public Type getMetadataType() {
- return metadataType;
- }
-
- public List<TempMetadataID> getPrimaryKey() {
- return getTableData().primaryKey;
- }
-
- public void setPrimaryKey(List<TempMetadataID> primaryKey) {
- this.getTableData().primaryKey = primaryKey;
- }
-
- public int getPosition() {
- return position;
- }
-
- public void setPosition(int position) {
- this.position = position;
- }
-
- public QueryNode getQueryNode() {
- return getTableData().queryNode;
- }
-
- public void setQueryNode(QueryNode queryNode) {
- this.getTableData().queryNode = queryNode;
- }
-
- public CacheHint getCacheHint() {
- return getTableData().cacheHint;
- }
-
- public void setCacheHint(CacheHint cacheHint) {
- this.getTableData().cacheHint = cacheHint;
- }
-
- public List<List<TempMetadataID>> getIndexes() {
- return getTableData().indexes;
- }
-
- public void addIndex(List<TempMetadataID> index) {
- if (this.getTableData().indexes == null) {
- this.getTableData().indexes = new LinkedList<List<TempMetadataID>>();
- }
- this.getTableData().indexes.add(index);
- }
-
- public List<List<TempMetadataID>> getUniqueKeys() {
- return getTableData().keys;
- }
-
- public void addUniqueKey(List<TempMetadataID> key) {
- if (this.getTableData().keys == null) {
- this.getTableData().keys = new LinkedList<List<TempMetadataID>>();
- }
- this.getTableData().keys.add(key);
- }
-
- public TableData getTableData() {
- if (data == null) {
- return DUMMY_DATA;
- }
- return data;
- }
-
- public boolean isAutoIncrement() {
- return autoIncrement;
- }
-
- public void setAutoIncrement(boolean autoIncrement) {
- this.autoIncrement = autoIncrement;
- }
-
- public boolean isNotNull() {
- return notNull;
- }
-
- public void setNotNull(boolean notNull) {
- this.notNull = notNull;
- }
-
- public void setUpdatable(boolean updatable) {
- this.updatable = updatable;
- }
-
- public boolean isUpdatable() {
- return updatable;
- }
-
- public String getName() {
- if (this.name == null) {
- this.name = SingleElementSymbol.getShortName(this.ID);
- }
- return this.name;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataID.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/metadata/TempMetadataID.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataID.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TempMetadataID.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,416 @@
+/*
+ * 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.metadata;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.teiid.core.util.LRUCache;
+import org.teiid.metadata.AbstractMetadataRecord.DataModifiable;
+import org.teiid.metadata.AbstractMetadataRecord.Modifiable;
+import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.sql.lang.CacheHint;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+
+/**
+ * This class represents a temporary metadata ID. A temporary metadata ID
+ * does not exist in a real metadata source. Rather, it is used temporarily
+ * in context of processing a single query. This metadata ID can be used to
+ * represent either a group or an element depending on the constructor used.
+ *
+ * TODO: we should be using the real metadata objects, but internal and
+ * designer legacy keep us on the temp framework
+ */
+public class TempMetadataID implements Serializable, Modifiable, DataModifiable {
+
+ private static final long serialVersionUID = -1879211827339120135L;
+ private static final int LOCAL_CACHE_SIZE = 8;
+
+ private static final int MOD_COUNT_FOR_COST_UPDATE = 8;
+
+ public static class TableData {
+ Collection<TempMetadataID> accessPatterns;
+ List<TempMetadataID> elements;
+ int cardinality = QueryMetadataInterface.UNKNOWN_CARDINALITY;
+ List<TempMetadataID> primaryKey;
+ QueryNode queryNode;
+ LRUCache<Object, Object> localCache;
+ CacheHint cacheHint;
+ List<List<TempMetadataID>> keys;
+ List<List<TempMetadataID>> indexes;
+ long lastDataModification;
+ long lastModified;
+ int modCount;
+
+ public long getLastDataModification() {
+ return lastDataModification;
+ }
+
+ public void dataModified(int updateCount) {
+ if (updateCount == 0) {
+ return;
+ }
+ long ts = System.currentTimeMillis();
+ modCount += updateCount;
+ if (modCount > MOD_COUNT_FOR_COST_UPDATE) {
+ this.lastModified = ts;
+ modCount = 0;
+ }
+ this.lastDataModification = ts;
+ }
+
+ public long getLastModified() {
+ return lastModified;
+ }
+
+ }
+
+ private static TableData DUMMY_DATA = new TableData();
+
+ public enum Type {
+ VIRTUAL,
+ TEMP,
+ SCALAR,
+ XML
+ }
+
+ private String ID; // never null, upper cased fully-qualified string
+ private String name;
+ private Type metadataType = Type.VIRTUAL;
+ private Object originalMetadataID;
+
+ private TableData data;
+
+ //Column metadata
+ private int position;
+ private Class<?> type; // type of this element, only for element
+ private boolean autoIncrement;
+ private boolean notNull;
+ private boolean updatable;
+
+ /**
+ * Constructor for group form of metadata ID.
+ * @param ID Fully-qualified, upper-case name of ID
+ * @param elements List of TempMetadataID representing elements
+ */
+ public TempMetadataID(String ID, List<TempMetadataID> elements) {
+ this(ID, elements, Type.VIRTUAL);
+ }
+
+ /**
+ * Constructor for group form of metadata ID.
+ * @param ID Fully-qualified, upper-case name of ID
+ * @param elements List of TempMetadataID representing elements
+ * @param isVirtual whether or not the group is a virtual group
+ */
+ public TempMetadataID(String ID, List<TempMetadataID> elements, Type type) {
+ this.data = new TableData();
+ this.ID = ID;
+ this.data.elements = elements;
+ int pos = 1;
+ for (TempMetadataID tempMetadataID : elements) {
+ tempMetadataID.setPosition(pos++);
+ }
+ this.name = ID;
+ this.metadataType = type;
+ }
+
+ /**
+ * Constructor for element form of metadata ID.
+ * @param ID Fully-qualified, upper-case name of ID
+ * @param type Type of elements List of TempMetadataID representing elements
+ */
+ public TempMetadataID(String ID, Class<?> type) {
+ this.ID = ID;
+ this.type = type;
+ }
+
+ /**
+ * Constructor for element form of metadata ID with the underlying element.
+ * @param ID Fully-qualified, upper-case name of ID
+ * @param type Type of elements List of TempMetadataID representing elements
+ * @param metadataID the orginal metadataID
+ */
+ public TempMetadataID(String ID, Class<?> type, Object metadataID) {
+ this.ID = ID;
+ this.type = type;
+ this.originalMetadataID = metadataID;
+ }
+
+ @Override
+ public long getLastDataModification() {
+ return getTableData().getLastDataModification();
+ }
+
+ @Override
+ public long getLastModified() {
+ return getTableData().getLastModified();
+ }
+
+ /**
+ * Get ID value
+ * @return ID value
+ */
+ public String getID() {
+ return this.ID;
+ }
+
+ /**
+ * Get type - only valid for elements
+ * @return Type for elements, null for groups
+ */
+ public Class<?> getType() {
+ return this.type;
+ }
+
+ /**
+ * Get elements - only valid for groups
+ * @return List of TempMetadataID for groups, null for elements
+ */
+ public List<TempMetadataID> getElements() {
+ return this.getTableData().elements;
+ }
+
+ /**
+ * add a element to the temp table.
+ * @param elem
+ */
+ protected void addElement(TempMetadataID elem) {
+ if (this.getTableData().elements != null) {
+ this.getTableData().elements.add(elem);
+ elem.setPosition(this.getTableData().elements.size());
+ }
+ if (this.getTableData().localCache != null) {
+ this.getTableData().localCache.clear();
+ }
+ }
+
+ /**
+ * Check whether this group is virtual
+ * @return True if virtual
+ */
+ public boolean isVirtual() {
+ return metadataType == Type.VIRTUAL;
+ }
+
+ /**
+ * Whether it is a temporary table
+ * @return
+ * @since 5.5
+ */
+ public boolean isTempTable() {
+ return this.metadataType == Type.TEMP;
+ }
+
+ /**
+ * Return string representation of ID
+ * @return String representation
+ */
+ public String toString() {
+ return ID;
+ }
+
+ /**
+ * Compare this temp metadata ID with another object.
+ * @return True if obj is another TempMetadataID with same ID value
+ */
+ public boolean equals(Object obj) {
+ if(this == obj) {
+ return true;
+ }
+
+ if(!(obj instanceof TempMetadataID)) {
+ return false;
+ }
+ return this.getID().equals( ((TempMetadataID) obj).getID());
+ }
+
+ /**
+ * Return hash code
+ * @return Hash code value for object
+ */
+ public int hashCode() {
+ return this.ID.hashCode();
+ }
+
+ public void setOriginalMetadataID(Object metadataId) {
+ this.originalMetadataID = metadataId;
+ }
+
+ /**
+ * @return Returns the originalMetadataID.
+ * @since 4.3
+ */
+ public Object getOriginalMetadataID() {
+ return this.originalMetadataID;
+ }
+
+ public Collection<TempMetadataID> getAccessPatterns() {
+ if (this.getTableData().accessPatterns == null) {
+ return Collections.emptyList();
+ }
+ return this.getTableData().accessPatterns;
+ }
+
+ public void setAccessPatterns(Collection<TempMetadataID> accessPatterns) {
+ this.getTableData().accessPatterns = accessPatterns;
+ }
+
+ public int getCardinality() {
+ return this.getTableData().cardinality;
+ }
+
+ public void setCardinality(int cardinality) {
+ this.getTableData().cardinality = cardinality;
+ }
+
+ public void setTempTable(boolean isTempTable) {
+ if (isTempTable) {
+ this.metadataType = Type.TEMP;
+ } else {
+ this.metadataType = Type.VIRTUAL;
+ }
+ }
+
+ Object getProperty(Object key) {
+ if (this.getTableData().localCache != null) {
+ return this.getTableData().localCache.get(key);
+ }
+ return null;
+ }
+
+ Object setProperty(Object key, Object value) {
+ if (this.getTableData().localCache == null) {
+ this.getTableData().localCache = new LRUCache<Object, Object>(LOCAL_CACHE_SIZE);
+ }
+ return this.getTableData().localCache.put(key, value);
+ }
+
+ public boolean isScalarGroup() {
+ return this.metadataType == Type.SCALAR;
+ }
+
+ public void setMetadataType(Type metadataType) {
+ this.metadataType = metadataType;
+ }
+
+ public Type getMetadataType() {
+ return metadataType;
+ }
+
+ public List<TempMetadataID> getPrimaryKey() {
+ return getTableData().primaryKey;
+ }
+
+ public void setPrimaryKey(List<TempMetadataID> primaryKey) {
+ this.getTableData().primaryKey = primaryKey;
+ }
+
+ public int getPosition() {
+ return position;
+ }
+
+ public void setPosition(int position) {
+ this.position = position;
+ }
+
+ public QueryNode getQueryNode() {
+ return getTableData().queryNode;
+ }
+
+ public void setQueryNode(QueryNode queryNode) {
+ this.getTableData().queryNode = queryNode;
+ }
+
+ public CacheHint getCacheHint() {
+ return getTableData().cacheHint;
+ }
+
+ public void setCacheHint(CacheHint cacheHint) {
+ this.getTableData().cacheHint = cacheHint;
+ }
+
+ public List<List<TempMetadataID>> getIndexes() {
+ return getTableData().indexes;
+ }
+
+ public void addIndex(List<TempMetadataID> index) {
+ if (this.getTableData().indexes == null) {
+ this.getTableData().indexes = new LinkedList<List<TempMetadataID>>();
+ }
+ this.getTableData().indexes.add(index);
+ }
+
+ public List<List<TempMetadataID>> getUniqueKeys() {
+ return getTableData().keys;
+ }
+
+ public void addUniqueKey(List<TempMetadataID> key) {
+ if (this.getTableData().keys == null) {
+ this.getTableData().keys = new LinkedList<List<TempMetadataID>>();
+ }
+ this.getTableData().keys.add(key);
+ }
+
+ public TableData getTableData() {
+ if (data == null) {
+ return DUMMY_DATA;
+ }
+ return data;
+ }
+
+ public boolean isAutoIncrement() {
+ return autoIncrement;
+ }
+
+ public void setAutoIncrement(boolean autoIncrement) {
+ this.autoIncrement = autoIncrement;
+ }
+
+ public boolean isNotNull() {
+ return notNull;
+ }
+
+ public void setNotNull(boolean notNull) {
+ this.notNull = notNull;
+ }
+
+ public void setUpdatable(boolean updatable) {
+ this.updatable = updatable;
+ }
+
+ public boolean isUpdatable() {
+ return updatable;
+ }
+
+ public String getName() {
+ if (this.name == null) {
+ this.name = SingleElementSymbol.getShortName(this.ID);
+ }
+ return this.name;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TransformationMetadata.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/metadata/TransformationMetadata.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TransformationMetadata.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1097 +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.metadata;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Serializable;
-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.Map;
-import java.util.Properties;
-
-import org.jboss.virtual.VirtualFile;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.BlobImpl;
-import org.teiid.core.types.ClobImpl;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.types.InputStreamFactory;
-import org.teiid.core.types.SQLXMLImpl;
-import org.teiid.core.util.ArgCheck;
-import org.teiid.core.util.LRUCache;
-import org.teiid.core.util.ObjectConverterUtil;
-import org.teiid.core.util.StringUtil;
-import org.teiid.metadata.AbstractMetadataRecord;
-import org.teiid.metadata.Column;
-import org.teiid.metadata.ColumnSet;
-import org.teiid.metadata.Datatype;
-import org.teiid.metadata.ForeignKey;
-import org.teiid.metadata.KeyRecord;
-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.metadata.ProcedureParameter.Type;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.function.FunctionTree;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.mapping.xml.MappingDocument;
-import org.teiid.query.mapping.xml.MappingLoader;
-import org.teiid.query.mapping.xml.MappingNode;
-import org.teiid.query.sql.lang.SPParameter;
-
-
-/**
- * Teiid's implementation of the QueryMetadataInterface that reads columns, groups, models etc.
- * from the metadata object model.
- */
-public class TransformationMetadata extends BasicQueryMetadata implements Serializable {
-
- private final class LiveQueryNode extends QueryNode {
- Procedure p;
- private LiveQueryNode(Procedure p) {
- super(null);
- this.p = p;
- }
-
- public String getQuery() {
- return p.getQueryPlan();
- }
- }
-
- private final class VirtualFileInputStreamFactory extends
- InputStreamFactory {
- private final VirtualFile f;
-
- private VirtualFileInputStreamFactory(VirtualFile f) {
- this.f = f;
- }
-
- @Override
- public InputStream getInputStream() throws IOException {
- return f.openStream();
- }
-
- @Override
- public long getLength() {
- try {
- return f.getSize();
- } catch (IOException e) {
- }
- return super.getLength();
- }
-
- @Override
- public void free() throws IOException {
- f.close();
- }
- }
-
- public static class Resource {
- public Resource(VirtualFile file, boolean visible) {
- this.file = file;
- this.visible = visible;
- }
- VirtualFile file;
- boolean visible;
- }
-
- private static final long serialVersionUID = 1058627332954475287L;
-
- /** Delimiter character used when specifying fully qualified entity names */
- public static final char DELIMITER_CHAR = StringUtil.Constants.DOT_CHAR;
- public static final String DELIMITER_STRING = String.valueOf(DELIMITER_CHAR);
-
- // error message cached to avoid i18n lookup each time
- public static String NOT_EXISTS_MESSAGE = StringUtil.Constants.SPACE+QueryPlugin.Util.getString("TransformationMetadata.does_not_exist._1"); //$NON-NLS-1$
-
- private static Properties EMPTY_PROPS = new Properties();
-
- private final CompositeMetadataStore store;
- private Map<String, Resource> vdbEntries;
- private FunctionLibrary functionLibrary;
- private VDBMetaData vdbMetaData;
-
- /*
- * TODO: move caching to jboss cache structure
- */
- private Map<String, Object> metadataCache = Collections.synchronizedMap(new LRUCache<String, Object>(250));
- private Map<String, Object> groupInfoCache = Collections.synchronizedMap(new LRUCache<String, Object>(250));
- private Map<String, Collection<Table>> partialNameToFullNameCache = Collections.synchronizedMap(new LRUCache<String, Collection<Table>>(1000));
- private Map<String, Collection<StoredProcedureInfo>> procedureCache = Collections.synchronizedMap(new LRUCache<String, Collection<StoredProcedureInfo>>(200));
- /**
- * TransformationMetadata constructor
- * @param context Object containing the info needed to lookup metadta.
- */
- public TransformationMetadata(VDBMetaData vdbMetadata, final CompositeMetadataStore store, Map<String, Resource> vdbEntries, FunctionTree systemFunctions, Collection<FunctionTree> functionTrees) {
- ArgCheck.isNotNull(store);
- this.vdbMetaData = vdbMetadata;
- this.store = store;
- if (vdbEntries == null) {
- this.vdbEntries = Collections.emptyMap();
- } else {
- this.vdbEntries = vdbEntries;
- }
- if (functionTrees == null) {
- this.functionLibrary = new FunctionLibrary(systemFunctions);
- } else {
- this.functionLibrary = new FunctionLibrary(systemFunctions, functionTrees.toArray(new FunctionTree[functionTrees.size()]));
- }
- }
-
- private TransformationMetadata(final CompositeMetadataStore store, FunctionLibrary functionLibrary) {
- ArgCheck.isNotNull(store);
- this.store = store;
- this.vdbEntries = Collections.emptyMap();
- this.functionLibrary = functionLibrary;
- }
-
- //==================================================================================
- // 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 {
- 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)) {
- if (column.getName().equalsIgnoreCase(shortElementName)) {
- return column;
- }
- }
- throw new QueryMetadataException(elementName+TransformationMetadata.NOT_EXISTS_MESSAGE);
- }
-
- public Table getGroupID(final String groupName) throws TeiidComponentException, QueryMetadataException {
- return getMetadataStore().findGroup(groupName.toUpperCase());
- }
-
- public Collection<String> getGroupsForPartialName(final String partialGroupName)
- throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isNotEmpty(partialGroupName);
-
- Collection<Table> matches = this.partialNameToFullNameCache.get(partialGroupName);
-
- if (matches == null) {
- matches = getMetadataStore().getGroupsForPartialName(partialGroupName);
-
- this.partialNameToFullNameCache.put(partialGroupName, matches);
- }
-
- if (matches.isEmpty()) {
- return Collections.emptyList();
- }
-
- Collection<String> filteredResult = new ArrayList<String>(matches.size());
- for (Table table : matches) {
- if (vdbMetaData == null || vdbMetaData.isVisible(table.getParent().getName())) {
- filteredResult.add(table.getFullName());
- }
- }
- return filteredResult;
- }
-
- public Object getModelID(final Object groupOrElementID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(AbstractMetadataRecord.class, groupOrElementID);
- AbstractMetadataRecord metadataRecord = (AbstractMetadataRecord) groupOrElementID;
- AbstractMetadataRecord parent = metadataRecord.getParent();
- if (parent instanceof Schema) {
- return parent;
- }
- if (parent == null) {
- throw createInvalidRecordTypeException(groupOrElementID);
- }
- parent = parent.getParent();
- if (parent instanceof Schema) {
- return parent;
- }
- throw createInvalidRecordTypeException(groupOrElementID);
- }
-
- public String getFullName(final Object metadataID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(AbstractMetadataRecord.class, metadataID);
- AbstractMetadataRecord metadataRecord = (AbstractMetadataRecord) metadataID;
- return metadataRecord.getFullName();
- }
-
- @Override
- public String getName(Object metadataID) throws TeiidComponentException,
- QueryMetadataException {
- ArgCheck.isInstanceOf(AbstractMetadataRecord.class, metadataID);
- AbstractMetadataRecord metadataRecord = (AbstractMetadataRecord) metadataID;
- return metadataRecord.getName();
- }
-
- public List getElementIDsInGroupID(final Object groupID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- return ((Table)groupID).getColumns();
- }
-
- public Object getGroupIDForElementID(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- Column columnRecord = (Column) elementID;
- AbstractMetadataRecord parent = columnRecord.getParent();
- if (parent instanceof Table) {
- return parent;
- }
- }
- throw createInvalidRecordTypeException(elementID);
- }
-
- public boolean hasProcedure(String name) throws TeiidComponentException {
- try {
- return getStoredProcInfoDirect(name) != null;
- } catch (QueryMetadataException e) {
- return true;
- }
- }
-
- public StoredProcedureInfo getStoredProcedureInfoForProcedure(final String name)
- throws TeiidComponentException, QueryMetadataException {
- StoredProcedureInfo result = getStoredProcInfoDirect(name);
-
- if (result == null) {
- throw new QueryMetadataException(name+NOT_EXISTS_MESSAGE);
- }
-
- return result;
- }
-
- private StoredProcedureInfo getStoredProcInfoDirect(
- final String name)
- throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isNotEmpty(name);
- String canonicalName = name.toUpperCase();
- Collection<StoredProcedureInfo> results = this.procedureCache.get(canonicalName);
-
- if (results == null) {
- Collection<Procedure> procRecords = getMetadataStore().getStoredProcedure(canonicalName);
- results = new ArrayList<StoredProcedureInfo>(procRecords.size());
- for (Procedure procRecord : procRecords) {
- String procedureFullName = procRecord.getFullName();
-
- // create the storedProcedure info object that would hold procedure's metadata
- StoredProcedureInfo procInfo = new StoredProcedureInfo();
- procInfo.setProcedureCallableName(procedureFullName);
- procInfo.setProcedureID(procRecord);
-
- // modelID for the procedure
- procInfo.setModelID(procRecord.getParent());
-
- // get the parameter metadata info
- for (ProcedureParameter paramRecord : procRecord.getParameters()) {
- String runtimeType = paramRecord.getRuntimeType();
- int direction = this.convertParamRecordTypeToStoredProcedureType(paramRecord.getType());
- // create a parameter and add it to the procedure object
- SPParameter spParam = new SPParameter(paramRecord.getPosition(), direction, paramRecord.getFullName());
- spParam.setMetadataID(paramRecord);
- spParam.setClassType(DataTypeManager.getDataTypeClass(runtimeType));
- procInfo.addParameter(spParam);
- }
-
- // if the procedure returns a resultSet, obtain resultSet metadata
- if(procRecord.getResultSet() != null) {
- ColumnSet<Procedure> resultRecord = procRecord.getResultSet();
- // resultSet is the last parameter in the procedure
- int lastParamIndex = procInfo.getParameters().size() + 1;
- SPParameter param = new SPParameter(lastParamIndex, SPParameter.RESULT_SET, resultRecord.getFullName());
- param.setClassType(java.sql.ResultSet.class);
- param.setMetadataID(resultRecord);
-
- for (Column columnRecord : resultRecord.getColumns()) {
- String colType = columnRecord.getRuntimeType();
- param.addResultSetColumn(columnRecord.getFullName(), DataTypeManager.getDataTypeClass(colType), columnRecord);
- }
-
- procInfo.addParameter(param);
- }
-
- // if this is a virtual procedure get the procedure plan
- if(procRecord.isVirtual()) {
- QueryNode queryNode = new LiveQueryNode(procRecord);
- procInfo.setQueryPlan(queryNode);
- }
-
- //subtract 1, to match up with the server
- procInfo.setUpdateCount(procRecord.getUpdateCount() -1);
- results.add(procInfo);
- }
- this.procedureCache.put(canonicalName, results);
- }
-
- StoredProcedureInfo result = null;
-
- for (StoredProcedureInfo storedProcedureInfo : results) {
- Schema schema = (Schema)storedProcedureInfo.getModelID();
- if(name.equalsIgnoreCase(storedProcedureInfo.getProcedureCallableName()) || vdbMetaData == null || vdbMetaData.isVisible(schema.getName())){
- if (result != null) {
- throw new QueryMetadataException(QueryPlugin.Util.getString("ambiguous_procedure", name)); //$NON-NLS-1$
- }
- result = storedProcedureInfo;
- }
- }
- return result;
- }
-
- /**
- * Method to convert the parameter type returned from a ProcedureParameterRecord
- * to the parameter type expected by StoredProcedureInfo
- * @param parameterType
- * @return
- */
- private int convertParamRecordTypeToStoredProcedureType(final ProcedureParameter.Type parameterType) {
- switch (parameterType) {
- case In : return SPParameter.IN;
- case Out : return SPParameter.OUT;
- case InOut : return SPParameter.INOUT;
- case ReturnValue : return SPParameter.RETURN_VALUE;
- default :
- return -1;
- }
- }
-
- public String getElementType(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- return ((Column) elementID).getRuntimeType();
- } else if(elementID instanceof ProcedureParameter){
- return ((ProcedureParameter) elementID).getRuntimeType();
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- public Object getDefaultValue(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- return ((Column) elementID).getDefaultValue();
- } else if(elementID instanceof ProcedureParameter){
- return ((ProcedureParameter) elementID).getDefaultValue();
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- public Object getMinimumValue(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- return ((Column) elementID).getMinimumValue();
- } else if(elementID instanceof ProcedureParameter){
- return null;
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- public Object getMaximumValue(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- return ((Column) elementID).getMaximumValue();
- } else if(elementID instanceof ProcedureParameter){
- return null;
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- public boolean isVirtualGroup(final Object groupID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- return ((Table) groupID).isVirtual();
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#isProcedureInputElement(java.lang.Object)
- * @since 4.2
- */
- public boolean isProcedure(final Object groupID) throws TeiidComponentException, QueryMetadataException {
- if(groupID instanceof Procedure) {
- return true;
- }
- if(groupID instanceof Table){
- return false;
- }
- throw createInvalidRecordTypeException(groupID);
- }
-
- public boolean isVirtualModel(final Object modelID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Schema.class, modelID);
- Schema modelRecord = (Schema) modelID;
- return !modelRecord.isPhysical();
- }
-
- public QueryNode getVirtualPlan(final Object groupID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
-
- Table tableRecord = (Table) groupID;
- 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);
-
- // get any bindings and add them onto the query node
- List bindings = tableRecord.getBindings();
- if(bindings != null) {
- for(Iterator bindIter = bindings.iterator();bindIter.hasNext();) {
- queryNode.addBinding((String)bindIter.next());
- }
- }
-
- return queryNode;
- }
-
- public String getInsertPlan(final Object groupID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- Table tableRecordImpl = (Table)groupID;
- if (!tableRecordImpl.isVirtual()) {
- throw new QueryMetadataException(QueryPlugin.Util.getString("TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__8")+tableRecordImpl.getFullName()); //$NON-NLS-1$
- }
- return tableRecordImpl.isInsertPlanEnabled()?tableRecordImpl.getInsertPlan():null;
- }
-
- public String getUpdatePlan(final Object groupID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- Table tableRecordImpl = (Table)groupID;
- if (!tableRecordImpl.isVirtual()) {
- throw new QueryMetadataException(QueryPlugin.Util.getString("TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__10")+tableRecordImpl.getFullName()); //$NON-NLS-1$
- }
- return tableRecordImpl.isUpdatePlanEnabled()?tableRecordImpl.getUpdatePlan():null;
- }
-
- public String getDeletePlan(final Object groupID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- Table tableRecordImpl = (Table)groupID;
- if (!tableRecordImpl.isVirtual()) {
- throw new QueryMetadataException(QueryPlugin.Util.getString("TransformationMetadata.DeletePlan_could_not_be_found_for_physical_group__12")+tableRecordImpl.getFullName()); //$NON-NLS-1$
- }
- return tableRecordImpl.isDeletePlanEnabled()?tableRecordImpl.getDeletePlan():null;
- }
-
- public boolean modelSupports(final Object modelID, final int modelConstant)
- throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Schema.class, modelID);
-
- switch(modelConstant) {
- default:
- throw new UnsupportedOperationException(QueryPlugin.Util.getString("TransformationMetadata.Unknown_support_constant___12") + modelConstant); //$NON-NLS-1$
- }
- }
-
- public boolean groupSupports(final Object groupID, final int groupConstant)
- throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- Table tableRecord = (Table) groupID;
-
- switch(groupConstant) {
- case SupportConstants.Group.UPDATE:
- return tableRecord.supportsUpdate();
- default:
- throw new UnsupportedOperationException(QueryPlugin.Util.getString("TransformationMetadata.Unknown_support_constant___12") + groupConstant); //$NON-NLS-1$
- }
- }
-
- public boolean elementSupports(final Object elementID, final int elementConstant)
- throws TeiidComponentException, QueryMetadataException {
-
- if(elementID instanceof Column) {
- Column columnRecord = (Column) elementID;
- switch(elementConstant) {
- case SupportConstants.Element.NULL:
- return columnRecord.getNullType() == NullType.Nullable;
- case SupportConstants.Element.NULL_UNKNOWN:
- return columnRecord.getNullType() == NullType.Unknown;
- case SupportConstants.Element.SEARCHABLE_COMPARE:
- return (columnRecord.getSearchType() == SearchType.Searchable || columnRecord.getSearchType() == SearchType.All_Except_Like);
- case SupportConstants.Element.SEARCHABLE_LIKE:
- return (columnRecord.getSearchType() == SearchType.Searchable || columnRecord.getSearchType() == SearchType.Like_Only);
- case SupportConstants.Element.SELECT:
- return columnRecord.isSelectable();
- case SupportConstants.Element.UPDATE:
- return columnRecord.isUpdatable();
- case SupportConstants.Element.DEFAULT_VALUE:
- Object defaultValue = columnRecord.getDefaultValue();
- if(defaultValue == null) {
- return false;
- }
- return true;
- case SupportConstants.Element.AUTO_INCREMENT:
- return columnRecord.isAutoIncremented();
- case SupportConstants.Element.CASE_SENSITIVE:
- return columnRecord.isCaseSensitive();
- case SupportConstants.Element.SIGNED:
- return columnRecord.isSigned();
- default:
- throw new UnsupportedOperationException(QueryPlugin.Util.getString("TransformationMetadata.Unknown_support_constant___12") + elementConstant); //$NON-NLS-1$
- }
- } else if(elementID instanceof ProcedureParameter) {
- ProcedureParameter columnRecord = (ProcedureParameter) elementID;
- switch(elementConstant) {
- case SupportConstants.Element.NULL:
- return columnRecord.getNullType() == NullType.Nullable;
- case SupportConstants.Element.NULL_UNKNOWN:
- return columnRecord.getNullType() == NullType.Unknown;
- case SupportConstants.Element.SEARCHABLE_COMPARE:
- case SupportConstants.Element.SEARCHABLE_LIKE:
- return false;
- case SupportConstants.Element.SELECT:
- return columnRecord.getType() != Type.In;
- case SupportConstants.Element.UPDATE:
- return false;
- case SupportConstants.Element.DEFAULT_VALUE:
- Object defaultValue = columnRecord.getDefaultValue();
- if(defaultValue == null) {
- return false;
- }
- return true;
- case SupportConstants.Element.AUTO_INCREMENT:
- return false;
- case SupportConstants.Element.CASE_SENSITIVE:
- return false;
- case SupportConstants.Element.SIGNED:
- return true;
- default:
- throw new UnsupportedOperationException(QueryPlugin.Util.getString("TransformationMetadata.Unknown_support_constant___12") + elementConstant); //$NON-NLS-1$
- }
-
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- private IllegalArgumentException createInvalidRecordTypeException(Object elementID) {
- return new IllegalArgumentException(QueryPlugin.Util.getString("TransformationMetadata.Invalid_type", elementID.getClass().getName())); //$NON-NLS-1$
- }
-
- public int getMaxSetSize(final Object modelID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Schema.class, modelID);
- return 0;
- }
-
- public Collection getIndexesInGroup(final Object groupID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- return ((Table)groupID).getIndexes();
- }
-
- public Collection getUniqueKeysInGroup(final Object groupID)
- throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- Table tableRecordImpl = (Table)groupID;
- ArrayList<ColumnSet> result = new ArrayList<ColumnSet>(tableRecordImpl.getUniqueKeys());
- if (tableRecordImpl.getPrimaryKey() != null) {
- result.add(tableRecordImpl.getPrimaryKey());
- }
- for (KeyRecord key : tableRecordImpl.getIndexes()) {
- if (key.getType() == KeyRecord.Type.Unique) {
- result.add(key);
- }
- }
- return result;
- }
-
- public Collection getForeignKeysInGroup(final Object groupID)
- throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- return ((Table)groupID).getForeignKeys();
- }
-
- public Object getPrimaryKeyIDForForeignKeyID(final Object foreignKeyID)
- throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(ForeignKey.class, foreignKeyID);
- ForeignKey fkRecord = (ForeignKey) foreignKeyID;
- return fkRecord.getPrimaryKey();
- }
-
- public Collection getAccessPatternsInGroup(final Object groupID)
- throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- return ((Table)groupID).getAccessPatterns();
- }
-
- public List getElementIDsInIndex(final Object index) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(ColumnSet.class, index);
- return ((ColumnSet)index).getColumns();
- }
-
- public List getElementIDsInKey(final Object key) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(ColumnSet.class, key);
- return ((ColumnSet)key).getColumns();
- }
-
- public List getElementIDsInAccessPattern(final Object accessPattern)
- throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(ColumnSet.class, accessPattern);
- return ((ColumnSet)accessPattern).getColumns();
- }
-
- public boolean isXMLGroup(final Object groupID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
-
- Table tableRecord = (Table) groupID;
- return tableRecord.getTableType() == Table.Type.Document;
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#hasMaterialization(java.lang.Object)
- * @since 4.2
- */
- public boolean hasMaterialization(final Object groupID) throws TeiidComponentException,
- QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- Table tableRecord = (Table) groupID;
- return tableRecord.isMaterialized();
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getMaterialization(java.lang.Object)
- * @since 4.2
- */
- public Object getMaterialization(final Object groupID) throws TeiidComponentException,
- QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- Table tableRecord = (Table) groupID;
- if(tableRecord.isMaterialized()) {
- return tableRecord.getMaterializedTable();
- }
- return null;
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getMaterializationStage(java.lang.Object)
- * @since 4.2
- */
- public Object getMaterializationStage(final Object groupID) throws TeiidComponentException,
- QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- Table tableRecord = (Table) groupID;
- if(tableRecord.isMaterialized()) {
- return tableRecord.getMaterializedStageTable();
- }
- return null;
- }
-
- public MappingNode getMappingNode(final Object groupID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
-
- Table tableRecord = (Table) groupID;
- final String groupName = tableRecord.getFullName();
- if(tableRecord.isVirtual()) {
- // get mappin 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);
- } catch (Exception e){
- throw new TeiidComponentException(e, QueryPlugin.Util.getString("TransformationMetadata.Error_trying_to_read_virtual_document_{0},_with_body__n{1}_1", groupName, mappingDoc)); //$NON-NLS-1$
- } finally {
- try {
- inputStream.close();
- } catch(Exception e) {}
- }
- return (MappingDocument)mappingDoc.clone();
- }
-
- return null;
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getVirtualDatabaseName()
- */
- public String getVirtualDatabaseName() throws TeiidComponentException, QueryMetadataException {
- if (vdbMetaData == null) {
- return null;
- }
- return vdbMetaData.getName();
- }
-
- public int getVirtualDatabaseVersion() {
- if (vdbMetaData == null) {
- return 0;
- }
- return vdbMetaData.getVersion();
- }
-
- public VDBMetaData getVdbMetaData() {
- return vdbMetaData;
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getXMLTempGroups(java.lang.Object)
- */
- public Collection 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;
- }
-
- public int getCardinality(final Object groupID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(Table.class, groupID);
- return ((Table) groupID).getCardinality();
- }
-
- public List<SQLXMLImpl> getXMLSchemas(final Object groupID) throws TeiidComponentException, QueryMetadataException {
-
- ArgCheck.isInstanceOf(Table.class, groupID);
- Table tableRecord = (Table) groupID;
-
- // lookup transformation record for the group
- String groupName = tableRecord.getFullName();
-
- // get the schema Paths
- List<String> schemaPaths = tableRecord.getSchemaPaths();
-
- List<SQLXMLImpl> schemas = new LinkedList<SQLXMLImpl>();
- if (schemaPaths == null) {
- return schemas;
- }
- File f = new File(tableRecord.getResourcePath());
- String path = f.getParent();
- if (File.separatorChar != '/') {
- path = path.replace(File.separatorChar, '/');
- }
- for (String string : schemaPaths) {
- String parentPath = path;
- boolean relative = false;
- while (string.startsWith("../")) { //$NON-NLS-1$
- relative = true;
- string = string.substring(3);
- parentPath = new File(parentPath).getParent();
- }
- SQLXMLImpl schema = null;
- if (!relative) {
- schema = getVDBResourceAsSQLXML(string);
- }
- if (schema == null) {
- if (!parentPath.endsWith("/")) { //$NON-NLS-1$
- parentPath += "/"; //$NON-NLS-1$
- }
- schema = getVDBResourceAsSQLXML(parentPath + string);
- }
-
- if (schema == null) {
- throw new QueryMetadataException(QueryPlugin.Util.getString("TransformationMetadata.Error_trying_to_read_schemas_for_the_document/table____1")+groupName); //$NON-NLS-1$
- }
- schemas.add(schema);
- }
-
- return schemas;
- }
-
- public String getNameInSource(final Object metadataID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(AbstractMetadataRecord.class, metadataID);
- return ((AbstractMetadataRecord) metadataID).getNameInSource();
- }
-
- public int getElementLength(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- return ((Column) elementID).getLength();
- } else if(elementID instanceof ProcedureParameter){
- return ((ProcedureParameter) elementID).getLength();
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- public int getPosition(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- return ((Column) elementID).getPosition();
- } else if(elementID instanceof ProcedureParameter) {
- return ((ProcedureParameter) elementID).getPosition();
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- public int getPrecision(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- return ((Column) elementID).getPrecision();
- } else if(elementID instanceof ProcedureParameter) {
- return ((ProcedureParameter) elementID).getPrecision();
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- public int getRadix(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- return ((Column) elementID).getRadix();
- } else if(elementID instanceof ProcedureParameter) {
- return ((ProcedureParameter) elementID).getRadix();
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- public String getFormat(Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- return ((Column) elementID).getFormat();
- }
- throw createInvalidRecordTypeException(elementID);
- }
-
- public int getScale(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- return ((Column) elementID).getScale();
- } else if(elementID instanceof ProcedureParameter) {
- return ((ProcedureParameter) elementID).getScale();
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- public int getDistinctValues(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- return ((Column) elementID).getDistinctValues();
- } else if(elementID instanceof ProcedureParameter) {
- return -1;
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- public int getNullValues(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- return ((Column) elementID).getNullValues();
- } else if(elementID instanceof ProcedureParameter) {
- return -1;
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- public String getNativeType(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- if(elementID instanceof Column) {
- return ((Column) elementID).getNativeType();
- } else if(elementID instanceof ProcedureParameter) {
- return null;
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- public Properties getExtensionProperties(final Object metadataID) throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(AbstractMetadataRecord.class, metadataID);
- AbstractMetadataRecord metadataRecord = (AbstractMetadataRecord) metadataID;
- Map<String, String> result = metadataRecord.getProperties();
- if (result == null) {
- return EMPTY_PROPS;
- }
- Properties p = new Properties();
- p.putAll(result);
- return p;
- }
-
- /**
- * @see org.teiid.query.metadata.BasicQueryMetadata#getBinaryVDBResource(java.lang.String)
- * @since 4.3
- */
- public byte[] getBinaryVDBResource(String resourcePath) throws TeiidComponentException, QueryMetadataException {
- final VirtualFile f = getFile(resourcePath);
- if (f == null) {
- return null;
- }
- try {
- return ObjectConverterUtil.convertToByteArray(f.openStream());
- } catch (IOException e) {
- throw new TeiidComponentException(e);
- }
- }
-
- public ClobImpl getVDBResourceAsClob(String resourcePath) {
- final VirtualFile f = getFile(resourcePath);
- if (f == null) {
- return null;
- }
- return new ClobImpl(new VirtualFileInputStreamFactory(f), -1);
- }
-
- public SQLXMLImpl getVDBResourceAsSQLXML(String resourcePath) {
- final VirtualFile f = getFile(resourcePath);
- if (f == null) {
- return null;
- }
- return new SQLXMLImpl(new VirtualFileInputStreamFactory(f));
- }
-
- public BlobImpl getVDBResourceAsBlob(String resourcePath) {
- final VirtualFile f = getFile(resourcePath);
- if (f == null) {
- return null;
- }
- return new BlobImpl(new VirtualFileInputStreamFactory(f));
- }
-
- private VirtualFile getFile(String resourcePath) {
- if (resourcePath == null) {
- return null;
- }
- Resource r = this.vdbEntries.get(resourcePath);
- if (r != null) {
- return r.file;
- }
- return null;
- }
-
- /**
- * @see org.teiid.query.metadata.BasicQueryMetadata#getCharacterVDBResource(java.lang.String)
- * @since 4.3
- */
- public String getCharacterVDBResource(String resourcePath) throws TeiidComponentException, QueryMetadataException {
- try {
- byte[] bytes = getBinaryVDBResource(resourcePath);
- if (bytes == null) {
- return null;
- }
- return ObjectConverterUtil.convertToString(new ByteArrayInputStream(bytes));
- } catch (IOException e) {
- throw new TeiidComponentException(e);
- }
- }
-
- public CompositeMetadataStore getMetadataStore() {
- return this.store;
- }
-
- /**
- * @see org.teiid.query.metadata.BasicQueryMetadata#getVDBResourcePaths()
- * @since 4.3
- */
- public String[] getVDBResourcePaths() throws TeiidComponentException, QueryMetadataException {
- LinkedList<String> paths = new LinkedList<String>();
- for (Map.Entry<String, Resource> entry : this.vdbEntries.entrySet()) {
- paths.add(entry.getKey());
- }
- return paths.toArray(new String[paths.size()]);
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getModeledType(java.lang.Object)
- * @since 5.0
- */
- public String getModeledType(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- Datatype record = getDatatypeRecord(elementID);
- if (record != null) {
- return record.getDatatypeID();
- }
- return null;
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getModeledBaseType(java.lang.Object)
- * @since 5.0
- */
- public String getModeledBaseType(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- Datatype record = getDatatypeRecord(elementID);
- if (record != null) {
- return record.getBasetypeID();
- }
- return null;
- }
-
- /**
- * @see org.teiid.query.metadata.QueryMetadataInterface#getModeledPrimitiveType(java.lang.Object)
- * @since 5.0
- */
- public String getModeledPrimitiveType(final Object elementID) throws TeiidComponentException, QueryMetadataException {
- Datatype record = getDatatypeRecord(elementID);
- if (record != null) {
- return record.getPrimitiveTypeID();
- }
- return null;
- }
-
- private Datatype getDatatypeRecord(final Object elementID) {
- if (elementID instanceof Column) {
- return ((Column)elementID).getDatatype();
- } else if (elementID instanceof ProcedureParameter) {
- return ((ProcedureParameter)elementID).getDatatype();
- } else {
- throw createInvalidRecordTypeException(elementID);
- }
- }
-
- @Override
- public Object addToMetadataCache(Object metadataID, String key, Object value) {
- ArgCheck.isInstanceOf(AbstractMetadataRecord.class, metadataID);
- boolean groupInfo = key.startsWith(GroupInfo.CACHE_PREFIX);
- key = getCacheKey(key, (AbstractMetadataRecord)metadataID);
- if (groupInfo) {
- return this.groupInfoCache.put(key, value);
- }
- return this.metadataCache.put(key, value);
- }
-
- @Override
- public Object getFromMetadataCache(Object metadataID, String key)
- throws TeiidComponentException, QueryMetadataException {
- ArgCheck.isInstanceOf(AbstractMetadataRecord.class, metadataID);
- boolean groupInfo = key.startsWith(GroupInfo.CACHE_PREFIX);
- key = getCacheKey(key, (AbstractMetadataRecord)metadataID);
- if (groupInfo) {
- return this.groupInfoCache.get(key);
- }
- return this.metadataCache.get(key);
- }
-
- private String getCacheKey(String key, AbstractMetadataRecord record) {
- return record.getUUID() + "/" + key; //$NON-NLS-1$
- }
-
- @Override
- public FunctionLibrary getFunctionLibrary() {
- return this.functionLibrary;
- }
-
- @Override
- public Object getPrimaryKey(Object metadataID) {
- ArgCheck.isInstanceOf(Table.class, metadataID);
- Table table = (Table)metadataID;
- return table.getPrimaryKey();
- }
-
- @Override
- public QueryMetadataInterface getDesignTimeMetadata() {
- TransformationMetadata tm = new TransformationMetadata(store, functionLibrary);
- tm.groupInfoCache = this.groupInfoCache;
- tm.metadataCache = this.metadataCache;
- tm.partialNameToFullNameCache = this.partialNameToFullNameCache;
- tm.procedureCache = this.procedureCache;
- return tm;
- }
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TransformationMetadata.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/metadata/TransformationMetadata.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TransformationMetadata.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/metadata/TransformationMetadata.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1111 @@
+/*
+ * 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.metadata;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Serializable;
+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.Map;
+import java.util.Properties;
+
+import org.jboss.virtual.VirtualFile;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.types.BlobImpl;
+import org.teiid.core.types.ClobImpl;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.InputStreamFactory;
+import org.teiid.core.types.SQLXMLImpl;
+import org.teiid.core.util.ArgCheck;
+import org.teiid.core.util.LRUCache;
+import org.teiid.core.util.ObjectConverterUtil;
+import org.teiid.core.util.StringUtil;
+import org.teiid.metadata.AbstractMetadataRecord;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.ColumnSet;
+import org.teiid.metadata.Datatype;
+import org.teiid.metadata.ForeignKey;
+import org.teiid.metadata.KeyRecord;
+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.metadata.ProcedureParameter.Type;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.function.FunctionTree;
+import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.mapping.xml.MappingDocument;
+import org.teiid.query.mapping.xml.MappingLoader;
+import org.teiid.query.mapping.xml.MappingNode;
+import org.teiid.query.sql.lang.SPParameter;
+
+
+/**
+ * Teiid's implementation of the QueryMetadataInterface that reads columns, groups, models etc.
+ * from the metadata object model.
+ */
+public class TransformationMetadata extends BasicQueryMetadata implements Serializable {
+
+ private final class LiveQueryNode extends QueryNode {
+ Procedure p;
+ private LiveQueryNode(Procedure p) {
+ super(null);
+ this.p = p;
+ }
+
+ public String getQuery() {
+ return p.getQueryPlan();
+ }
+ }
+
+ private final class VirtualFileInputStreamFactory extends
+ InputStreamFactory {
+ private final VirtualFile f;
+
+ private VirtualFileInputStreamFactory(VirtualFile f) {
+ this.f = f;
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException {
+ return f.openStream();
+ }
+
+ @Override
+ public long getLength() {
+ try {
+ return f.getSize();
+ } catch (IOException e) {
+ }
+ return super.getLength();
+ }
+
+ @Override
+ public void free() throws IOException {
+ f.close();
+ }
+ }
+
+ public static class Resource {
+ public Resource(VirtualFile file, boolean visible) {
+ this.file = file;
+ this.visible = visible;
+ }
+ VirtualFile file;
+ boolean visible;
+ }
+
+ private static final long serialVersionUID = 1058627332954475287L;
+
+ /** Delimiter character used when specifying fully qualified entity names */
+ public static final char DELIMITER_CHAR = StringUtil.Constants.DOT_CHAR;
+ public static final String DELIMITER_STRING = String.valueOf(DELIMITER_CHAR);
+
+ // error message cached to avoid i18n lookup each time
+ public static String NOT_EXISTS_MESSAGE = StringUtil.Constants.SPACE+QueryPlugin.Util.getString("TransformationMetadata.does_not_exist._1"); //$NON-NLS-1$
+
+ private static Properties EMPTY_PROPS = new Properties();
+
+ private final CompositeMetadataStore store;
+ private Map<String, Resource> vdbEntries;
+ private FunctionLibrary functionLibrary;
+ private VDBMetaData vdbMetaData;
+
+ /*
+ * TODO: move caching to jboss cache structure
+ */
+ private Map<String, Object> metadataCache = Collections.synchronizedMap(new LRUCache<String, Object>(250));
+ private Map<String, Object> groupInfoCache = Collections.synchronizedMap(new LRUCache<String, Object>(250));
+ private Map<String, Collection<Table>> partialNameToFullNameCache = Collections.synchronizedMap(new LRUCache<String, Collection<Table>>(1000));
+ private Map<String, Collection<StoredProcedureInfo>> procedureCache = Collections.synchronizedMap(new LRUCache<String, Collection<StoredProcedureInfo>>(200));
+ /**
+ * TransformationMetadata constructor
+ * @param context Object containing the info needed to lookup metadta.
+ */
+ public TransformationMetadata(VDBMetaData vdbMetadata, final CompositeMetadataStore store, Map<String, Resource> vdbEntries, FunctionTree systemFunctions, Collection<FunctionTree> functionTrees) {
+ ArgCheck.isNotNull(store);
+ this.vdbMetaData = vdbMetadata;
+ this.store = store;
+ if (vdbEntries == null) {
+ this.vdbEntries = Collections.emptyMap();
+ } else {
+ this.vdbEntries = vdbEntries;
+ }
+ if (functionTrees == null) {
+ this.functionLibrary = new FunctionLibrary(systemFunctions);
+ } else {
+ this.functionLibrary = new FunctionLibrary(systemFunctions, functionTrees.toArray(new FunctionTree[functionTrees.size()]));
+ }
+ }
+
+ private TransformationMetadata(final CompositeMetadataStore store, FunctionLibrary functionLibrary) {
+ ArgCheck.isNotNull(store);
+ this.store = store;
+ this.vdbEntries = Collections.emptyMap();
+ this.functionLibrary = functionLibrary;
+ }
+
+ //==================================================================================
+ // I N T E R F A C E M E T H O D S
+ //==================================================================================
+
+ 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 : getElementIDsInGroupID(table)) {
+ if (column.getName().equalsIgnoreCase(shortElementName)) {
+ return column;
+ }
+ }
+ throw new QueryMetadataException(elementName+TransformationMetadata.NOT_EXISTS_MESSAGE);
+ }
+
+ public Table getGroupID(final String groupName) throws TeiidComponentException, QueryMetadataException {
+ return getMetadataStore().findGroup(groupName.toUpperCase());
+ }
+
+ public Collection<String> getGroupsForPartialName(final String partialGroupName)
+ throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isNotEmpty(partialGroupName);
+
+ Collection<Table> matches = this.partialNameToFullNameCache.get(partialGroupName);
+
+ if (matches == null) {
+ matches = getMetadataStore().getGroupsForPartialName(partialGroupName);
+
+ this.partialNameToFullNameCache.put(partialGroupName, matches);
+ }
+
+ if (matches.isEmpty()) {
+ return Collections.emptyList();
+ }
+
+ Collection<String> filteredResult = new ArrayList<String>(matches.size());
+ for (Table table : matches) {
+ if (vdbMetaData == null || vdbMetaData.isVisible(table.getParent().getName())) {
+ filteredResult.add(table.getFullName());
+ }
+ }
+ return filteredResult;
+ }
+
+ public Object getModelID(final Object groupOrElementID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(AbstractMetadataRecord.class, groupOrElementID);
+ AbstractMetadataRecord metadataRecord = (AbstractMetadataRecord) groupOrElementID;
+ AbstractMetadataRecord parent = metadataRecord.getParent();
+ if (parent instanceof Schema) {
+ return parent;
+ }
+ if (parent == null) {
+ throw createInvalidRecordTypeException(groupOrElementID);
+ }
+ parent = parent.getParent();
+ if (parent instanceof Schema) {
+ return parent;
+ }
+ throw createInvalidRecordTypeException(groupOrElementID);
+ }
+
+ public String getFullName(final Object metadataID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(AbstractMetadataRecord.class, metadataID);
+ AbstractMetadataRecord metadataRecord = (AbstractMetadataRecord) metadataID;
+ return metadataRecord.getFullName();
+ }
+
+ @Override
+ public String getName(Object metadataID) throws TeiidComponentException,
+ QueryMetadataException {
+ ArgCheck.isInstanceOf(AbstractMetadataRecord.class, metadataID);
+ AbstractMetadataRecord metadataRecord = (AbstractMetadataRecord) metadataID;
+ return metadataRecord.getName();
+ }
+
+ public List<Column> getElementIDsInGroupID(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ return ((Table)groupID).getColumns();
+ }
+
+ public Object getGroupIDForElementID(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ Column columnRecord = (Column) elementID;
+ AbstractMetadataRecord parent = columnRecord.getParent();
+ if (parent instanceof Table) {
+ return parent;
+ }
+ }
+ if(elementID instanceof ProcedureParameter) {
+ ProcedureParameter columnRecord = (ProcedureParameter) elementID;
+ return columnRecord.getParent();
+ }
+ throw createInvalidRecordTypeException(elementID);
+ }
+
+ public boolean hasProcedure(String name) throws TeiidComponentException {
+ try {
+ return getStoredProcInfoDirect(name) != null;
+ } catch (QueryMetadataException e) {
+ return true;
+ }
+ }
+
+ public StoredProcedureInfo getStoredProcedureInfoForProcedure(final String name)
+ throws TeiidComponentException, QueryMetadataException {
+ StoredProcedureInfo result = getStoredProcInfoDirect(name);
+
+ if (result == null) {
+ throw new QueryMetadataException(name+NOT_EXISTS_MESSAGE);
+ }
+
+ return result;
+ }
+
+ private StoredProcedureInfo getStoredProcInfoDirect(
+ final String name)
+ throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isNotEmpty(name);
+ String canonicalName = name.toUpperCase();
+ Collection<StoredProcedureInfo> results = this.procedureCache.get(canonicalName);
+
+ if (results == null) {
+ 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();
+
+ // create the storedProcedure info object that would hold procedure's metadata
+ StoredProcedureInfo procInfo = new StoredProcedureInfo();
+ procInfo.setProcedureCallableName(procedureFullName);
+ procInfo.setProcedureID(procRecord);
+
+ // modelID for the procedure
+ procInfo.setModelID(procRecord.getParent());
+
+ // get the parameter metadata info
+ for (ProcedureParameter paramRecord : procRecord.getParameters()) {
+ String runtimeType = paramRecord.getRuntimeType();
+ int direction = this.convertParamRecordTypeToStoredProcedureType(paramRecord.getType());
+ // create a parameter and add it to the procedure object
+ SPParameter spParam = new SPParameter(paramRecord.getPosition(), direction, paramRecord.getFullName());
+ spParam.setMetadataID(paramRecord);
+ spParam.setClassType(DataTypeManager.getDataTypeClass(runtimeType));
+ procInfo.addParameter(spParam);
+ }
+
+ // if the procedure returns a resultSet, obtain resultSet metadata
+ if(procRecord.getResultSet() != null) {
+ ColumnSet<Procedure> resultRecord = procRecord.getResultSet();
+ // resultSet is the last parameter in the procedure
+ int lastParamIndex = procInfo.getParameters().size() + 1;
+ SPParameter param = new SPParameter(lastParamIndex, SPParameter.RESULT_SET, resultRecord.getFullName());
+ param.setClassType(java.sql.ResultSet.class);
+ param.setMetadataID(resultRecord);
+
+ for (Column columnRecord : resultRecord.getColumns()) {
+ String colType = columnRecord.getRuntimeType();
+ param.addResultSetColumn(columnRecord.getFullName(), DataTypeManager.getDataTypeClass(colType), columnRecord);
+ }
+
+ procInfo.addParameter(param);
+ }
+
+ // if this is a virtual procedure get the procedure plan
+ if(procRecord.isVirtual()) {
+ QueryNode queryNode = new LiveQueryNode(procRecord);
+ procInfo.setQueryPlan(queryNode);
+ }
+
+ //subtract 1, to match up with the server
+ procInfo.setUpdateCount(procRecord.getUpdateCount() -1);
+ results.add(procInfo);
+ }
+ this.procedureCache.put(canonicalName, results);
+ }
+
+ StoredProcedureInfo result = null;
+
+ for (StoredProcedureInfo storedProcedureInfo : results) {
+ Schema schema = (Schema)storedProcedureInfo.getModelID();
+ if(name.equalsIgnoreCase(storedProcedureInfo.getProcedureCallableName()) || vdbMetaData == null || vdbMetaData.isVisible(schema.getName())){
+ if (result != null) {
+ throw new QueryMetadataException(QueryPlugin.Util.getString("ambiguous_procedure", name)); //$NON-NLS-1$
+ }
+ result = storedProcedureInfo;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Method to convert the parameter type returned from a ProcedureParameterRecord
+ * to the parameter type expected by StoredProcedureInfo
+ * @param parameterType
+ * @return
+ */
+ private int convertParamRecordTypeToStoredProcedureType(final ProcedureParameter.Type parameterType) {
+ switch (parameterType) {
+ case In : return SPParameter.IN;
+ case Out : return SPParameter.OUT;
+ case InOut : return SPParameter.INOUT;
+ case ReturnValue : return SPParameter.RETURN_VALUE;
+ default :
+ return -1;
+ }
+ }
+
+ public String getElementType(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ return ((Column) elementID).getRuntimeType();
+ } else if(elementID instanceof ProcedureParameter){
+ return ((ProcedureParameter) elementID).getRuntimeType();
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ public Object getDefaultValue(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ return ((Column) elementID).getDefaultValue();
+ } else if(elementID instanceof ProcedureParameter){
+ return ((ProcedureParameter) elementID).getDefaultValue();
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ public Object getMinimumValue(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ return ((Column) elementID).getMinimumValue();
+ } else if(elementID instanceof ProcedureParameter){
+ return null;
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ public Object getMaximumValue(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ return ((Column) elementID).getMaximumValue();
+ } else if(elementID instanceof ProcedureParameter){
+ return null;
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ public boolean isVirtualGroup(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ return ((Table) groupID).isVirtual();
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#isProcedureInputElement(java.lang.Object)
+ * @since 4.2
+ */
+ public boolean isProcedure(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+ if(groupID instanceof Procedure) {
+ return true;
+ }
+ if(groupID instanceof Table){
+ return false;
+ }
+ throw createInvalidRecordTypeException(groupID);
+ }
+
+ public boolean isVirtualModel(final Object modelID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Schema.class, modelID);
+ Schema modelRecord = (Schema) modelID;
+ return !modelRecord.isPhysical();
+ }
+
+ public QueryNode getVirtualPlan(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+
+ Table tableRecord = (Table) groupID;
+ 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);
+
+ // get any bindings and add them onto the query node
+ List bindings = tableRecord.getBindings();
+ if(bindings != null) {
+ for(Iterator bindIter = bindings.iterator();bindIter.hasNext();) {
+ queryNode.addBinding((String)bindIter.next());
+ }
+ }
+
+ return queryNode;
+ }
+
+ public String getInsertPlan(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ Table tableRecordImpl = (Table)groupID;
+ if (!tableRecordImpl.isVirtual()) {
+ throw new QueryMetadataException(QueryPlugin.Util.getString("TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__8")+tableRecordImpl.getFullName()); //$NON-NLS-1$
+ }
+ return tableRecordImpl.isInsertPlanEnabled()?tableRecordImpl.getInsertPlan():null;
+ }
+
+ public String getUpdatePlan(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ Table tableRecordImpl = (Table)groupID;
+ if (!tableRecordImpl.isVirtual()) {
+ throw new QueryMetadataException(QueryPlugin.Util.getString("TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__10")+tableRecordImpl.getFullName()); //$NON-NLS-1$
+ }
+ return tableRecordImpl.isUpdatePlanEnabled()?tableRecordImpl.getUpdatePlan():null;
+ }
+
+ public String getDeletePlan(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ Table tableRecordImpl = (Table)groupID;
+ if (!tableRecordImpl.isVirtual()) {
+ throw new QueryMetadataException(QueryPlugin.Util.getString("TransformationMetadata.DeletePlan_could_not_be_found_for_physical_group__12")+tableRecordImpl.getFullName()); //$NON-NLS-1$
+ }
+ return tableRecordImpl.isDeletePlanEnabled()?tableRecordImpl.getDeletePlan():null;
+ }
+
+ public boolean modelSupports(final Object modelID, final int modelConstant)
+ throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Schema.class, modelID);
+
+ switch(modelConstant) {
+ default:
+ throw new UnsupportedOperationException(QueryPlugin.Util.getString("TransformationMetadata.Unknown_support_constant___12") + modelConstant); //$NON-NLS-1$
+ }
+ }
+
+ public boolean groupSupports(final Object groupID, final int groupConstant)
+ throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ Table tableRecord = (Table) groupID;
+
+ switch(groupConstant) {
+ case SupportConstants.Group.UPDATE:
+ return tableRecord.supportsUpdate();
+ default:
+ throw new UnsupportedOperationException(QueryPlugin.Util.getString("TransformationMetadata.Unknown_support_constant___12") + groupConstant); //$NON-NLS-1$
+ }
+ }
+
+ public boolean elementSupports(final Object elementID, final int elementConstant)
+ throws TeiidComponentException, QueryMetadataException {
+
+ if(elementID instanceof Column) {
+ Column columnRecord = (Column) elementID;
+ switch(elementConstant) {
+ case SupportConstants.Element.NULL:
+ return columnRecord.getNullType() == NullType.Nullable;
+ case SupportConstants.Element.NULL_UNKNOWN:
+ return columnRecord.getNullType() == NullType.Unknown;
+ case SupportConstants.Element.SEARCHABLE_COMPARE:
+ return (columnRecord.getSearchType() == SearchType.Searchable || columnRecord.getSearchType() == SearchType.All_Except_Like);
+ case SupportConstants.Element.SEARCHABLE_LIKE:
+ return (columnRecord.getSearchType() == SearchType.Searchable || columnRecord.getSearchType() == SearchType.Like_Only);
+ case SupportConstants.Element.SELECT:
+ return columnRecord.isSelectable();
+ case SupportConstants.Element.UPDATE:
+ return columnRecord.isUpdatable();
+ case SupportConstants.Element.DEFAULT_VALUE:
+ Object defaultValue = columnRecord.getDefaultValue();
+ if(defaultValue == null) {
+ return false;
+ }
+ return true;
+ case SupportConstants.Element.AUTO_INCREMENT:
+ return columnRecord.isAutoIncremented();
+ case SupportConstants.Element.CASE_SENSITIVE:
+ return columnRecord.isCaseSensitive();
+ case SupportConstants.Element.SIGNED:
+ return columnRecord.isSigned();
+ default:
+ throw new UnsupportedOperationException(QueryPlugin.Util.getString("TransformationMetadata.Unknown_support_constant___12") + elementConstant); //$NON-NLS-1$
+ }
+ } else if(elementID instanceof ProcedureParameter) {
+ ProcedureParameter columnRecord = (ProcedureParameter) elementID;
+ switch(elementConstant) {
+ case SupportConstants.Element.NULL:
+ return columnRecord.getNullType() == NullType.Nullable;
+ case SupportConstants.Element.NULL_UNKNOWN:
+ return columnRecord.getNullType() == NullType.Unknown;
+ case SupportConstants.Element.SEARCHABLE_COMPARE:
+ case SupportConstants.Element.SEARCHABLE_LIKE:
+ return false;
+ case SupportConstants.Element.SELECT:
+ return columnRecord.getType() != Type.In;
+ case SupportConstants.Element.UPDATE:
+ return false;
+ case SupportConstants.Element.DEFAULT_VALUE:
+ Object defaultValue = columnRecord.getDefaultValue();
+ if(defaultValue == null) {
+ return false;
+ }
+ return true;
+ case SupportConstants.Element.AUTO_INCREMENT:
+ return false;
+ case SupportConstants.Element.CASE_SENSITIVE:
+ return false;
+ case SupportConstants.Element.SIGNED:
+ return true;
+ default:
+ throw new UnsupportedOperationException(QueryPlugin.Util.getString("TransformationMetadata.Unknown_support_constant___12") + elementConstant); //$NON-NLS-1$
+ }
+
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ private IllegalArgumentException createInvalidRecordTypeException(Object elementID) {
+ return new IllegalArgumentException(QueryPlugin.Util.getString("TransformationMetadata.Invalid_type", elementID.getClass().getName())); //$NON-NLS-1$
+ }
+
+ public int getMaxSetSize(final Object modelID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Schema.class, modelID);
+ return 0;
+ }
+
+ public Collection getIndexesInGroup(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ return ((Table)groupID).getIndexes();
+ }
+
+ public Collection getUniqueKeysInGroup(final Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ Table tableRecordImpl = (Table)groupID;
+ ArrayList<ColumnSet> result = new ArrayList<ColumnSet>(tableRecordImpl.getUniqueKeys());
+ if (tableRecordImpl.getPrimaryKey() != null) {
+ result.add(tableRecordImpl.getPrimaryKey());
+ }
+ for (KeyRecord key : tableRecordImpl.getIndexes()) {
+ if (key.getType() == KeyRecord.Type.Unique) {
+ result.add(key);
+ }
+ }
+ return result;
+ }
+
+ public Collection getForeignKeysInGroup(final Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ return ((Table)groupID).getForeignKeys();
+ }
+
+ public Object getPrimaryKeyIDForForeignKeyID(final Object foreignKeyID)
+ throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(ForeignKey.class, foreignKeyID);
+ ForeignKey fkRecord = (ForeignKey) foreignKeyID;
+ return fkRecord.getPrimaryKey();
+ }
+
+ public Collection getAccessPatternsInGroup(final Object groupID)
+ throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ return ((Table)groupID).getAccessPatterns();
+ }
+
+ public List getElementIDsInIndex(final Object index) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(ColumnSet.class, index);
+ return ((ColumnSet)index).getColumns();
+ }
+
+ public List getElementIDsInKey(final Object key) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(ColumnSet.class, key);
+ return ((ColumnSet)key).getColumns();
+ }
+
+ public List getElementIDsInAccessPattern(final Object accessPattern)
+ throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(ColumnSet.class, accessPattern);
+ return ((ColumnSet)accessPattern).getColumns();
+ }
+
+ public boolean isXMLGroup(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+
+ Table tableRecord = (Table) groupID;
+ return tableRecord.getTableType() == Table.Type.Document;
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#hasMaterialization(java.lang.Object)
+ * @since 4.2
+ */
+ public boolean hasMaterialization(final Object groupID) throws TeiidComponentException,
+ QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ Table tableRecord = (Table) groupID;
+ return tableRecord.isMaterialized();
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getMaterialization(java.lang.Object)
+ * @since 4.2
+ */
+ public Object getMaterialization(final Object groupID) throws TeiidComponentException,
+ QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ Table tableRecord = (Table) groupID;
+ if(tableRecord.isMaterialized()) {
+ return tableRecord.getMaterializedTable();
+ }
+ return null;
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getMaterializationStage(java.lang.Object)
+ * @since 4.2
+ */
+ public Object getMaterializationStage(final Object groupID) throws TeiidComponentException,
+ QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ Table tableRecord = (Table) groupID;
+ if(tableRecord.isMaterialized()) {
+ return tableRecord.getMaterializedStageTable();
+ }
+ return null;
+ }
+
+ public MappingNode getMappingNode(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+ 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 mapping transform
+ String document = tableRecord.getSelectTransformation();
+ InputStream inputStream = new ByteArrayInputStream(document.getBytes());
+ MappingLoader reader = new MappingLoader();
+ try{
+ mappingDoc = reader.loadDocument(inputStream);
+ mappingDoc.setName(groupName);
+ } catch (Exception e){
+ throw new TeiidComponentException(e, QueryPlugin.Util.getString("TransformationMetadata.Error_trying_to_read_virtual_document_{0},_with_body__n{1}_1", groupName, mappingDoc)); //$NON-NLS-1$
+ } finally {
+ try {
+ inputStream.close();
+ } catch(Exception e) {}
+ }
+ tableRecord.addAttchment(MappingDocument.class, mappingDoc);
+ return mappingDoc;
+ }
+
+ return null;
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getVirtualDatabaseName()
+ */
+ public String getVirtualDatabaseName() throws TeiidComponentException, QueryMetadataException {
+ if (vdbMetaData == null) {
+ return null;
+ }
+ return vdbMetaData.getName();
+ }
+
+ public int getVirtualDatabaseVersion() {
+ if (vdbMetaData == null) {
+ return 0;
+ }
+ return vdbMetaData.getVersion();
+ }
+
+ public VDBMetaData getVdbMetaData() {
+ return vdbMetaData;
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getXMLTempGroups(java.lang.Object)
+ */
+ 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.emptySet();
+ }
+
+ public int getCardinality(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ return ((Table) groupID).getCardinality();
+ }
+
+ public List<SQLXMLImpl> getXMLSchemas(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+
+ ArgCheck.isInstanceOf(Table.class, groupID);
+ Table tableRecord = (Table) groupID;
+
+ // lookup transformation record for the group
+ String groupName = tableRecord.getFullName();
+
+ // get the schema Paths
+ List<String> schemaPaths = tableRecord.getSchemaPaths();
+
+ List<SQLXMLImpl> schemas = new LinkedList<SQLXMLImpl>();
+ if (schemaPaths == null) {
+ return schemas;
+ }
+ File f = new File(tableRecord.getResourcePath());
+ String path = f.getParent();
+ if (File.separatorChar != '/') {
+ path = path.replace(File.separatorChar, '/');
+ }
+ for (String string : schemaPaths) {
+ String parentPath = path;
+ boolean relative = false;
+ while (string.startsWith("../")) { //$NON-NLS-1$
+ relative = true;
+ string = string.substring(3);
+ parentPath = new File(parentPath).getParent();
+ }
+ SQLXMLImpl schema = null;
+ if (!relative) {
+ schema = getVDBResourceAsSQLXML(string);
+ }
+ if (schema == null) {
+ if (!parentPath.endsWith("/")) { //$NON-NLS-1$
+ parentPath += "/"; //$NON-NLS-1$
+ }
+ schema = getVDBResourceAsSQLXML(parentPath + string);
+ }
+
+ if (schema == null) {
+ throw new QueryMetadataException(QueryPlugin.Util.getString("TransformationMetadata.Error_trying_to_read_schemas_for_the_document/table____1")+groupName); //$NON-NLS-1$
+ }
+ schemas.add(schema);
+ }
+
+ return schemas;
+ }
+
+ public String getNameInSource(final Object metadataID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(AbstractMetadataRecord.class, metadataID);
+ return ((AbstractMetadataRecord) metadataID).getNameInSource();
+ }
+
+ public int getElementLength(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ return ((Column) elementID).getLength();
+ } else if(elementID instanceof ProcedureParameter){
+ return ((ProcedureParameter) elementID).getLength();
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ public int getPosition(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ return ((Column) elementID).getPosition();
+ } else if(elementID instanceof ProcedureParameter) {
+ return ((ProcedureParameter) elementID).getPosition();
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ public int getPrecision(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ return ((Column) elementID).getPrecision();
+ } else if(elementID instanceof ProcedureParameter) {
+ return ((ProcedureParameter) elementID).getPrecision();
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ public int getRadix(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ return ((Column) elementID).getRadix();
+ } else if(elementID instanceof ProcedureParameter) {
+ return ((ProcedureParameter) elementID).getRadix();
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ public String getFormat(Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ return ((Column) elementID).getFormat();
+ }
+ throw createInvalidRecordTypeException(elementID);
+ }
+
+ public int getScale(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ return ((Column) elementID).getScale();
+ } else if(elementID instanceof ProcedureParameter) {
+ return ((ProcedureParameter) elementID).getScale();
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ public int getDistinctValues(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ return ((Column) elementID).getDistinctValues();
+ } else if(elementID instanceof ProcedureParameter) {
+ return -1;
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ public int getNullValues(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ return ((Column) elementID).getNullValues();
+ } else if(elementID instanceof ProcedureParameter) {
+ return -1;
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ public String getNativeType(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ if(elementID instanceof Column) {
+ return ((Column) elementID).getNativeType();
+ } else if(elementID instanceof ProcedureParameter) {
+ return null;
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ public Properties getExtensionProperties(final Object metadataID) throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(AbstractMetadataRecord.class, metadataID);
+ AbstractMetadataRecord metadataRecord = (AbstractMetadataRecord) metadataID;
+ Map<String, String> result = metadataRecord.getProperties();
+ if (result == null) {
+ return EMPTY_PROPS;
+ }
+ Properties p = new Properties();
+ p.putAll(result);
+ return p;
+ }
+
+ /**
+ * @see org.teiid.query.metadata.BasicQueryMetadata#getBinaryVDBResource(java.lang.String)
+ * @since 4.3
+ */
+ public byte[] getBinaryVDBResource(String resourcePath) throws TeiidComponentException, QueryMetadataException {
+ final VirtualFile f = getFile(resourcePath);
+ if (f == null) {
+ return null;
+ }
+ try {
+ return ObjectConverterUtil.convertToByteArray(f.openStream());
+ } catch (IOException e) {
+ throw new TeiidComponentException(e);
+ }
+ }
+
+ public ClobImpl getVDBResourceAsClob(String resourcePath) {
+ final VirtualFile f = getFile(resourcePath);
+ if (f == null) {
+ return null;
+ }
+ return new ClobImpl(new VirtualFileInputStreamFactory(f), -1);
+ }
+
+ public SQLXMLImpl getVDBResourceAsSQLXML(String resourcePath) {
+ final VirtualFile f = getFile(resourcePath);
+ if (f == null) {
+ return null;
+ }
+ return new SQLXMLImpl(new VirtualFileInputStreamFactory(f));
+ }
+
+ public BlobImpl getVDBResourceAsBlob(String resourcePath) {
+ final VirtualFile f = getFile(resourcePath);
+ if (f == null) {
+ return null;
+ }
+ return new BlobImpl(new VirtualFileInputStreamFactory(f));
+ }
+
+ private VirtualFile getFile(String resourcePath) {
+ if (resourcePath == null) {
+ return null;
+ }
+ Resource r = this.vdbEntries.get(resourcePath);
+ if (r != null) {
+ return r.file;
+ }
+ return null;
+ }
+
+ /**
+ * @see org.teiid.query.metadata.BasicQueryMetadata#getCharacterVDBResource(java.lang.String)
+ * @since 4.3
+ */
+ public String getCharacterVDBResource(String resourcePath) throws TeiidComponentException, QueryMetadataException {
+ try {
+ byte[] bytes = getBinaryVDBResource(resourcePath);
+ if (bytes == null) {
+ return null;
+ }
+ return ObjectConverterUtil.convertToString(new ByteArrayInputStream(bytes));
+ } catch (IOException e) {
+ throw new TeiidComponentException(e);
+ }
+ }
+
+ public CompositeMetadataStore getMetadataStore() {
+ return this.store;
+ }
+
+ /**
+ * @see org.teiid.query.metadata.BasicQueryMetadata#getVDBResourcePaths()
+ * @since 4.3
+ */
+ public String[] getVDBResourcePaths() throws TeiidComponentException, QueryMetadataException {
+ LinkedList<String> paths = new LinkedList<String>();
+ for (Map.Entry<String, Resource> entry : this.vdbEntries.entrySet()) {
+ paths.add(entry.getKey());
+ }
+ return paths.toArray(new String[paths.size()]);
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getModeledType(java.lang.Object)
+ * @since 5.0
+ */
+ public String getModeledType(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ Datatype record = getDatatypeRecord(elementID);
+ if (record != null) {
+ return record.getDatatypeID();
+ }
+ return null;
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getModeledBaseType(java.lang.Object)
+ * @since 5.0
+ */
+ public String getModeledBaseType(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ Datatype record = getDatatypeRecord(elementID);
+ if (record != null) {
+ return record.getBasetypeID();
+ }
+ return null;
+ }
+
+ /**
+ * @see org.teiid.query.metadata.QueryMetadataInterface#getModeledPrimitiveType(java.lang.Object)
+ * @since 5.0
+ */
+ public String getModeledPrimitiveType(final Object elementID) throws TeiidComponentException, QueryMetadataException {
+ Datatype record = getDatatypeRecord(elementID);
+ if (record != null) {
+ return record.getPrimitiveTypeID();
+ }
+ return null;
+ }
+
+ private Datatype getDatatypeRecord(final Object elementID) {
+ if (elementID instanceof Column) {
+ return ((Column)elementID).getDatatype();
+ } else if (elementID instanceof ProcedureParameter) {
+ return ((ProcedureParameter)elementID).getDatatype();
+ } else {
+ throw createInvalidRecordTypeException(elementID);
+ }
+ }
+
+ @Override
+ public Object addToMetadataCache(Object metadataID, String key, Object value) {
+ ArgCheck.isInstanceOf(AbstractMetadataRecord.class, metadataID);
+ boolean groupInfo = key.startsWith(GroupInfo.CACHE_PREFIX);
+ key = getCacheKey(key, (AbstractMetadataRecord)metadataID);
+ if (groupInfo) {
+ return this.groupInfoCache.put(key, value);
+ }
+ return this.metadataCache.put(key, value);
+ }
+
+ @Override
+ public Object getFromMetadataCache(Object metadataID, String key)
+ throws TeiidComponentException, QueryMetadataException {
+ ArgCheck.isInstanceOf(AbstractMetadataRecord.class, metadataID);
+ boolean groupInfo = key.startsWith(GroupInfo.CACHE_PREFIX);
+ key = getCacheKey(key, (AbstractMetadataRecord)metadataID);
+ if (groupInfo) {
+ return this.groupInfoCache.get(key);
+ }
+ return this.metadataCache.get(key);
+ }
+
+ private String getCacheKey(String key, AbstractMetadataRecord record) {
+ return record.getUUID() + "/" + key; //$NON-NLS-1$
+ }
+
+ @Override
+ public FunctionLibrary getFunctionLibrary() {
+ return this.functionLibrary;
+ }
+
+ @Override
+ public Object getPrimaryKey(Object metadataID) {
+ ArgCheck.isInstanceOf(Table.class, metadataID);
+ Table table = (Table)metadataID;
+ return table.getPrimaryKey();
+ }
+
+ @Override
+ public QueryMetadataInterface getDesignTimeMetadata() {
+ TransformationMetadata tm = new TransformationMetadata(store, functionLibrary);
+ tm.groupInfoCache = this.groupInfoCache;
+ tm.metadataCache = this.metadataCache;
+ tm.partialNameToFullNameCache = this.partialNameToFullNameCache;
+ tm.procedureCache = this.procedureCache;
+ return tm;
+ }
+}
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/BasicSourceCapabilities.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/capabilities/BasicSourceCapabilities.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/BasicSourceCapabilities.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,96 +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.optimizer.capabilities;
-
-import java.io.Serializable;
-import java.util.*;
-
-/**
- */
-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();
-
- /**
- * Construct a basic capabilities object.
- */
- public BasicSourceCapabilities() {
- }
-
- public boolean supportsCapability(Capability capability) {
- Boolean supports = (Boolean) capabilityMap.get(capability);
- return (supports == null) ? false : supports.booleanValue();
- }
-
- public boolean supportsFunction(String functionName) {
- Boolean supports = (Boolean) functionMap.get(functionName);
- return (supports == null) ? false : supports.booleanValue();
- }
-
- public void setCapabilitySupport(Capability capability, boolean supports) {
- if (supports && capability == Capability.QUERY_AGGREGATES) {
- capabilityMap.put(Capability.QUERY_GROUP_BY, true);
- capabilityMap.put(Capability.QUERY_HAVING, true);
- } else {
- capabilityMap.put(capability, supports);
- }
- }
-
- public void setFunctionSupport(String function, boolean supports) {
- functionMap.put(function, Boolean.valueOf(supports));
- }
-
- public Scope getScope() {
- return this.scope;
- }
-
- public void setScope(Scope scope) {
- this.scope = scope;
- }
-
- public String toString() {
- return "BasicSourceCapabilities<"+scope+", caps=" + capabilityMap + ", funcs=" + functionMap + ">"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- /**
- * This method adds the Source Property to the Property Map
- * @param propertyName
- * @param value
- * @since 4.4
- */
- public void setSourceProperty(Capability propertyName, Object value) {
- this.propertyMap.put(propertyName, value);
- }
-
- /**
- * @see org.teiid.query.optimizer.capabilities.SourceCapabilities#getSourceProperty(java.lang.String)
- * @since 4.2
- */
- public Object getSourceProperty(Capability propertyName) {
- return this.propertyMap.get(propertyName);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/BasicSourceCapabilities.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/capabilities/BasicSourceCapabilities.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/BasicSourceCapabilities.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/BasicSourceCapabilities.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.query.optimizer.capabilities;
+
+import java.io.Serializable;
+import java.util.*;
+
+/**
+ */
+public class BasicSourceCapabilities implements SourceCapabilities, Serializable {
+
+ 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.
+ */
+ public BasicSourceCapabilities() {
+ }
+
+ public boolean supportsCapability(Capability capability) {
+ Boolean supports = capabilityMap.get(capability);
+ return (supports == null) ? false : supports.booleanValue();
+ }
+
+ public boolean supportsFunction(String functionName) {
+ Boolean supports = functionMap.get(functionName);
+ return (supports == null) ? false : supports.booleanValue();
+ }
+
+ public void setCapabilitySupport(Capability capability, boolean supports) {
+ if (supports && capability == Capability.QUERY_AGGREGATES) {
+ capabilityMap.put(Capability.QUERY_GROUP_BY, true);
+ capabilityMap.put(Capability.QUERY_HAVING, true);
+ } else {
+ capabilityMap.put(capability, supports);
+ }
+ }
+
+ public void setFunctionSupport(String function, boolean supports) {
+ functionMap.put(function, Boolean.valueOf(supports));
+ }
+
+ public Scope getScope() {
+ return this.scope;
+ }
+
+ public void setScope(Scope scope) {
+ this.scope = scope;
+ }
+
+ public String toString() {
+ return "BasicSourceCapabilities<"+scope+", caps=" + capabilityMap + ", funcs=" + functionMap + ">"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ /**
+ * This method adds the Source Property to the Property Map
+ * @param propertyName
+ * @param value
+ * @since 4.4
+ */
+ public void setSourceProperty(Capability propertyName, Object value) {
+ this.propertyMap.put(propertyName, value);
+ }
+
+ /**
+ * @see org.teiid.query.optimizer.capabilities.SourceCapabilities#getSourceProperty(java.lang.String)
+ * @since 4.2
+ */
+ public Object getSourceProperty(Capability propertyName) {
+ return this.propertyMap.get(propertyName);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/SourceCapabilities.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/capabilities/SourceCapabilities.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/SourceCapabilities.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,369 +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.optimizer.capabilities;
-
-public interface SourceCapabilities {
-
- public enum Capability {
- /**
- * Support indicates connector can accept queries with SELECT DISTINCT
- */
- QUERY_SELECT_DISTINCT,
- /**
- * Support indicates connector can accept queries non-elements in the SELECT
- */
- QUERY_SELECT_EXPRESSION,
- /**
- * Support indicates connector can accept joins where groups have aliases (required for QUERY_FROM_JOIN_SELFJOIN)
- *
- * @since 3.1 SP2
- */
- QUERY_FROM_GROUP_ALIAS,
- /**
- * Max number of groups appearing in a from clause
- */
- MAX_QUERY_FROM_GROUPS,
- /**
- * @since 6.1.0
- */
- JOIN_CRITERIA_ALLOWED,
- /**
- * Support indicates connector can accept inner joins
- *
- * @since 3.1 SP2
- */
- QUERY_FROM_JOIN_INNER,
- /**
- * Indicates that the source prefers ANSI style joins
- *
- * @since 6.0.0
- */
- QUERY_FROM_ANSI_JOIN,
- /**
- * Support indicates connector can accept self-joins where a group is joined to itself with aliases
- *
- * @since 3.1 SP2
- */
- QUERY_FROM_JOIN_SELFJOIN,
- /**
- * Support indicates connector can accept right or left outer joins
- *
- * @since 3.1 SP2
- */
- QUERY_FROM_JOIN_OUTER,
- /**
- * Support indicates connector can push down inline views
- *
- * @since 4.1
- */
- QUERY_FROM_INLINE_VIEWS,
- /**
- * Support indicates connector can accept full outer joins
- *
- * @since 3.1 SP2
- */
- QUERY_FROM_JOIN_OUTER_FULL,
- /**
- * Support indicates connector accepts criteria of form (element BETWEEN constant AND constant)
- *
- * @since 4.0
- */
- CRITERIA_BETWEEN,
- /**
- * Support indicates connector accepts criteria of form (element operator constant)
- *
- * @since 3.1 SP2
- */
- CRITERIA_COMPARE_EQ,
- CRITERIA_COMPARE_ORDERED,
- /**
- * Support indicates connector accepts criteria of form (element LIKE constant)
- *
- * @since 3.1 SP2
- */
- CRITERIA_LIKE,
- /**
- * Support indicates connector accepts criteria of form (element LIKE constant ESCAPE char) - CURRENTLY NOT USED
- *
- * @since 3.1 SP2
- */
- CRITERIA_LIKE_ESCAPE,
- /**
- * Support indicates connector accepts criteria of form (element IN set)
- *
- * @since 3.1 SP2
- */
- CRITERIA_IN,
- /**
- * Support indicates connector accepts IN criteria with a subquery on the right side
- *
- * @since 4.0
- */
- CRITERIA_IN_SUBQUERY,
- /**
- * Support indicates connector accepts criteria of form (element IS NULL)
- *
- * @since 3.1 SP2
- */
- CRITERIA_ISNULL,
- /**
- * Support indicates connector accepts logical criteria connected by OR
- *
- * @since 3.1 SP2
- */
- CRITERIA_OR,
- /**
- * Support indicates connector accepts logical criteria NOT
- *
- * @since 3.1 SP2
- */
- CRITERIA_NOT,
- /**
- * Support indicates connector accepts the EXISTS criteria
- *
- * @since 4.0
- */
- CRITERIA_EXISTS,
- /**
- * Support indicates connector accepts the quantified comparison criteria that use SOME
- *
- * @since 4.0
- */
- CRITERIA_QUANTIFIED_SOME,
- /**
- * Support indicates connector accepts the quantified comparison criteria that use ALL
- *
- * @since 4.0
- */
- CRITERIA_QUANTIFIED_ALL,
- /**
- * Support indicates connector accepts ORDER BY clause
- *
- * @since 3.1 SP2
- */
- QUERY_ORDERBY,
-
- QUERY_ORDERBY_UNRELATED,
- QUERY_ORDERBY_NULL_ORDERING,
- QUERY_ORDERBY_DEFAULT_NULL_ORDER,
- /**
- * Composite support for group by and having - not
- * used by the connector layer
- */
- QUERY_AGGREGATES,
- /**
- * @since 6.1.0 indicates support for GROUP BY
- */
- QUERY_GROUP_BY,
- /**
- * @since 6.1.0 indicates support for HAVING
- */
- QUERY_HAVING,
- /**
- * Support indicates connector can accept the SUM aggregate function
- *
- * @since 3.1 SP2
- */
- QUERY_AGGREGATES_SUM,
- /**
- * Support indicates connector can accept the AVG aggregate function
- *
- * @since 3.1 SP2
- */
- QUERY_AGGREGATES_AVG,
- /**
- * Support indicates connector can accept the MIN aggregate function
- *
- * @since 3.1 SP2
- */
- QUERY_AGGREGATES_MIN,
- /**
- * Support indicates connector can accept the MAX aggregate function
- *
- * @since 3.1 SP2
- */
- QUERY_AGGREGATES_MAX,
- /**
- * Support indicates connector can accept the enhanced numeric aggregates
- *
- * @since 3.1 SP2
- */
- QUERY_AGGREGATES_ENHANCED_NUMERIC,
- /**
- * Support indicates connector can accept the COUNT aggregate function
- *
- * @since 3.1 SP2
- */
- QUERY_AGGREGATES_COUNT,
- /**
- * Support indicates connector can accept the COUNT(*) aggregate function
- *
- * @since 3.1 SP2
- */
- QUERY_AGGREGATES_COUNT_STAR,
- /**
- * Support indicates connector can accept DISTINCT within aggregate functions
- *
- * @since 3.1 SP2
- */
- QUERY_AGGREGATES_DISTINCT,
- /**
- * Support indicates connector can accept scalar subqueries in the SELECT, WHERE, and HAVING clauses
- *
- * @since 4.0
- */
- QUERY_SUBQUERIES_SCALAR,
- /**
- * Support indicates connector can accept correalted subqueries wherever subqueries are accepted
- *
- * @since 4.0
- */
- QUERY_SUBQUERIES_CORRELATED,
- /**
- * Support indicates connector can accept queries with non-searched CASE <expression> WHEN <expression> ... END
- *
- * @since 4.0
- */
- QUERY_CASE,
- /**
- * Support indicates connector can accept queries with searched CASE WHEN <criteria> ... END
- *
- * @since 4.0
- */
- QUERY_SEARCHED_CASE,
- /**
- * Support indicates connector can accept UNION and UNION ALL
- *
- * @since 4.2
- */
- QUERY_UNION,
- /**
- * Support indicates connector can accept INTERSECT
- *
- * @since 5.6
- */
- QUERY_INTERSECT,
- /**
- * Support indicates connector can accept EXCEPT
- *
- * @since 5.6
- */
- QUERY_EXCEPT,
- /**
- * Support indicates connector can accept SET QUERY with an ORDER BY clause
- *
- * @since 4.2
- */
- QUERY_SET_ORDER_BY,
- /**
- * Support indicates connector can accept GROUP BY with functions in it.
- *
- * @since 5.0
- */
- QUERY_FUNCTIONS_IN_GROUP_BY,
- /**
- * Support indicates connector can accept queries with searched CASE WHEN <criteria> ... END
- *
- * @since 4.2
- */
- BATCHED_UPDATES,
- BULK_UPDATE,
- /**
- * Support indicates connector can limit result rows
- *
- * @since 5.0 SP1
- */
- ROW_LIMIT,
- /**
- * Support indicates connector support a SQL clause whose output rows offset from the query's result rows (similar to
- * LIMIT with offset)
- *
- * @since 5.0 SP1
- */
- ROW_OFFSET,
- /**
- * The Maximum number of values allowed in an IN criteria (Integer)
- *
- * @since 4.4
- */
- MAX_IN_CRITERIA_SIZE,
- /**
- * The connector ID, which is used by the optimizer to determine when two models are bound to the same connector
- *
- * @since 5.0.2
- */
- CONNECTOR_ID,
- /**
- * @since 6.0.0 indicates support for where all
- */
- REQUIRES_CRITERIA,
- INSERT_WITH_QUERYEXPRESSION,
- INSERT_WITH_ITERATOR,
- COMMON_TABLE_EXPRESSIONS,
- MAX_DEPENDENT_PREDICATES,
- }
-
- public enum Scope {
- /**
- * A legal value for the {@link #SCOPE} property.
- */
- SCOPE_GLOBAL,
- /**
- * A legal value for the {@link #SCOPE} property.
- */
- SCOPE_PER_USER
- }
-
- /**
- * Determine the scope of these capabilities.
- */
- Scope getScope();
-
- /**
- * Returns true if the capability is supported. The capability constants are all defined in this interface with the meaning of
- * supporting that capability.
- *
- * @param capability
- * Name of capability
- * @return True if supported, false otherwise
- */
- public boolean supportsCapability(Capability capability);
-
- /**
- * This method can be used to check whether a particular function is supported by this connector. This method should only be
- * 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.)
- * @return True if function is supported.
- */
- public boolean supportsFunction(String functionName);
-
- /**
- * This method returns an Object corresponding to the Source Property
- *
- * @since 4.4
- */
- public Object getSourceProperty(Capability propertyName);
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/SourceCapabilities.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/capabilities/SourceCapabilities.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/SourceCapabilities.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/capabilities/SourceCapabilities.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,368 @@
+/*
+ * 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.capabilities;
+
+public interface SourceCapabilities {
+
+ public enum Capability {
+ /**
+ * Support indicates connector can accept queries with SELECT DISTINCT
+ */
+ QUERY_SELECT_DISTINCT,
+ /**
+ * Support indicates connector can accept queries non-elements in the SELECT
+ */
+ QUERY_SELECT_EXPRESSION,
+ /**
+ * Support indicates connector can accept joins where groups have aliases (required for QUERY_FROM_JOIN_SELFJOIN)
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_FROM_GROUP_ALIAS,
+ /**
+ * Max number of groups appearing in a from clause
+ */
+ MAX_QUERY_FROM_GROUPS,
+ /**
+ * @since 6.1.0
+ */
+ JOIN_CRITERIA_ALLOWED,
+ /**
+ * Support indicates connector can accept inner joins
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_FROM_JOIN_INNER,
+ /**
+ * Indicates that the source prefers ANSI style joins
+ *
+ * @since 6.0.0
+ */
+ QUERY_FROM_ANSI_JOIN,
+ /**
+ * Support indicates connector can accept self-joins where a group is joined to itself with aliases
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_FROM_JOIN_SELFJOIN,
+ /**
+ * Support indicates connector can accept right or left outer joins
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_FROM_JOIN_OUTER,
+ /**
+ * Support indicates connector can push down inline views
+ *
+ * @since 4.1
+ */
+ QUERY_FROM_INLINE_VIEWS,
+ /**
+ * Support indicates connector can accept full outer joins
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_FROM_JOIN_OUTER_FULL,
+ /**
+ * Support indicates connector accepts criteria of form (element BETWEEN constant AND constant)
+ *
+ * @since 4.0
+ */
+ CRITERIA_BETWEEN,
+ /**
+ * Support indicates connector accepts criteria of form (element operator constant)
+ *
+ * @since 3.1 SP2
+ */
+ CRITERIA_COMPARE_EQ,
+ CRITERIA_COMPARE_ORDERED,
+ /**
+ * Support indicates connector accepts criteria of form (element LIKE constant)
+ *
+ * @since 3.1 SP2
+ */
+ CRITERIA_LIKE,
+ /**
+ * Support indicates connector accepts criteria of form (element LIKE constant ESCAPE char) - CURRENTLY NOT USED
+ *
+ * @since 3.1 SP2
+ */
+ CRITERIA_LIKE_ESCAPE,
+ /**
+ * Support indicates connector accepts criteria of form (element IN set)
+ *
+ * @since 3.1 SP2
+ */
+ CRITERIA_IN,
+ /**
+ * Support indicates connector accepts IN criteria with a subquery on the right side
+ *
+ * @since 4.0
+ */
+ CRITERIA_IN_SUBQUERY,
+ /**
+ * Support indicates connector accepts criteria of form (element IS NULL)
+ *
+ * @since 3.1 SP2
+ */
+ CRITERIA_ISNULL,
+ /**
+ * Support indicates connector accepts logical criteria connected by OR
+ *
+ * @since 3.1 SP2
+ */
+ CRITERIA_OR,
+ /**
+ * Support indicates connector accepts logical criteria NOT
+ *
+ * @since 3.1 SP2
+ */
+ CRITERIA_NOT,
+ /**
+ * Support indicates connector accepts the EXISTS criteria
+ *
+ * @since 4.0
+ */
+ CRITERIA_EXISTS,
+ /**
+ * Support indicates connector accepts the quantified comparison criteria that use SOME
+ *
+ * @since 4.0
+ */
+ CRITERIA_QUANTIFIED_SOME,
+ /**
+ * Support indicates connector accepts the quantified comparison criteria that use ALL
+ *
+ * @since 4.0
+ */
+ CRITERIA_QUANTIFIED_ALL,
+ /**
+ * Support indicates connector accepts ORDER BY clause
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_ORDERBY,
+
+ QUERY_ORDERBY_UNRELATED,
+ QUERY_ORDERBY_NULL_ORDERING,
+ QUERY_ORDERBY_DEFAULT_NULL_ORDER,
+ /**
+ * Composite support for group by and having - not
+ * used by the connector layer
+ */
+ QUERY_AGGREGATES,
+ /**
+ * @since 6.1.0 indicates support for GROUP BY
+ */
+ QUERY_GROUP_BY,
+ /**
+ * @since 6.1.0 indicates support for HAVING
+ */
+ QUERY_HAVING,
+ /**
+ * Support indicates connector can accept the SUM aggregate function
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_AGGREGATES_SUM,
+ /**
+ * Support indicates connector can accept the AVG aggregate function
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_AGGREGATES_AVG,
+ /**
+ * Support indicates connector can accept the MIN aggregate function
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_AGGREGATES_MIN,
+ /**
+ * Support indicates connector can accept the MAX aggregate function
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_AGGREGATES_MAX,
+ /**
+ * Support indicates connector can accept the enhanced numeric aggregates
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_AGGREGATES_ENHANCED_NUMERIC,
+ /**
+ * Support indicates connector can accept the COUNT aggregate function
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_AGGREGATES_COUNT,
+ /**
+ * Support indicates connector can accept the COUNT(*) aggregate function
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_AGGREGATES_COUNT_STAR,
+ /**
+ * Support indicates connector can accept DISTINCT within aggregate functions
+ *
+ * @since 3.1 SP2
+ */
+ QUERY_AGGREGATES_DISTINCT,
+ /**
+ * Support indicates connector can accept scalar subqueries in the SELECT, WHERE, and HAVING clauses
+ *
+ * @since 4.0
+ */
+ QUERY_SUBQUERIES_SCALAR,
+ /**
+ * Support indicates connector can accept correalted subqueries wherever subqueries are accepted
+ *
+ * @since 4.0
+ */
+ QUERY_SUBQUERIES_CORRELATED,
+ /**
+ * Support indicates connector can accept queries with non-searched CASE <expression> WHEN <expression> ... END
+ *
+ * @since 4.0
+ */
+ QUERY_CASE,
+ /**
+ * Support indicates connector can accept queries with searched CASE WHEN <criteria> ... END
+ *
+ * @since 4.0
+ */
+ QUERY_SEARCHED_CASE,
+ /**
+ * Support indicates connector can accept UNION and UNION ALL
+ *
+ * @since 4.2
+ */
+ QUERY_UNION,
+ /**
+ * Support indicates connector can accept INTERSECT
+ *
+ * @since 5.6
+ */
+ QUERY_INTERSECT,
+ /**
+ * Support indicates connector can accept EXCEPT
+ *
+ * @since 5.6
+ */
+ QUERY_EXCEPT,
+ /**
+ * Support indicates connector can accept SET QUERY with an ORDER BY clause
+ *
+ * @since 4.2
+ */
+ QUERY_SET_ORDER_BY,
+ /**
+ * Support indicates connector can accept GROUP BY with functions in it.
+ *
+ * @since 5.0
+ */
+ QUERY_FUNCTIONS_IN_GROUP_BY,
+ /**
+ * Support indicates connector can accept queries with searched CASE WHEN <criteria> ... END
+ *
+ * @since 4.2
+ */
+ BATCHED_UPDATES,
+ BULK_UPDATE,
+ /**
+ * Support indicates connector can limit result rows
+ *
+ * @since 5.0 SP1
+ */
+ ROW_LIMIT,
+ /**
+ * Support indicates connector support a SQL clause whose output rows offset from the query's result rows (similar to
+ * LIMIT with offset)
+ *
+ * @since 5.0 SP1
+ */
+ ROW_OFFSET,
+ /**
+ * The Maximum number of values allowed in an IN criteria (Integer)
+ *
+ * @since 4.4
+ */
+ MAX_IN_CRITERIA_SIZE,
+ /**
+ * The connector ID, which is used by the optimizer to determine when two models are bound to the same connector
+ *
+ * @since 5.0.2
+ */
+ CONNECTOR_ID,
+ /**
+ * @since 6.0.0 indicates support for where all
+ */
+ REQUIRES_CRITERIA,
+ INSERT_WITH_QUERYEXPRESSION,
+ INSERT_WITH_ITERATOR,
+ COMMON_TABLE_EXPRESSIONS,
+ MAX_DEPENDENT_PREDICATES,
+ }
+
+ public enum Scope {
+ /**
+ * A legal value for the {@link #SCOPE} property.
+ */
+ SCOPE_GLOBAL,
+ /**
+ * A legal value for the {@link #SCOPE} property.
+ */
+ SCOPE_PER_USER
+ }
+
+ /**
+ * Determine the scope of these capabilities.
+ */
+ Scope getScope();
+
+ /**
+ * Returns true if the capability is supported. The capability constants are all defined in this interface with the meaning of
+ * supporting that capability.
+ *
+ * @param capability
+ * Name of capability
+ * @return True if supported, false otherwise
+ */
+ public boolean supportsCapability(Capability capability);
+
+ /**
+ * This method can be used to check whether a particular function is supported by this connector. This method should only be
+ * used if the capability FUNCTION is true.
+ *
+ * @param functionName
+ * The function that may be supported
+ * @return True if function is supported.
+ */
+ public boolean supportsFunction(String functionName);
+
+ /**
+ * This method returns an Object corresponding to the Source Property
+ *
+ * @since 4.4
+ */
+ public Object getSourceProperty(Capability propertyName);
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,567 +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.optimizer.relational;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-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;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataID;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.optimizer.relational.plantree.NodeConstants;
-import org.teiid.query.optimizer.relational.plantree.PlanNode;
-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.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.GroupingNode;
-import org.teiid.query.processor.relational.InsertPlanExecutionNode;
-import org.teiid.query.processor.relational.JoinNode;
-import org.teiid.query.processor.relational.LimitNode;
-import org.teiid.query.processor.relational.MergeJoinStrategy;
-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;
-import org.teiid.query.processor.relational.RelationalNode;
-import org.teiid.query.processor.relational.RelationalPlan;
-import org.teiid.query.processor.relational.SelectNode;
-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.XMLTableNode;
-import org.teiid.query.processor.relational.JoinNode.JoinStrategyType;
-import org.teiid.query.processor.relational.MergeJoinStrategy.SortOption;
-import org.teiid.query.processor.relational.SortUtility.Mode;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.sql.lang.ArrayTable;
-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.JoinType;
-import org.teiid.query.sql.lang.OrderBy;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.TableFunctionReference;
-import org.teiid.query.sql.lang.TextTable;
-import org.teiid.query.sql.lang.XMLTable;
-import org.teiid.query.sql.lang.SetQuery.Operation;
-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.GroupSymbol;
-import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.sql.visitor.EvaluatableVisitor;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-
-
-public class PlanToProcessConverter {
- protected QueryMetadataInterface metadata;
- private IDGenerator idGenerator;
- private AnalysisRecord analysisRecord;
- private CapabilitiesFinder capFinder;
-
- public PlanToProcessConverter(QueryMetadataInterface metadata, IDGenerator idGenerator, AnalysisRecord analysisRecord, CapabilitiesFinder capFinder) {
- this.metadata = metadata;
- this.idGenerator = idGenerator;
- this.analysisRecord = analysisRecord;
- this.capFinder = capFinder;
- }
-
- public RelationalPlan convert(PlanNode planNode)
- throws QueryPlannerException, TeiidComponentException {
-
- boolean debug = analysisRecord.recordDebug();
- if(debug) {
- analysisRecord.println("\n============================================================================"); //$NON-NLS-1$
- analysisRecord.println("CONVERTING PLAN TREE TO PROCESS TREE"); //$NON-NLS-1$
- }
-
- // Convert plan tree nodes into process tree nodes
- RelationalNode processNode = convertPlan(planNode);
- if(debug) {
- analysisRecord.println("\nPROCESS PLAN = \n" + processNode); //$NON-NLS-1$
- analysisRecord.println("============================================================================"); //$NON-NLS-1$
- }
-
- RelationalPlan processPlan = new RelationalPlan(processNode);
- return processPlan;
-
- }
-
- private RelationalNode convertPlan(PlanNode planNode)
- throws QueryPlannerException, TeiidComponentException {
-
- // Convert current node in planTree
- RelationalNode convertedNode = convertNode(planNode);
-
- if(convertedNode == null) {
- Assertion.assertTrue(planNode.getChildCount() == 1);
- return convertPlan(planNode.getFirstChild());
- }
-
- RelationalNode nextParent = convertedNode;
-
- // convertedNode may be the head of 1 or more nodes - go to end of chain
- while(nextParent.getChildren()[0] != null) {
- nextParent = nextParent.getChildren()[0];
- }
-
- // Call convertPlan recursively on children
- for (PlanNode childNode : planNode.getChildren()) {
- RelationalNode child = convertPlan(childNode);
- if (planNode.getType() == NodeConstants.Types.SET_OP && childNode.getType() == NodeConstants.Types.SET_OP && childNode.hasBooleanProperty(Info.USE_ALL)) {
- for (RelationalNode grandChild : child.getChildren()) {
- if (grandChild != null) {
- nextParent.addChild(grandChild);
- }
- }
- } else {
- nextParent.addChild(child);
- }
- }
-
- // Return root of tree for top node
- return convertedNode;
- }
-
- protected int getID() {
- IntegerIDFactory intFactory = (IntegerIDFactory) idGenerator.getDefaultFactory();
- return ((IntegerID) intFactory.create()).getValue();
- }
-
- protected RelationalNode convertNode(PlanNode node)
- throws QueryPlannerException, TeiidComponentException {
-
- RelationalNode processNode = null;
-
- switch(node.getType()) {
- case NodeConstants.Types.PROJECT:
- GroupSymbol intoGroup = (GroupSymbol) node.getProperty(NodeConstants.Info.INTO_GROUP);
- if(intoGroup != null) {
- try {
- Insert insert = (Insert)node.getFirstChild().getProperty(Info.VIRTUAL_COMMAND);
- List<ElementSymbol> allIntoElements = insert.getVariables();
-
- Object groupID = intoGroup.getMetadataID();
- Object modelID = metadata.getModelID(groupID);
- String modelName = metadata.getFullName(modelID);
- if (metadata.isVirtualGroup(groupID)) {
- InsertPlanExecutionNode ipen = new InsertPlanExecutionNode(getID(), metadata);
- ipen.setProcessorPlan((ProcessorPlan)node.getFirstChild().getProperty(Info.PROCESSOR_PLAN));
- ipen.setReferences(insert.getValues());
- processNode = ipen;
- } else {
- ProjectIntoNode pinode = new ProjectIntoNode(getID());
- pinode.setIntoGroup(intoGroup);
- pinode.setIntoElements(allIntoElements);
- pinode.setModelName(modelName);
- processNode = pinode;
- SourceCapabilities caps = capFinder.findCapabilities(modelName);
- if (caps.supportsCapability(Capability.INSERT_WITH_ITERATOR)) {
- pinode.setMode(org.teiid.query.processor.relational.ProjectIntoNode.Mode.ITERATOR);
- } else if (caps.supportsCapability(Capability.BULK_UPDATE)) {
- pinode.setMode(org.teiid.query.processor.relational.ProjectIntoNode.Mode.BULK);
- } else if (caps.supportsCapability(Capability.BATCHED_UPDATES)) {
- pinode.setMode(org.teiid.query.processor.relational.ProjectIntoNode.Mode.BATCH);
- } else {
- pinode.setMode(org.teiid.query.processor.relational.ProjectIntoNode.Mode.SINGLE);
- }
- }
- } catch(QueryMetadataException e) {
- throw new TeiidComponentException(e);
- }
-
- } else {
- List symbols = (List) node.getProperty(NodeConstants.Info.PROJECT_COLS);
-
- ProjectNode pnode = new ProjectNode(getID());
- pnode.setSelectSymbols(symbols);
- processNode = pnode;
- }
- break;
-
- case NodeConstants.Types.JOIN:
- JoinType jtype = (JoinType) node.getProperty(NodeConstants.Info.JOIN_TYPE);
- JoinStrategyType stype = (JoinStrategyType) node.getProperty(NodeConstants.Info.JOIN_STRATEGY);
-
- JoinNode jnode = new JoinNode(getID());
- jnode.setJoinType(jtype);
- jnode.setLeftDistinct(node.hasBooleanProperty(NodeConstants.Info.IS_LEFT_DISTINCT));
- jnode.setRightDistinct(node.hasBooleanProperty(NodeConstants.Info.IS_RIGHT_DISTINCT));
- List joinCrits = (List) node.getProperty(NodeConstants.Info.JOIN_CRITERIA);
- String depValueSource = (String) node.getProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE);
- SortOption leftSort = (SortOption)node.getProperty(NodeConstants.Info.SORT_LEFT);
- 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));
- } else {
- mjStrategy = new MergeJoinStrategy(leftSort, (SortOption)node.getProperty(NodeConstants.Info.SORT_RIGHT), false);
- }
- jnode.setJoinStrategy(mjStrategy);
- List leftExpressions = (List) node.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS);
- List rightExpressions = (List) node.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS);
- jnode.setJoinExpressions(leftExpressions, rightExpressions);
- joinCrits = (List) node.getProperty(NodeConstants.Info.NON_EQUI_JOIN_CRITERIA);
- } else if (stype == JoinStrategyType.NESTED_TABLE) {
- NestedTableJoinStrategy ntjStrategy = new NestedTableJoinStrategy();
- jnode.setJoinStrategy(ntjStrategy);
- SymbolMap references = (SymbolMap)FrameUtil.findJoinSourceNode(node.getFirstChild()).getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
- ntjStrategy.setLeftMap(references);
- references = (SymbolMap)FrameUtil.findJoinSourceNode(node.getLastChild()).getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
- ntjStrategy.setRightMap(references);
- } else {
- NestedLoopJoinStrategy nljStrategy = new NestedLoopJoinStrategy();
- jnode.setJoinStrategy(nljStrategy);
- }
- Criteria joinCrit = Criteria.combineCriteria(joinCrits);
- jnode.setJoinCriteria(joinCrit);
-
- processNode = jnode;
-
- jnode.setDependentValueSource(depValueSource);
-
- break;
-
- case NodeConstants.Types.ACCESS:
- ProcessorPlan plan = (ProcessorPlan) node.getProperty(NodeConstants.Info.PROCESSOR_PLAN);
- if(plan != null) {
-
- PlanExecutionNode peNode = null;
-
- Criteria crit = (Criteria)node.getProperty(NodeConstants.Info.PROCEDURE_CRITERIA);
-
- if (crit != null) {
- List references = (List)node.getProperty(NodeConstants.Info.PROCEDURE_INPUTS);
- List defaults = (List)node.getProperty(NodeConstants.Info.PROCEDURE_DEFAULTS);
-
- peNode = new DependentProcedureExecutionNode(getID(), crit, references, defaults);
- } else {
- peNode = new PlanExecutionNode(getID());
- }
-
- peNode.setProcessorPlan(plan);
- processNode = peNode;
-
- } else {
- AccessNode aNode = null;
- Command command = (Command) node.getProperty(NodeConstants.Info.ATOMIC_REQUEST);
- Object modelID = node.getProperty(NodeConstants.Info.MODEL_ID);
-
- if(node.hasBooleanProperty(NodeConstants.Info.IS_DEPENDENT_SET)) {
- if (command instanceof StoredProcedure) {
- List references = (List)node.getProperty(NodeConstants.Info.PROCEDURE_INPUTS);
- List defaults = (List)node.getProperty(NodeConstants.Info.PROCEDURE_DEFAULTS);
- Criteria crit = (Criteria)node.getProperty(NodeConstants.Info.PROCEDURE_CRITERIA);
-
- DependentProcedureAccessNode depAccessNode = new DependentProcedureAccessNode(getID(), crit, references, defaults);
- processNode = depAccessNode;
- aNode = depAccessNode;
- } else {
- //create dependent access node
- DependentAccessNode depAccessNode = new DependentAccessNode(getID());
-
- if(modelID != null){
- depAccessNode.setMaxSetSize(CapabilitiesUtil.getMaxInCriteriaSize(modelID, metadata, capFinder));
- depAccessNode.setMaxPredicates(CapabilitiesUtil.getMaxDependentPredicates(modelID, metadata, capFinder));
- }
- processNode = depAccessNode;
- aNode = depAccessNode;
- }
- aNode.setShouldEvaluateExpressions(true);
- } else {
-
- // create access node
- aNode = new AccessNode(getID());
- processNode = aNode;
-
- //-- special handling for temp tables. currently they cannot perform projection
- try {
- if (command instanceof Query) {
- processNode = correctProjectionInternalTables(node, aNode);
- }
- } catch (QueryMetadataException err) {
- throw new TeiidComponentException(err);
- }
- aNode.setShouldEvaluateExpressions(EvaluatableVisitor.needsProcessingEvaluation(command));
- }
-
- if (command instanceof QueryCommand) {
- try {
- command = (Command)command.clone();
- boolean aliasGroups = modelID != null && CapabilitiesUtil.supportsGroupAliases(modelID, metadata, capFinder);
- boolean aliasColumns = modelID != null && CapabilitiesUtil.supports(Capability.QUERY_SELECT_EXPRESSION, modelID, metadata, capFinder);
- command.acceptVisitor(new AliasGenerator(aliasGroups, !aliasColumns));
- } catch (QueryMetadataException err) {
- throw new TeiidComponentException(err);
- }
- }
- aNode.setCommand(command);
- aNode.setModelName(getRoutingName(node));
- }
- break;
-
- case NodeConstants.Types.SELECT:
-
- Criteria crit = (Criteria) node.getProperty(NodeConstants.Info.SELECT_CRITERIA);
-
- SelectNode selnode = new SelectNode(getID());
- selnode.setCriteria(crit);
- processNode = selnode;
-
- break;
-
- case NodeConstants.Types.SORT:
- case NodeConstants.Types.DUP_REMOVE:
- SortNode sortNode = new SortNode(getID());
- OrderBy orderBy = (OrderBy) node.getProperty(NodeConstants.Info.SORT_ORDER);
- if (orderBy != null) {
- sortNode.setSortElements(orderBy.getOrderByItems());
- }
- if (node.getType() == NodeConstants.Types.DUP_REMOVE) {
- sortNode.setMode(Mode.DUP_REMOVE);
- } else if (node.hasBooleanProperty(NodeConstants.Info.IS_DUP_REMOVAL)) {
- sortNode.setMode(Mode.DUP_REMOVE_SORT);
- }
-
- processNode = sortNode;
- break;
- case NodeConstants.Types.GROUP:
- GroupingNode gnode = new GroupingNode(getID());
- gnode.setGroupingElements( (List) node.getProperty(NodeConstants.Info.GROUP_COLS) );
- gnode.setRemoveDuplicates(node.hasBooleanProperty(NodeConstants.Info.IS_DUP_REMOVAL));
- processNode = gnode;
- break;
-
- case NodeConstants.Types.SOURCE:
- SymbolMap symbolMap = (SymbolMap) node.getProperty(NodeConstants.Info.SYMBOL_MAP);
- if(symbolMap != null) {
- PlanNode child = node.getLastChild();
-
- if (node.getParent().getType() != NodeConstants.Types.PROJECT || node.getParent().getProperty(NodeConstants.Info.INTO_GROUP) == null) {
- if (child.getType() == NodeConstants.Types.PROJECT) {
- //update the project cols based upon the original output
- child.setProperty(NodeConstants.Info.PROJECT_COLS, child.getProperty(NodeConstants.Info.OUTPUT_COLS));
- }
- child.setProperty(NodeConstants.Info.OUTPUT_COLS, node.getProperty(NodeConstants.Info.OUTPUT_COLS));
- }
- }
- Object source = node.getProperty(NodeConstants.Info.TABLE_FUNCTION);
- if (source instanceof XMLTable) {
- XMLTable xt = (XMLTable)source;
- XMLTableNode xtn = new XMLTableNode(getID());
- //we handle the projection filtering once here rather than repeating the
- //path analysis on a per plan basis
- updateGroupName(node, xt);
- Map elementMap = RelationalNode.createLookupMap(xt.getProjectedSymbols());
- List cols = (List) node.getProperty(NodeConstants.Info.OUTPUT_COLS);
- int[] projectionIndexes = RelationalNode.getProjectionIndexes(elementMap, cols);
- ArrayList<XMLColumn> filteredColumns = new ArrayList<XMLColumn>(projectionIndexes.length);
- for (int col : projectionIndexes) {
- filteredColumns.add(xt.getColumns().get(col));
- }
- xt.getXQueryExpression().useDocumentProjection(filteredColumns, analysisRecord);
- xtn.setProjectedColumns(filteredColumns);
- xtn.setTable(xt);
- processNode = xtn;
- break;
- }
- if (source instanceof TextTable) {
- TextTableNode ttn = new TextTableNode(getID());
- TextTable tt = (TextTable)source;
- updateGroupName(node, tt);
- ttn.setTable(tt);
- processNode = ttn;
- break;
- }
- if (source instanceof ArrayTable) {
- ArrayTableNode atn = new ArrayTableNode(getID());
- ArrayTable at = (ArrayTable)source;
- updateGroupName(node, at);
- atn.setTable(at);
- processNode = atn;
- break;
- }
- return null;
- case NodeConstants.Types.SET_OP:
- Operation setOp = (Operation) node.getProperty(NodeConstants.Info.SET_OPERATION);
- boolean useAll = ((Boolean) node.getProperty(NodeConstants.Info.USE_ALL)).booleanValue();
- if(setOp == Operation.UNION) {
- RelationalNode unionAllNode = new UnionAllNode(getID());
-
- if(useAll) {
- processNode = unionAllNode;
- } else {
- SortNode sNode = new SortNode(getID());
- boolean onlyDupRemoval = node.hasBooleanProperty(NodeConstants.Info.IS_DUP_REMOVAL);
- sNode.setMode(onlyDupRemoval?Mode.DUP_REMOVE:Mode.DUP_REMOVE_SORT);
- processNode = sNode;
-
- unionAllNode.setElements( (List) node.getProperty(NodeConstants.Info.OUTPUT_COLS) );
- processNode.addChild(unionAllNode);
- }
- } else {
- JoinNode joinAsSet = new JoinNode(getID());
- joinAsSet.setJoinStrategy(new MergeJoinStrategy(SortOption.SORT_DISTINCT, SortOption.SORT_DISTINCT, true));
- List leftExpressions = (List) node.getFirstChild().getProperty(NodeConstants.Info.OUTPUT_COLS);
- List rightExpressions = (List) node.getLastChild().getProperty(NodeConstants.Info.OUTPUT_COLS);
- joinAsSet.setJoinType(setOp == Operation.EXCEPT ? JoinType.JOIN_ANTI_SEMI : JoinType.JOIN_SEMI);
- joinAsSet.setJoinExpressions(leftExpressions, rightExpressions);
- processNode = joinAsSet;
- }
-
- break;
-
- case NodeConstants.Types.TUPLE_LIMIT:
- Expression rowLimit = (Expression)node.getProperty(NodeConstants.Info.MAX_TUPLE_LIMIT);
- Expression offset = (Expression)node.getProperty(NodeConstants.Info.OFFSET_TUPLE_COUNT);
- LimitNode ln = new LimitNode(getID(), rowLimit, offset);
- ln.setImplicit(node.hasBooleanProperty(Info.IS_IMPLICIT_LIMIT));
- processNode = ln;
- break;
-
- case NodeConstants.Types.NULL:
- processNode = new NullNode(getID());
- break;
-
- default:
- throw new QueryPlannerException(QueryPlugin.Util.getString("ERR.015.004.0007", NodeConstants.getNodeTypeString(node.getType()))); //$NON-NLS-1$
- }
-
- if(processNode != null) {
- processNode = prepareToAdd(node, processNode);
- }
-
- return processNode;
- }
-
- private void updateGroupName(PlanNode node, TableFunctionReference tt) {
- String groupName = node.getGroups().iterator().next().getName();
- tt.getGroupSymbol().setName(groupName);
- for (ElementSymbol symbol : tt.getProjectedSymbols()) {
- symbol.setGroupSymbol(new GroupSymbol(groupName));
- }
- }
-
- private RelationalNode correctProjectionInternalTables(PlanNode node,
- AccessNode aNode) throws QueryMetadataException,
- TeiidComponentException {
- if (node.getGroups().size() != 1) {
- return aNode;
- }
- GroupSymbol group = node.getGroups().iterator().next();
- if (!CoreConstants.SYSTEM_MODEL.equals(metadata.getFullName(metadata.getModelID(group.getMetadataID())))
- && !CoreConstants.SYSTEM_ADMIN_MODEL.equals(metadata.getFullName(metadata.getModelID(group.getMetadataID())))) {
- return aNode;
- }
- List projectSymbols = (List) node.getProperty(NodeConstants.Info.OUTPUT_COLS);
- List<ElementSymbol> acutalColumns = ResolverUtil.resolveElementsInGroup(group, metadata);
- if (projectSymbols.equals(acutalColumns)) {
- return aNode;
- }
- node.setProperty(NodeConstants.Info.OUTPUT_COLS, acutalColumns);
- if (node.getParent() != null && node.getParent().getType() == NodeConstants.Types.PROJECT) {
- //if the parent is already a project, just correcting the output cols is enough
- return aNode;
- }
- ProjectNode pnode = new ProjectNode(getID());
-
- pnode.setSelectSymbols(projectSymbols);
- //if the following cast fails it means that we have a dependent temp table - that is not yet possible
- aNode = (AccessNode)prepareToAdd(node, aNode);
- node.setProperty(NodeConstants.Info.OUTPUT_COLS, projectSymbols);
- pnode.addChild(aNode);
- return pnode;
- }
-
- private RelationalNode prepareToAdd(PlanNode node,
- RelationalNode processNode) {
- // Set the output elements from the plan node
- List cols = (List) node.getProperty(NodeConstants.Info.OUTPUT_COLS);
-
- processNode.setElements(cols);
-
- // Set the Cost Estimates
- Number estimateNodeCardinality = (Number) node.getProperty(NodeConstants.Info.EST_CARDINALITY);
- processNode.setEstimateNodeCardinality(estimateNodeCardinality);
- Number estimateNodeSetSize = (Number) node.getProperty(NodeConstants.Info.EST_SET_SIZE);
- processNode.setEstimateNodeSetSize(estimateNodeSetSize);
- Number estimateDepAccessCardinality = (Number) node.getProperty(NodeConstants.Info.EST_DEP_CARDINALITY);
- processNode.setEstimateDepAccessCardinality(estimateDepAccessCardinality);
- Number estimateDepJoinCost = (Number) node.getProperty(NodeConstants.Info.EST_DEP_JOIN_COST);
- processNode.setEstimateDepJoinCost(estimateDepJoinCost);
- Number estimateJoinCost = (Number) node.getProperty(NodeConstants.Info.EST_JOIN_COST);
- processNode.setEstimateJoinCost(estimateJoinCost);
-
- return processNode;
- }
-
- private String getRoutingName(PlanNode node)
- throws QueryPlannerException, TeiidComponentException {
-
- // Look up connector binding name
- try {
- Object modelID = node.getProperty(NodeConstants.Info.MODEL_ID);
- if(modelID == null || modelID instanceof TempMetadataID) {
- Command command = (Command) node.getProperty(NodeConstants.Info.ATOMIC_REQUEST);
- if(command instanceof StoredProcedure){
- modelID = ((StoredProcedure)command).getModelID();
- }else{
- Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(command, true);
- GroupSymbol group = groups.iterator().next();
-
- modelID = metadata.getModelID(group.getMetadataID());
- }
- }
- String cbName = metadata.getFullName(modelID);
- return cbName;
- } catch(QueryMetadataException e) {
- throw new QueryPlannerException(e, QueryPlugin.Util.getString("ERR.015.004.0009")); //$NON-NLS-1$
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,573 @@
+/*
+ * 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.relational;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+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;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataID;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.optimizer.relational.plantree.NodeConstants;
+import org.teiid.query.optimizer.relational.plantree.PlanNode;
+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.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.GroupingNode;
+import org.teiid.query.processor.relational.InsertPlanExecutionNode;
+import org.teiid.query.processor.relational.JoinNode;
+import org.teiid.query.processor.relational.LimitNode;
+import org.teiid.query.processor.relational.MergeJoinStrategy;
+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;
+import org.teiid.query.processor.relational.RelationalNode;
+import org.teiid.query.processor.relational.RelationalPlan;
+import org.teiid.query.processor.relational.SelectNode;
+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.XMLTableNode;
+import org.teiid.query.processor.relational.JoinNode.JoinStrategyType;
+import org.teiid.query.processor.relational.MergeJoinStrategy.SortOption;
+import org.teiid.query.processor.relational.SortUtility.Mode;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.sql.lang.ArrayTable;
+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.JoinType;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.TableFunctionReference;
+import org.teiid.query.sql.lang.TextTable;
+import org.teiid.query.sql.lang.XMLTable;
+import org.teiid.query.sql.lang.SetQuery.Operation;
+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.GroupSymbol;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.sql.visitor.EvaluatableVisitor;
+import org.teiid.query.sql.visitor.GroupCollectorVisitor;
+
+
+public class PlanToProcessConverter {
+ protected QueryMetadataInterface metadata;
+ private IDGenerator idGenerator;
+ private AnalysisRecord analysisRecord;
+ private CapabilitiesFinder capFinder;
+
+ public PlanToProcessConverter(QueryMetadataInterface metadata, IDGenerator idGenerator, AnalysisRecord analysisRecord, CapabilitiesFinder capFinder) {
+ this.metadata = metadata;
+ this.idGenerator = idGenerator;
+ this.analysisRecord = analysisRecord;
+ this.capFinder = capFinder;
+ }
+
+ public RelationalPlan convert(PlanNode planNode)
+ throws QueryPlannerException, TeiidComponentException {
+
+ boolean debug = analysisRecord.recordDebug();
+ if(debug) {
+ analysisRecord.println("\n============================================================================"); //$NON-NLS-1$
+ analysisRecord.println("CONVERTING PLAN TREE TO PROCESS TREE"); //$NON-NLS-1$
+ }
+
+ // Convert plan tree nodes into process tree nodes
+ RelationalNode processNode = convertPlan(planNode);
+ if(debug) {
+ analysisRecord.println("\nPROCESS PLAN = \n" + processNode); //$NON-NLS-1$
+ analysisRecord.println("============================================================================"); //$NON-NLS-1$
+ }
+
+ RelationalPlan processPlan = new RelationalPlan(processNode);
+ return processPlan;
+
+ }
+
+ private RelationalNode convertPlan(PlanNode planNode)
+ throws QueryPlannerException, TeiidComponentException {
+
+ // Convert current node in planTree
+ RelationalNode convertedNode = convertNode(planNode);
+
+ if(convertedNode == null) {
+ Assertion.assertTrue(planNode.getChildCount() == 1);
+ return convertPlan(planNode.getFirstChild());
+ }
+
+ RelationalNode nextParent = convertedNode;
+
+ // convertedNode may be the head of 1 or more nodes - go to end of chain
+ while(nextParent.getChildren()[0] != null) {
+ nextParent = nextParent.getChildren()[0];
+ }
+
+ // Call convertPlan recursively on children
+ for (PlanNode childNode : planNode.getChildren()) {
+ RelationalNode child = convertPlan(childNode);
+ if (planNode.getType() == NodeConstants.Types.SET_OP && childNode.getType() == NodeConstants.Types.SET_OP && childNode.hasBooleanProperty(Info.USE_ALL)) {
+ for (RelationalNode grandChild : child.getChildren()) {
+ if (grandChild != null) {
+ nextParent.addChild(grandChild);
+ }
+ }
+ } else {
+ nextParent.addChild(child);
+ }
+ }
+
+ // Return root of tree for top node
+ return convertedNode;
+ }
+
+ protected int getID() {
+ IntegerIDFactory intFactory = (IntegerIDFactory) idGenerator.getDefaultFactory();
+ return ((IntegerID) intFactory.create()).getValue();
+ }
+
+ protected RelationalNode convertNode(PlanNode node)
+ throws QueryPlannerException, TeiidComponentException {
+
+ RelationalNode processNode = null;
+
+ switch(node.getType()) {
+ case NodeConstants.Types.PROJECT:
+ GroupSymbol intoGroup = (GroupSymbol) node.getProperty(NodeConstants.Info.INTO_GROUP);
+ if(intoGroup != null) {
+ try {
+ Insert insert = (Insert)node.getFirstChild().getProperty(Info.VIRTUAL_COMMAND);
+ List<ElementSymbol> allIntoElements = insert.getVariables();
+
+ Object groupID = intoGroup.getMetadataID();
+ Object modelID = metadata.getModelID(groupID);
+ String modelName = metadata.getFullName(modelID);
+ if (metadata.isVirtualGroup(groupID)) {
+ InsertPlanExecutionNode ipen = new InsertPlanExecutionNode(getID(), metadata);
+ ipen.setProcessorPlan((ProcessorPlan)node.getFirstChild().getProperty(Info.PROCESSOR_PLAN));
+ ipen.setReferences(insert.getValues());
+ processNode = ipen;
+ } else {
+ ProjectIntoNode pinode = new ProjectIntoNode(getID());
+ pinode.setIntoGroup(intoGroup);
+ pinode.setIntoElements(allIntoElements);
+ pinode.setModelName(modelName);
+ processNode = pinode;
+ SourceCapabilities caps = capFinder.findCapabilities(modelName);
+ if (caps.supportsCapability(Capability.INSERT_WITH_ITERATOR)) {
+ pinode.setMode(org.teiid.query.processor.relational.ProjectIntoNode.Mode.ITERATOR);
+ } else if (caps.supportsCapability(Capability.BULK_UPDATE)) {
+ pinode.setMode(org.teiid.query.processor.relational.ProjectIntoNode.Mode.BULK);
+ } else if (caps.supportsCapability(Capability.BATCHED_UPDATES)) {
+ pinode.setMode(org.teiid.query.processor.relational.ProjectIntoNode.Mode.BATCH);
+ } else {
+ pinode.setMode(org.teiid.query.processor.relational.ProjectIntoNode.Mode.SINGLE);
+ }
+ }
+ } catch(QueryMetadataException e) {
+ throw new TeiidComponentException(e);
+ }
+
+ } else {
+ List symbols = (List) node.getProperty(NodeConstants.Info.PROJECT_COLS);
+
+ ProjectNode pnode = new ProjectNode(getID());
+ pnode.setSelectSymbols(symbols);
+ processNode = pnode;
+ }
+ break;
+
+ case NodeConstants.Types.JOIN:
+ JoinType jtype = (JoinType) node.getProperty(NodeConstants.Info.JOIN_TYPE);
+ JoinStrategyType stype = (JoinStrategyType) node.getProperty(NodeConstants.Info.JOIN_STRATEGY);
+
+ JoinNode jnode = new JoinNode(getID());
+ jnode.setJoinType(jtype);
+ jnode.setLeftDistinct(node.hasBooleanProperty(NodeConstants.Info.IS_LEFT_DISTINCT));
+ jnode.setRightDistinct(node.hasBooleanProperty(NodeConstants.Info.IS_RIGHT_DISTINCT));
+ List joinCrits = (List) node.getProperty(NodeConstants.Info.JOIN_CRITERIA);
+ String depValueSource = (String) node.getProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE);
+ SortOption leftSort = (SortOption)node.getProperty(NodeConstants.Info.SORT_LEFT);
+ if(stype == JoinStrategyType.MERGE || stype == JoinStrategyType.ENHANCED_SORT) {
+ MergeJoinStrategy mjStrategy = null;
+ if (stype.equals(JoinStrategyType.ENHANCED_SORT)) {
+ 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);
+ }
+ jnode.setJoinStrategy(mjStrategy);
+ List leftExpressions = (List) node.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS);
+ List rightExpressions = (List) node.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS);
+ jnode.setJoinExpressions(leftExpressions, rightExpressions);
+ joinCrits = (List) node.getProperty(NodeConstants.Info.NON_EQUI_JOIN_CRITERIA);
+ } else if (stype == JoinStrategyType.NESTED_TABLE) {
+ NestedTableJoinStrategy ntjStrategy = new NestedTableJoinStrategy();
+ jnode.setJoinStrategy(ntjStrategy);
+ SymbolMap references = (SymbolMap)FrameUtil.findJoinSourceNode(node.getFirstChild()).getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
+ ntjStrategy.setLeftMap(references);
+ references = (SymbolMap)FrameUtil.findJoinSourceNode(node.getLastChild()).getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
+ ntjStrategy.setRightMap(references);
+ } else {
+ NestedLoopJoinStrategy nljStrategy = new NestedLoopJoinStrategy();
+ jnode.setJoinStrategy(nljStrategy);
+ }
+ Criteria joinCrit = Criteria.combineCriteria(joinCrits);
+ jnode.setJoinCriteria(joinCrit);
+
+ processNode = jnode;
+
+ jnode.setDependentValueSource(depValueSource);
+
+ break;
+
+ case NodeConstants.Types.ACCESS:
+ ProcessorPlan plan = (ProcessorPlan) node.getProperty(NodeConstants.Info.PROCESSOR_PLAN);
+ if(plan != null) {
+
+ PlanExecutionNode peNode = null;
+
+ Criteria crit = (Criteria)node.getProperty(NodeConstants.Info.PROCEDURE_CRITERIA);
+
+ if (crit != null) {
+ List references = (List)node.getProperty(NodeConstants.Info.PROCEDURE_INPUTS);
+ List defaults = (List)node.getProperty(NodeConstants.Info.PROCEDURE_DEFAULTS);
+
+ peNode = new DependentProcedureExecutionNode(getID(), crit, references, defaults);
+ } else {
+ peNode = new PlanExecutionNode(getID());
+ }
+
+ peNode.setProcessorPlan(plan);
+ processNode = peNode;
+
+ } else {
+ AccessNode aNode = null;
+ Command command = (Command) node.getProperty(NodeConstants.Info.ATOMIC_REQUEST);
+ Object modelID = node.getProperty(NodeConstants.Info.MODEL_ID);
+
+ if(node.hasBooleanProperty(NodeConstants.Info.IS_DEPENDENT_SET)) {
+ if (command instanceof StoredProcedure) {
+ List references = (List)node.getProperty(NodeConstants.Info.PROCEDURE_INPUTS);
+ List defaults = (List)node.getProperty(NodeConstants.Info.PROCEDURE_DEFAULTS);
+ Criteria crit = (Criteria)node.getProperty(NodeConstants.Info.PROCEDURE_CRITERIA);
+
+ DependentProcedureAccessNode depAccessNode = new DependentProcedureAccessNode(getID(), crit, references, defaults);
+ processNode = depAccessNode;
+ aNode = depAccessNode;
+ } else {
+ //create dependent access node
+ DependentAccessNode depAccessNode = new DependentAccessNode(getID());
+
+ if(modelID != null){
+ depAccessNode.setMaxSetSize(CapabilitiesUtil.getMaxInCriteriaSize(modelID, metadata, capFinder));
+ depAccessNode.setMaxPredicates(CapabilitiesUtil.getMaxDependentPredicates(modelID, metadata, capFinder));
+ }
+ processNode = depAccessNode;
+ aNode = depAccessNode;
+ }
+ aNode.setShouldEvaluateExpressions(true);
+ } else {
+
+ // create access node
+ aNode = new AccessNode(getID());
+ processNode = aNode;
+
+ //-- special handling for temp tables. currently they cannot perform projection
+ try {
+ if (command instanceof Query) {
+ processNode = correctProjectionInternalTables(node, aNode);
+ }
+ } catch (QueryMetadataException err) {
+ throw new TeiidComponentException(err);
+ }
+ aNode.setShouldEvaluateExpressions(EvaluatableVisitor.needsProcessingEvaluation(command));
+ }
+
+ if (command instanceof QueryCommand) {
+ try {
+ command = (Command)command.clone();
+ boolean aliasGroups = modelID != null && CapabilitiesUtil.supportsGroupAliases(modelID, metadata, capFinder);
+ boolean aliasColumns = modelID != null && CapabilitiesUtil.supports(Capability.QUERY_SELECT_EXPRESSION, modelID, metadata, capFinder);
+ command.acceptVisitor(new AliasGenerator(aliasGroups, !aliasColumns));
+ } catch (QueryMetadataException err) {
+ throw new TeiidComponentException(err);
+ }
+ }
+ aNode.setCommand(command);
+ if (!aNode.isShouldEvaluate()) {
+ aNode.minimizeProject(command);
+ }
+ setRoutingName(aNode, node);
+ }
+ break;
+
+ case NodeConstants.Types.SELECT:
+
+ Criteria crit = (Criteria) node.getProperty(NodeConstants.Info.SELECT_CRITERIA);
+
+ SelectNode selnode = new SelectNode(getID());
+ selnode.setCriteria(crit);
+ processNode = selnode;
+
+ break;
+
+ case NodeConstants.Types.SORT:
+ case NodeConstants.Types.DUP_REMOVE:
+ SortNode sortNode = new SortNode(getID());
+ OrderBy orderBy = (OrderBy) node.getProperty(NodeConstants.Info.SORT_ORDER);
+ if (orderBy != null) {
+ sortNode.setSortElements(orderBy.getOrderByItems());
+ }
+ if (node.getType() == NodeConstants.Types.DUP_REMOVE) {
+ sortNode.setMode(Mode.DUP_REMOVE);
+ } else if (node.hasBooleanProperty(NodeConstants.Info.IS_DUP_REMOVAL)) {
+ sortNode.setMode(Mode.DUP_REMOVE_SORT);
+ }
+
+ processNode = sortNode;
+ break;
+ case NodeConstants.Types.GROUP:
+ GroupingNode gnode = new GroupingNode(getID());
+ gnode.setGroupingElements( (List) node.getProperty(NodeConstants.Info.GROUP_COLS) );
+ gnode.setRemoveDuplicates(node.hasBooleanProperty(NodeConstants.Info.IS_DUP_REMOVAL));
+ processNode = gnode;
+ break;
+
+ case NodeConstants.Types.SOURCE:
+ SymbolMap symbolMap = (SymbolMap) node.getProperty(NodeConstants.Info.SYMBOL_MAP);
+ if(symbolMap != null) {
+ PlanNode child = node.getLastChild();
+
+ if (node.getParent().getType() != NodeConstants.Types.PROJECT || node.getParent().getProperty(NodeConstants.Info.INTO_GROUP) == null) {
+ if (child.getType() == NodeConstants.Types.PROJECT) {
+ //update the project cols based upon the original output
+ child.setProperty(NodeConstants.Info.PROJECT_COLS, child.getProperty(NodeConstants.Info.OUTPUT_COLS));
+ }
+ child.setProperty(NodeConstants.Info.OUTPUT_COLS, node.getProperty(NodeConstants.Info.OUTPUT_COLS));
+ }
+ }
+ Object source = node.getProperty(NodeConstants.Info.TABLE_FUNCTION);
+ if (source instanceof XMLTable) {
+ XMLTable xt = (XMLTable)source;
+ XMLTableNode xtn = new XMLTableNode(getID());
+ //we handle the projection filtering once here rather than repeating the
+ //path analysis on a per plan basis
+ updateGroupName(node, xt);
+ Map elementMap = RelationalNode.createLookupMap(xt.getProjectedSymbols());
+ List cols = (List) node.getProperty(NodeConstants.Info.OUTPUT_COLS);
+ int[] projectionIndexes = RelationalNode.getProjectionIndexes(elementMap, cols);
+ ArrayList<XMLColumn> filteredColumns = new ArrayList<XMLColumn>(projectionIndexes.length);
+ for (int col : projectionIndexes) {
+ filteredColumns.add(xt.getColumns().get(col));
+ }
+ xt.getXQueryExpression().useDocumentProjection(filteredColumns, analysisRecord);
+ xtn.setProjectedColumns(filteredColumns);
+ xtn.setTable(xt);
+ processNode = xtn;
+ break;
+ }
+ if (source instanceof TextTable) {
+ TextTableNode ttn = new TextTableNode(getID());
+ TextTable tt = (TextTable)source;
+ updateGroupName(node, tt);
+ ttn.setTable(tt);
+ processNode = ttn;
+ break;
+ }
+ if (source instanceof ArrayTable) {
+ ArrayTableNode atn = new ArrayTableNode(getID());
+ ArrayTable at = (ArrayTable)source;
+ updateGroupName(node, at);
+ atn.setTable(at);
+ processNode = atn;
+ break;
+ }
+ return null;
+ case NodeConstants.Types.SET_OP:
+ Operation setOp = (Operation) node.getProperty(NodeConstants.Info.SET_OPERATION);
+ boolean useAll = ((Boolean) node.getProperty(NodeConstants.Info.USE_ALL)).booleanValue();
+ if(setOp == Operation.UNION) {
+ RelationalNode unionAllNode = new UnionAllNode(getID());
+
+ if(useAll) {
+ processNode = unionAllNode;
+ } else {
+ SortNode sNode = new SortNode(getID());
+ boolean onlyDupRemoval = node.hasBooleanProperty(NodeConstants.Info.IS_DUP_REMOVAL);
+ sNode.setMode(onlyDupRemoval?Mode.DUP_REMOVE:Mode.DUP_REMOVE_SORT);
+ processNode = sNode;
+
+ unionAllNode.setElements( (List) node.getProperty(NodeConstants.Info.OUTPUT_COLS) );
+ processNode.addChild(unionAllNode);
+ }
+ } else {
+ JoinNode joinAsSet = new JoinNode(getID());
+ joinAsSet.setJoinStrategy(new MergeJoinStrategy(SortOption.SORT_DISTINCT, SortOption.SORT_DISTINCT, true));
+ List leftExpressions = (List) node.getFirstChild().getProperty(NodeConstants.Info.OUTPUT_COLS);
+ List rightExpressions = (List) node.getLastChild().getProperty(NodeConstants.Info.OUTPUT_COLS);
+ joinAsSet.setJoinType(setOp == Operation.EXCEPT ? JoinType.JOIN_ANTI_SEMI : JoinType.JOIN_SEMI);
+ joinAsSet.setJoinExpressions(leftExpressions, rightExpressions);
+ processNode = joinAsSet;
+ }
+
+ break;
+
+ case NodeConstants.Types.TUPLE_LIMIT:
+ Expression rowLimit = (Expression)node.getProperty(NodeConstants.Info.MAX_TUPLE_LIMIT);
+ Expression offset = (Expression)node.getProperty(NodeConstants.Info.OFFSET_TUPLE_COUNT);
+ LimitNode ln = new LimitNode(getID(), rowLimit, offset);
+ ln.setImplicit(node.hasBooleanProperty(Info.IS_IMPLICIT_LIMIT));
+ processNode = ln;
+ break;
+
+ case NodeConstants.Types.NULL:
+ processNode = new NullNode(getID());
+ break;
+
+ default:
+ throw new QueryPlannerException(QueryPlugin.Util.getString("ERR.015.004.0007", NodeConstants.getNodeTypeString(node.getType()))); //$NON-NLS-1$
+ }
+
+ if(processNode != null) {
+ processNode = prepareToAdd(node, processNode);
+ }
+
+ return processNode;
+ }
+
+ private void updateGroupName(PlanNode node, TableFunctionReference tt) {
+ String groupName = node.getGroups().iterator().next().getName();
+ tt.getGroupSymbol().setName(groupName);
+ for (ElementSymbol symbol : tt.getProjectedSymbols()) {
+ symbol.setGroupSymbol(new GroupSymbol(groupName));
+ }
+ }
+
+ private RelationalNode correctProjectionInternalTables(PlanNode node,
+ AccessNode aNode) throws QueryMetadataException,
+ TeiidComponentException {
+ if (node.getGroups().size() != 1) {
+ return aNode;
+ }
+ GroupSymbol group = node.getGroups().iterator().next();
+ if (!CoreConstants.SYSTEM_MODEL.equals(metadata.getFullName(metadata.getModelID(group.getMetadataID())))
+ && !CoreConstants.SYSTEM_ADMIN_MODEL.equals(metadata.getFullName(metadata.getModelID(group.getMetadataID())))) {
+ return aNode;
+ }
+ List projectSymbols = (List) node.getProperty(NodeConstants.Info.OUTPUT_COLS);
+ List<ElementSymbol> acutalColumns = ResolverUtil.resolveElementsInGroup(group, metadata);
+ if (projectSymbols.equals(acutalColumns)) {
+ return aNode;
+ }
+ node.setProperty(NodeConstants.Info.OUTPUT_COLS, acutalColumns);
+ if (node.getParent() != null && node.getParent().getType() == NodeConstants.Types.PROJECT) {
+ //if the parent is already a project, just correcting the output cols is enough
+ return aNode;
+ }
+ ProjectNode pnode = new ProjectNode(getID());
+
+ pnode.setSelectSymbols(projectSymbols);
+ //if the following cast fails it means that we have a dependent temp table - that is not yet possible
+ aNode = (AccessNode)prepareToAdd(node, aNode);
+ node.setProperty(NodeConstants.Info.OUTPUT_COLS, projectSymbols);
+ pnode.addChild(aNode);
+ return pnode;
+ }
+
+ private RelationalNode prepareToAdd(PlanNode node,
+ RelationalNode processNode) {
+ // Set the output elements from the plan node
+ List cols = (List) node.getProperty(NodeConstants.Info.OUTPUT_COLS);
+
+ processNode.setElements(cols);
+
+ // Set the Cost Estimates
+ Number estimateNodeCardinality = (Number) node.getProperty(NodeConstants.Info.EST_CARDINALITY);
+ processNode.setEstimateNodeCardinality(estimateNodeCardinality);
+ Number estimateNodeSetSize = (Number) node.getProperty(NodeConstants.Info.EST_SET_SIZE);
+ processNode.setEstimateNodeSetSize(estimateNodeSetSize);
+ Number estimateDepAccessCardinality = (Number) node.getProperty(NodeConstants.Info.EST_DEP_CARDINALITY);
+ processNode.setEstimateDepAccessCardinality(estimateDepAccessCardinality);
+ Number estimateDepJoinCost = (Number) node.getProperty(NodeConstants.Info.EST_DEP_JOIN_COST);
+ processNode.setEstimateDepJoinCost(estimateDepJoinCost);
+ Number estimateJoinCost = (Number) node.getProperty(NodeConstants.Info.EST_JOIN_COST);
+ processNode.setEstimateJoinCost(estimateJoinCost);
+
+ return processNode;
+ }
+
+ private void setRoutingName(AccessNode accessNode, PlanNode node)
+ throws QueryPlannerException, TeiidComponentException {
+
+ // Look up connector binding name
+ try {
+ Object modelID = node.getProperty(NodeConstants.Info.MODEL_ID);
+ if(modelID == null || modelID instanceof TempMetadataID) {
+ Command command = (Command) node.getProperty(NodeConstants.Info.ATOMIC_REQUEST);
+ if(command instanceof StoredProcedure){
+ modelID = ((StoredProcedure)command).getModelID();
+ }else{
+ Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(command, true);
+ GroupSymbol group = groups.iterator().next();
+
+ modelID = metadata.getModelID(group.getMetadataID());
+ }
+ }
+ String cbName = metadata.getFullName(modelID);
+ accessNode.setModelName(cbName);
+ accessNode.setModelId(modelID);
+ } catch(QueryMetadataException e) {
+ throw new QueryPlannerException(e, QueryPlugin.Util.getString("ERR.015.004.0009")); //$NON-NLS-1$
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1192 +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.optimizer.relational;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-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.client.plan.Annotation;
-import org.teiid.client.plan.Annotation.Priority;
-import org.teiid.common.buffer.LobManager;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.id.IDGenerator;
-import org.teiid.dqp.internal.process.Request;
-import org.teiid.language.SQLConstants;
-import org.teiid.metadata.Procedure;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.metadata.TempMetadataID;
-import org.teiid.query.optimizer.QueryOptimizer;
-import org.teiid.query.optimizer.TriggerActionPlanner;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-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.optimizer.relational.rules.CapabilitiesUtil;
-import org.teiid.query.optimizer.relational.rules.CriteriaCapabilityValidatorVisitor;
-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.processor.ProcessorPlan;
-import org.teiid.query.processor.relational.RelationalPlan;
-import org.teiid.query.processor.relational.JoinNode.JoinStrategyType;
-import org.teiid.query.resolver.ProcedureContainerResolver;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.rewriter.QueryRewriter;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.LanguageObject.Util;
-import org.teiid.query.sql.lang.CacheHint;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.From;
-import org.teiid.query.sql.lang.FromClause;
-import org.teiid.query.sql.lang.GroupBy;
-import org.teiid.query.sql.lang.Insert;
-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.Option;
-import org.teiid.query.sql.lang.OrderBy;
-import org.teiid.query.sql.lang.ProcedureContainer;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.SubqueryContainer;
-import org.teiid.query.sql.lang.SubqueryFromClause;
-import org.teiid.query.sql.lang.TableFunctionReference;
-import org.teiid.query.sql.lang.TargetedCommand;
-import org.teiid.query.sql.lang.TranslatableProcedureContainer;
-import org.teiid.query.sql.lang.UnaryFromClause;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.lang.WithQueryCommand;
-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.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.symbol.ScalarSubquery;
-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.sql.visitor.AggregateSymbolCollectorVisitor;
-import org.teiid.query.sql.visitor.CorrelatedReferenceCollectorVisitor;
-import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
-import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
-import org.teiid.query.util.CommandContext;
-import org.teiid.query.validator.ValidationVisitor;
-import org.teiid.query.validator.UpdateValidator.UpdateInfo;
-
-
-/**
- * This class generates a relational plan for query execution. The output of
- * this class is a {@link org.teiid.query.optimizer.relational.plantree.PlanNode PlanNode}
- * object - this object then becomes the input to
- * {@link PlanToProcessConverter PlanToProcessConverter}
- * to produce a
- * {@link org.teiid.query.processor.relational.RelationalPlan RelationalPlan}.
- */
-public class RelationalPlanner {
-
- public static final String MAT_PREFIX = "#MAT_"; //$NON-NLS-1$
-
- private AnalysisRecord analysisRecord;
- private Command parentCommand;
- private IDGenerator idGenerator;
- private CommandContext context;
- private CapabilitiesFinder capFinder;
- private QueryMetadataInterface metadata;
- private PlanHints hints = new PlanHints();
- private Option option;
-
- public ProcessorPlan optimize(
- Command command)
- throws
- QueryPlannerException,
- QueryMetadataException,
- TeiidComponentException {
-
- boolean debug = analysisRecord.recordDebug();
- if(debug) {
- analysisRecord.println("\n----------------------------------------------------------------------------"); //$NON-NLS-1$
- analysisRecord.println("GENERATE CANONICAL: \n" + command); //$NON-NLS-1$
- }
-
- PlanToProcessConverter planToProcessConverter = null;
- if (context != null) {
- planToProcessConverter = context.getPlanToProcessConverter();
- }
- if (planToProcessConverter == null) {
- planToProcessConverter = new PlanToProcessConverter(metadata, idGenerator, analysisRecord, capFinder);
- }
-
- //plan with
- List<WithQueryCommand> withList = null;
- Object modelID = null;
- boolean supportsWithPushdown = true;
- List<WithQueryCommand> pushDownWith = null;
- if (command instanceof QueryCommand) {
- QueryCommand queryCommand = (QueryCommand)command;
- final HashSet<String> names = new HashSet<String>();
- if (queryCommand.getWith() != null) {
- withList = queryCommand.getWith();
- for (WithQueryCommand with : queryCommand.getWith()) {
- 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);
- }
- if (modelID == null) {
- supportsWithPushdown = false;
- } else {
- if (pushDownWith == null) {
- pushDownWith = new ArrayList<WithQueryCommand>();
- }
- WithQueryCommand wqc = new WithQueryCommand(with.getGroupSymbol(), with.getColumns(), withCommand);
- pushDownWith.add(wqc);
- }
- names.add(with.getGroupSymbol().getCanonicalName());
- }
- if (modelID != null && supportsWithPushdown) {
- supportsWithPushdown = CapabilitiesUtil.supports(Capability.COMMON_TABLE_EXPRESSIONS, modelID, metadata, capFinder);
- }
- if (supportsWithPushdown) {
- addModelIds(command, modelID, names);
- }
- }
- }
-
- PlanNode plan;
- try {
- plan = generatePlan(command);
- } catch (TeiidProcessingException e) {
- throw new QueryPlannerException(e, e.getMessage());
- }
-
- if(debug) {
- analysisRecord.println("\nCANONICAL PLAN: \n" + plan); //$NON-NLS-1$
- }
-
- // Connect ProcessorPlan to SubqueryContainer (if any) of SELECT or PROJECT nodes
- connectSubqueryContainers(plan); //TODO: merge with node creation
-
- // Set top column information on top node
- List<SingleElementSymbol> topCols = Util.deepClone(command.getProjectedSymbols(), SingleElementSymbol.class);
-
- // Build rule set based on hints
- RuleStack rules = buildRules();
-
- // Run rule-based optimizer
- plan = executeRules(rules, plan);
-
- 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) {
- supportsWithPushdown = false;
- } else {
- queryCommand.setWith(pushDownWith);
- }
- } else {
- supportsWithPushdown = false;
- }
- }
- if (!supportsWithPushdown) {
- result.setWith(withList);
- }
- result.setOutputElements(topCols);
-
- return result;
- }
-
- /**
- * mark all relevant group symbols as being from the modelid
- * @param command
- * @param modelID
- * @param names
- */
- private void addModelIds(Command command, final Object modelID,
- final HashSet<String> names) {
- PreOrPostOrderNavigator.doVisit(command, new LanguageVisitor() {
- @Override
- public void visit(UnaryFromClause obj) {
- GroupSymbol group = obj.getGroup();
- if (names.contains(group.getNonCorrelationName().toUpperCase())) {
- group.setModelMetadataId(modelID);
- }
- }
- }, PreOrPostOrderNavigator.POST_ORDER, true);
- }
-
- public void initialize(Command command, IDGenerator idGenerator,
- QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
- AnalysisRecord analysisRecord, CommandContext context) {
- this.parentCommand = command;
- this.idGenerator = idGenerator;
- this.metadata = metadata;
- this.capFinder = capFinder;
- this.analysisRecord = analysisRecord;
- this.context = context;
- }
-
- private void connectSubqueryContainers(PlanNode plan) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
- Set<GroupSymbol> groupSymbols = getGroupSymbols(plan);
-
- for (PlanNode node : NodeEditor.findAllNodes(plan, NodeConstants.Types.PROJECT | NodeConstants.Types.SELECT | NodeConstants.Types.JOIN)) {
- List<SubqueryContainer> subqueryContainers = node.getSubqueryContainers();
- if (subqueryContainers.isEmpty()){
- continue;
- }
- Set<GroupSymbol> localGroupSymbols = groupSymbols;
- if (node.getType() == NodeConstants.Types.JOIN) {
- localGroupSymbols = getGroupSymbols(node);
- }
- for (SubqueryContainer container : subqueryContainers) {
- //a clone is needed here because the command could get modified during planning
- Command subCommand = (Command)container.getCommand().clone();
- ArrayList<Reference> correlatedReferences = new ArrayList<Reference>();
- CorrelatedReferenceCollectorVisitor.collectReferences(subCommand, localGroupSymbols, correlatedReferences);
- ProcessorPlan procPlan = QueryOptimizer.optimizePlan(subCommand, metadata, idGenerator, capFinder, analysisRecord, context);
- container.getCommand().setProcessorPlan(procPlan);
- if (!correlatedReferences.isEmpty()) {
- SymbolMap map = new SymbolMap();
- for (Reference reference : correlatedReferences) {
- map.addMapping(reference.getExpression(), reference.getExpression());
- }
- container.getCommand().setCorrelatedReferences(map);
- }
- }
- node.addGroups(GroupsUsedByElementsVisitor.getGroups(node.getCorrelatedReferenceElements()));
- }
- }
-
- private static Set<GroupSymbol> getGroupSymbols(PlanNode plan) {
- Set<GroupSymbol> groupSymbols = new HashSet<GroupSymbol>();
- for (PlanNode source : NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE)) {
- groupSymbols.addAll(source.getGroups());
- }
- return groupSymbols;
- }
-
- /**
- * Distribute and "make (not) dependent" hints specified in the query into the
- * fully resolved query plan. This is done after virtual group resolution so
- * that all groups in the plan are known. The hint is attached to all SOURCE
- * nodes for each group that should be made dependent/not dependent.
- * @param groups List of groups (Strings) to be made dependent
- * @param plan The canonical plan
- */
- private void distributeDependentHints(Collection<String> groups, PlanNode plan, NodeConstants.Info hintProperty)
- throws QueryMetadataException, TeiidComponentException {
-
- if(groups == null || groups.isEmpty()) {
- return;
- }
- // Get all source nodes
- List<PlanNode> nodes = NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE);
-
- // Walk through each dependent group hint and
- // attach to the correct source node
- for (String groupName : groups) {
- // Walk through nodes and apply hint to all that match group name
- boolean appliedHint = applyHint(nodes, groupName, hintProperty);
-
- if(! appliedHint) {
- //check if it is partial group name
- Collection groupNames = metadata.getGroupsForPartialName(groupName);
- if(groupNames.size() == 1) {
- groupName = (String)groupNames.iterator().next();
- appliedHint = applyHint(nodes, groupName, hintProperty);
- }
-
- if(! appliedHint) {
- String msg = QueryPlugin.Util.getString("ERR.015.004.0010", groupName); //$NON-NLS-1$
- if (this.analysisRecord.recordAnnotations()) {
- this.analysisRecord.addAnnotation(new Annotation(Annotation.HINTS, msg, "ignoring hint", Priority.MEDIUM)); //$NON-NLS-1$
- }
- }
- }
- }
- }
-
- private static boolean applyHint(List<PlanNode> nodes, String groupName, NodeConstants.Info hintProperty) {
- boolean appliedHint = false;
- for (PlanNode node : nodes) {
- GroupSymbol nodeGroup = node.getGroups().iterator().next();
-
- String sDefinition = nodeGroup.getDefinition();
-
- if (nodeGroup.getName().equalsIgnoreCase(groupName)
- || (sDefinition != null && sDefinition.equalsIgnoreCase(groupName)) ) {
- node.setProperty(hintProperty, Boolean.TRUE);
- appliedHint = true;
- }
- }
- return appliedHint;
- }
-
- public RuleStack buildRules() {
- RuleStack rules = new RuleStack();
-
- rules.push(RuleConstants.COLLAPSE_SOURCE);
-
- rules.push(RuleConstants.PLAN_SORTS);
-
- //TODO: update plan sorts to take advantage or semi-join ordering
- if (hints.hasJoin || hints.hasCriteria) {
- rules.push(new RuleMergeCriteria(idGenerator, capFinder, analysisRecord, context, metadata));
- }
-
- if(hints.hasJoin) {
- rules.push(RuleConstants.IMPLEMENT_JOIN_STRATEGY);
- }
-
- rules.push(RuleConstants.CALCULATE_COST);
-
- rules.push(RuleConstants.ASSIGN_OUTPUT_ELEMENTS);
-
- if (hints.hasLimit) {
- rules.push(RuleConstants.PUSH_LIMIT);
- }
- if (hints.hasRelationalProc) {
- rules.push(RuleConstants.PLAN_PROCEDURES);
- }
- if(hints.hasAggregates) {
- rules.push(RuleConstants.PUSH_AGGREGATES);
- }
- if(hints.hasJoin) {
- rules.push(RuleConstants.CHOOSE_DEPENDENT);
- }
- if(hints.hasJoin) {
- rules.push(RuleConstants.CHOOSE_JOIN_STRATEGY);
- rules.push(RuleConstants.RAISE_ACCESS);
- //after planning the joins, let the criteria be pushed back into place
- rules.push(RuleConstants.PUSH_SELECT_CRITERIA);
- rules.push(RuleConstants.PLAN_JOINS);
- }
- rules.push(RuleConstants.RAISE_ACCESS);
- if (hints.hasSetQuery) {
- rules.push(RuleConstants.PLAN_UNIONS);
- }
- if(hints.hasCriteria || hints.hasJoin) {
- //after copy criteria, it is no longer necessary to have phantom criteria nodes, so do some cleaning
- rules.push(RuleConstants.CLEAN_CRITERIA);
- }
- if(hints.hasJoin) {
- rules.push(RuleConstants.COPY_CRITERIA);
- rules.push(RuleConstants.PUSH_NON_JOIN_CRITERIA);
- }
- if(hints.hasVirtualGroups) {
- rules.push(RuleConstants.MERGE_VIRTUAL);
- }
- if(hints.hasCriteria) {
- rules.push(RuleConstants.PUSH_SELECT_CRITERIA);
- }
- if (hints.hasJoin && hints.hasSetQuery) {
- rules.push(RuleConstants.DECOMPOSE_JOIN);
- rules.push(RuleConstants.MERGE_VIRTUAL);
- }
- if (hints.hasJoin && hints.hasOptionalJoin) {
- rules.push(RuleConstants.REMOVE_OPTIONAL_JOINS);
- }
- if (hints.hasVirtualGroups || (hints.hasJoin && hints.hasOptionalJoin)) {
- //do initial filtering to make merging and optional join logic easier
- rules.push(RuleConstants.ASSIGN_OUTPUT_ELEMENTS);
- }
- rules.push(RuleConstants.PLACE_ACCESS);
- return rules;
- }
-
- private PlanNode executeRules(RuleStack rules, PlanNode plan)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- boolean debug = analysisRecord.recordDebug();
- while(! rules.isEmpty()) {
- if(debug) {
- analysisRecord.println("\n============================================================================"); //$NON-NLS-1$
- }
-
- OptimizerRule rule = rules.pop();
- if(debug) {
- analysisRecord.println("EXECUTING " + rule); //$NON-NLS-1$
- }
-
- plan = rule.execute(plan, metadata, capFinder, rules, analysisRecord, context);
- if(debug) {
- analysisRecord.println("\nAFTER: \n" + plan); //$NON-NLS-1$
- }
- }
- return plan;
- }
-
- public PlanNode generatePlan(Command cmd) throws TeiidComponentException, TeiidProcessingException {
- //cascade the option clause nocache
- Option savedOption = option;
- option = cmd.getOption();
- if (option == null) {
- if (savedOption != null) {
- option = savedOption;
- }
- } else if (savedOption != null && savedOption.isNoCache()) { //merge no cache settings
- if (savedOption.getNoCacheGroups() == null || savedOption.getNoCacheGroups().isEmpty()) {
- if (option.getNoCacheGroups() != null) {
- option.getNoCacheGroups().clear(); // full no cache
- }
- } else if (option.getNoCacheGroups() != null && !option.getNoCacheGroups().isEmpty()) {
- for (String noCache : savedOption.getNoCacheGroups()) {
- option.addNoCacheGroup(noCache); // only groups
- }
- }
- option.setNoCache(true);
- }
-
- PlanNode result = null;
- switch (cmd.getType()) {
- case Command.TYPE_QUERY:
- result = createQueryPlan((QueryCommand)cmd);
- break;
- case Command.TYPE_INSERT:
- case Command.TYPE_UPDATE:
- case Command.TYPE_DELETE:
- case Command.TYPE_CREATE:
- case Command.TYPE_DROP:
- result = createUpdatePlan(cmd);
- break;
- case Command.TYPE_STORED_PROCEDURE:
- result = createStoredProcedurePlan((StoredProcedure)cmd);
- break;
- default:
- throw new AssertionError("Invalid command type"); //$NON-NLS-1$
- }
- // Distribute make dependent hints as necessary
- if (cmd.getOption() != null) {
- if(cmd.getOption().getDependentGroups() != null) {
- distributeDependentHints(cmd.getOption().getDependentGroups(), result, NodeConstants.Info.MAKE_DEP);
- }
- if (cmd.getOption().getNotDependentGroups() != null) {
- distributeDependentHints(cmd.getOption().getNotDependentGroups(), result, NodeConstants.Info.MAKE_NOT_DEP);
- }
- }
- this.option = savedOption;
- return result;
- }
-
- PlanNode createUpdatePlan(Command command) throws TeiidComponentException, TeiidProcessingException {
- // Create top project node - define output columns for stored query / procedure
- PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
-
- // Set output columns
- List<SingleElementSymbol> cols = command.getProjectedSymbols();
- projectNode.setProperty(NodeConstants.Info.PROJECT_COLS, cols);
-
- // Define source of data for stored query / procedure
- PlanNode sourceNode = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
- sourceNode.setProperty(NodeConstants.Info.ATOMIC_REQUEST, command);
- sourceNode.setProperty(NodeConstants.Info.VIRTUAL_COMMAND, command);
- boolean usingTriggerAction = false;
- if (command instanceof ProcedureContainer) {
- ProcedureContainer container = (ProcedureContainer)command;
- usingTriggerAction = addNestedProcedure(sourceNode, container, container.getGroup().getMetadataID());
- }
- GroupSymbol target = ((TargetedCommand)command).getGroup();
- sourceNode.addGroup(target);
- Object id = getTrackableGroup(target, metadata);
- if (id != null) {
- context.accessedPlanningObject(id);
- }
- attachLast(projectNode, sourceNode);
-
- //for INTO query, attach source and project nodes
- if(!usingTriggerAction && command instanceof Insert){
- Insert insert = (Insert)command;
- if (insert.getQueryExpression() != null) {
- PlanNode plan = generatePlan(insert.getQueryExpression());
- attachLast(sourceNode, plan);
- mergeTempMetadata(insert.getQueryExpression(), insert);
- projectNode.setProperty(NodeConstants.Info.INTO_GROUP, insert.getGroup());
- }
- }
-
- return projectNode;
- }
-
- private boolean addNestedProcedure(PlanNode sourceNode,
- ProcedureContainer container, Object metadataId) throws TeiidComponentException,
- QueryMetadataException, TeiidProcessingException {
- if (container instanceof StoredProcedure) {
- StoredProcedure sp = (StoredProcedure)container;
- if (sp.getProcedureID() instanceof Procedure) {
- context.accessedPlanningObject(sp.getProcedureID());
- }
- }
- String cacheString = "transformation/" + container.getClass().getSimpleName().toUpperCase(); //$NON-NLS-1$
- Command c = (Command)metadata.getFromMetadataCache(metadataId, cacheString);
- if (c == null) {
- c = QueryResolver.expandCommand(container, metadata, analysisRecord);
- if (c != null) {
- Request.validateWithVisitor(new ValidationVisitor(), metadata, c);
- metadata.addToMetadataCache(metadataId, cacheString, c.clone());
- }
- } else {
- c = (Command)c.clone();
- if (c instanceof CreateUpdateProcedureCommand) {
- ((CreateUpdateProcedureCommand)c).setUserCommand(container);
- }
- }
- if (c != null) {
- if (c instanceof TriggerAction) {
- TriggerAction ta = (TriggerAction)c;
- ProcessorPlan plan = new TriggerActionPlanner().optimize(container, ta, idGenerator, metadata, capFinder, analysisRecord, context);
- sourceNode.setProperty(NodeConstants.Info.PROCESSOR_PLAN, plan);
- return true;
- }
- if (c.getCacheHint() != null) {
- if (container instanceof StoredProcedure) {
- boolean noCache = isNoCacheGroup(metadata, ((StoredProcedure) container).getProcedureID(), option);
- if (!noCache) {
- if (context.isResultSetCacheEnabled() && container.areResultsCachable() && LobManager.getLobIndexes(new ArrayList<ElementSymbol>(container.getProcedureParameters().keySet())) == null) {
- container.getGroup().setGlobalTable(true);
- container.setCacheHint(c.getCacheHint());
- recordAnnotation(analysisRecord, Annotation.CACHED_PROCEDURE, Priority.LOW, "SimpleQueryResolver.procedure_cache_used", container.getGroup()); //$NON-NLS-1$
- return false;
- }
- recordAnnotation(analysisRecord, Annotation.CACHED_PROCEDURE, Priority.MEDIUM, "SimpleQueryResolver.procedure_cache_not_usable", container.getGroup()); //$NON-NLS-1$
- } else {
- recordAnnotation(analysisRecord, Annotation.CACHED_PROCEDURE, Priority.LOW, "SimpleQueryResolver.procedure_cache_not_used", container.getGroup()); //$NON-NLS-1$
- }
- }
- }
- //skip the rewrite here, we'll do that in the optimizer
- //so that we know what the determinism level is.
- addNestedCommand(sourceNode, container.getGroup(), container, c, false);
- } else if (!container.getGroup().isTempTable() && //we hope for the best, and do a specific validation for subqueries below
- container instanceof TranslatableProcedureContainer //we force the evaluation of procedure params - TODO: inserts are fine except for nonpushdown functions on columns
- && !CriteriaCapabilityValidatorVisitor.canPushLanguageObject(container, metadata.getModelID(container.getGroup().getMetadataID()), metadata, capFinder, analysisRecord)) {
- //do a workaround of row-by-row processing for update/delete
- if (metadata.getUniqueKeysInGroup(container.getGroup().getMetadataID()).isEmpty()
- || !CapabilitiesUtil.supports(Capability.CRITERIA_COMPARE_EQ, metadata.getModelID(container.getGroup().getMetadataID()), metadata, capFinder)) {
- throw new QueryPlannerException(QueryPlugin.Util.getString("RelationalPlanner.nonpushdown_command", container)); //$NON-NLS-1$
- }
-
- //treat this as an update procedure
- if (container instanceof Update) {
- c = QueryRewriter.createUpdateProcedure((Update)container, metadata, context);
- } else {
- c = QueryRewriter.createDeleteProcedure((Delete)container, metadata, context);
- }
- addNestedCommand(sourceNode, container.getGroup(), container, c, false);
- return false;
- }
-
- //plan any subqueries in criteria/parameters/values
- for (SubqueryContainer<?> subqueryContainer : ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(container)) {
- if (c == null && container.getGroup().isTempTable()) {
- if (subqueryContainer.getCommand().getCorrelatedReferences() == null) {
- if (subqueryContainer instanceof ScalarSubquery) {
- ((ScalarSubquery) subqueryContainer).setShouldEvaluate(true);
- } else if (subqueryContainer instanceof ExistsCriteria) {
- ((ExistsCriteria) subqueryContainer).setShouldEvaluate(true);
- } else {
- throw new QueryPlannerException(QueryPlugin.Util.getString("RelationalPlanner.nonpushdown_command", container)); //$NON-NLS-1$
- }
- } else {
- throw new QueryPlannerException(QueryPlugin.Util.getString("RelationalPlanner.nonpushdown_command", container)); //$NON-NLS-1$
- }
- }
- ProcessorPlan plan = QueryOptimizer.optimizePlan(subqueryContainer.getCommand(), metadata, null, capFinder, analysisRecord, context);
- subqueryContainer.getCommand().setProcessorPlan(plan);
-
- if (c == null) {
- RuleCollapseSource.prepareSubquery(subqueryContainer);
- }
- }
- return false;
- }
-
- PlanNode createStoredProcedurePlan(StoredProcedure storedProc) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
- // Create top project node - define output columns for stored query / procedure
- PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
-
- // Set output columns
- List cols = storedProc.getProjectedSymbols();
- projectNode.setProperty(NodeConstants.Info.PROJECT_COLS, cols);
-
- // Define source of data for stored query / procedure
- PlanNode sourceNode = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
- sourceNode.setProperty(NodeConstants.Info.VIRTUAL_COMMAND, storedProc);
- addNestedProcedure(sourceNode, storedProc, storedProc.getProcedureID());
-
- hints.hasRelationalProc |= storedProc.isProcedureRelational();
-
- // Set group on source node
- sourceNode.addGroup(storedProc.getGroup());
-
- attachLast(projectNode, sourceNode);
-
- return projectNode;
- }
-
- PlanNode createQueryPlan(QueryCommand command)
- throws TeiidComponentException, TeiidProcessingException {
- // Build canonical plan
- PlanNode node = null;
- if(command instanceof Query) {
- node = createQueryPlan((Query) command);
- } else {
- hints.hasSetQuery = true;
- SetQuery query = (SetQuery)command;
- PlanNode leftPlan = createQueryPlan( query.getLeftQuery());
- PlanNode rightPlan = createQueryPlan( query.getRightQuery());
-
- node = NodeFactory.getNewNode(NodeConstants.Types.SET_OP);
- node.setProperty(NodeConstants.Info.SET_OPERATION, query.getOperation());
- node.setProperty(NodeConstants.Info.USE_ALL, query.isAll());
-
- attachLast(node, leftPlan);
- attachLast(node, rightPlan);
- }
-
- if(command.getOrderBy() != null) {
- node = attachSorting(node, command.getOrderBy());
- }
-
- if (command.getLimit() != null) {
- node = attachTupleLimit(node, command.getLimit(), hints);
- }
-
- return node;
- }
-
- private PlanNode createQueryPlan(Query query)
- throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
-
- PlanNode plan = null;
-
- if(query.getFrom() != null){
- FromClause fromClause = mergeClauseTrees(query.getFrom());
-
- PlanNode dummyRoot = new PlanNode();
-
- buildTree(fromClause, dummyRoot);
-
- plan = dummyRoot.getFirstChild();
-
- hints.hasJoin |= plan.getType() == NodeConstants.Types.JOIN;
-
- // Attach criteria on top
- if(query.getCriteria() != null) {
- plan = attachCriteria(plan, query.getCriteria(), false);
- hints.hasCriteria = true;
- }
-
- // Attach grouping node on top
- if(query.hasAggregates()) {
- plan = attachGrouping(plan, query, hints);
- }
-
- // Attach having criteria node on top
- if(query.getHaving() != null) {
- plan = attachCriteria(plan, query.getHaving(), true);
- hints.hasCriteria = true;
- }
-
- }
-
- // Attach project on top
- plan = attachProject(plan, query.getSelect());
-
- // Attach dup removal on top
- if(query.getSelect().isDistinct()) {
- plan = attachDupRemoval(plan);
- }
-
- return plan;
- }
-
- /**
- * 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();
-
- while (clauses.size() > 1) {
- FromClause first = (FromClause)from.getClauses().remove(0);
- FromClause second = (FromClause)from.getClauses().remove(0);
- JoinPredicate jp = new JoinPredicate(first, second, JoinType.JOIN_CROSS);
- clauses.add(0, jp);
- }
-
- return (FromClause)clauses.get(0);
- }
-
- /**
- * Build a join plan based on the structure in a clause. These structures should be
- * essentially the same tree, but with different objects and details.
- * @param clause Clause to build tree from
- * @param parent Parent node to attach join node structure to
- * @param sourceMap Map of group to source node, used for connecting children to join plan
- * @param markJoinsInternal Flag saying whether joins built in this method should be marked
- * as internal
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- * @throws TeiidProcessingException
- */
- void buildTree(FromClause clause, PlanNode parent)
- throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
-
- PlanNode node = null;
-
- if(clause instanceof UnaryFromClause) {
- // No join required
- UnaryFromClause ufc = (UnaryFromClause)clause;
- GroupSymbol group = ufc.getGroup();
- if (metadata.isVirtualGroup(group.getMetadataID())) {
- hints.hasVirtualGroups = true;
- }
- Command nestedCommand = ufc.getExpandedCommand();
- if (nestedCommand == null && !group.isProcedure()) {
- Object id = getTrackableGroup(group, metadata);
- if (id != null) {
- context.accessedPlanningObject(id);
- }
- if (!group.isTempGroupSymbol() && metadata.isVirtualGroup(group.getMetadataID())) {
- nestedCommand = resolveVirtualGroup(group);
- }
- }
- node = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
- if (group.getModelMetadataId() != null) {
- node.setProperty(Info.MODEL_ID, group.getModelMetadataId());
- }
- node.addGroup(group);
- if (nestedCommand != null) {
- UpdateInfo info = ProcedureContainerResolver.getUpdateInfo(group, metadata);
- if (info != null && info.getPartitionInfo() != null && !info.getPartitionInfo().isEmpty()) {
- node.setProperty(NodeConstants.Info.PARTITION_INFO, info.getPartitionInfo());
- }
- addNestedCommand(node, group, nestedCommand, nestedCommand, true);
- }
- parent.addLastChild(node);
- } else if(clause instanceof JoinPredicate) {
- JoinPredicate jp = (JoinPredicate) clause;
-
- // Set up new join node corresponding to this join predicate
- node = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- node.setProperty(NodeConstants.Info.JOIN_TYPE, jp.getJoinType());
- node.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.NESTED_LOOP);
- node.setProperty(NodeConstants.Info.JOIN_CRITERIA, jp.getJoinCriteria());
-
- if (jp.getJoinType() == JoinType.JOIN_LEFT_OUTER) {
- hints.hasOptionalJoin = true;
- }
-
- // Attach join node to parent
- parent.addLastChild(node);
-
- // Handle each child
- FromClause[] clauses = new FromClause[] {jp.getLeftClause(), jp.getRightClause()};
- for(int i=0; i<2; i++) {
- buildTree(clauses[i], node);
-
- // Add groups to joinNode
- for (PlanNode child : node.getChildren()) {
- node.addGroups(child.getGroups());
- }
- }
- } else if (clause instanceof SubqueryFromClause) {
- SubqueryFromClause sfc = (SubqueryFromClause)clause;
- GroupSymbol group = sfc.getGroupSymbol();
- Command nestedCommand = sfc.getCommand();
- node = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
- if (sfc.isTable()) {
- sfc.getCommand().setCorrelatedReferences(getCorrelatedReferences(parent, node, sfc));
- }
- node.addGroup(group);
- addNestedCommand(node, group, nestedCommand, nestedCommand, true);
- if (nestedCommand instanceof SetQuery) {
- Map<ElementSymbol, List<Set<Constant>>> partitionInfo = PartitionAnalyzer.extractPartionInfo((SetQuery)nestedCommand, ResolverUtil.resolveElementsInGroup(group, metadata));
- if (!partitionInfo.isEmpty()) {
- node.setProperty(NodeConstants.Info.PARTITION_INFO, partitionInfo);
- }
- }
- hints.hasVirtualGroups = true;
- parent.addLastChild(node);
- } else if (clause instanceof TableFunctionReference) {
- TableFunctionReference tt = (TableFunctionReference)clause;
- GroupSymbol group = tt.getGroupSymbol();
- node = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
- node.setProperty(NodeConstants.Info.TABLE_FUNCTION, tt);
- tt.setCorrelatedReferences(getCorrelatedReferences(parent, node, tt));
- node.addGroup(group);
- parent.addLastChild(node);
- }
-
- if (clause.isOptional()) {
- node.setProperty(NodeConstants.Info.IS_OPTIONAL, Boolean.TRUE);
- hints.hasOptionalJoin = true;
- }
-
- if (clause.isMakeDep()) {
- node.setProperty(NodeConstants.Info.MAKE_DEP, Boolean.TRUE);
- } else if (clause.isMakeNotDep()) {
- node.setProperty(NodeConstants.Info.MAKE_NOT_DEP, Boolean.TRUE);
- }
- }
-
- public static Object getTrackableGroup(GroupSymbol group, QueryMetadataInterface metadata)
- throws TeiidComponentException, QueryMetadataException {
- if (group.isTempGroupSymbol()) {
- QueryMetadataInterface qmi = metadata.getSessionMetadata();
- try {
- //exclude proc scoped temp tables
- if (group.isGlobalTable() || (qmi != null && qmi.getGroupID(group.getNonCorrelationName()) == group.getMetadataID())) {
- return group.getMetadataID();
- }
- } catch (QueryMetadataException e) {
- //not a session table
- }
- } else {
- return group.getMetadataID();
- }
- return null;
- }
-
- private SymbolMap getCorrelatedReferences(PlanNode parent, PlanNode node,
- LanguageObject lo) {
- PlanNode rootJoin = parent;
- while (rootJoin.getParent() != null && rootJoin.getParent().getType() == NodeConstants.Types.JOIN && !rootJoin.getParent().getGroups().isEmpty()) {
- rootJoin = rootJoin.getParent();
- }
- List<Reference> correlatedReferences = new ArrayList<Reference>();
- CorrelatedReferenceCollectorVisitor.collectReferences(lo, rootJoin.getGroups(), correlatedReferences);
-
- if (correlatedReferences.isEmpty()) {
- return null;
- }
- SymbolMap map = new SymbolMap();
- for (Reference reference : correlatedReferences) {
- map.addMapping(reference.getExpression(), reference.getExpression());
- }
- node.setProperty(NodeConstants.Info.CORRELATED_REFERENCES, map);
- return map;
- }
-
- private void addNestedCommand(PlanNode node,
- GroupSymbol group, Command nestedCommand, Command toPlan, boolean merge) throws TeiidComponentException, QueryMetadataException, TeiidProcessingException {
- if (nestedCommand instanceof QueryCommand) {
- //remove unnecessary order by
- QueryCommand queryCommand = (QueryCommand)nestedCommand;
- if (queryCommand.getLimit() == null) {
- queryCommand.setOrderBy(null);
- }
- if (merge && queryCommand.getWith() != null) {
- //TODO: should recontext with and merge
- merge = false;
- }
- }
- node.setProperty(NodeConstants.Info.NESTED_COMMAND, nestedCommand);
-
- if (merge && nestedCommand instanceof Query && QueryResolver.isXMLQuery((Query)nestedCommand, metadata)) {
- merge = false;
- }
-
- if (merge) {
- mergeTempMetadata(nestedCommand, parentCommand);
- PlanNode childRoot = generatePlan(nestedCommand);
- node.addFirstChild(childRoot);
- List<SingleElementSymbol> projectCols = nestedCommand.getProjectedSymbols();
- SymbolMap map = SymbolMap.createSymbolMap(group, projectCols, metadata);
- node.setProperty(NodeConstants.Info.SYMBOL_MAP, map);
- } else {
- QueryMetadataInterface actualMetadata = metadata;
- if (actualMetadata instanceof TempMetadataAdapter) {
- actualMetadata = ((TempMetadataAdapter)metadata).getMetadata();
- }
- ProcessorPlan plan = QueryOptimizer.optimizePlan(toPlan, actualMetadata, idGenerator, capFinder, analysisRecord, context);
- node.setProperty(NodeConstants.Info.PROCESSOR_PLAN, plan);
- }
- }
-
- /**
- * Attach all criteria above the join nodes. The optimizer will push these
- * criteria down to the appropriate source.
- * @param plan Existing plan, which joins all source groups
- * @param criteria Criteria from query
- * @return Updated tree
- */
- private static PlanNode attachCriteria(PlanNode plan, Criteria criteria, boolean isHaving) {
- List<Criteria> crits = Criteria.separateCriteriaByAnd(criteria);
-
- for (Criteria crit : crits) {
- PlanNode critNode = createSelectNode(crit, isHaving);
- attachLast(critNode, plan);
- plan = critNode;
- }
-
- return plan;
- }
-
- 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()) {
- critNode.setProperty(NodeConstants.Info.IS_HAVING, Boolean.TRUE);
- }
- // Add groups to crit node
- critNode.addGroups(GroupsUsedByElementsVisitor.getGroups(crit));
- critNode.addGroups(GroupsUsedByElementsVisitor.getGroups(critNode.getCorrelatedReferenceElements()));
- return critNode;
- }
-
- /**
- * Attach a grouping node at top of tree.
- * @param plan Existing plan
- * @param groupBy Group by clause, which may be null
- * @return Updated plan
- */
- private static PlanNode attachGrouping(PlanNode plan, Query query, PlanHints hints) {
- PlanNode groupNode = NodeFactory.getNewNode(NodeConstants.Types.GROUP);
-
- GroupBy groupBy = query.getGroupBy();
- if(groupBy != null) {
- groupNode.setProperty(NodeConstants.Info.GROUP_COLS, groupBy.getSymbols());
- groupNode.addGroups(GroupsUsedByElementsVisitor.getGroups(groupBy));
- }
-
- attachLast(groupNode, plan);
-
- // Mark in hints
- hints.hasAggregates = true;
-
- return groupNode;
- }
-
- /**
- * Attach SORT node at top of tree. The SORT may be pushed down to a source (or sources)
- * if possible by the optimizer.
- * @param plan Existing plan
- * @param orderBy Sort description from the query
- * @return Updated plan
- */
- private static PlanNode attachSorting(PlanNode plan, OrderBy orderBy) {
- PlanNode sortNode = NodeFactory.getNewNode(NodeConstants.Types.SORT);
-
- sortNode.setProperty(NodeConstants.Info.SORT_ORDER, orderBy);
- if (orderBy.hasUnrelated()) {
- sortNode.setProperty(Info.UNRELATED_SORT, true);
- }
- sortNode.addGroups(GroupsUsedByElementsVisitor.getGroups(orderBy));
-
- attachLast(sortNode, plan);
- return sortNode;
- }
-
- private static PlanNode attachTupleLimit(PlanNode plan, Limit limit, PlanHints hints) {
- hints.hasLimit = true;
- PlanNode limitNode = NodeFactory.getNewNode(NodeConstants.Types.TUPLE_LIMIT);
-
- boolean attach = false;
- if (limit.getOffset() != null) {
- limitNode.setProperty(NodeConstants.Info.OFFSET_TUPLE_COUNT, limit.getOffset());
- attach = true;
- }
- if (limit.getRowLimit() != null) {
- limitNode.setProperty(NodeConstants.Info.MAX_TUPLE_LIMIT, limit.getRowLimit());
- attach = true;
- }
- if (attach) {
- if (limit.isImplicit()) {
- limitNode.setProperty(Info.IS_IMPLICIT_LIMIT, true);
- }
- attachLast(limitNode, plan);
- plan = limitNode;
- }
- return plan;
- }
-
- /**
- * Attach DUP_REMOVE node at top of tree. The DUP_REMOVE may be pushed down
- * to a source (or sources) if possible by the optimizer.
- * @param plan Existing plan
- * @return Updated plan
- */
- private static PlanNode attachDupRemoval(PlanNode plan) {
- PlanNode dupNode = NodeFactory.getNewNode(NodeConstants.Types.DUP_REMOVE);
- attachLast(dupNode, plan);
- return dupNode;
- }
-
- private static PlanNode attachProject(PlanNode plan, Select select) {
- PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
- projectNode.setProperty(NodeConstants.Info.PROJECT_COLS, select.getProjectedSymbols());
-
- // Set groups
- projectNode.addGroups(GroupsUsedByElementsVisitor.getGroups(select));
-
- attachLast(projectNode, plan);
- return projectNode;
- }
-
- static final void attachLast(PlanNode parent, PlanNode child) {
- if(child != null) {
- parent.addLastChild(child);
- }
- }
-
- /**
- * Adds temp metadata (if any) of child command to temp metadata
- * (if any) of parent command.
- * @param childCommand
- * @param parentCommand
- */
- static void mergeTempMetadata(
- Command childCommand,
- Command parentCommand) {
- Map childTempMetadata = childCommand.getTemporaryMetadata();
- if (childTempMetadata != null && !childTempMetadata.isEmpty()){
- // Add to parent temp metadata
- Map parentTempMetadata = parentCommand.getTemporaryMetadata();
- if (parentTempMetadata == null){
- parentCommand.setTemporaryMetadata(new HashMap(childTempMetadata));
- } else {
- parentTempMetadata.putAll(childTempMetadata);
- }
- }
- }
-
- private Command resolveVirtualGroup(GroupSymbol virtualGroup)
- throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
-
- QueryNode qnode = null;
-
- Object metadataID = virtualGroup.getMetadataID();
- boolean noCache = isNoCacheGroup(metadata, metadataID, option);
- boolean isMaterializedGroup = metadata.hasMaterialization(metadataID);
- String cacheString = SQLConstants.Reserved.SELECT;
-
- if( isMaterializedGroup) {
- Object matMetadataId = metadata.getMaterialization(metadataID);
- String matTableName = null;
- CacheHint hint = null;
- boolean isImplicitGlobal = matMetadataId == null;
- if (isImplicitGlobal) {
- TempMetadataID tid = context.getGlobalTableStore().getGlobalTempTableMetadataId(metadataID, metadata);
- matTableName = tid.getID();
- hint = tid.getCacheHint();
- if (hint != null) {
- recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.cache_hint_used", virtualGroup, matTableName, tid); //$NON-NLS-1$
- }
- matMetadataId = tid;
- } else {
- matTableName = metadata.getFullName(matMetadataId);
- }
-
- if(noCache){
- //not use cache
- qnode = metadata.getVirtualPlan(metadataID);
- //TODO: update the table for defaultMat
- recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.materialized_table_not_used", virtualGroup, matTableName); //$NON-NLS-1$
- }else{
- this.context.accessedPlanningObject(matMetadataId);
- qnode = new QueryNode(null);
- Query query = createMatViewQuery(matMetadataId, matTableName, Arrays.asList(new AllSymbol()), isImplicitGlobal);
- query.setCacheHint(hint);
- qnode.setCommand(query);
- cacheString = "matview"; //$NON-NLS-1$
- recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.Query_was_redirected_to_Mat_table", virtualGroup, matTableName); //$NON-NLS-1$
- }
- } else {
- // Not a materialized view - query the primary transformation
- qnode = metadata.getVirtualPlan(metadataID);
- }
-
- Command result = (Command)QueryResolver.resolveView(virtualGroup, qnode, cacheString, metadata).getCommand().clone();
- return QueryRewriter.rewrite(result, metadata, context);
- }
-
- public static Query createMatViewQuery(Object matMetadataId, String matTableName, List<? extends SelectSymbol> select, boolean isGlobal) {
- Query query = new Query();
- query.setSelect(new Select(select));
- GroupSymbol gs = new GroupSymbol(matTableName);
- gs.setGlobalTable(isGlobal);
- gs.setMetadataID(matMetadataId);
- query.setFrom(new From(Arrays.asList(new UnaryFromClause(gs))));
- return query;
- }
-
- public static boolean isNoCacheGroup(QueryMetadataInterface metadata,
- Object metadataID,
- Option option) throws QueryMetadataException,
- TeiidComponentException {
- if(option == null || !option.isNoCache()){
- return false;
- }
- if(option.getNoCacheGroups() == null || option.getNoCacheGroups().isEmpty()){
- //only OPTION NOCACHE, no group specified
- return true;
- }
- String fullName = metadata.getFullName(metadataID);
- for (String groupName : option.getNoCacheGroups()) {
- if(groupName.equalsIgnoreCase(fullName)){
- return true;
- }
- }
- return false;
- }
-
- private static void recordAnnotation(AnalysisRecord analysis, String type, Priority priority, String msgKey, Object... parts) {
- if (analysis.recordAnnotations()) {
- Annotation annotation = new Annotation(type,
- QueryPlugin.Util.getString(msgKey, parts),
- null,
- priority);
- analysis.addAnnotation(annotation);
- }
- }
-
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1200 @@
+/*
+ * 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.relational;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+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.client.plan.Annotation;
+import org.teiid.client.plan.Annotation.Priority;
+import org.teiid.common.buffer.LobManager;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.id.IDGenerator;
+import org.teiid.dqp.internal.process.Request;
+import org.teiid.language.SQLConstants;
+import org.teiid.metadata.Procedure;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.metadata.TempMetadataID;
+import org.teiid.query.optimizer.QueryOptimizer;
+import org.teiid.query.optimizer.TriggerActionPlanner;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+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.optimizer.relational.rules.CapabilitiesUtil;
+import org.teiid.query.optimizer.relational.rules.CriteriaCapabilityValidatorVisitor;
+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.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;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.LanguageObject.Util;
+import org.teiid.query.sql.lang.CacheHint;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.From;
+import org.teiid.query.sql.lang.FromClause;
+import org.teiid.query.sql.lang.GroupBy;
+import org.teiid.query.sql.lang.Insert;
+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.Option;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.ProcedureContainer;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.SubqueryContainer;
+import org.teiid.query.sql.lang.SubqueryFromClause;
+import org.teiid.query.sql.lang.TableFunctionReference;
+import org.teiid.query.sql.lang.TargetedCommand;
+import org.teiid.query.sql.lang.TranslatableProcedureContainer;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.lang.WithQueryCommand;
+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.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.symbol.ScalarSubquery;
+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.sql.visitor.AggregateSymbolCollectorVisitor;
+import org.teiid.query.sql.visitor.CorrelatedReferenceCollectorVisitor;
+import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
+import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
+import org.teiid.query.util.CommandContext;
+import org.teiid.query.validator.ValidationVisitor;
+import org.teiid.query.validator.UpdateValidator.UpdateInfo;
+
+
+/**
+ * This class generates a relational plan for query execution. The output of
+ * this class is a {@link org.teiid.query.optimizer.relational.plantree.PlanNode PlanNode}
+ * object - this object then becomes the input to
+ * {@link PlanToProcessConverter PlanToProcessConverter}
+ * to produce a
+ * {@link org.teiid.query.processor.relational.RelationalPlan RelationalPlan}.
+ */
+public class RelationalPlanner {
+
+ public static final String MAT_PREFIX = "#MAT_"; //$NON-NLS-1$
+
+ private AnalysisRecord analysisRecord;
+ private Command parentCommand;
+ private IDGenerator idGenerator;
+ private CommandContext context;
+ private CapabilitiesFinder capFinder;
+ private QueryMetadataInterface metadata;
+ private PlanHints hints = new PlanHints();
+ private Option option;
+
+ public ProcessorPlan optimize(
+ Command command)
+ throws
+ QueryPlannerException,
+ QueryMetadataException,
+ TeiidComponentException {
+
+ boolean debug = analysisRecord.recordDebug();
+ if(debug) {
+ analysisRecord.println("\n----------------------------------------------------------------------------"); //$NON-NLS-1$
+ analysisRecord.println("GENERATE CANONICAL: \n" + command); //$NON-NLS-1$
+ }
+
+ PlanToProcessConverter planToProcessConverter = null;
+ if (context != null) {
+ planToProcessConverter = context.getPlanToProcessConverter();
+ }
+ if (planToProcessConverter == null) {
+ planToProcessConverter = new PlanToProcessConverter(metadata, idGenerator, analysisRecord, capFinder);
+ }
+
+ //plan with
+ List<WithQueryCommand> withList = null;
+ Object modelID = null;
+ boolean supportsWithPushdown = true;
+ List<WithQueryCommand> pushDownWith = null;
+ if (command instanceof QueryCommand) {
+ QueryCommand queryCommand = (QueryCommand)command;
+ final HashSet<String> names = new HashSet<String>();
+ if (queryCommand.getWith() != null) {
+ withList = queryCommand.getWith();
+ for (WithQueryCommand with : queryCommand.getWith()) {
+ Command subCommand = with.getCommand();
+ ProcessorPlan procPlan = QueryOptimizer.optimizePlan(subCommand, metadata, idGenerator, capFinder, analysisRecord, context);
+ subCommand.setProcessorPlan(procPlan);
+ AccessNode aNode = CriteriaCapabilityValidatorVisitor.getAccessNode(procPlan);
+ if (aNode != null && supportsWithPushdown) {
+ modelID = CriteriaCapabilityValidatorVisitor.validateCommandPushdown(modelID, metadata, capFinder, aNode);
+ }
+ QueryCommand withCommand = CriteriaCapabilityValidatorVisitor.getQueryCommand(aNode);
+ if (modelID == null || withCommand == null) {
+ supportsWithPushdown = false;
+ } else {
+ if (pushDownWith == null) {
+ pushDownWith = new ArrayList<WithQueryCommand>();
+ }
+ WithQueryCommand wqc = new WithQueryCommand(with.getGroupSymbol(), with.getColumns(), withCommand);
+ pushDownWith.add(wqc);
+ }
+ names.add(with.getGroupSymbol().getCanonicalName());
+ }
+ if (modelID != null && supportsWithPushdown) {
+ supportsWithPushdown = CapabilitiesUtil.supports(Capability.COMMON_TABLE_EXPRESSIONS, modelID, metadata, capFinder);
+ }
+ if (supportsWithPushdown) {
+ addModelIds(command, modelID, names);
+ }
+ }
+ }
+
+ PlanNode plan;
+ try {
+ plan = generatePlan(command);
+ } catch (TeiidProcessingException e) {
+ throw new QueryPlannerException(e, e.getMessage());
+ }
+
+ if(debug) {
+ analysisRecord.println("\nCANONICAL PLAN: \n" + plan); //$NON-NLS-1$
+ }
+
+ // Connect ProcessorPlan to SubqueryContainer (if any) of SELECT or PROJECT nodes
+ connectSubqueryContainers(plan); //TODO: merge with node creation
+
+ // Set top column information on top node
+ List<SingleElementSymbol> topCols = Util.deepClone(command.getProjectedSymbols(), SingleElementSymbol.class);
+
+ // Build rule set based on hints
+ RuleStack rules = buildRules();
+
+ // Run rule-based optimizer
+ plan = executeRules(rules, plan);
+
+ RelationalPlan result = planToProcessConverter.convert(plan);
+ if (withList != null && supportsWithPushdown) {
+ 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);
+ }
+ } else {
+ supportsWithPushdown = false;
+ }
+ }
+ if (!supportsWithPushdown) {
+ result.setWith(withList);
+ }
+ result.setOutputElements(topCols);
+
+ return result;
+ }
+
+ /**
+ * mark all relevant group symbols as being from the modelid
+ * @param command
+ * @param modelID
+ * @param names
+ */
+ private void addModelIds(Command command, final Object modelID,
+ final HashSet<String> names) {
+ PreOrPostOrderNavigator.doVisit(command, new LanguageVisitor() {
+ @Override
+ public void visit(UnaryFromClause obj) {
+ GroupSymbol group = obj.getGroup();
+ if (names.contains(group.getNonCorrelationName().toUpperCase())) {
+ group.setModelMetadataId(modelID);
+ }
+ }
+ }, PreOrPostOrderNavigator.POST_ORDER, true);
+ }
+
+ public void initialize(Command command, IDGenerator idGenerator,
+ QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
+ AnalysisRecord analysisRecord, CommandContext context) {
+ this.parentCommand = command;
+ this.idGenerator = idGenerator;
+ this.metadata = metadata;
+ this.capFinder = capFinder;
+ this.analysisRecord = analysisRecord;
+ this.context = context;
+ }
+
+ private void connectSubqueryContainers(PlanNode plan) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+ Set<GroupSymbol> groupSymbols = getGroupSymbols(plan);
+
+ for (PlanNode node : NodeEditor.findAllNodes(plan, NodeConstants.Types.PROJECT | NodeConstants.Types.SELECT | NodeConstants.Types.JOIN)) {
+ List<SubqueryContainer> subqueryContainers = node.getSubqueryContainers();
+ if (subqueryContainers.isEmpty()){
+ continue;
+ }
+ Set<GroupSymbol> localGroupSymbols = groupSymbols;
+ if (node.getType() == NodeConstants.Types.JOIN) {
+ localGroupSymbols = getGroupSymbols(node);
+ }
+ for (SubqueryContainer container : subqueryContainers) {
+ //a clone is needed here because the command could get modified during planning
+ Command subCommand = (Command)container.getCommand().clone();
+ ArrayList<Reference> correlatedReferences = new ArrayList<Reference>();
+ CorrelatedReferenceCollectorVisitor.collectReferences(subCommand, localGroupSymbols, correlatedReferences);
+ ProcessorPlan procPlan = QueryOptimizer.optimizePlan(subCommand, metadata, idGenerator, capFinder, analysisRecord, context);
+ container.getCommand().setProcessorPlan(procPlan);
+ if (!correlatedReferences.isEmpty()) {
+ SymbolMap map = new SymbolMap();
+ for (Reference reference : correlatedReferences) {
+ map.addMapping(reference.getExpression(), reference.getExpression());
+ }
+ container.getCommand().setCorrelatedReferences(map);
+ }
+ }
+ node.addGroups(GroupsUsedByElementsVisitor.getGroups(node.getCorrelatedReferenceElements()));
+ }
+ }
+
+ private static Set<GroupSymbol> getGroupSymbols(PlanNode plan) {
+ Set<GroupSymbol> groupSymbols = new HashSet<GroupSymbol>();
+ for (PlanNode source : NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE)) {
+ groupSymbols.addAll(source.getGroups());
+ }
+ return groupSymbols;
+ }
+
+ /**
+ * Distribute and "make (not) dependent" hints specified in the query into the
+ * fully resolved query plan. This is done after virtual group resolution so
+ * that all groups in the plan are known. The hint is attached to all SOURCE
+ * nodes for each group that should be made dependent/not dependent.
+ * @param groups List of groups (Strings) to be made dependent
+ * @param plan The canonical plan
+ */
+ private void distributeDependentHints(Collection<String> groups, PlanNode plan, NodeConstants.Info hintProperty)
+ throws QueryMetadataException, TeiidComponentException {
+
+ if(groups == null || groups.isEmpty()) {
+ return;
+ }
+ // Get all source nodes
+ List<PlanNode> nodes = NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE);
+
+ // Walk through each dependent group hint and
+ // attach to the correct source node
+ for (String groupName : groups) {
+ // Walk through nodes and apply hint to all that match group name
+ boolean appliedHint = applyHint(nodes, groupName, hintProperty);
+
+ if(! appliedHint) {
+ //check if it is partial group name
+ Collection groupNames = metadata.getGroupsForPartialName(groupName);
+ if(groupNames.size() == 1) {
+ groupName = (String)groupNames.iterator().next();
+ appliedHint = applyHint(nodes, groupName, hintProperty);
+ }
+
+ if(! appliedHint) {
+ String msg = QueryPlugin.Util.getString("ERR.015.004.0010", groupName); //$NON-NLS-1$
+ if (this.analysisRecord.recordAnnotations()) {
+ this.analysisRecord.addAnnotation(new Annotation(Annotation.HINTS, msg, "ignoring hint", Priority.MEDIUM)); //$NON-NLS-1$
+ }
+ }
+ }
+ }
+ }
+
+ private static boolean applyHint(List<PlanNode> nodes, String groupName, NodeConstants.Info hintProperty) {
+ boolean appliedHint = false;
+ for (PlanNode node : nodes) {
+ GroupSymbol nodeGroup = node.getGroups().iterator().next();
+
+ String sDefinition = nodeGroup.getDefinition();
+
+ if (nodeGroup.getName().equalsIgnoreCase(groupName)
+ || (sDefinition != null && sDefinition.equalsIgnoreCase(groupName)) ) {
+ node.setProperty(hintProperty, Boolean.TRUE);
+ appliedHint = true;
+ }
+ }
+ return appliedHint;
+ }
+
+ public RuleStack buildRules() {
+ RuleStack rules = new RuleStack();
+
+ rules.push(RuleConstants.COLLAPSE_SOURCE);
+
+ rules.push(RuleConstants.PLAN_SORTS);
+
+ //TODO: update plan sorts to take advantage or semi-join ordering
+ if (hints.hasJoin || hints.hasCriteria) {
+ rules.push(new RuleMergeCriteria(idGenerator, capFinder, analysisRecord, context, metadata));
+ }
+
+ if(hints.hasJoin) {
+ rules.push(RuleConstants.IMPLEMENT_JOIN_STRATEGY);
+ }
+
+ rules.push(RuleConstants.CALCULATE_COST);
+
+ rules.push(RuleConstants.ASSIGN_OUTPUT_ELEMENTS);
+
+ if (hints.hasLimit) {
+ rules.push(RuleConstants.PUSH_LIMIT);
+ }
+ if (hints.hasRelationalProc) {
+ rules.push(RuleConstants.PLAN_PROCEDURES);
+ }
+ if(hints.hasAggregates) {
+ rules.push(RuleConstants.PUSH_AGGREGATES);
+ }
+ if(hints.hasJoin) {
+ rules.push(RuleConstants.CHOOSE_DEPENDENT);
+ }
+ if(hints.hasJoin) {
+ rules.push(RuleConstants.CHOOSE_JOIN_STRATEGY);
+ rules.push(RuleConstants.RAISE_ACCESS);
+ //after planning the joins, let the criteria be pushed back into place
+ rules.push(RuleConstants.PUSH_SELECT_CRITERIA);
+ rules.push(RuleConstants.PLAN_JOINS);
+ }
+ rules.push(RuleConstants.RAISE_ACCESS);
+ if (hints.hasSetQuery) {
+ rules.push(RuleConstants.PLAN_UNIONS);
+ }
+ if(hints.hasCriteria || hints.hasJoin) {
+ //after copy criteria, it is no longer necessary to have phantom criteria nodes, so do some cleaning
+ rules.push(RuleConstants.CLEAN_CRITERIA);
+ }
+ if(hints.hasJoin) {
+ rules.push(RuleConstants.COPY_CRITERIA);
+ rules.push(RuleConstants.PUSH_NON_JOIN_CRITERIA);
+ }
+ if(hints.hasVirtualGroups) {
+ rules.push(RuleConstants.MERGE_VIRTUAL);
+ }
+ if(hints.hasCriteria) {
+ rules.push(RuleConstants.PUSH_SELECT_CRITERIA);
+ }
+ if (hints.hasJoin && hints.hasSetQuery) {
+ rules.push(RuleConstants.DECOMPOSE_JOIN);
+ rules.push(RuleConstants.MERGE_VIRTUAL);
+ }
+ if (hints.hasJoin && hints.hasOptionalJoin) {
+ rules.push(RuleConstants.REMOVE_OPTIONAL_JOINS);
+ }
+ if (hints.hasVirtualGroups || (hints.hasJoin && hints.hasOptionalJoin)) {
+ //do initial filtering to make merging and optional join logic easier
+ rules.push(RuleConstants.ASSIGN_OUTPUT_ELEMENTS);
+ }
+ rules.push(RuleConstants.PLACE_ACCESS);
+ return rules;
+ }
+
+ private PlanNode executeRules(RuleStack rules, PlanNode plan)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ boolean debug = analysisRecord.recordDebug();
+ while(! rules.isEmpty()) {
+ if(debug) {
+ analysisRecord.println("\n============================================================================"); //$NON-NLS-1$
+ }
+
+ OptimizerRule rule = rules.pop();
+ if(debug) {
+ analysisRecord.println("EXECUTING " + rule); //$NON-NLS-1$
+ }
+
+ plan = rule.execute(plan, metadata, capFinder, rules, analysisRecord, context);
+ if(debug) {
+ analysisRecord.println("\nAFTER: \n" + plan); //$NON-NLS-1$
+ }
+ }
+ return plan;
+ }
+
+ public PlanNode generatePlan(Command cmd) throws TeiidComponentException, TeiidProcessingException {
+ //cascade the option clause nocache
+ Option savedOption = option;
+ option = cmd.getOption();
+ if (option == null) {
+ if (savedOption != null) {
+ option = savedOption;
+ }
+ } else if (savedOption != null && savedOption.isNoCache()) { //merge no cache settings
+ if (savedOption.getNoCacheGroups() == null || savedOption.getNoCacheGroups().isEmpty()) {
+ if (option.getNoCacheGroups() != null) {
+ option.getNoCacheGroups().clear(); // full no cache
+ }
+ } else if (option.getNoCacheGroups() != null && !option.getNoCacheGroups().isEmpty()) {
+ for (String noCache : savedOption.getNoCacheGroups()) {
+ option.addNoCacheGroup(noCache); // only groups
+ }
+ }
+ option.setNoCache(true);
+ }
+
+ PlanNode result = null;
+ switch (cmd.getType()) {
+ case Command.TYPE_QUERY:
+ result = createQueryPlan((QueryCommand)cmd);
+ break;
+ case Command.TYPE_INSERT:
+ case Command.TYPE_UPDATE:
+ case Command.TYPE_DELETE:
+ case Command.TYPE_CREATE:
+ case Command.TYPE_DROP:
+ result = createUpdatePlan(cmd);
+ break;
+ case Command.TYPE_STORED_PROCEDURE:
+ result = createStoredProcedurePlan((StoredProcedure)cmd);
+ break;
+ default:
+ throw new AssertionError("Invalid command type"); //$NON-NLS-1$
+ }
+ // Distribute make dependent hints as necessary
+ if (cmd.getOption() != null) {
+ if(cmd.getOption().getDependentGroups() != null) {
+ distributeDependentHints(cmd.getOption().getDependentGroups(), result, NodeConstants.Info.MAKE_DEP);
+ }
+ if (cmd.getOption().getNotDependentGroups() != null) {
+ distributeDependentHints(cmd.getOption().getNotDependentGroups(), result, NodeConstants.Info.MAKE_NOT_DEP);
+ }
+ }
+ this.option = savedOption;
+ return result;
+ }
+
+ PlanNode createUpdatePlan(Command command) throws TeiidComponentException, TeiidProcessingException {
+ // Create top project node - define output columns for stored query / procedure
+ PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+
+ // Set output columns
+ List<SingleElementSymbol> cols = command.getProjectedSymbols();
+ projectNode.setProperty(NodeConstants.Info.PROJECT_COLS, cols);
+
+ // Define source of data for stored query / procedure
+ PlanNode sourceNode = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+ sourceNode.setProperty(NodeConstants.Info.ATOMIC_REQUEST, command);
+ sourceNode.setProperty(NodeConstants.Info.VIRTUAL_COMMAND, command);
+ boolean usingTriggerAction = false;
+ if (command instanceof ProcedureContainer) {
+ ProcedureContainer container = (ProcedureContainer)command;
+ usingTriggerAction = addNestedProcedure(sourceNode, container, container.getGroup().getMetadataID());
+ }
+ GroupSymbol target = ((TargetedCommand)command).getGroup();
+ sourceNode.addGroup(target);
+ Object id = getTrackableGroup(target, metadata);
+ if (id != null) {
+ context.accessedPlanningObject(id);
+ }
+ attachLast(projectNode, sourceNode);
+
+ //for INTO query, attach source and project nodes
+ if(!usingTriggerAction && command instanceof Insert){
+ Insert insert = (Insert)command;
+ if (insert.getQueryExpression() != null) {
+ PlanNode plan = generatePlan(insert.getQueryExpression());
+ attachLast(sourceNode, plan);
+ mergeTempMetadata(insert.getQueryExpression(), insert);
+ projectNode.setProperty(NodeConstants.Info.INTO_GROUP, insert.getGroup());
+ }
+ }
+
+ return projectNode;
+ }
+
+ private boolean addNestedProcedure(PlanNode sourceNode,
+ ProcedureContainer container, Object metadataId) throws TeiidComponentException,
+ QueryMetadataException, TeiidProcessingException {
+ if (container instanceof StoredProcedure) {
+ StoredProcedure sp = (StoredProcedure)container;
+ if (sp.getProcedureID() instanceof Procedure) {
+ context.accessedPlanningObject(sp.getProcedureID());
+ }
+ }
+ String cacheString = "transformation/" + container.getClass().getSimpleName().toUpperCase(); //$NON-NLS-1$
+ Command c = (Command)metadata.getFromMetadataCache(metadataId, cacheString);
+ if (c == null) {
+ c = QueryResolver.expandCommand(container, metadata, analysisRecord);
+ if (c != null) {
+ Request.validateWithVisitor(new ValidationVisitor(), metadata, c);
+ metadata.addToMetadataCache(metadataId, cacheString, c.clone());
+ }
+ } else {
+ c = (Command)c.clone();
+ if (c instanceof CreateUpdateProcedureCommand) {
+ ((CreateUpdateProcedureCommand)c).setUserCommand(container);
+ }
+ }
+ if (c != null) {
+ if (c instanceof TriggerAction) {
+ TriggerAction ta = (TriggerAction)c;
+ ProcessorPlan plan = new TriggerActionPlanner().optimize(container, ta, idGenerator, metadata, capFinder, analysisRecord, context);
+ sourceNode.setProperty(NodeConstants.Info.PROCESSOR_PLAN, plan);
+ return true;
+ }
+ if (c.getCacheHint() != null) {
+ if (container instanceof StoredProcedure) {
+ boolean noCache = isNoCacheGroup(metadata, ((StoredProcedure) container).getProcedureID(), option);
+ if (!noCache) {
+ if (context.isResultSetCacheEnabled() && container.areResultsCachable() && LobManager.getLobIndexes(new ArrayList<ElementSymbol>(container.getProcedureParameters().keySet())) == null) {
+ container.getGroup().setGlobalTable(true);
+ container.setCacheHint(c.getCacheHint());
+ recordAnnotation(analysisRecord, Annotation.CACHED_PROCEDURE, Priority.LOW, "SimpleQueryResolver.procedure_cache_used", container.getGroup()); //$NON-NLS-1$
+ return false;
+ }
+ recordAnnotation(analysisRecord, Annotation.CACHED_PROCEDURE, Priority.MEDIUM, "SimpleQueryResolver.procedure_cache_not_usable", container.getGroup()); //$NON-NLS-1$
+ } else {
+ recordAnnotation(analysisRecord, Annotation.CACHED_PROCEDURE, Priority.LOW, "SimpleQueryResolver.procedure_cache_not_used", container.getGroup()); //$NON-NLS-1$
+ }
+ }
+ }
+ //skip the rewrite here, we'll do that in the optimizer
+ //so that we know what the determinism level is.
+ addNestedCommand(sourceNode, container.getGroup(), container, c, false);
+ } else if (!container.getGroup().isTempTable() && //we hope for the best, and do a specific validation for subqueries below
+ container instanceof TranslatableProcedureContainer //we force the evaluation of procedure params - TODO: inserts are fine except for nonpushdown functions on columns
+ && !CriteriaCapabilityValidatorVisitor.canPushLanguageObject(container, metadata.getModelID(container.getGroup().getMetadataID()), metadata, capFinder, analysisRecord)) {
+ //do a workaround of row-by-row processing for update/delete
+ if (metadata.getUniqueKeysInGroup(container.getGroup().getMetadataID()).isEmpty()
+ || !CapabilitiesUtil.supports(Capability.CRITERIA_COMPARE_EQ, metadata.getModelID(container.getGroup().getMetadataID()), metadata, capFinder)) {
+ throw new QueryPlannerException(QueryPlugin.Util.getString("RelationalPlanner.nonpushdown_command", container)); //$NON-NLS-1$
+ }
+
+ //treat this as an update procedure
+ if (container instanceof Update) {
+ c = QueryRewriter.createUpdateProcedure((Update)container, metadata, context);
+ } else {
+ c = QueryRewriter.createDeleteProcedure((Delete)container, metadata, context);
+ }
+ addNestedCommand(sourceNode, container.getGroup(), container, c, false);
+ return false;
+ }
+
+ //plan any subqueries in criteria/parameters/values
+ for (SubqueryContainer<?> subqueryContainer : ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(container)) {
+ if (c == null && container.getGroup().isTempTable()) {
+ if (subqueryContainer.getCommand().getCorrelatedReferences() == null) {
+ if (subqueryContainer instanceof ScalarSubquery) {
+ ((ScalarSubquery) subqueryContainer).setShouldEvaluate(true);
+ } else if (subqueryContainer instanceof ExistsCriteria) {
+ ((ExistsCriteria) subqueryContainer).setShouldEvaluate(true);
+ } else {
+ throw new QueryPlannerException(QueryPlugin.Util.getString("RelationalPlanner.nonpushdown_command", container)); //$NON-NLS-1$
+ }
+ } else {
+ throw new QueryPlannerException(QueryPlugin.Util.getString("RelationalPlanner.nonpushdown_command", container)); //$NON-NLS-1$
+ }
+ }
+ ProcessorPlan plan = QueryOptimizer.optimizePlan(subqueryContainer.getCommand(), metadata, null, capFinder, analysisRecord, context);
+ subqueryContainer.getCommand().setProcessorPlan(plan);
+
+ if (c == null) {
+ RuleCollapseSource.prepareSubquery(subqueryContainer);
+ }
+ }
+ return false;
+ }
+
+ PlanNode createStoredProcedurePlan(StoredProcedure storedProc) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+ // Create top project node - define output columns for stored query / procedure
+ PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+
+ // Set output columns
+ List cols = storedProc.getProjectedSymbols();
+ projectNode.setProperty(NodeConstants.Info.PROJECT_COLS, cols);
+
+ // Define source of data for stored query / procedure
+ PlanNode sourceNode = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+ sourceNode.setProperty(NodeConstants.Info.VIRTUAL_COMMAND, storedProc);
+ addNestedProcedure(sourceNode, storedProc, storedProc.getProcedureID());
+
+ hints.hasRelationalProc |= storedProc.isProcedureRelational();
+
+ // Set group on source node
+ sourceNode.addGroup(storedProc.getGroup());
+
+ attachLast(projectNode, sourceNode);
+
+ return projectNode;
+ }
+
+ PlanNode createQueryPlan(QueryCommand command)
+ throws TeiidComponentException, TeiidProcessingException {
+ // Build canonical plan
+ PlanNode node = null;
+ if(command instanceof Query) {
+ node = createQueryPlan((Query) command);
+ } else {
+ hints.hasSetQuery = true;
+ SetQuery query = (SetQuery)command;
+ PlanNode leftPlan = createQueryPlan( query.getLeftQuery());
+ PlanNode rightPlan = createQueryPlan( query.getRightQuery());
+
+ node = NodeFactory.getNewNode(NodeConstants.Types.SET_OP);
+ node.setProperty(NodeConstants.Info.SET_OPERATION, query.getOperation());
+ node.setProperty(NodeConstants.Info.USE_ALL, query.isAll());
+
+ attachLast(node, leftPlan);
+ attachLast(node, rightPlan);
+ }
+
+ if(command.getOrderBy() != null) {
+ node = attachSorting(node, command.getOrderBy());
+ }
+
+ if (command.getLimit() != null) {
+ node = attachTupleLimit(node, command.getLimit(), hints);
+ }
+
+ return node;
+ }
+
+ private PlanNode createQueryPlan(Query query)
+ throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+
+ PlanNode plan = null;
+
+ if(query.getFrom() != null){
+ FromClause fromClause = mergeClauseTrees(query.getFrom());
+
+ PlanNode dummyRoot = new PlanNode();
+
+ buildTree(fromClause, dummyRoot);
+
+ plan = dummyRoot.getFirstChild();
+
+ hints.hasJoin |= plan.getType() == NodeConstants.Types.JOIN;
+
+ // Attach criteria on top
+ if(query.getCriteria() != null) {
+ plan = attachCriteria(plan, query.getCriteria(), false);
+ hints.hasCriteria = true;
+ }
+
+ // Attach grouping node on top
+ if(query.hasAggregates()) {
+ plan = attachGrouping(plan, query, hints);
+ }
+
+ // Attach having criteria node on top
+ if(query.getHaving() != null) {
+ plan = attachCriteria(plan, query.getHaving(), true);
+ hints.hasCriteria = true;
+ }
+
+ }
+
+ // Attach project on top
+ plan = attachProject(plan, query.getSelect());
+
+ // Attach dup removal on top
+ if(query.getSelect().isDistinct()) {
+ plan = attachDupRemoval(plan);
+ }
+
+ return plan;
+ }
+
+ /**
+ * Merges the from clause into a single join predicate if there are more than 1 from clauses
+ */
+ private static FromClause mergeClauseTrees(From from) {
+ List<FromClause> clauses = from.getClauses();
+
+ while (clauses.size() > 1) {
+ 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 clauses.get(0);
+ }
+
+ /**
+ * Build a join plan based on the structure in a clause. These structures should be
+ * essentially the same tree, but with different objects and details.
+ * @param clause Clause to build tree from
+ * @param parent Parent node to attach join node structure to
+ * @param sourceMap Map of group to source node, used for connecting children to join plan
+ * @param markJoinsInternal Flag saying whether joins built in this method should be marked
+ * as internal
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ * @throws TeiidProcessingException
+ */
+ void buildTree(FromClause clause, PlanNode parent)
+ throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+
+ PlanNode node = null;
+
+ if(clause instanceof UnaryFromClause) {
+ // No join required
+ UnaryFromClause ufc = (UnaryFromClause)clause;
+ GroupSymbol group = ufc.getGroup();
+ if (metadata.isVirtualGroup(group.getMetadataID())) {
+ hints.hasVirtualGroups = true;
+ }
+ Command nestedCommand = ufc.getExpandedCommand();
+ if (nestedCommand == null && !group.isProcedure()) {
+ Object id = getTrackableGroup(group, metadata);
+ if (id != null) {
+ context.accessedPlanningObject(id);
+ }
+ if (!group.isTempGroupSymbol() && metadata.isVirtualGroup(group.getMetadataID())) {
+ nestedCommand = resolveVirtualGroup(group);
+ }
+ }
+ node = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+ if (group.getModelMetadataId() != null) {
+ node.setProperty(Info.MODEL_ID, group.getModelMetadataId());
+ }
+ node.addGroup(group);
+ if (nestedCommand != null) {
+ UpdateInfo info = ProcedureContainerResolver.getUpdateInfo(group, metadata);
+ if (info != null && info.getPartitionInfo() != null && !info.getPartitionInfo().isEmpty()) {
+ node.setProperty(NodeConstants.Info.PARTITION_INFO, info.getPartitionInfo());
+ }
+ addNestedCommand(node, group, nestedCommand, nestedCommand, true);
+ }
+ parent.addLastChild(node);
+ } else if(clause instanceof JoinPredicate) {
+ JoinPredicate jp = (JoinPredicate) clause;
+
+ // Set up new join node corresponding to this join predicate
+ node = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+ node.setProperty(NodeConstants.Info.JOIN_TYPE, jp.getJoinType());
+ node.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.NESTED_LOOP);
+ node.setProperty(NodeConstants.Info.JOIN_CRITERIA, jp.getJoinCriteria());
+
+ if (jp.getJoinType() == JoinType.JOIN_LEFT_OUTER) {
+ hints.hasOptionalJoin = true;
+ }
+
+ // Attach join node to parent
+ parent.addLastChild(node);
+
+ // Handle each child
+ FromClause[] clauses = new FromClause[] {jp.getLeftClause(), jp.getRightClause()};
+ for(int i=0; i<2; i++) {
+ buildTree(clauses[i], node);
+
+ // Add groups to joinNode
+ for (PlanNode child : node.getChildren()) {
+ node.addGroups(child.getGroups());
+ }
+ }
+ } else if (clause instanceof SubqueryFromClause) {
+ SubqueryFromClause sfc = (SubqueryFromClause)clause;
+ GroupSymbol group = sfc.getGroupSymbol();
+ Command nestedCommand = sfc.getCommand();
+ node = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+ if (sfc.isTable()) {
+ sfc.getCommand().setCorrelatedReferences(getCorrelatedReferences(parent, node, sfc));
+ }
+ node.addGroup(group);
+ addNestedCommand(node, group, nestedCommand, nestedCommand, true);
+ if (nestedCommand instanceof SetQuery) {
+ Map<ElementSymbol, List<Set<Constant>>> partitionInfo = PartitionAnalyzer.extractPartionInfo((SetQuery)nestedCommand, ResolverUtil.resolveElementsInGroup(group, metadata));
+ if (!partitionInfo.isEmpty()) {
+ node.setProperty(NodeConstants.Info.PARTITION_INFO, partitionInfo);
+ }
+ }
+ hints.hasVirtualGroups = true;
+ parent.addLastChild(node);
+ } else if (clause instanceof TableFunctionReference) {
+ TableFunctionReference tt = (TableFunctionReference)clause;
+ GroupSymbol group = tt.getGroupSymbol();
+ node = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+ node.setProperty(NodeConstants.Info.TABLE_FUNCTION, tt);
+ tt.setCorrelatedReferences(getCorrelatedReferences(parent, node, tt));
+ node.addGroup(group);
+ parent.addLastChild(node);
+ } else {
+ throw new AssertionError("Unknown Type"); //$NON-NLS-1$
+ }
+
+ if (clause.isOptional()) {
+ node.setProperty(NodeConstants.Info.IS_OPTIONAL, Boolean.TRUE);
+ hints.hasOptionalJoin = true;
+ }
+
+ if (clause.isMakeDep()) {
+ node.setProperty(NodeConstants.Info.MAKE_DEP, Boolean.TRUE);
+ } 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)
+ throws TeiidComponentException, QueryMetadataException {
+ if (group.isTempGroupSymbol()) {
+ QueryMetadataInterface qmi = metadata.getSessionMetadata();
+ try {
+ //exclude proc scoped temp tables
+ if (group.isGlobalTable() || (qmi != null && qmi.getGroupID(group.getNonCorrelationName()) == group.getMetadataID())) {
+ return group.getMetadataID();
+ }
+ } catch (QueryMetadataException e) {
+ //not a session table
+ }
+ } else {
+ return group.getMetadataID();
+ }
+ return null;
+ }
+
+ private SymbolMap getCorrelatedReferences(PlanNode parent, PlanNode node,
+ LanguageObject lo) {
+ PlanNode rootJoin = parent;
+ while (rootJoin.getParent() != null && rootJoin.getParent().getType() == NodeConstants.Types.JOIN && !rootJoin.getParent().getGroups().isEmpty()) {
+ rootJoin = rootJoin.getParent();
+ }
+ List<Reference> correlatedReferences = new ArrayList<Reference>();
+ CorrelatedReferenceCollectorVisitor.collectReferences(lo, rootJoin.getGroups(), correlatedReferences);
+
+ if (correlatedReferences.isEmpty()) {
+ return null;
+ }
+ SymbolMap map = new SymbolMap();
+ for (Reference reference : correlatedReferences) {
+ map.addMapping(reference.getExpression(), reference.getExpression());
+ }
+ node.setProperty(NodeConstants.Info.CORRELATED_REFERENCES, map);
+ return map;
+ }
+
+ private void addNestedCommand(PlanNode node,
+ GroupSymbol group, Command nestedCommand, Command toPlan, boolean merge) throws TeiidComponentException, QueryMetadataException, TeiidProcessingException {
+ if (nestedCommand instanceof QueryCommand) {
+ //remove unnecessary order by
+ QueryCommand queryCommand = (QueryCommand)nestedCommand;
+ if (queryCommand.getLimit() == null) {
+ queryCommand.setOrderBy(null);
+ }
+ if (merge && queryCommand.getWith() != null) {
+ //TODO: should recontext with and merge
+ merge = false;
+ }
+ }
+ node.setProperty(NodeConstants.Info.NESTED_COMMAND, nestedCommand);
+
+ if (merge && nestedCommand instanceof Query && QueryResolver.isXMLQuery((Query)nestedCommand, metadata)) {
+ merge = false;
+ }
+
+ if (merge) {
+ mergeTempMetadata(nestedCommand, parentCommand);
+ PlanNode childRoot = generatePlan(nestedCommand);
+ node.addFirstChild(childRoot);
+ List<SingleElementSymbol> projectCols = nestedCommand.getProjectedSymbols();
+ SymbolMap map = SymbolMap.createSymbolMap(group, projectCols, metadata);
+ node.setProperty(NodeConstants.Info.SYMBOL_MAP, map);
+ } else {
+ QueryMetadataInterface actualMetadata = metadata;
+ if (actualMetadata instanceof TempMetadataAdapter) {
+ actualMetadata = ((TempMetadataAdapter)metadata).getMetadata();
+ }
+ ProcessorPlan plan = QueryOptimizer.optimizePlan(toPlan, actualMetadata, idGenerator, capFinder, analysisRecord, context);
+ node.setProperty(NodeConstants.Info.PROCESSOR_PLAN, plan);
+ }
+ }
+
+ /**
+ * Attach all criteria above the join nodes. The optimizer will push these
+ * criteria down to the appropriate source.
+ * @param plan Existing plan, which joins all source groups
+ * @param criteria Criteria from query
+ * @return Updated tree
+ */
+ private static PlanNode attachCriteria(PlanNode plan, Criteria criteria, boolean isHaving) {
+ List<Criteria> crits = Criteria.separateCriteriaByAnd(criteria);
+
+ for (Criteria crit : crits) {
+ PlanNode critNode = createSelectNode(crit, isHaving);
+ attachLast(critNode, plan);
+ plan = critNode;
+ }
+
+ return plan;
+ }
+
+ 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()) {
+ critNode.setProperty(NodeConstants.Info.IS_HAVING, Boolean.TRUE);
+ }
+ // Add groups to crit node
+ critNode.addGroups(GroupsUsedByElementsVisitor.getGroups(crit));
+ critNode.addGroups(GroupsUsedByElementsVisitor.getGroups(critNode.getCorrelatedReferenceElements()));
+ return critNode;
+ }
+
+ /**
+ * Attach a grouping node at top of tree.
+ * @param plan Existing plan
+ * @param groupBy Group by clause, which may be null
+ * @return Updated plan
+ */
+ private static PlanNode attachGrouping(PlanNode plan, Query query, PlanHints hints) {
+ PlanNode groupNode = NodeFactory.getNewNode(NodeConstants.Types.GROUP);
+
+ GroupBy groupBy = query.getGroupBy();
+ if(groupBy != null) {
+ groupNode.setProperty(NodeConstants.Info.GROUP_COLS, groupBy.getSymbols());
+ groupNode.addGroups(GroupsUsedByElementsVisitor.getGroups(groupBy));
+ }
+
+ attachLast(groupNode, plan);
+
+ // Mark in hints
+ hints.hasAggregates = true;
+
+ return groupNode;
+ }
+
+ /**
+ * Attach SORT node at top of tree. The SORT may be pushed down to a source (or sources)
+ * if possible by the optimizer.
+ * @param plan Existing plan
+ * @param orderBy Sort description from the query
+ * @return Updated plan
+ */
+ private static PlanNode attachSorting(PlanNode plan, OrderBy orderBy) {
+ PlanNode sortNode = NodeFactory.getNewNode(NodeConstants.Types.SORT);
+
+ sortNode.setProperty(NodeConstants.Info.SORT_ORDER, orderBy);
+ if (orderBy.hasUnrelated()) {
+ sortNode.setProperty(Info.UNRELATED_SORT, true);
+ }
+ sortNode.addGroups(GroupsUsedByElementsVisitor.getGroups(orderBy));
+
+ attachLast(sortNode, plan);
+ return sortNode;
+ }
+
+ private static PlanNode attachTupleLimit(PlanNode plan, Limit limit, PlanHints hints) {
+ hints.hasLimit = true;
+ PlanNode limitNode = NodeFactory.getNewNode(NodeConstants.Types.TUPLE_LIMIT);
+
+ boolean attach = false;
+ if (limit.getOffset() != null) {
+ limitNode.setProperty(NodeConstants.Info.OFFSET_TUPLE_COUNT, limit.getOffset());
+ attach = true;
+ }
+ if (limit.getRowLimit() != null) {
+ limitNode.setProperty(NodeConstants.Info.MAX_TUPLE_LIMIT, limit.getRowLimit());
+ attach = true;
+ }
+ if (attach) {
+ if (limit.isImplicit()) {
+ limitNode.setProperty(Info.IS_IMPLICIT_LIMIT, true);
+ }
+ attachLast(limitNode, plan);
+ plan = limitNode;
+ }
+ return plan;
+ }
+
+ /**
+ * Attach DUP_REMOVE node at top of tree. The DUP_REMOVE may be pushed down
+ * to a source (or sources) if possible by the optimizer.
+ * @param plan Existing plan
+ * @return Updated plan
+ */
+ private static PlanNode attachDupRemoval(PlanNode plan) {
+ PlanNode dupNode = NodeFactory.getNewNode(NodeConstants.Types.DUP_REMOVE);
+ attachLast(dupNode, plan);
+ return dupNode;
+ }
+
+ private static PlanNode attachProject(PlanNode plan, Select select) {
+ PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+ projectNode.setProperty(NodeConstants.Info.PROJECT_COLS, select.getProjectedSymbols());
+
+ // Set groups
+ projectNode.addGroups(GroupsUsedByElementsVisitor.getGroups(select));
+
+ attachLast(projectNode, plan);
+ return projectNode;
+ }
+
+ static final void attachLast(PlanNode parent, PlanNode child) {
+ if(child != null) {
+ parent.addLastChild(child);
+ }
+ }
+
+ /**
+ * Adds temp metadata (if any) of child command to temp metadata
+ * (if any) of parent command.
+ * @param childCommand
+ * @param parentCommand
+ */
+ static void mergeTempMetadata(
+ Command childCommand,
+ Command parentCommand) {
+ Map childTempMetadata = childCommand.getTemporaryMetadata();
+ if (childTempMetadata != null && !childTempMetadata.isEmpty()){
+ // Add to parent temp metadata
+ Map parentTempMetadata = parentCommand.getTemporaryMetadata();
+ if (parentTempMetadata == null){
+ parentCommand.setTemporaryMetadata(new HashMap(childTempMetadata));
+ } else {
+ parentTempMetadata.putAll(childTempMetadata);
+ }
+ }
+ }
+
+ private Command resolveVirtualGroup(GroupSymbol virtualGroup)
+ throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+
+ QueryNode qnode = null;
+
+ Object metadataID = virtualGroup.getMetadataID();
+ boolean noCache = isNoCacheGroup(metadata, metadataID, option);
+ boolean isMaterializedGroup = metadata.hasMaterialization(metadataID);
+ String cacheString = SQLConstants.Reserved.SELECT;
+
+ if( isMaterializedGroup) {
+ Object matMetadataId = metadata.getMaterialization(metadataID);
+ String matTableName = null;
+ CacheHint hint = null;
+ boolean isImplicitGlobal = matMetadataId == null;
+ if (isImplicitGlobal) {
+ TempMetadataID tid = context.getGlobalTableStore().getGlobalTempTableMetadataId(metadataID, metadata);
+ matTableName = tid.getID();
+ hint = tid.getCacheHint();
+ if (hint != null) {
+ recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.cache_hint_used", virtualGroup, matTableName, tid); //$NON-NLS-1$
+ }
+ matMetadataId = tid;
+ } else {
+ matTableName = metadata.getFullName(matMetadataId);
+ }
+
+ if(noCache){
+ //not use cache
+ qnode = metadata.getVirtualPlan(metadataID);
+ //TODO: update the table for defaultMat
+ recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.materialized_table_not_used", virtualGroup, matTableName); //$NON-NLS-1$
+ }else{
+ this.context.accessedPlanningObject(matMetadataId);
+ qnode = new QueryNode(null);
+ Query query = createMatViewQuery(matMetadataId, matTableName, Arrays.asList(new AllSymbol()), isImplicitGlobal);
+ query.setCacheHint(hint);
+ qnode.setCommand(query);
+ cacheString = "matview"; //$NON-NLS-1$
+ recordAnnotation(analysisRecord, Annotation.MATERIALIZED_VIEW, Priority.LOW, "SimpleQueryResolver.Query_was_redirected_to_Mat_table", virtualGroup, matTableName); //$NON-NLS-1$
+ }
+ } else {
+ // Not a materialized view - query the primary transformation
+ qnode = metadata.getVirtualPlan(metadataID);
+ }
+
+ Command result = (Command)QueryResolver.resolveView(virtualGroup, qnode, cacheString, metadata).getCommand().clone();
+ return QueryRewriter.rewrite(result, metadata, context);
+ }
+
+ public static Query createMatViewQuery(Object matMetadataId, String matTableName, List<? extends SelectSymbol> select, boolean isGlobal) {
+ Query query = new Query();
+ query.setSelect(new Select(select));
+ GroupSymbol gs = new GroupSymbol(matTableName);
+ gs.setGlobalTable(isGlobal);
+ gs.setMetadataID(matMetadataId);
+ query.setFrom(new From(Arrays.asList(new UnaryFromClause(gs))));
+ return query;
+ }
+
+ public static boolean isNoCacheGroup(QueryMetadataInterface metadata,
+ Object metadataID,
+ Option option) throws QueryMetadataException,
+ TeiidComponentException {
+ if(option == null || !option.isNoCache()){
+ return false;
+ }
+ if(option.getNoCacheGroups() == null || option.getNoCacheGroups().isEmpty()){
+ //only OPTION NOCACHE, no group specified
+ return true;
+ }
+ String fullName = metadata.getFullName(metadataID);
+ for (String groupName : option.getNoCacheGroups()) {
+ if(groupName.equalsIgnoreCase(fullName)){
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static void recordAnnotation(AnalysisRecord analysis, String type, Priority priority, String msgKey, Object... parts) {
+ if (analysis.recordAnnotations()) {
+ Annotation annotation = new Annotation(type,
+ QueryPlugin.Util.getString(msgKey, parts),
+ null,
+ priority);
+ analysis.addAnnotation(annotation);
+ }
+ }
+
+}
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/plantree/NodeConstants.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/plantree/NodeConstants.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/plantree/NodeConstants.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,155 +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.optimizer.relational.plantree;
-
-public final class NodeConstants {
-
- // Can't instantiate
- private NodeConstants() { }
-
- /** Types of nodes */
- public static final class Types {
- private Types() {}
-
- static final int NO_TYPE = 0;
- public static final int ACCESS = 1<<0;
- public static final int DUP_REMOVE = 1<<1;
- public static final int JOIN = 1<<2;
- public static final int PROJECT = 1<<3;
- public static final int SELECT = 1<<4;
- public static final int SORT = 1<<5;
- public static final int SOURCE = 1<<6;
- public static final int GROUP = 1<<7;
- 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;
- }
-
- /**
- * Convert a type code into a type string.
- * @param type Type code, as defined in NodeConstants.Types
- * @return String representation for code
- */
- public static final String getNodeTypeString(int type) {
- switch(type) {
- case NodeConstants.Types.ACCESS: return "Access"; //$NON-NLS-1$
- case NodeConstants.Types.DUP_REMOVE: return "DupRemoval"; //$NON-NLS-1$
- case NodeConstants.Types.JOIN: return "Join"; //$NON-NLS-1$
- case NodeConstants.Types.PROJECT: return "Project"; //$NON-NLS-1$
- case NodeConstants.Types.SELECT: return "Select"; //$NON-NLS-1$
- case NodeConstants.Types.SORT: return "Sort"; //$NON-NLS-1$
- case NodeConstants.Types.SOURCE: return "Source"; //$NON-NLS-1$
- case NodeConstants.Types.GROUP: return "Group"; //$NON-NLS-1$
- 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$
- }
- }
-
- /** Property names for type-specific node properties */
- public enum Info {
- ATOMIC_REQUEST, // Command
- MODEL_ID, // Object (model ID)
- IS_COMMON_TABLE,
- PROCEDURE_CRITERIA,
- PROCEDURE_INPUTS,
- PROCEDURE_DEFAULTS,
-
- // Set operation properties
- SET_OPERATION, // SetOperation
- USE_ALL, // Boolean
-
- // Join node properties
- JOIN_CRITERIA, // List <CompareCriteria>
- JOIN_TYPE, // JoinType
- JOIN_STRATEGY, // JoinStrategyType
- LEFT_EXPRESSIONS, // List <SingleElementSymbol>
- RIGHT_EXPRESSIONS, // List <SingleElementSymbol>
- DEPENDENT_VALUE_SOURCE, // String
- NON_EQUI_JOIN_CRITERIA, // List <CompareCriteria>
- SORT_LEFT, // SortOption
- SORT_RIGHT, // SortOption
- IS_OPTIONAL, // Boolean
- IS_LEFT_DISTINCT, // Boolean
- IS_RIGHT_DISTINCT, // Boolean
-
- // Project node properties
- PROJECT_COLS, // List <SingleElementSymbol>
- INTO_GROUP, // GroupSymbol
-
- // Select node properties
- SELECT_CRITERIA, // Criteria
- IS_HAVING, // Boolean
- //phantom nodes represent the previous position of criteria that has been pushed across a source, group, or union node.
- //phantom nodes are used by RuleCopyCriteria and removed by RuleCleanCriteria.
- IS_PHANTOM, // Boolean
- IS_COPIED, // Boolean - used in CopyCriteria to mark which selects have already been copied
- IS_PUSHED, // true if this node has already been pushed
- IS_DEPENDENT_SET, // Boolean - only used with dependent joins
-
- // Sort node properties
- SORT_ORDER, // OrderBy
- UNRELATED_SORT, // Boolean
- IS_DUP_REMOVAL, // Boolean
-
- // Source node properties
- 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 ???
- 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
- INLINE_VIEW, // If the source node represents an inline view
-
- // Group node properties
- GROUP_COLS, // List <SingleElementSymbol>
-
- // Special constant used in converting plan to process for all nodes
- OUTPUT_COLS, // List <SingleElementSymbol>
-
- // Plan Node Cost Estimate Constants
- EST_SET_SIZE, // Integer represents the estimated set size this node would produce for a sibling node as the independent node in a dependent join scenario
- EST_DEP_CARDINALITY, // Float value that represents the estimated cardinality (amount of rows) produced by this node as the dependent node in a dependent join scenario
- EST_DEP_JOIN_COST, // Float value that represents the estimated cost of a dependent join (the join strategy for this could be Nested Loop or Merge)
- EST_JOIN_COST, // Float value that represents the estimated cost of a merge join (the join strategy for this could be Nested Loop or Merge)
- EST_CARDINALITY, // Float represents the estimated cardinality (amount of rows) produced by this node
- EST_COL_STATS,
- EST_SELECTIVITY, // Float that represents the selectivity of a criteria node
-
- // Tuple limit and offset
- MAX_TUPLE_LIMIT, // Expression that evaluates to the max number of tuples generated
- OFFSET_TUPLE_COUNT, // Expression that evaluates to the tuple offset of the starting tuple
- IS_IMPLICIT_LIMIT, // Boolean if the limit is created by the rewriter as part of a subquery optimization
-
- // Common AP Information
- ACCESS_PATTERNS, // Collection <List <Object element ID> >
- ACCESS_PATTERN_USED, // List <Object element ID>
- REQUIRED_ACCESS_PATTERN_GROUPS
- }
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/plantree/NodeConstants.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/plantree/NodeConstants.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/plantree/NodeConstants.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/plantree/NodeConstants.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,157 @@
+/*
+ * 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.relational.plantree;
+
+public final class NodeConstants {
+
+ // Can't instantiate
+ private NodeConstants() { }
+
+ /** Types of nodes */
+ public static final class Types {
+ private Types() {}
+
+ static final int NO_TYPE = 0;
+ public static final int ACCESS = 1<<0;
+ public static final int DUP_REMOVE = 1<<1;
+ public static final int JOIN = 1<<2;
+ public static final int PROJECT = 1<<3;
+ public static final int SELECT = 1<<4;
+ public static final int SORT = 1<<5;
+ public static final int SOURCE = 1<<6;
+ public static final int GROUP = 1<<7;
+ 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;
+ }
+
+ /**
+ * Convert a type code into a type string.
+ * @param type Type code, as defined in NodeConstants.Types
+ * @return String representation for code
+ */
+ public static final String getNodeTypeString(int type) {
+ switch(type) {
+ case NodeConstants.Types.ACCESS: return "Access"; //$NON-NLS-1$
+ case NodeConstants.Types.DUP_REMOVE: return "DupRemoval"; //$NON-NLS-1$
+ case NodeConstants.Types.JOIN: return "Join"; //$NON-NLS-1$
+ case NodeConstants.Types.PROJECT: return "Project"; //$NON-NLS-1$
+ case NodeConstants.Types.SELECT: return "Select"; //$NON-NLS-1$
+ case NodeConstants.Types.SORT: return "Sort"; //$NON-NLS-1$
+ case NodeConstants.Types.SOURCE: return "Source"; //$NON-NLS-1$
+ case NodeConstants.Types.GROUP: return "Group"; //$NON-NLS-1$
+ 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$
+ }
+ }
+
+ /** Property names for type-specific node properties */
+ public enum Info {
+ ATOMIC_REQUEST, // Command
+ MODEL_ID, // Object (model ID)
+ IS_COMMON_TABLE,
+ PROCEDURE_CRITERIA,
+ PROCEDURE_INPUTS,
+ PROCEDURE_DEFAULTS,
+
+ // Set operation properties
+ SET_OPERATION, // SetOperation
+ USE_ALL, // Boolean
+
+ // Join node properties
+ JOIN_CRITERIA, // List <CompareCriteria>
+ JOIN_TYPE, // JoinType
+ JOIN_STRATEGY, // JoinStrategyType
+ LEFT_EXPRESSIONS, // List <SingleElementSymbol>
+ RIGHT_EXPRESSIONS, // List <SingleElementSymbol>
+ DEPENDENT_VALUE_SOURCE, // String
+ NON_EQUI_JOIN_CRITERIA, // List <CompareCriteria>
+ SORT_LEFT, // SortOption
+ SORT_RIGHT, // SortOption
+ 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
+
+ // Select node properties
+ SELECT_CRITERIA, // Criteria
+ IS_HAVING, // Boolean
+ //phantom nodes represent the previous position of criteria that has been pushed across a source, group, or union node.
+ //phantom nodes are used by RuleCopyCriteria and removed by RuleCleanCriteria.
+ IS_PHANTOM, // Boolean
+ IS_COPIED, // Boolean - used in CopyCriteria to mark which selects have already been copied
+ IS_PUSHED, // true if this node has already been pushed
+ IS_DEPENDENT_SET, // Boolean - only used with dependent joins
+
+ // Sort node properties
+ SORT_ORDER, // OrderBy
+ UNRELATED_SORT, // Boolean
+ IS_DUP_REMOVAL, // Boolean
+
+ // Source node properties
+ 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, // 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, // Boolean
+ INLINE_VIEW, // If the source node represents an inline view
+ MAKE_IND,
+
+ // Group node properties
+ GROUP_COLS, // List <SingleElementSymbol>
+
+ // Special constant used in converting plan to process for all nodes
+ OUTPUT_COLS, // List <SingleElementSymbol>
+
+ // Plan Node Cost Estimate Constants
+ EST_SET_SIZE, // Integer represents the estimated set size this node would produce for a sibling node as the independent node in a dependent join scenario
+ EST_DEP_CARDINALITY, // Float value that represents the estimated cardinality (amount of rows) produced by this node as the dependent node in a dependent join scenario
+ EST_DEP_JOIN_COST, // Float value that represents the estimated cost of a dependent join (the join strategy for this could be Nested Loop or Merge)
+ EST_JOIN_COST, // Float value that represents the estimated cost of a merge join (the join strategy for this could be Nested Loop or Merge)
+ EST_CARDINALITY, // Float represents the estimated cardinality (amount of rows) produced by this node
+ EST_COL_STATS,
+ EST_SELECTIVITY, // Float that represents the selectivity of a criteria node
+
+ // Tuple limit and offset
+ MAX_TUPLE_LIMIT, // Expression that evaluates to the max number of tuples generated
+ OFFSET_TUPLE_COUNT, // Expression that evaluates to the tuple offset of the starting tuple
+ IS_IMPLICIT_LIMIT, // Boolean if the limit is created by the rewriter as part of a subquery optimization
+
+ // Common AP Information
+ ACCESS_PATTERNS, // Collection <List <Object element ID> >
+ ACCESS_PATTERN_USED, // List <Object element ID>
+ REQUIRED_ACCESS_PATTERN_GROUPS
+ }
+}
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CapabilitiesUtil.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CapabilitiesUtil.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CapabilitiesUtil.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,450 +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.optimizer.relational.rules;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.metadata.Schema;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.SetQuery.Operation;
-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.sql.symbol.AggregateSymbol.Type;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.translator.ExecutionFactory.NullOrder;
-import org.teiid.translator.ExecutionFactory.SupportedJoinCriteria;
-
-
-/**
- */
-public class CapabilitiesUtil {
-
- /**
- * Can't construct - just a utilities class
- */
- private CapabilitiesUtil() {
- }
-
- static boolean supportsInlineView(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return supports(Capability.QUERY_FROM_INLINE_VIEWS, modelID, metadata, capFinder);
- }
-
- public static boolean supportsSelfJoins(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
-
- if (metadata.isVirtualModel(modelID)){
- return false;
- }
-
- // Find capabilities
- SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
-
- return caps.supportsCapability(Capability.QUERY_FROM_JOIN_SELFJOIN) &&
- caps.supportsCapability(Capability.QUERY_FROM_GROUP_ALIAS);
- }
-
- public static boolean supportsGroupAliases(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return supports(Capability.QUERY_FROM_GROUP_ALIAS, modelID, metadata, capFinder);
- }
-
- public static boolean supportsJoin(Object modelID, JoinType joinType, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
-
- if (metadata.isVirtualModel(modelID)){
- return false;
- }
-
- // Find capabilities
- SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
-
- if (!joinType.isOuter()) {
- return caps.supportsCapability(Capability.QUERY_FROM_JOIN_INNER);
- }
-
- if(! caps.supportsCapability(Capability.QUERY_FROM_JOIN_OUTER)) {
- return false;
- }
-
- return !joinType.equals(JoinType.JOIN_FULL_OUTER) || caps.supportsCapability(Capability.QUERY_FROM_JOIN_OUTER_FULL);
- }
-
- public static boolean supportsAggregates(List groupCols, Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
-
- if (metadata.isVirtualModel(modelID)){
- return false;
- }
-
- // Find capabilities
- SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
-
- if (groupCols != null && !groupCols.isEmpty()) {
- if (!caps.supportsCapability(Capability.QUERY_GROUP_BY)) {
- return false;
- }
- boolean supportsFunctionsInGroupBy = caps.supportsCapability(Capability.QUERY_FUNCTIONS_IN_GROUP_BY);
-
- // 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) {
- // Function in GROUP BY can't be pushed
- return false;
- }
- }
- }
-
- return true;
- }
-
- public static boolean supportsAggregateFunction(Object modelID, AggregateSymbol aggregate, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
-
- if (metadata.isVirtualModel(modelID)){
- return false;
- }
-
- // Find capabilities
- SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
-
- // Check particular function
- Type func = aggregate.getAggregateFunction();
- switch (func) {
- case COUNT:
- if(aggregate.getExpression() == null) {
- if(! caps.supportsCapability(Capability.QUERY_AGGREGATES_COUNT_STAR)) {
- return false;
- }
- } else {
- if(! caps.supportsCapability(Capability.QUERY_AGGREGATES_COUNT)) {
- return false;
- }
- }
- break;
- case SUM:
- if(! caps.supportsCapability(Capability.QUERY_AGGREGATES_SUM)) {
- return false;
- }
- break;
- case AVG:
- if(! caps.supportsCapability(Capability.QUERY_AGGREGATES_AVG)) {
- return false;
- }
- break;
- case MIN:
- if(! caps.supportsCapability(Capability.QUERY_AGGREGATES_MIN)) {
- return false;
- }
- break;
- case MAX:
- if(! caps.supportsCapability(Capability.QUERY_AGGREGATES_MAX)) {
- return false;
- }
- break;
- default:
- if (aggregate.isEnhancedNumeric()) {
- if (!caps.supportsCapability(Capability.QUERY_AGGREGATES_ENHANCED_NUMERIC)) {
- return false;
- }
- } else {
- return false;
- }
- break;
- }
-
- // Check DISTINCT if necessary
- if(aggregate.isDistinct() && ! caps.supportsCapability(Capability.QUERY_AGGREGATES_DISTINCT)) {
- return false;
- }
-
- // Passed all the checks!
- return true;
-
-
- }
-
- public static boolean supportsScalarFunction(Object modelID, Function function, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
-
- if (metadata.isVirtualModel(modelID)){
- return false;
- }
-
- //capabilities check is only valid for non-schema scoped functions
- //technically the other functions are scoped to SYS, 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())) {
- return false;
- }
- } else if (!schema.getFullName().equalsIgnoreCase(metadata.getFullName(modelID))) {
- return false; //not the right schema
- }
-
- //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();
- //object or clob to anything cannot be pushed down
- if (DataTypeManager.DefaultDataClasses.OBJECT.equals(fromType)
- || DataTypeManager.DefaultDataClasses.CLOB.equals(fromType)
- || DataTypeManager.DefaultDataClasses.XML.equals(fromType)) {
- return false;
- }
- String targetType = (String)((Constant)function.getArg(1)).getValue();
- if (DataTypeManager.DefaultDataTypes.CLOB.equalsIgnoreCase(targetType)
- || DataTypeManager.DefaultDataTypes.XML.equalsIgnoreCase(targetType)) {
- return false;
- }
- }
-
- return true;
- }
-
- public static boolean supportsSelectDistinct(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return supports(Capability.QUERY_SELECT_DISTINCT, modelID, metadata, capFinder);
- }
-
- public static boolean supportsSelectExpression(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return supports(Capability.QUERY_SELECT_EXPRESSION, modelID, metadata, capFinder);
- }
-
- public static boolean supportsOrderBy(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return supports(Capability.QUERY_ORDERBY, modelID, metadata, capFinder);
- }
-
- public static boolean supportsSetOp(Object modelID, Operation setOp, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
-
- if (metadata.isVirtualModel(modelID)){
- return false;
- }
-
- // Find capabilities
- SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
-
- switch (setOp) {
- case EXCEPT:
- return caps.supportsCapability(Capability.QUERY_EXCEPT);
- case INTERSECT:
- return caps.supportsCapability(Capability.QUERY_INTERSECT);
- case UNION:
- return caps.supportsCapability(Capability.QUERY_UNION);
- }
-
- return false;
- }
-
- public static boolean supportsSetQueryOrderBy(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return supports(Capability.QUERY_SET_ORDER_BY, modelID, metadata, capFinder);
- }
-
- public static boolean supportsCaseExpression(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return supports(Capability.QUERY_CASE, modelID, metadata, capFinder);
- }
-
- public static boolean supportsSearchedCaseExpression(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return supports(Capability.QUERY_SEARCHED_CASE, modelID, metadata, capFinder);
- }
-
- public static int getMaxInCriteriaSize(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return getProperty(Capability.MAX_IN_CRITERIA_SIZE, modelID, metadata, capFinder);
- }
-
- private static int getProperty(Capability cap, Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
-
- if (metadata.isVirtualModel(modelID)){
- return -1;
- }
-
- // Find capabilities
- SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
- Object maxInCriteriaSize = caps.getSourceProperty(cap);
- int value = -1;
- if(maxInCriteriaSize != null) {
- value = ((Integer)maxInCriteriaSize).intValue();
- }
-
- // Check for invalid values and send back code for UNKNOWN
- if(value <= 0) {
- value = -1;
- }
- return value;
- }
-
- public static int getMaxDependentPredicates(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return getProperty(Capability.MAX_DEPENDENT_PREDICATES, modelID, metadata, capFinder);
- }
-
- public static int getMaxFromGroups(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
-
- if (metadata.isVirtualModel(modelID)){
- return -1;
- }
-
- // Find capabilities
- SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
- Object maxGroups = caps.getSourceProperty(Capability.MAX_QUERY_FROM_GROUPS);
- int value = -1;
- if(maxGroups != null) {
- value = ((Integer)maxGroups).intValue();
- }
-
- // Check for invalid values and send back code for UNKNOWN
- if(value <= 0) {
- value = -1;
- }
- return value;
- }
-
- public static SupportedJoinCriteria getSupportedJoinCriteria(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder) throws QueryMetadataException, TeiidComponentException {
- if (metadata.isVirtualModel(modelID)){
- return SupportedJoinCriteria.ANY;
- }
- SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
- SupportedJoinCriteria crits = (SupportedJoinCriteria)caps.getSourceProperty(Capability.JOIN_CRITERIA_ALLOWED);
- if (crits == null) {
- return SupportedJoinCriteria.ANY;
- }
- return crits;
- }
-
- public static NullOrder getDefaultNullOrder(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder) throws QueryMetadataException, TeiidComponentException {
- if (metadata.isVirtualModel(modelID)){
- return NullOrder.UNKNOWN;
- }
- SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
- NullOrder order = (NullOrder)caps.getSourceProperty(Capability.QUERY_ORDERBY_DEFAULT_NULL_ORDER);
- if (order == null) {
- return NullOrder.UNKNOWN;
- }
- return order;
- }
-
- public static boolean supportsRowLimit(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return supports(Capability.ROW_LIMIT, modelID, metadata, capFinder);
- }
-
- public static boolean supportsRowOffset(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return supports(Capability.ROW_OFFSET, modelID, metadata, capFinder);
- }
-
- public static boolean isSameConnector(Object modelID, Object modelID1, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
-
- if (modelID == null || modelID1 == null || metadata.isVirtualModel(modelID) || metadata.isVirtualModel(modelID1)){
- return false;
- }
-
- if (modelID.equals(modelID1)) {
- return true;
- }
-
- // Find capabilities
- SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
- SourceCapabilities caps1 = getCapabilities(modelID1, metadata, capFinder);
-
- Object connectorID = caps.getSourceProperty(Capability.CONNECTOR_ID);
-
- return connectorID != null && connectorID.equals(caps1.getSourceProperty(Capability.CONNECTOR_ID));
- }
-
- private static SourceCapabilities getCapabilities(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
-
- // Find capabilities
- String modelName = metadata.getFullName(modelID);
- return capFinder.findCapabilities(modelName);
- }
-
- public static boolean requiresCriteria(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return supports(Capability.REQUIRES_CRITERIA, modelID, metadata, capFinder);
- }
-
- public static boolean useAnsiJoin(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- return supports(Capability.QUERY_FROM_ANSI_JOIN, modelID, metadata, capFinder);
- }
-
- public static boolean supports(Capability cap, Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
- throws QueryMetadataException, TeiidComponentException {
- if (metadata.isVirtualModel(modelID)){
- return false;
- }
-
- // Find capabilities
- SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
-
- return caps.supportsCapability(cap);
- }
-
- /**
- * Validate that the elements are searchable and can be used in a criteria against this source.
- * TODO: this check is too general and not type based
- */
- static boolean checkElementsAreSearchable(List<? extends LanguageObject> objs, QueryMetadataInterface metadata, int searchableType)
- throws QueryMetadataException, TeiidComponentException {
- Collection<ElementSymbol> elements = new ArrayList<ElementSymbol>();
- ElementCollectorVisitor.getElements(objs, elements);
- for (ElementSymbol elementSymbol : elements) {
- if (!metadata.elementSupports(elementSymbol.getMetadataID(), searchableType)) {
- return false;
- }
- }
- return true;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CapabilitiesUtil.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CapabilitiesUtil.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CapabilitiesUtil.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CapabilitiesUtil.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,450 @@
+/*
+ * 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.relational.rules;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.Schema;
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.lang.SetQuery.Operation;
+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.sql.symbol.AggregateSymbol.Type;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.translator.ExecutionFactory.NullOrder;
+import org.teiid.translator.ExecutionFactory.SupportedJoinCriteria;
+
+
+/**
+ */
+public class CapabilitiesUtil {
+
+ /**
+ * Can't construct - just a utilities class
+ */
+ private CapabilitiesUtil() {
+ }
+
+ static boolean supportsInlineView(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return supports(Capability.QUERY_FROM_INLINE_VIEWS, modelID, metadata, capFinder);
+ }
+
+ public static boolean supportsSelfJoins(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+
+ if (metadata.isVirtualModel(modelID)){
+ return false;
+ }
+
+ // Find capabilities
+ SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
+
+ return caps.supportsCapability(Capability.QUERY_FROM_JOIN_SELFJOIN) &&
+ caps.supportsCapability(Capability.QUERY_FROM_GROUP_ALIAS);
+ }
+
+ public static boolean supportsGroupAliases(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return supports(Capability.QUERY_FROM_GROUP_ALIAS, modelID, metadata, capFinder);
+ }
+
+ public static boolean supportsJoin(Object modelID, JoinType joinType, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+
+ if (metadata.isVirtualModel(modelID)){
+ return false;
+ }
+
+ // Find capabilities
+ SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
+
+ if (!joinType.isOuter()) {
+ return caps.supportsCapability(Capability.QUERY_FROM_JOIN_INNER);
+ }
+
+ if(! caps.supportsCapability(Capability.QUERY_FROM_JOIN_OUTER)) {
+ return false;
+ }
+
+ return !joinType.equals(JoinType.JOIN_FULL_OUTER) || caps.supportsCapability(Capability.QUERY_FROM_JOIN_OUTER_FULL);
+ }
+
+ public static boolean supportsAggregates(List groupCols, Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+
+ if (metadata.isVirtualModel(modelID)){
+ return false;
+ }
+
+ // Find capabilities
+ SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
+
+ if (groupCols != null && !groupCols.isEmpty()) {
+ if (!caps.supportsCapability(Capability.QUERY_GROUP_BY)) {
+ return false;
+ }
+ boolean supportsFunctionsInGroupBy = caps.supportsCapability(Capability.QUERY_FUNCTIONS_IN_GROUP_BY);
+
+ // 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) {
+ // Function in GROUP BY can't be pushed
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ public static boolean supportsAggregateFunction(Object modelID, AggregateSymbol aggregate, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+
+ if (metadata.isVirtualModel(modelID)){
+ return false;
+ }
+
+ // Find capabilities
+ SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
+
+ // Check particular function
+ Type func = aggregate.getAggregateFunction();
+ switch (func) {
+ case COUNT:
+ if(aggregate.getExpression() == null) {
+ if(! caps.supportsCapability(Capability.QUERY_AGGREGATES_COUNT_STAR)) {
+ return false;
+ }
+ } else {
+ if(! caps.supportsCapability(Capability.QUERY_AGGREGATES_COUNT)) {
+ return false;
+ }
+ }
+ break;
+ case SUM:
+ if(! caps.supportsCapability(Capability.QUERY_AGGREGATES_SUM)) {
+ return false;
+ }
+ break;
+ case AVG:
+ if(! caps.supportsCapability(Capability.QUERY_AGGREGATES_AVG)) {
+ return false;
+ }
+ break;
+ case MIN:
+ if(! caps.supportsCapability(Capability.QUERY_AGGREGATES_MIN)) {
+ return false;
+ }
+ break;
+ case MAX:
+ if(! caps.supportsCapability(Capability.QUERY_AGGREGATES_MAX)) {
+ return false;
+ }
+ break;
+ default:
+ if (aggregate.isEnhancedNumeric()) {
+ if (!caps.supportsCapability(Capability.QUERY_AGGREGATES_ENHANCED_NUMERIC)) {
+ return false;
+ }
+ } else {
+ return false;
+ }
+ break;
+ }
+
+ // Check DISTINCT if necessary
+ if(aggregate.isDistinct() && ! caps.supportsCapability(Capability.QUERY_AGGREGATES_DISTINCT)) {
+ return false;
+ }
+
+ // Passed all the checks!
+ return true;
+
+
+ }
+
+ public static boolean supportsScalarFunction(Object modelID, Function function, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+
+ if (metadata.isVirtualModel(modelID)){
+ return false;
+ }
+
+ //capabilities check is only valid for non-schema scoped functions
+ //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())) {
+ return false;
+ }
+ } else if (!schema.getFullName().equalsIgnoreCase(metadata.getFullName(modelID))) {
+ return false; //not the right schema
+ }
+
+ //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();
+ //object or clob to anything cannot be pushed down
+ if (DataTypeManager.DefaultDataClasses.OBJECT.equals(fromType)
+ || DataTypeManager.DefaultDataClasses.CLOB.equals(fromType)
+ || DataTypeManager.DefaultDataClasses.XML.equals(fromType)) {
+ return false;
+ }
+ String targetType = (String)((Constant)function.getArg(1)).getValue();
+ if (DataTypeManager.DefaultDataTypes.CLOB.equalsIgnoreCase(targetType)
+ || DataTypeManager.DefaultDataTypes.XML.equalsIgnoreCase(targetType)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public static boolean supportsSelectDistinct(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return supports(Capability.QUERY_SELECT_DISTINCT, modelID, metadata, capFinder);
+ }
+
+ public static boolean supportsSelectExpression(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return supports(Capability.QUERY_SELECT_EXPRESSION, modelID, metadata, capFinder);
+ }
+
+ public static boolean supportsOrderBy(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return supports(Capability.QUERY_ORDERBY, modelID, metadata, capFinder);
+ }
+
+ public static boolean supportsSetOp(Object modelID, Operation setOp, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+
+ if (metadata.isVirtualModel(modelID)){
+ return false;
+ }
+
+ // Find capabilities
+ SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
+
+ switch (setOp) {
+ case EXCEPT:
+ return caps.supportsCapability(Capability.QUERY_EXCEPT);
+ case INTERSECT:
+ return caps.supportsCapability(Capability.QUERY_INTERSECT);
+ case UNION:
+ return caps.supportsCapability(Capability.QUERY_UNION);
+ }
+
+ return false;
+ }
+
+ public static boolean supportsSetQueryOrderBy(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return supports(Capability.QUERY_SET_ORDER_BY, modelID, metadata, capFinder);
+ }
+
+ public static boolean supportsCaseExpression(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return supports(Capability.QUERY_CASE, modelID, metadata, capFinder);
+ }
+
+ public static boolean supportsSearchedCaseExpression(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return supports(Capability.QUERY_SEARCHED_CASE, modelID, metadata, capFinder);
+ }
+
+ public static int getMaxInCriteriaSize(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return getProperty(Capability.MAX_IN_CRITERIA_SIZE, modelID, metadata, capFinder);
+ }
+
+ private static int getProperty(Capability cap, Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+
+ if (metadata.isVirtualModel(modelID)){
+ return -1;
+ }
+
+ // Find capabilities
+ SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
+ Object maxInCriteriaSize = caps.getSourceProperty(cap);
+ int value = -1;
+ if(maxInCriteriaSize != null) {
+ value = ((Integer)maxInCriteriaSize).intValue();
+ }
+
+ // Check for invalid values and send back code for UNKNOWN
+ if(value <= 0) {
+ value = -1;
+ }
+ return value;
+ }
+
+ public static int getMaxDependentPredicates(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return getProperty(Capability.MAX_DEPENDENT_PREDICATES, modelID, metadata, capFinder);
+ }
+
+ public static int getMaxFromGroups(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+
+ if (metadata.isVirtualModel(modelID)){
+ return -1;
+ }
+
+ // Find capabilities
+ SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
+ Object maxGroups = caps.getSourceProperty(Capability.MAX_QUERY_FROM_GROUPS);
+ int value = -1;
+ if(maxGroups != null) {
+ value = ((Integer)maxGroups).intValue();
+ }
+
+ // Check for invalid values and send back code for UNKNOWN
+ if(value <= 0) {
+ value = -1;
+ }
+ return value;
+ }
+
+ public static SupportedJoinCriteria getSupportedJoinCriteria(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder) throws QueryMetadataException, TeiidComponentException {
+ if (metadata.isVirtualModel(modelID)){
+ return SupportedJoinCriteria.ANY;
+ }
+ SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
+ SupportedJoinCriteria crits = (SupportedJoinCriteria)caps.getSourceProperty(Capability.JOIN_CRITERIA_ALLOWED);
+ if (crits == null) {
+ return SupportedJoinCriteria.ANY;
+ }
+ return crits;
+ }
+
+ public static NullOrder getDefaultNullOrder(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder) throws QueryMetadataException, TeiidComponentException {
+ if (metadata.isVirtualModel(modelID)){
+ return NullOrder.UNKNOWN;
+ }
+ SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
+ NullOrder order = (NullOrder)caps.getSourceProperty(Capability.QUERY_ORDERBY_DEFAULT_NULL_ORDER);
+ if (order == null) {
+ return NullOrder.UNKNOWN;
+ }
+ return order;
+ }
+
+ public static boolean supportsRowLimit(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return supports(Capability.ROW_LIMIT, modelID, metadata, capFinder);
+ }
+
+ public static boolean supportsRowOffset(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return supports(Capability.ROW_OFFSET, modelID, metadata, capFinder);
+ }
+
+ public static boolean isSameConnector(Object modelID, Object modelID1, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+
+ if (modelID == null || modelID1 == null || metadata.isVirtualModel(modelID) || metadata.isVirtualModel(modelID1)){
+ return false;
+ }
+
+ if (modelID.equals(modelID1)) {
+ return true;
+ }
+
+ // Find capabilities
+ SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
+ SourceCapabilities caps1 = getCapabilities(modelID1, metadata, capFinder);
+
+ Object connectorID = caps.getSourceProperty(Capability.CONNECTOR_ID);
+
+ return connectorID != null && connectorID.equals(caps1.getSourceProperty(Capability.CONNECTOR_ID));
+ }
+
+ private static SourceCapabilities getCapabilities(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+
+ // Find capabilities
+ String modelName = metadata.getFullName(modelID);
+ return capFinder.findCapabilities(modelName);
+ }
+
+ public static boolean requiresCriteria(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return supports(Capability.REQUIRES_CRITERIA, modelID, metadata, capFinder);
+ }
+
+ public static boolean useAnsiJoin(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ return supports(Capability.QUERY_FROM_ANSI_JOIN, modelID, metadata, capFinder);
+ }
+
+ public static boolean supports(Capability cap, Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
+ throws QueryMetadataException, TeiidComponentException {
+ if (metadata.isVirtualModel(modelID)){
+ return false;
+ }
+
+ // Find capabilities
+ SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
+
+ return caps.supportsCapability(cap);
+ }
+
+ /**
+ * Validate that the elements are searchable and can be used in a criteria against this source.
+ * TODO: this check is too general and not type based
+ */
+ static boolean checkElementsAreSearchable(List<? extends LanguageObject> objs, QueryMetadataInterface metadata, int searchableType)
+ throws QueryMetadataException, TeiidComponentException {
+ Collection<ElementSymbol> elements = new ArrayList<ElementSymbol>();
+ ElementCollectorVisitor.getElements(objs, elements);
+ for (ElementSymbol elementSymbol : elements) {
+ if (!metadata.elementSupports(elementSymbol.getMetadataID(), searchableType)) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,611 +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.optimizer.relational.rules;
-
-import java.util.Arrays;
-import java.util.Collection;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.metadata.FunctionMethod.PushDown;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.SupportConstants;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.relational.AccessNode;
-import org.teiid.query.processor.relational.LimitNode;
-import org.teiid.query.processor.relational.RelationalNode;
-import org.teiid.query.processor.relational.RelationalPlan;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.lang.AbstractCompareCriteria;
-import org.teiid.query.sql.lang.AbstractSetCriteria;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.DependentSetCriteria;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.IsNullCriteria;
-import org.teiid.query.sql.lang.MatchCriteria;
-import org.teiid.query.sql.lang.NotCriteria;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SubqueryCompareCriteria;
-import org.teiid.query.sql.lang.SubqueryContainer;
-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.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.XMLAttributes;
-import org.teiid.query.sql.symbol.XMLElement;
-import org.teiid.query.sql.symbol.XMLForest;
-import org.teiid.query.sql.symbol.XMLNamespaces;
-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.util.SymbolMap;
-import org.teiid.query.sql.visitor.EvaluatableVisitor;
-import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-
-
-/**
- */
-public class CriteriaCapabilityValidatorVisitor extends LanguageVisitor {
-
- // Initialization state
- private Object modelID;
- private QueryMetadataInterface metadata;
- private CapabilitiesFinder capFinder;
- private AnalysisRecord analysisRecord;
-
- // Retrieved during initialization and cached
- private SourceCapabilities caps;
-
- // Output state
- private TeiidComponentException exception;
- private boolean valid = true;
-
- /**
- * @param iterator
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- */
- CriteriaCapabilityValidatorVisitor(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, SourceCapabilities caps) throws QueryMetadataException, TeiidComponentException {
- this.modelID = modelID;
- this.metadata = metadata;
- this.capFinder = capFinder;
- this.caps = caps;
- }
-
- @Override
- public void visit(XMLAttributes obj) {
- markInvalid(obj, "Pushdown of XMLAttributes not allowed"); //$NON-NLS-1$
- }
-
- @Override
- public void visit(XMLNamespaces obj) {
- markInvalid(obj, "Pushdown of XMLNamespaces not allowed"); //$NON-NLS-1$
- }
-
- @Override
- public void visit(TextLine obj) {
- markInvalid(obj, "Pushdown of TextLine not allowed"); //$NON-NLS-1$
- }
-
- @Override
- public void visit(XMLForest obj) {
- markInvalid(obj, "Pushdown of XMLForest not allowed"); //$NON-NLS-1$
- }
-
- @Override
- public void visit(XMLElement obj) {
- markInvalid(obj, "Pushdown of XMLElement not allowed"); //$NON-NLS-1$
- }
-
- @Override
- public void visit(XMLSerialize obj) {
- markInvalid(obj, "Pushdown of XMLSerialize not allowed"); //$NON-NLS-1$
- }
-
- @Override
- public void visit(XMLParse obj) {
- markInvalid(obj, "Pushdown of XMLParse not allowed"); //$NON-NLS-1$
- }
-
- @Override
- public void visit(XMLQuery obj) {
- markInvalid(obj, "Pushdown of XMLQuery not allowed"); //$NON-NLS-1$
- }
-
- @Override
- public void visit(QueryString obj) {
- markInvalid(obj, "Pushdown of QueryString not allowed"); //$NON-NLS-1$
- }
-
- public void visit(AggregateSymbol obj) {
- try {
- if(! CapabilitiesUtil.supportsAggregateFunction(modelID, obj, metadata, capFinder)) {
- markInvalid(obj, "Aggregate function pushdown not supported by source"); //$NON-NLS-1$
- }
- } catch(QueryMetadataException e) {
- handleException(new TeiidComponentException(e));
- } catch(TeiidComponentException e) {
- handleException(e);
- }
- }
-
- public void visit(CaseExpression obj) {
- if(! this.caps.supportsCapability(Capability.QUERY_CASE)) {
- markInvalid(obj, "CaseExpression pushdown not supported by source"); //$NON-NLS-1$
- }
- }
-
- public void visit(CompareCriteria obj) {
- checkCompareCriteria(obj);
- }
-
- public void checkCompareCriteria(AbstractCompareCriteria obj) {
- boolean negated = false;
- // Check if operation is allowed
- Capability operatorCap = null;
- switch(obj.getOperator()) {
- case CompareCriteria.NE:
- negated = true;
- case CompareCriteria.EQ:
- operatorCap = Capability.CRITERIA_COMPARE_EQ;
- break;
- case CompareCriteria.LT:
- case CompareCriteria.GT:
- negated = true;
- case CompareCriteria.LE:
- case CompareCriteria.GE:
- operatorCap = Capability.CRITERIA_COMPARE_ORDERED;
- break;
- }
-
- // Check if compares are allowed
- if(! this.caps.supportsCapability(operatorCap)) {
- markInvalid(obj, "ordered CompareCriteria not supported by source"); //$NON-NLS-1$
- return;
- }
- if (negated && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
- markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
- return;
- }
-
- // Check capabilities of the elements
- try {
- checkElementsAreSearchable(obj, SupportConstants.Element.SEARCHABLE_COMPARE);
- } catch(QueryMetadataException e) {
- handleException(new TeiidComponentException(e));
- } catch(TeiidComponentException e) {
- handleException(e);
- }
- }
-
- public void visit(CompoundCriteria crit) {
- int operator = crit.getOperator();
-
- // Verify capabilities are supported
- if(operator == CompoundCriteria.OR && !this.caps.supportsCapability(Capability.CRITERIA_OR)) {
- markInvalid(crit, "OR criteria not supported by source"); //$NON-NLS-1$
- }
- }
-
- public void visit(Function obj) {
- try {
- //if the function can be evaluated then return as it will get replaced during the final rewrite
- if (EvaluatableVisitor.willBecomeConstant(obj, true)) {
- return;
- }
- if(obj.getFunctionDescriptor().getPushdown() == PushDown.CANNOT_PUSHDOWN) {
- markInvalid(obj, "Function metadata indicates it cannot be pusheddown."); //$NON-NLS-1$
- return;
- }
- if (! CapabilitiesUtil.supportsScalarFunction(modelID, obj, metadata, capFinder)) {
- markInvalid(obj, (obj.isImplicit()?"(implicit) ":"") + obj.getName() + " function not supported by source"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- } catch(QueryMetadataException e) {
- handleException(new TeiidComponentException(e));
- } catch(TeiidComponentException e) {
- handleException(e);
- }
- }
-
- public void visit(IsNullCriteria obj) {
- // Check if compares are allowed
- if(! this.caps.supportsCapability(Capability.CRITERIA_ISNULL)) {
- markInvalid(obj, "IsNull not supported by source"); //$NON-NLS-1$
- return;
- }
-
- if (obj.isNegated() && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
- markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
- return;
- }
- }
-
- 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;
- }
-
- // 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;
- }
- }
-
- //check NOT
- if(obj.isNegated() && ! this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
- markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
- return;
- }
-
- // Check capabilities of the elements
- try {
- checkElementsAreSearchable(obj, SupportConstants.Element.SEARCHABLE_LIKE);
- } catch(QueryMetadataException e) {
- handleException(new TeiidComponentException(e));
- } catch(TeiidComponentException e) {
- handleException(e);
- }
- }
-
- public void visit(NotCriteria obj) {
- // Check if compares are allowed
- if(! this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
- markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
- return;
- }
- }
-
- public void visit(SearchedCaseExpression obj) {
- if(! this.caps.supportsCapability(Capability.QUERY_SEARCHED_CASE)) {
- markInvalid(obj, "SearchedCase is not supported by source"); //$NON-NLS-1$
- }
- }
-
- public void visit(SetCriteria crit) {
- checkAbstractSetCriteria(crit);
- try {
- int maxSize = CapabilitiesUtil.getMaxInCriteriaSize(modelID, metadata, capFinder);
-
- if (maxSize > 0 && crit.getValues().size() > maxSize) {
- markInvalid(crit, "SetCriteria size exceeds maximum for source"); //$NON-NLS-1$
- return;
- }
- } catch(QueryMetadataException e) {
- handleException(new TeiidComponentException(e));
- } catch(TeiidComponentException e) {
- handleException(e);
- }
- }
-
- /**
- * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.ExistsCriteria)
- */
- public void visit(ExistsCriteria crit) {
- // Check if exists criteria are allowed
- if(! this.caps.supportsCapability(Capability.CRITERIA_EXISTS)) {
- markInvalid(crit, "Exists is not supported by source"); //$NON-NLS-1$
- return;
- }
-
- if (crit.isNegated() && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
- markInvalid(crit, "Negation is not supported by source"); //$NON-NLS-1$
- return;
- }
-
- try {
- if (validateSubqueryPushdown(crit, modelID, metadata, capFinder, analysisRecord) == null) {
- if (crit.getCommand().getCorrelatedReferences() == null) {
- crit.setShouldEvaluate(true);
- } else {
- markInvalid(crit.getCommand(), "Subquery cannot be pushed down"); //$NON-NLS-1$
- }
- }
- } catch (TeiidComponentException e) {
- handleException(e);
- }
- }
-
- /**
- * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.SubqueryCompareCriteria)
- */
- public void visit(SubqueryCompareCriteria crit) {
- // Check if quantification operator is allowed
- Capability capability = Capability.QUERY_SUBQUERIES_SCALAR;
- switch(crit.getPredicateQuantifier()) {
- case SubqueryCompareCriteria.ALL:
- capability = Capability.CRITERIA_QUANTIFIED_ALL;
- break;
- case SubqueryCompareCriteria.ANY:
- capability = Capability.CRITERIA_QUANTIFIED_SOME;
- break;
- case SubqueryCompareCriteria.SOME:
- capability = Capability.CRITERIA_QUANTIFIED_SOME;
- break;
- }
- if(! this.caps.supportsCapability(capability)) {
- markInvalid(crit, "SubqueryCompare not supported by source"); //$NON-NLS-1$
- return;
- }
-
- checkCompareCriteria(crit);
-
- // Check capabilities of the elements
- try {
- if (validateSubqueryPushdown(crit, modelID, metadata, capFinder, analysisRecord) == null) {
- markInvalid(crit.getCommand(), "Subquery cannot be pushed down"); //$NON-NLS-1$
- }
- } catch(QueryMetadataException e) {
- handleException(new TeiidComponentException(e));
- } catch(TeiidComponentException e) {
- handleException(e);
- }
- }
-
- @Override
- public void visit(ScalarSubquery obj) {
- try {
- if(!this.caps.supportsCapability(Capability.QUERY_SUBQUERIES_SCALAR)
- || validateSubqueryPushdown(obj, modelID, metadata, capFinder, analysisRecord) == null) {
- if (obj.getCommand().getCorrelatedReferences() == null && !FunctionCollectorVisitor.isNonDeterministic(obj.getCommand())) {
- obj.setShouldEvaluate(true);
- } else {
- markInvalid(obj.getCommand(), !this.caps.supportsCapability(Capability.QUERY_SUBQUERIES_SCALAR)?
- "Correlated ScalarSubquery is not supported":"Subquery cannot be pushed down"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- } catch(QueryMetadataException e) {
- handleException(new TeiidComponentException(e));
- } catch(TeiidComponentException e) {
- handleException(e);
- }
- }
-
- public void visit(SubquerySetCriteria crit) {
- checkAbstractSetCriteria(crit);
- try {
- // Check if compares with subqueries are allowed
- if(! this.caps.supportsCapability(Capability.CRITERIA_IN_SUBQUERY)) {
- markInvalid(crit, "SubqueryIn is not supported by source"); //$NON-NLS-1$
- return;
- }
-
- if (validateSubqueryPushdown(crit, modelID, metadata, capFinder, analysisRecord) == null) {
- markInvalid(crit.getCommand(), "Subquery cannot be pushed down"); //$NON-NLS-1$
- }
- } catch(QueryMetadataException e) {
- handleException(new TeiidComponentException(e));
- } catch(TeiidComponentException e) {
- handleException(e);
- }
- }
-
- public void checkAbstractSetCriteria(AbstractSetCriteria crit) {
- try {
- // Check if compares are allowed
- if(! this.caps.supportsCapability(Capability.CRITERIA_IN)) {
- markInvalid(crit, "In is not supported by source"); //$NON-NLS-1$
- return;
- }
-
- if (crit.isNegated() && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
- markInvalid(crit, "Negation is not supported by source"); //$NON-NLS-1$
- return;
- }
- // Check capabilities of the elements
- checkElementsAreSearchable(crit, SupportConstants.Element.SEARCHABLE_COMPARE);
-
- } catch(QueryMetadataException e) {
- handleException(new TeiidComponentException(e));
- } catch(TeiidComponentException e) {
- handleException(e);
- }
-
- }
-
- public void visit(DependentSetCriteria crit) {
- checkAbstractSetCriteria(crit);
- }
-
- private void checkElementsAreSearchable(LanguageObject crit, int searchableType)
- throws QueryMetadataException, TeiidComponentException {
- if (!CapabilitiesUtil.checkElementsAreSearchable(Arrays.asList(crit), metadata, searchableType)) {
- markInvalid(crit, "not all source columns support search type"); //$NON-NLS-1$
- }
- }
-
- /**
- * Return null if the subquery cannot be pushed down, otherwise the model
- * id of the pushdown target.
- * @param subqueryContainer
- * @param critNodeModelID
- * @param metadata
- * @param capFinder
- * @return
- * @throws TeiidComponentException
- */
- 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);
-
- if (queryCommand == null) {
- return null;
- }
-
- critNodeModelID = validateCommandPushdown(critNodeModelID, metadata, capFinder, queryCommand);
- }
- if (critNodeModelID == null) {
- return null;
- }
- // Check whether source supports correlated subqueries and if not, whether criteria has them
- SymbolMap refs = subqueryContainer.getCommand().getCorrelatedReferences();
- try {
- if(refs != null && !refs.asMap().isEmpty()) {
- if(! CapabilitiesUtil.supports(Capability.QUERY_SUBQUERIES_CORRELATED, critNodeModelID, metadata, capFinder)) {
- return null;
- }
- //TODO: this check sees as correlated references as coming from the containing scope
- //but this is only an issue with deeply nested subqueries
- if (!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(subqueryContainer.getCommand(), critNodeModelID, metadata, capFinder, analysisRecord )) {
- return null;
- }
- }
- } catch(QueryMetadataException e) {
- throw new TeiidComponentException(e);
- }
-
- // Found no reason why this node is not eligible
- return critNodeModelID;
- }
-
- public static Object validateCommandPushdown(Object critNodeModelID,
- QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
- QueryCommand queryCommand) 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 (critNodeModelID == null) {
- critNodeModelID = modelID;
- } else if(!CapabilitiesUtil.isSameConnector(critNodeModelID, modelID, metadata, capFinder)) {
- return null;
- }
- } catch(QueryMetadataException e) {
- throw new TeiidComponentException(e, QueryPlugin.Util.getString("RulePushSelectCriteria.Error_getting_modelID")); //$NON-NLS-1$
- }
- return critNodeModelID;
- }
-
- public static QueryCommand getQueryCommand(ProcessorPlan plan) {
- if(!(plan instanceof RelationalPlan)) {
- return null;
- }
-
- RelationalPlan rplan = (RelationalPlan) plan;
-
- // Check that the plan is just an access node
- RelationalNode accessNode = rplan.getRootNode();
-
- if (accessNode instanceof LimitNode) {
- LimitNode ln = (LimitNode)accessNode;
- if (!ln.isImplicit()) {
- return null;
- }
- accessNode = ln.getChildren()[0];
- }
-
- if (! (accessNode instanceof AccessNode) || accessNode.getChildren()[0] != null) {
- 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 null;
- }
-
- QueryCommand queryCommand = (QueryCommand)command;
- return queryCommand;
- }
-
- private void handleException(TeiidComponentException e) {
- this.valid = false;
- this.exception = e;
- setAbort(true);
- }
-
- public TeiidComponentException getException() {
- return this.exception;
- }
-
- private void markInvalid(LanguageObject object, String reason) {
- this.valid = false;
- setAbort(true);
- if (analysisRecord != null && analysisRecord.recordDebug()) {
- analysisRecord.println(reason + " " + object); //$NON-NLS-1$
- }
- }
-
- public boolean isValid() {
- return this.valid;
- }
-
- public static boolean canPushLanguageObject(LanguageObject obj, Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord) throws QueryMetadataException, TeiidComponentException {
- if(obj == null) {
- return true;
- }
-
- if(modelID == null || metadata.isVirtualModel(modelID)) {
- // Couldn't determine model ID, so give up
- return false;
- }
-
- String modelName = metadata.getFullName(modelID);
- SourceCapabilities caps = capFinder.findCapabilities(modelName);
-
- if (caps == null) {
- return true; //this doesn't seem right, but tests were expecting it...
- }
-
- CriteriaCapabilityValidatorVisitor visitor = new CriteriaCapabilityValidatorVisitor(modelID, metadata, capFinder, caps);
- PostOrderNavigator.doVisit(obj, visitor);
-
- if(visitor.getException() != null) {
- throw visitor.getException();
- }
-
- return visitor.isValid();
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,613 @@
+/*
+ * 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.relational.rules;
+
+import java.util.Arrays;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.metadata.FunctionMethod.PushDown;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.SupportConstants;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.relational.AccessNode;
+import org.teiid.query.processor.relational.LimitNode;
+import org.teiid.query.processor.relational.RelationalNode;
+import org.teiid.query.processor.relational.RelationalPlan;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.lang.AbstractCompareCriteria;
+import org.teiid.query.sql.lang.AbstractSetCriteria;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.DependentSetCriteria;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.MatchCriteria;
+import org.teiid.query.sql.lang.NotCriteria;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SubqueryCompareCriteria;
+import org.teiid.query.sql.lang.SubqueryContainer;
+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.Expression;
+import org.teiid.query.sql.symbol.Function;
+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.XMLAttributes;
+import org.teiid.query.sql.symbol.XMLElement;
+import org.teiid.query.sql.symbol.XMLForest;
+import org.teiid.query.sql.symbol.XMLNamespaces;
+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.util.SymbolMap;
+import org.teiid.query.sql.visitor.EvaluatableVisitor;
+import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
+
+
+/**
+ */
+public class CriteriaCapabilityValidatorVisitor extends LanguageVisitor {
+
+ // Initialization state
+ private Object modelID;
+ private QueryMetadataInterface metadata;
+ private CapabilitiesFinder capFinder;
+ private AnalysisRecord analysisRecord;
+
+ // Retrieved during initialization and cached
+ private SourceCapabilities caps;
+
+ // Output state
+ private TeiidComponentException exception;
+ private boolean valid = true;
+
+ /**
+ * @param iterator
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ */
+ CriteriaCapabilityValidatorVisitor(Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, SourceCapabilities caps) throws QueryMetadataException, TeiidComponentException {
+ this.modelID = modelID;
+ this.metadata = metadata;
+ this.capFinder = capFinder;
+ this.caps = caps;
+ }
+
+ @Override
+ public void visit(XMLAttributes obj) {
+ markInvalid(obj, "Pushdown of XMLAttributes not allowed"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void visit(XMLNamespaces obj) {
+ markInvalid(obj, "Pushdown of XMLNamespaces not allowed"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void visit(TextLine obj) {
+ markInvalid(obj, "Pushdown of TextLine not allowed"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void visit(XMLForest obj) {
+ markInvalid(obj, "Pushdown of XMLForest not allowed"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void visit(XMLElement obj) {
+ markInvalid(obj, "Pushdown of XMLElement not allowed"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void visit(XMLSerialize obj) {
+ markInvalid(obj, "Pushdown of XMLSerialize not allowed"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void visit(XMLParse obj) {
+ markInvalid(obj, "Pushdown of XMLParse not allowed"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void visit(XMLQuery obj) {
+ markInvalid(obj, "Pushdown of XMLQuery not allowed"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void visit(QueryString obj) {
+ markInvalid(obj, "Pushdown of QueryString not allowed"); //$NON-NLS-1$
+ }
+
+ public void visit(AggregateSymbol obj) {
+ try {
+ if(! CapabilitiesUtil.supportsAggregateFunction(modelID, obj, metadata, capFinder)) {
+ markInvalid(obj, "Aggregate function pushdown not supported by source"); //$NON-NLS-1$
+ }
+ } catch(QueryMetadataException e) {
+ handleException(new TeiidComponentException(e));
+ } catch(TeiidComponentException e) {
+ handleException(e);
+ }
+ }
+
+ public void visit(CaseExpression obj) {
+ if(! this.caps.supportsCapability(Capability.QUERY_CASE)) {
+ markInvalid(obj, "CaseExpression pushdown not supported by source"); //$NON-NLS-1$
+ }
+ }
+
+ public void visit(CompareCriteria obj) {
+ checkCompareCriteria(obj);
+ }
+
+ public void checkCompareCriteria(AbstractCompareCriteria obj) {
+ boolean negated = false;
+ // Check if operation is allowed
+ Capability operatorCap = null;
+ switch(obj.getOperator()) {
+ case CompareCriteria.NE:
+ negated = true;
+ case CompareCriteria.EQ:
+ operatorCap = Capability.CRITERIA_COMPARE_EQ;
+ break;
+ case CompareCriteria.LT:
+ case CompareCriteria.GT:
+ negated = true;
+ case CompareCriteria.LE:
+ case CompareCriteria.GE:
+ operatorCap = Capability.CRITERIA_COMPARE_ORDERED;
+ break;
+ }
+
+ // Check if compares are allowed
+ if(! this.caps.supportsCapability(operatorCap)) {
+ markInvalid(obj, "ordered CompareCriteria not supported by source"); //$NON-NLS-1$
+ return;
+ }
+ if (negated && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
+ markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
+ return;
+ }
+
+ // Check capabilities of the elements
+ try {
+ checkElementsAreSearchable(obj, SupportConstants.Element.SEARCHABLE_COMPARE);
+ } catch(QueryMetadataException e) {
+ handleException(new TeiidComponentException(e));
+ } catch(TeiidComponentException e) {
+ handleException(e);
+ }
+ }
+
+ public void visit(CompoundCriteria crit) {
+ int operator = crit.getOperator();
+
+ // Verify capabilities are supported
+ if(operator == CompoundCriteria.OR && !this.caps.supportsCapability(Capability.CRITERIA_OR)) {
+ markInvalid(crit, "OR criteria not supported by source"); //$NON-NLS-1$
+ }
+ }
+
+ public void visit(Function obj) {
+ try {
+ //if the function can be evaluated then return as it will get replaced during the final rewrite
+ if (EvaluatableVisitor.willBecomeConstant(obj, true)) {
+ return;
+ }
+ if(obj.getFunctionDescriptor().getPushdown() == PushDown.CANNOT_PUSHDOWN) {
+ markInvalid(obj, "Function metadata indicates it cannot be pusheddown."); //$NON-NLS-1$
+ return;
+ }
+ if (! CapabilitiesUtil.supportsScalarFunction(modelID, obj, metadata, capFinder)) {
+ markInvalid(obj, (obj.isImplicit()?"(implicit) ":"") + obj.getName() + " function not supported by source"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ } catch(QueryMetadataException e) {
+ handleException(new TeiidComponentException(e));
+ } catch(TeiidComponentException e) {
+ handleException(e);
+ }
+ }
+
+ public void visit(IsNullCriteria obj) {
+ // Check if compares are allowed
+ if(! this.caps.supportsCapability(Capability.CRITERIA_ISNULL)) {
+ markInvalid(obj, "IsNull not supported by source"); //$NON-NLS-1$
+ return;
+ }
+
+ if (obj.isNegated() && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
+ markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
+ return;
+ }
+ }
+
+ 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;
+ }
+
+ // 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;
+ }
+ }
+
+ //check NOT
+ if(obj.isNegated() && ! this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
+ markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
+ return;
+ }
+
+ // Check capabilities of the elements
+ try {
+ checkElementsAreSearchable(obj, SupportConstants.Element.SEARCHABLE_LIKE);
+ } catch(QueryMetadataException e) {
+ handleException(new TeiidComponentException(e));
+ } catch(TeiidComponentException e) {
+ handleException(e);
+ }
+ }
+
+ public void visit(NotCriteria obj) {
+ // Check if compares are allowed
+ if(! this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
+ markInvalid(obj, "Negation is not supported by source"); //$NON-NLS-1$
+ return;
+ }
+ }
+
+ public void visit(SearchedCaseExpression obj) {
+ if(! this.caps.supportsCapability(Capability.QUERY_SEARCHED_CASE)) {
+ markInvalid(obj, "SearchedCase is not supported by source"); //$NON-NLS-1$
+ }
+ }
+
+ public void visit(SetCriteria crit) {
+ checkAbstractSetCriteria(crit);
+ try {
+ int maxSize = CapabilitiesUtil.getMaxInCriteriaSize(modelID, metadata, capFinder);
+
+ if (maxSize > 0 && crit.getValues().size() > maxSize) {
+ markInvalid(crit, "SetCriteria size exceeds maximum for source"); //$NON-NLS-1$
+ return;
+ }
+ } catch(QueryMetadataException e) {
+ handleException(new TeiidComponentException(e));
+ } catch(TeiidComponentException e) {
+ handleException(e);
+ }
+ }
+
+ /**
+ * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.ExistsCriteria)
+ */
+ public void visit(ExistsCriteria crit) {
+ // Check if exists criteria are allowed
+ if(! this.caps.supportsCapability(Capability.CRITERIA_EXISTS)) {
+ markInvalid(crit, "Exists is not supported by source"); //$NON-NLS-1$
+ return;
+ }
+
+ if (crit.isNegated() && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
+ markInvalid(crit, "Negation is not supported by source"); //$NON-NLS-1$
+ return;
+ }
+
+ try {
+ if (validateSubqueryPushdown(crit, modelID, metadata, capFinder, analysisRecord) == null) {
+ if (crit.getCommand().getCorrelatedReferences() == null) {
+ crit.setShouldEvaluate(true);
+ } else {
+ markInvalid(crit.getCommand(), "Subquery cannot be pushed down"); //$NON-NLS-1$
+ }
+ }
+ } catch (TeiidComponentException e) {
+ handleException(e);
+ }
+ }
+
+ /**
+ * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.SubqueryCompareCriteria)
+ */
+ public void visit(SubqueryCompareCriteria crit) {
+ // Check if quantification operator is allowed
+ Capability capability = Capability.QUERY_SUBQUERIES_SCALAR;
+ switch(crit.getPredicateQuantifier()) {
+ case SubqueryCompareCriteria.ALL:
+ capability = Capability.CRITERIA_QUANTIFIED_ALL;
+ break;
+ case SubqueryCompareCriteria.ANY:
+ capability = Capability.CRITERIA_QUANTIFIED_SOME;
+ break;
+ case SubqueryCompareCriteria.SOME:
+ capability = Capability.CRITERIA_QUANTIFIED_SOME;
+ break;
+ }
+ if(! this.caps.supportsCapability(capability)) {
+ markInvalid(crit, "SubqueryCompare not supported by source"); //$NON-NLS-1$
+ return;
+ }
+
+ checkCompareCriteria(crit);
+
+ // Check capabilities of the elements
+ try {
+ if (validateSubqueryPushdown(crit, modelID, metadata, capFinder, analysisRecord) == null) {
+ markInvalid(crit.getCommand(), "Subquery cannot be pushed down"); //$NON-NLS-1$
+ }
+ } catch(QueryMetadataException e) {
+ handleException(new TeiidComponentException(e));
+ } catch(TeiidComponentException e) {
+ handleException(e);
+ }
+ }
+
+ @Override
+ public void visit(ScalarSubquery obj) {
+ try {
+ if(!this.caps.supportsCapability(Capability.QUERY_SUBQUERIES_SCALAR)
+ || validateSubqueryPushdown(obj, modelID, metadata, capFinder, analysisRecord) == null) {
+ if (obj.getCommand().getCorrelatedReferences() == null && !FunctionCollectorVisitor.isNonDeterministic(obj.getCommand())) {
+ obj.setShouldEvaluate(true);
+ } else {
+ markInvalid(obj.getCommand(), !this.caps.supportsCapability(Capability.QUERY_SUBQUERIES_SCALAR)?
+ "Correlated ScalarSubquery is not supported":"Subquery cannot be pushed down"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+ } catch(QueryMetadataException e) {
+ handleException(new TeiidComponentException(e));
+ } catch(TeiidComponentException e) {
+ handleException(e);
+ }
+ }
+
+ public void visit(SubquerySetCriteria crit) {
+ checkAbstractSetCriteria(crit);
+ try {
+ // Check if compares with subqueries are allowed
+ if(! this.caps.supportsCapability(Capability.CRITERIA_IN_SUBQUERY)) {
+ markInvalid(crit, "SubqueryIn is not supported by source"); //$NON-NLS-1$
+ return;
+ }
+
+ if (validateSubqueryPushdown(crit, modelID, metadata, capFinder, analysisRecord) == null) {
+ markInvalid(crit.getCommand(), "Subquery cannot be pushed down"); //$NON-NLS-1$
+ }
+ } catch(QueryMetadataException e) {
+ handleException(new TeiidComponentException(e));
+ } catch(TeiidComponentException e) {
+ handleException(e);
+ }
+ }
+
+ public void checkAbstractSetCriteria(AbstractSetCriteria crit) {
+ try {
+ // Check if compares are allowed
+ if(! this.caps.supportsCapability(Capability.CRITERIA_IN)) {
+ markInvalid(crit, "In is not supported by source"); //$NON-NLS-1$
+ return;
+ }
+
+ if (crit.isNegated() && !this.caps.supportsCapability(Capability.CRITERIA_NOT)) {
+ markInvalid(crit, "Negation is not supported by source"); //$NON-NLS-1$
+ return;
+ }
+ // Check capabilities of the elements
+ checkElementsAreSearchable(crit, SupportConstants.Element.SEARCHABLE_COMPARE);
+
+ } catch(QueryMetadataException e) {
+ handleException(new TeiidComponentException(e));
+ } catch(TeiidComponentException e) {
+ handleException(e);
+ }
+
+ }
+
+ public void visit(DependentSetCriteria crit) {
+ checkAbstractSetCriteria(crit);
+ }
+
+ private void checkElementsAreSearchable(LanguageObject crit, int searchableType)
+ throws QueryMetadataException, TeiidComponentException {
+ if (!CapabilitiesUtil.checkElementsAreSearchable(Arrays.asList(crit), metadata, searchableType)) {
+ markInvalid(crit, "not all source columns support search type"); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Return null if the subquery cannot be pushed down, otherwise the model
+ * id of the pushdown target.
+ * @param subqueryContainer
+ * @param critNodeModelID
+ * @param metadata
+ * @param capFinder
+ * @return
+ * @throws TeiidComponentException
+ */
+ public static Object validateSubqueryPushdown(SubqueryContainer<?> subqueryContainer, Object critNodeModelID,
+ QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord) throws TeiidComponentException {
+ ProcessorPlan plan = subqueryContainer.getCommand().getProcessorPlan();
+ if (plan != null) {
+ AccessNode aNode = getAccessNode(plan);
+
+ if (aNode == null) {
+ return null;
+ }
+
+ critNodeModelID = validateCommandPushdown(critNodeModelID, metadata, capFinder, aNode);
+ }
+ if (critNodeModelID == null) {
+ return null;
+ }
+ // Check whether source supports correlated subqueries and if not, whether criteria has them
+ SymbolMap refs = subqueryContainer.getCommand().getCorrelatedReferences();
+ try {
+ if(refs != null && !refs.asMap().isEmpty()) {
+ if(! CapabilitiesUtil.supports(Capability.QUERY_SUBQUERIES_CORRELATED, critNodeModelID, metadata, capFinder)) {
+ return null;
+ }
+ //TODO: this check sees as correlated references as coming from the containing scope
+ //but this is only an issue with deeply nested subqueries
+ if (!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(subqueryContainer.getCommand(), critNodeModelID, metadata, capFinder, analysisRecord )) {
+ return null;
+ }
+ }
+ } catch(QueryMetadataException e) {
+ throw new TeiidComponentException(e);
+ }
+
+ // Found no reason why this node is not eligible
+ return critNodeModelID;
+ }
+
+ public static Object validateCommandPushdown(Object critNodeModelID,
+ QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
+ AccessNode aNode) throws TeiidComponentException {
+ // Check that query in access node is for the same model as current node
+ try {
+ if (!(aNode.getCommand() instanceof QueryCommand)) {
+ return null;
+ }
+ Object modelID = aNode.getModelId();
+ if (critNodeModelID == null) {
+ critNodeModelID = modelID;
+ } else if(!CapabilitiesUtil.isSameConnector(critNodeModelID, modelID, metadata, capFinder)) {
+ return null;
+ }
+ } catch(QueryMetadataException e) {
+ throw new TeiidComponentException(e, QueryPlugin.Util.getString("RulePushSelectCriteria.Error_getting_modelID")); //$NON-NLS-1$
+ }
+ return critNodeModelID;
+ }
+
+ public static AccessNode getAccessNode(ProcessorPlan plan) {
+ if(!(plan instanceof RelationalPlan)) {
+ return null;
+ }
+
+ RelationalPlan rplan = (RelationalPlan) plan;
+
+ // Check that the plan is just an access node
+ RelationalNode accessNode = rplan.getRootNode();
+
+ if (accessNode instanceof LimitNode) {
+ LimitNode ln = (LimitNode)accessNode;
+ if (!ln.isImplicit()) {
+ return null;
+ }
+ accessNode = ln.getChildren()[0];
+ }
+
+ if (! (accessNode instanceof AccessNode)) {
+ return null;
+ }
+ 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;
+ }
+
+ private void handleException(TeiidComponentException e) {
+ this.valid = false;
+ this.exception = e;
+ setAbort(true);
+ }
+
+ public TeiidComponentException getException() {
+ return this.exception;
+ }
+
+ private void markInvalid(LanguageObject object, String reason) {
+ this.valid = false;
+ setAbort(true);
+ if (analysisRecord != null && analysisRecord.recordDebug()) {
+ analysisRecord.println(reason + " " + object); //$NON-NLS-1$
+ }
+ }
+
+ public boolean isValid() {
+ return this.valid;
+ }
+
+ public static boolean canPushLanguageObject(LanguageObject obj, Object modelID, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord) throws QueryMetadataException, TeiidComponentException {
+ if(obj == null) {
+ return true;
+ }
+
+ if(modelID == null || metadata.isVirtualModel(modelID)) {
+ // Couldn't determine model ID, so give up
+ return false;
+ }
+
+ String modelName = metadata.getFullName(modelID);
+ SourceCapabilities caps = capFinder.findCapabilities(modelName);
+
+ if (caps == null) {
+ return true; //this doesn't seem right, but tests were expecting it...
+ }
+
+ CriteriaCapabilityValidatorVisitor visitor = new CriteriaCapabilityValidatorVisitor(modelID, metadata, capFinder, caps);
+ PostOrderNavigator.doVisit(obj, visitor);
+
+ if(visitor.getException() != null) {
+ throw visitor.getException();
+ }
+
+ return visitor.isValid();
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseDependent.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseDependent.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseDependent.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,348 +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.optimizer.relational.rules;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-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.capabilities.CapabilitiesFinder;
-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;
-import org.teiid.query.optimizer.relational.plantree.PlanNode;
-import org.teiid.query.optimizer.relational.rules.NewCalculateCostUtil.DependentCostAnalysis;
-import org.teiid.query.sql.lang.DependentSetCriteria;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.util.CommandContext;
-
-
-/**
- * Finds nodes that can be turned into dependent joins
- */
-public final class RuleChooseDependent implements OptimizerRule {
-
- private static AtomicInteger ID = new AtomicInteger();
-
- private static class CandidateJoin {
- PlanNode joinNode;
- boolean leftCandidate;
- boolean rightCandidate;
- }
-
- public static final int DEFAULT_INDEPENDENT_CARDINALITY = 10;
-
- public PlanNode execute(PlanNode plan, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, RuleStack rules, AnalysisRecord analysisRecord, CommandContext context)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- // Find first criteria node in plan with conjuncts
- List<CandidateJoin> matches = findCandidate(plan, metadata, analysisRecord);
-
- boolean pushCriteria = false;
-
- // Handle all cases where both siblings are possible matches
- for (CandidateJoin entry : matches) {
- PlanNode joinNode = entry.joinNode;
-
- PlanNode sourceNode = entry.leftCandidate?joinNode.getFirstChild():joinNode.getLastChild();
-
- PlanNode siblingNode = entry.leftCandidate?joinNode.getLastChild():joinNode.getFirstChild();
-
- boolean bothCandidates = entry.leftCandidate&&entry.rightCandidate;
-
- PlanNode chosenNode = chooseDepWithoutCosting(sourceNode, bothCandidates?siblingNode:null, analysisRecord);
- if(chosenNode != null) {
- pushCriteria |= markDependent(chosenNode, joinNode, metadata, null);
- continue;
- }
-
- DependentCostAnalysis dca = NewCalculateCostUtil.computeCostForDepJoin(joinNode, !entry.leftCandidate, metadata, capFinder, context);
- PlanNode dependentNode = sourceNode;
-
- if (bothCandidates && dca.expectedCardinality == null) {
- dca = NewCalculateCostUtil.computeCostForDepJoin(joinNode, true, metadata, capFinder, context);
- if (dca.expectedCardinality != null) {
- dependentNode = siblingNode;
- }
- }
-
- if (dca.expectedCardinality != null) {
- pushCriteria |= markDependent(dependentNode, joinNode, metadata, dca);
- } else {
- float sourceCost = NewCalculateCostUtil.computeCostForTree(sourceNode, metadata);
- float siblingCost = NewCalculateCostUtil.computeCostForTree(siblingNode, metadata);
-
- if (bothCandidates && sourceCost != NewCalculateCostUtil.UNKNOWN_VALUE && sourceCost < RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY
- && (sourceCost < siblingCost || siblingCost == NewCalculateCostUtil.UNKNOWN_VALUE)) {
- pushCriteria |= markDependent(siblingNode, joinNode, metadata, null);
- } else if (siblingCost != NewCalculateCostUtil.UNKNOWN_VALUE && siblingCost < RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY) {
- pushCriteria |= markDependent(sourceNode, joinNode, metadata, null);
- }
- }
- }
-
- if (pushCriteria) {
- // Insert new rules to push down the SELECT criteria
- rules.push(RuleConstants.CLEAN_CRITERIA); //it's important to run clean criteria here since it will remove unnecessary dependent sets
- rules.push(RuleConstants.PUSH_SELECT_CRITERIA);
- }
-
- return plan;
- }
-
- /**
- * Walk the tree pre-order, finding all access nodes that are candidates and
- * adding them to the matches list.
- * @param metadata Metadata implementation
- * @param node Root node to search
- * @param matches Collection to accumulate matches in
- */
- List<CandidateJoin> findCandidate(PlanNode root, QueryMetadataInterface metadata, AnalysisRecord analysisRecord) {
-
- List<CandidateJoin> candidates = new ArrayList<CandidateJoin>();
-
- for (PlanNode joinNode : NodeEditor.findAllNodes(root, NodeConstants.Types.JOIN, NodeConstants.Types.ACCESS)) {
- CandidateJoin candidate = null;
-
- for (Iterator<PlanNode> j = joinNode.getChildren().iterator(); j.hasNext();) {
- PlanNode child = j.next();
- child = FrameUtil.findJoinSourceNode(child);
-
- if(child.hasBooleanProperty(NodeConstants.Info.MAKE_NOT_DEP) || !isValidJoin(joinNode, child, analysisRecord)) {
- continue;
- }
- if (candidate == null) {
- candidate = new CandidateJoin();
- candidate.joinNode = joinNode;
- candidates.add(candidate);
- }
- if (j.hasNext()) {
- candidate.leftCandidate=true;
- } else {
- candidate.rightCandidate=true;
- }
- }
- }
-
- return candidates;
-
- }
-
- /**
- * Check whether a join is valid. Invalid joins are CROSS JOIN, FULL OUTER JOIN,
- * any join without criteria, any join with no equality criteria, and any outer
- * join that has the outer side not the same as the dependent.
- * @param joinNode The join node to check
- * @param sourceNode The access node being considered
- * @param analysisRecord TODO
- * @return True if valid for making dependent
- */
- boolean isValidJoin(PlanNode joinNode, PlanNode sourceNode, AnalysisRecord analysisRecord) {
- JoinType jtype = (JoinType) joinNode.getProperty(NodeConstants.Info.JOIN_TYPE);
-
- // Check that join is not a CROSS join or FULL OUTER join
- if(jtype.equals(JoinType.JOIN_CROSS) || jtype.equals(JoinType.JOIN_FULL_OUTER)) {
- if (analysisRecord.recordDebug()) {
- analysisRecord.println("Rejecting dependent access node as parent join is CROSS or FULL OUTER: "+ sourceNode.nodeToString()); //$NON-NLS-1$
- }
- return false;
- }
-
- if (!joinNode.getExportedCorrelatedReferences().isEmpty()) {
- if (analysisRecord.recordDebug()) {
- analysisRecord.println("Rejecting dependent access node as parent join has a correlated nested table: "+ sourceNode.nodeToString()); //$NON-NLS-1$
- }
- return false;
- }
-
- // Check that join criteria exist
- List jcrit = (List) joinNode.getProperty(NodeConstants.Info.JOIN_CRITERIA);
- if(jcrit == null || jcrit.size() == 0) {
- if (analysisRecord.recordDebug()) {
- analysisRecord.println("Rejecting dependent access node as parent join has no join criteria: "+ sourceNode.nodeToString()); //$NON-NLS-1$
- }
- return false;
- }
-
- if(joinNode.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS) == null) {
- if (analysisRecord.recordDebug()) {
- analysisRecord.println("Rejecting dependent access node as parent join has no equality expressions: "+ sourceNode.nodeToString()); //$NON-NLS-1$
- }
- return false;
- }
-
- // Check that for a left or right outer join the dependent side must be the inner
- if(jtype.isOuter() && JoinUtil.getInnerSideJoinNodes(joinNode)[0] != sourceNode) {
- if (analysisRecord.recordDebug()) {
- analysisRecord.println("Rejecting dependent access node as it is on outer side of a join: "+ sourceNode.nodeToString()); //$NON-NLS-1$
- }
- return false;
- }
-
- return true;
- }
-
- PlanNode chooseDepWithoutCosting(PlanNode rootNode1, PlanNode rootNode2, AnalysisRecord analysisRecord) {
- PlanNode sourceNode1 = FrameUtil.findJoinSourceNode(rootNode1);
- PlanNode sourceNode2 = null;
-
- if (rootNode2 != null) {
- sourceNode2 = FrameUtil.findJoinSourceNode(rootNode2);
- }
- if(sourceNode1.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS) ) {
- if (sourceNode2 != null && sourceNode2.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS) ) {
- //Return null - query planning should fail because both access nodes
- //have unsatisfied access patterns
- if (analysisRecord.recordDebug()) {
- analysisRecord.println("Neither access node can be made dependent because both have unsatisfied access patterns: " + sourceNode1.nodeToString() + "\n" + sourceNode2.toString()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return null;
- }
- return rootNode1;
- } else if (sourceNode2 != null && sourceNode2.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS) ) {
- //Access node 2 has unsatisfied access pattern,
- //so try to make node 2 dependent
- if (analysisRecord.recordDebug()) {
- analysisRecord.println("Making access node dependent to satisfy access pattern: "+ sourceNode2.nodeToString()); //$NON-NLS-1$
- }
- return rootNode2;
- }
-
- // Check for hints, which over-rule heuristics
- if(sourceNode1.hasBooleanProperty(NodeConstants.Info.MAKE_DEP)) {
- if (analysisRecord.recordDebug()) {
- analysisRecord.println("Making access node dependent due to hint: "+ sourceNode1.nodeToString()); //$NON-NLS-1$
- }
- return rootNode1;
- } else if(sourceNode2 != null && sourceNode2.hasBooleanProperty(NodeConstants.Info.MAKE_DEP)) {
- if (analysisRecord.recordDebug()) {
- analysisRecord.println("Making access node dependent due to hint: "+ sourceNode2.nodeToString()); //$NON-NLS-1$
- }
- return rootNode2;
- }
-
- return null;
- }
-
- /**
- * Mark the specified access node to be made dependent
- * @param sourceNode Node to make dependent
- * @param dca
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- */
- boolean markDependent(PlanNode sourceNode, PlanNode joinNode, QueryMetadataInterface metadata, DependentCostAnalysis dca) throws QueryMetadataException, TeiidComponentException {
-
- boolean isLeft = joinNode.getFirstChild() == sourceNode;
-
- // Get new access join node properties based on join criteria
- List independentExpressions = (List)(isLeft?joinNode.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS):joinNode.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS));
- List dependentExpressions = (List)(isLeft?joinNode.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS):joinNode.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS));
-
- if(independentExpressions == null || independentExpressions.isEmpty()) {
- return false;
- }
-
- String id = "$dsc/id" + ID.getAndIncrement(); //$NON-NLS-1$
- // Create DependentValueSource and set on the independent side as this will feed the values
- joinNode.setProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE, id);
-
- List<PlanNode> crits = getDependentCriteriaNodes(id, independentExpressions, dependentExpressions, isLeft?joinNode.getLastChild():joinNode.getFirstChild(), metadata, dca);
-
- PlanNode newRoot = sourceNode;
-
- for (PlanNode crit : crits) {
- newRoot.addAsParent(crit);
- newRoot = crit;
- }
-
- if (isLeft) {
- JoinUtil.swapJoinChildren(joinNode);
- }
- return true;
- }
-
- /**
- * @param independentExpressions
- * @param dependentExpressions
- * @return
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- * @since 4.3
- */
- private List<PlanNode> getDependentCriteriaNodes(String id, List independentExpressions,
- List dependentExpressions, PlanNode indNode, QueryMetadataInterface metadata, DependentCostAnalysis dca) throws QueryMetadataException, TeiidComponentException {
-
- List<PlanNode> result = new LinkedList<PlanNode>();
-
- Float cardinality = null;
-
- for (int i = 0; i < dependentExpressions.size(); i++) {
- Expression depExpr = (Expression) dependentExpressions.get(i);
- Expression indepExpr = (Expression) independentExpressions.get(i);
- DependentSetCriteria crit = new DependentSetCriteria(SymbolMap.getExpression(depExpr), id);
- float ndv = NewCalculateCostUtil.UNKNOWN_VALUE;
- if (dca != null && dca.expectedNdv[i] != null) {
- if (dca.expectedNdv[i] > 4*dca.maxNdv[i]) {
- continue; //not necessary to use
- }
- ndv = dca.expectedNdv[i];
- crit.setMaxNdv(dca.maxNdv[i]);
- } else {
- Collection<ElementSymbol> elems = ElementCollectorVisitor.getElements(indepExpr, true);
- if (cardinality == null) {
- cardinality = NewCalculateCostUtil.computeCostForTree(indNode, metadata);
- }
- ndv = NewCalculateCostUtil.getNDVEstimate(indNode, metadata, cardinality, elems, true);
- }
- crit.setNdv(ndv);
- crit.setValueExpression(indepExpr);
-
- PlanNode selectNode = RelationalPlanner.createSelectNode(crit, false);
-
- selectNode.setProperty(NodeConstants.Info.IS_DEPENDENT_SET, Boolean.TRUE);
- result.add(selectNode);
- }
-
- return result;
- }
-
- public String toString() {
- return "ChooseDependent"; //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseDependent.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseDependent.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseDependent.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseDependent.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,358 @@
+/*
+ * 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.relational.rules;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+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.capabilities.CapabilitiesFinder;
+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;
+import org.teiid.query.optimizer.relational.plantree.PlanNode;
+import org.teiid.query.optimizer.relational.rules.NewCalculateCostUtil.DependentCostAnalysis;
+import org.teiid.query.sql.lang.DependentSetCriteria;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.util.CommandContext;
+
+
+/**
+ * Finds nodes that can be turned into dependent joins
+ */
+public final class RuleChooseDependent implements OptimizerRule {
+
+ private static AtomicInteger ID = new AtomicInteger();
+
+ private static class CandidateJoin {
+ PlanNode joinNode;
+ boolean leftCandidate;
+ boolean rightCandidate;
+ }
+
+ public static final int DEFAULT_INDEPENDENT_CARDINALITY = 10;
+
+ public PlanNode execute(PlanNode plan, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, RuleStack rules, AnalysisRecord analysisRecord, CommandContext context)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ // Find first criteria node in plan with conjuncts
+ List<CandidateJoin> matches = findCandidate(plan, metadata, analysisRecord);
+
+ boolean pushCriteria = false;
+
+ // Handle all cases where both siblings are possible matches
+ for (CandidateJoin entry : matches) {
+ PlanNode joinNode = entry.joinNode;
+
+ PlanNode sourceNode = entry.leftCandidate?joinNode.getFirstChild():joinNode.getLastChild();
+
+ PlanNode siblingNode = entry.leftCandidate?joinNode.getLastChild():joinNode.getFirstChild();
+
+ boolean bothCandidates = entry.leftCandidate&&entry.rightCandidate;
+
+ PlanNode chosenNode = chooseDepWithoutCosting(sourceNode, bothCandidates?siblingNode:null, analysisRecord);
+ if(chosenNode != null) {
+ pushCriteria |= markDependent(chosenNode, joinNode, metadata, null);
+ continue;
+ }
+
+ DependentCostAnalysis dca = NewCalculateCostUtil.computeCostForDepJoin(joinNode, !entry.leftCandidate, metadata, capFinder, context);
+ PlanNode dependentNode = sourceNode;
+
+ if (bothCandidates && dca.expectedCardinality == null) {
+ dca = NewCalculateCostUtil.computeCostForDepJoin(joinNode, true, metadata, capFinder, context);
+ if (dca.expectedCardinality != null) {
+ dependentNode = siblingNode;
+ }
+ }
+
+ if (dca.expectedCardinality != null) {
+ pushCriteria |= markDependent(dependentNode, joinNode, metadata, dca);
+ } else {
+ float sourceCost = NewCalculateCostUtil.computeCostForTree(sourceNode, metadata);
+ float siblingCost = NewCalculateCostUtil.computeCostForTree(siblingNode, metadata);
+
+ if (bothCandidates && sourceCost != NewCalculateCostUtil.UNKNOWN_VALUE && sourceCost < RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY
+ && (sourceCost < siblingCost || siblingCost == NewCalculateCostUtil.UNKNOWN_VALUE)) {
+ pushCriteria |= markDependent(siblingNode, joinNode, metadata, null);
+ } else if (siblingCost != NewCalculateCostUtil.UNKNOWN_VALUE && siblingCost < RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY) {
+ pushCriteria |= markDependent(sourceNode, joinNode, metadata, null);
+ }
+ }
+ }
+
+ if (pushCriteria) {
+ // Insert new rules to push down the SELECT criteria
+ rules.push(RuleConstants.CLEAN_CRITERIA); //it's important to run clean criteria here since it will remove unnecessary dependent sets
+ rules.push(RuleConstants.PUSH_SELECT_CRITERIA);
+ }
+
+ return plan;
+ }
+
+ /**
+ * Walk the tree pre-order, finding all access nodes that are candidates and
+ * adding them to the matches list.
+ * @param metadata Metadata implementation
+ * @param node Root node to search
+ * @param matches Collection to accumulate matches in
+ */
+ List<CandidateJoin> findCandidate(PlanNode root, QueryMetadataInterface metadata, AnalysisRecord analysisRecord) {
+
+ List<CandidateJoin> candidates = new ArrayList<CandidateJoin>();
+
+ for (PlanNode joinNode : NodeEditor.findAllNodes(root, NodeConstants.Types.JOIN, NodeConstants.Types.ACCESS)) {
+ CandidateJoin candidate = null;
+
+ for (Iterator<PlanNode> j = joinNode.getChildren().iterator(); j.hasNext();) {
+ PlanNode child = j.next();
+ child = FrameUtil.findJoinSourceNode(child);
+
+ if(child.hasBooleanProperty(NodeConstants.Info.MAKE_NOT_DEP) || !isValidJoin(joinNode, child, analysisRecord)) {
+ continue;
+ }
+ if (candidate == null) {
+ candidate = new CandidateJoin();
+ candidate.joinNode = joinNode;
+ candidates.add(candidate);
+ }
+ if (j.hasNext()) {
+ candidate.leftCandidate=true;
+ } else {
+ candidate.rightCandidate=true;
+ }
+ }
+ }
+
+ return candidates;
+
+ }
+
+ /**
+ * Check whether a join is valid. Invalid joins are CROSS JOIN, FULL OUTER JOIN,
+ * any join without criteria, any join with no equality criteria, and any outer
+ * join that has the outer side not the same as the dependent.
+ * @param joinNode The join node to check
+ * @param sourceNode The access node being considered
+ * @param analysisRecord TODO
+ * @return True if valid for making dependent
+ */
+ boolean isValidJoin(PlanNode joinNode, PlanNode sourceNode, AnalysisRecord analysisRecord) {
+ JoinType jtype = (JoinType) joinNode.getProperty(NodeConstants.Info.JOIN_TYPE);
+
+ // Check that join is not a CROSS join or FULL OUTER join
+ if(jtype.equals(JoinType.JOIN_CROSS) || jtype.equals(JoinType.JOIN_FULL_OUTER)) {
+ if (analysisRecord.recordDebug()) {
+ analysisRecord.println("Rejecting dependent access node as parent join is CROSS or FULL OUTER: "+ sourceNode.nodeToString()); //$NON-NLS-1$
+ }
+ return false;
+ }
+
+ if (!joinNode.getExportedCorrelatedReferences().isEmpty()) {
+ if (analysisRecord.recordDebug()) {
+ analysisRecord.println("Rejecting dependent access node as parent join has a correlated nested table: "+ sourceNode.nodeToString()); //$NON-NLS-1$
+ }
+ return false;
+ }
+
+ // Check that join criteria exist
+ List jcrit = (List) joinNode.getProperty(NodeConstants.Info.JOIN_CRITERIA);
+ if(jcrit == null || jcrit.size() == 0) {
+ if (analysisRecord.recordDebug()) {
+ analysisRecord.println("Rejecting dependent access node as parent join has no join criteria: "+ sourceNode.nodeToString()); //$NON-NLS-1$
+ }
+ return false;
+ }
+
+ if(joinNode.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS) == null) {
+ if (analysisRecord.recordDebug()) {
+ analysisRecord.println("Rejecting dependent access node as parent join has no equality expressions: "+ sourceNode.nodeToString()); //$NON-NLS-1$
+ }
+ return false;
+ }
+
+ // Check that for a left or right outer join the dependent side must be the inner
+ if(jtype.isOuter() && JoinUtil.getInnerSideJoinNodes(joinNode)[0] != sourceNode) {
+ if (analysisRecord.recordDebug()) {
+ analysisRecord.println("Rejecting dependent access node as it is on outer side of a join: "+ sourceNode.nodeToString()); //$NON-NLS-1$
+ }
+ return false;
+ }
+
+ return true;
+ }
+
+ PlanNode chooseDepWithoutCosting(PlanNode rootNode1, PlanNode rootNode2, AnalysisRecord analysisRecord) {
+ PlanNode sourceNode1 = FrameUtil.findJoinSourceNode(rootNode1);
+ PlanNode sourceNode2 = null;
+
+ if (rootNode2 != null) {
+ sourceNode2 = FrameUtil.findJoinSourceNode(rootNode2);
+ }
+ if(sourceNode1.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS) ) {
+ if (sourceNode2 != null && sourceNode2.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS) ) {
+ //Return null - query planning should fail because both access nodes
+ //have unsatisfied access patterns
+ if (analysisRecord.recordDebug()) {
+ analysisRecord.println("Neither access node can be made dependent because both have unsatisfied access patterns: " + sourceNode1.nodeToString() + "\n" + sourceNode2.toString()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return null;
+ }
+ return rootNode1;
+ } else if (sourceNode2 != null && sourceNode2.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS) ) {
+ //Access node 2 has unsatisfied access pattern,
+ //so try to make node 2 dependent
+ if (analysisRecord.recordDebug()) {
+ analysisRecord.println("Making access node dependent to satisfy access pattern: "+ sourceNode2.nodeToString()); //$NON-NLS-1$
+ }
+ return rootNode2;
+ }
+
+ // Check for hints, which over-rule heuristics
+ if(sourceNode1.hasBooleanProperty(NodeConstants.Info.MAKE_DEP)) {
+ if (analysisRecord.recordDebug()) {
+ analysisRecord.println("Making access node dependent due to hint: "+ sourceNode1.nodeToString()); //$NON-NLS-1$
+ }
+ return rootNode1;
+ } else if(sourceNode2 != null && sourceNode2.hasBooleanProperty(NodeConstants.Info.MAKE_DEP)) {
+ if (analysisRecord.recordDebug()) {
+ 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;
+ }
+
+ /**
+ * Mark the specified access node to be made dependent
+ * @param sourceNode Node to make dependent
+ * @param dca
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ */
+ boolean markDependent(PlanNode sourceNode, PlanNode joinNode, QueryMetadataInterface metadata, DependentCostAnalysis dca) throws QueryMetadataException, TeiidComponentException {
+
+ boolean isLeft = joinNode.getFirstChild() == sourceNode;
+
+ // Get new access join node properties based on join criteria
+ List independentExpressions = (List)(isLeft?joinNode.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS):joinNode.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS));
+ List dependentExpressions = (List)(isLeft?joinNode.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS):joinNode.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS));
+
+ if(independentExpressions == null || independentExpressions.isEmpty()) {
+ return false;
+ }
+
+ String id = "$dsc/id" + ID.getAndIncrement(); //$NON-NLS-1$
+ // Create DependentValueSource and set on the independent side as this will feed the values
+ joinNode.setProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE, id);
+
+ List<PlanNode> crits = getDependentCriteriaNodes(id, independentExpressions, dependentExpressions, isLeft?joinNode.getLastChild():joinNode.getFirstChild(), metadata, dca);
+
+ PlanNode newRoot = sourceNode;
+
+ for (PlanNode crit : crits) {
+ newRoot.addAsParent(crit);
+ newRoot = crit;
+ }
+
+ if (isLeft) {
+ JoinUtil.swapJoinChildren(joinNode);
+ }
+ return true;
+ }
+
+ /**
+ * @param independentExpressions
+ * @param dependentExpressions
+ * @return
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ * @since 4.3
+ */
+ private List<PlanNode> getDependentCriteriaNodes(String id, List independentExpressions,
+ List dependentExpressions, PlanNode indNode, QueryMetadataInterface metadata, DependentCostAnalysis dca) throws QueryMetadataException, TeiidComponentException {
+
+ List<PlanNode> result = new LinkedList<PlanNode>();
+
+ Float cardinality = null;
+
+ for (int i = 0; i < dependentExpressions.size(); i++) {
+ Expression depExpr = (Expression) dependentExpressions.get(i);
+ Expression indepExpr = (Expression) independentExpressions.get(i);
+ DependentSetCriteria crit = new DependentSetCriteria(SymbolMap.getExpression(depExpr), id);
+ float ndv = NewCalculateCostUtil.UNKNOWN_VALUE;
+ if (dca != null && dca.expectedNdv[i] != null) {
+ if (dca.expectedNdv[i] > 4*dca.maxNdv[i]) {
+ continue; //not necessary to use
+ }
+ ndv = dca.expectedNdv[i];
+ crit.setMaxNdv(dca.maxNdv[i]);
+ } else {
+ Collection<ElementSymbol> elems = ElementCollectorVisitor.getElements(indepExpr, true);
+ if (cardinality == null) {
+ cardinality = NewCalculateCostUtil.computeCostForTree(indNode, metadata);
+ }
+ ndv = NewCalculateCostUtil.getNDVEstimate(indNode, metadata, cardinality, elems, true);
+ }
+ crit.setNdv(ndv);
+ crit.setValueExpression(indepExpr);
+
+ PlanNode selectNode = RelationalPlanner.createSelectNode(crit, false);
+
+ selectNode.setProperty(NodeConstants.Info.IS_DEPENDENT_SET, Boolean.TRUE);
+ result.add(selectNode);
+ }
+
+ return result;
+ }
+
+ public String toString() {
+ return "ChooseDependent"; //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleCollapseSource.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleCollapseSource.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleCollapseSource.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,552 +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.optimizer.relational.rules;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedHashSet;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryPlannerException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.SupportConstants;
-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.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.ProcessorPlan;
-import org.teiid.query.processor.relational.RelationalPlan;
-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.CompoundCriteria;
-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.FromClause;
-import org.teiid.query.sql.lang.GroupBy;
-import org.teiid.query.sql.lang.Insert;
-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.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.Select;
-import org.teiid.query.sql.lang.SetQuery;
-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.lang.SetQuery.Operation;
-import org.teiid.query.sql.navigator.DeepPostOrderNavigator;
-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.ScalarSubquery;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
-import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
-import org.teiid.query.util.CommandContext;
-
-
-public final class RuleCollapseSource implements OptimizerRule {
-
- public PlanNode execute(PlanNode plan, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, RuleStack rules, AnalysisRecord analysisRecord, CommandContext context)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- for (PlanNode accessNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.ACCESS)) {
-
- // Get nested non-relational plan if there is one
- ProcessorPlan nonRelationalPlan = FrameUtil.getNestedPlan(accessNode);
- Command command = FrameUtil.getNonQueryCommand(accessNode);
-
- if(nonRelationalPlan != null) {
- accessNode.setProperty(NodeConstants.Info.PROCESSOR_PLAN, nonRelationalPlan);
- } else if (RuleRaiseAccess.getModelIDFromAccess(accessNode, metadata) == null) {
- //with query
- accessNode.setProperty(NodeConstants.Info.IS_COMMON_TABLE, Boolean.TRUE);
- } else if(command == null) {
- PlanNode commandRoot = accessNode;
- GroupSymbol intoGroup = (GroupSymbol)accessNode.getFirstChild().getProperty(NodeConstants.Info.INTO_GROUP);
- if (intoGroup != null) {
- commandRoot = NodeEditor.findNodePreOrder(accessNode, NodeConstants.Types.SOURCE).getFirstChild();
- }
- plan = removeUnnecessaryInlineView(plan, commandRoot);
- QueryCommand queryCommand = createQuery(metadata, capFinder, accessNode, commandRoot);
- addDistinct(metadata, capFinder, accessNode, queryCommand);
- command = queryCommand;
- if (intoGroup != null) {
- Insert insertCommand = new Insert(intoGroup, ResolverUtil.resolveElementsInGroup(intoGroup, metadata), null);
- insertCommand.setQueryExpression(queryCommand);
- command = insertCommand;
- }
- }
- if (command != null) {
- accessNode.setProperty(NodeConstants.Info.ATOMIC_REQUEST, command);
- }
- accessNode.removeAllChildren();
- }
-
- return plan;
- }
-
- /**
- * This functions as "RulePushDistinct", however we do not bother
- * checking to see if a parent dup removal can actually be removed
- * - which can only happen if there are sources/selects/simple projects/limits/order by
- * between the access node and the parent dup removal.
- *
- * @param metadata
- * @param capFinder
- * @param accessNode
- * @param queryCommand
- * @throws QueryMetadataException
- * @throws TeiidComponentException
- */
- private void addDistinct(QueryMetadataInterface metadata,
- CapabilitiesFinder capFinder, PlanNode accessNode,
- QueryCommand queryCommand) throws QueryMetadataException,
- TeiidComponentException {
- if (queryCommand.getLimit() != null) {
- return; //TODO: could create an inline view
- }
- if (queryCommand.getOrderBy() == null) {
- /*
- * we're assuming that a pushed order by implies that the cost of the distinct operation
- * will be marginal - which is not always true.
- *
- * TODO: we should add costing for the benefit of pushing distinct by itself
- * cardinality without = c
- * assume cost ~ c lg c for c' cardinality and a modification for associated bandwidth savings
- * recompute cost of processing plan with c' and see if new cost + c lg c < original cost
- */
- return;
- }
- if (RuleRemoveOptionalJoins.useNonDistinctRows(accessNode.getParent())) {
- return;
- }
- // ensure that all columns are comparable - they might not be if there is an intermediate project
- for (SingleElementSymbol ses : queryCommand.getProjectedSymbols()) {
- if (DataTypeManager.isNonComparable(DataTypeManager.getDataTypeName(ses.getType()))) {
- return;
- }
- }
- /*
- * TODO: if we are under a grouping/union not-all, then we should also fully order the results
- * and update the processing logic (this requires that we can guarantee null ordering) to assume sorted
- */
- 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)) {
- Query query = (Query)queryCommand;
- if (!QueryRewriter.isDistinctWithGroupBy(query)) {
- ((Query)queryCommand).getSelect().setDistinct(true);
- }
- }
- }
-
- private PlanNode removeUnnecessaryInlineView(PlanNode root, PlanNode accessNode) {
- PlanNode child = accessNode.getFirstChild();
-
- if (child.hasBooleanProperty(NodeConstants.Info.INLINE_VIEW)) {
- child.removeProperty(NodeConstants.Info.INLINE_VIEW);
- root = RuleRaiseAccess.performRaise(root, child, accessNode);
- //add the groups from the lower project
- accessNode.getGroups().clear();
- PlanNode sourceNode = FrameUtil.findJoinSourceNode(accessNode.getFirstChild());
- if (sourceNode != null) {
- accessNode.addGroups(sourceNode.getGroups());
- }
- accessNode.setProperty(Info.OUTPUT_COLS, accessNode.getFirstChild().getProperty(Info.OUTPUT_COLS));
- }
-
- return root;
- }
-
- private QueryCommand createQuery(QueryMetadataInterface metadata, CapabilitiesFinder capFinder, PlanNode accessRoot, PlanNode node) throws QueryMetadataException, TeiidComponentException, QueryPlannerException {
- PlanNode setOpNode = NodeEditor.findNodePreOrder(node, NodeConstants.Types.SET_OP, NodeConstants.Types.SOURCE);
- if (setOpNode != null) {
- Operation setOp = (Operation)setOpNode.getProperty(NodeConstants.Info.SET_OPERATION);
- SetQuery unionCommand = new SetQuery(setOp);
- boolean unionAll = ((Boolean)setOpNode.getProperty(NodeConstants.Info.USE_ALL)).booleanValue();
- unionCommand.setAll(unionAll);
- PlanNode sort = NodeEditor.findNodePreOrder(node, NodeConstants.Types.SORT, NodeConstants.Types.SET_OP);
- if (sort != null) {
- processOrderBy(sort, unionCommand);
- }
- PlanNode limit = NodeEditor.findNodePreOrder(node, NodeConstants.Types.TUPLE_LIMIT, NodeConstants.Types.SET_OP);
- if (limit != null) {
- processLimit(limit, unionCommand, metadata);
- }
- int count = 0;
- for (PlanNode child : setOpNode.getChildren()) {
- QueryCommand command = createQuery(metadata, capFinder, accessRoot, child);
- if (count == 0) {
- unionCommand.setLeftQuery(command);
- } else if (count == 1) {
- unionCommand.setRightQuery(command);
- } else {
- unionCommand = new SetQuery(setOp, unionAll, unionCommand, command);
- }
- count++;
- }
- return unionCommand;
- }
- Query query = new Query();
- Select select = new Select();
- List<SingleElementSymbol> columns = (List<SingleElementSymbol>)node.getProperty(NodeConstants.Info.OUTPUT_COLS);
- prepareSubqueries(ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(columns));
- select.addSymbols(columns);
- query.setSelect(select);
- query.setFrom(new From());
- buildQuery(accessRoot, node, query, metadata, capFinder);
- if (query.getCriteria() instanceof CompoundCriteria) {
- query.setCriteria(QueryRewriter.optimizeCriteria((CompoundCriteria)query.getCriteria(), metadata));
- }
- if (!CapabilitiesUtil.useAnsiJoin(RuleRaiseAccess.getModelIDFromAccess(accessRoot, metadata), metadata, capFinder)) {
- simplifyFromClause(query);
- }
- if (columns.isEmpty()) {
- if (CapabilitiesUtil.supports(Capability.QUERY_SELECT_EXPRESSION, RuleRaiseAccess.getModelIDFromAccess(accessRoot, metadata), metadata, capFinder)) {
- select.addSymbol(new ExpressionSymbol("dummy", new Constant(1))); //$NON-NLS-1$
- } else {
- //TODO: need to ensure the type is consistent
- //- should be rare as the source would typically support select expression if it supports union
- select.addSymbol(selectOutputElement(query.getFrom().getGroups(), metadata));
- }
- }
- return query;
- }
-
- /**
- * Find a selectable element in the specified groups. This is a helper for fixing
- * the "no elements" case.
- *
- * @param groups Bunch of groups
- * @param metadata Metadata implementation
- * @throws QueryPlannerException
- */
- private ElementSymbol selectOutputElement(Collection<GroupSymbol> groups, QueryMetadataInterface metadata)
- throws QueryMetadataException, TeiidComponentException {
-
- // Find a group with selectable elements and pick the first one
- for (GroupSymbol group : groups) {
- List<ElementSymbol> elements = (List<ElementSymbol>)ResolverUtil.resolveElementsInGroup(group, metadata);
-
- for (ElementSymbol element : elements) {
- if(metadata.elementSupports(element.getMetadataID(), SupportConstants.Element.SELECT)) {
- element = (ElementSymbol)element.clone();
- element.setGroupSymbol(group);
- return element;
- }
- }
- }
-
- return null;
- }
-
- void buildQuery(PlanNode accessRoot, PlanNode node, Query query, QueryMetadataInterface metadata, CapabilitiesFinder capFinder) throws QueryMetadataException, TeiidComponentException, QueryPlannerException {
-
- //visit source and join nodes as they appear
- switch(node.getType()) {
- case NodeConstants.Types.JOIN:
- {
- prepareSubqueries(node.getSubqueryContainers());
- JoinType joinType = (JoinType) node.getProperty(NodeConstants.Info.JOIN_TYPE);
- List<Criteria> crits = (List<Criteria>) node.getProperty(NodeConstants.Info.JOIN_CRITERIA);
-
- if (crits == null || crits.isEmpty()) {
- crits = new ArrayList<Criteria>();
- } else {
- RuleChooseJoinStrategy.filterOptionalCriteria(crits);
- if (crits.isEmpty() && joinType == JoinType.JOIN_INNER) {
- joinType = JoinType.JOIN_CROSS;
- }
- }
-
- PlanNode left = node.getFirstChild();
- PlanNode right = node.getLastChild();
-
- /* special handling is needed to determine criteria placement.
- *
- * if the join is a left outer join, criteria from the right side will be added to the on clause
- */
- Criteria savedCriteria = null;
- buildQuery(accessRoot, left, query, metadata, capFinder);
- if (joinType == JoinType.JOIN_LEFT_OUTER) {
- savedCriteria = query.getCriteria();
- query.setCriteria(null);
- }
- buildQuery(accessRoot, right, query, metadata, capFinder);
- if (joinType == JoinType.JOIN_LEFT_OUTER) {
- moveWhereClauseIntoOnClause(query, crits);
- query.setCriteria(savedCriteria);
- }
-
- // Get last two clauses added to the FROM and combine them into a JoinPredicate
- From from = query.getFrom();
- List clauses = from.getClauses();
- int lastClause = clauses.size()-1;
- FromClause clause1 = (FromClause) clauses.get(lastClause-1);
- FromClause clause2 = (FromClause) clauses.get(lastClause);
-
- //correct the criteria or the join type if necessary
- if (joinType != JoinType.JOIN_CROSS && crits.isEmpty()) {
- crits.add(QueryRewriter.TRUE_CRITERIA);
- } else if (joinType == JoinType.JOIN_CROSS && !crits.isEmpty()) {
- joinType = JoinType.JOIN_INNER;
- }
-
- JoinPredicate jp = new JoinPredicate(clause1, clause2, joinType, crits);
-
- // Replace last two clauses with new predicate
- clauses.remove(lastClause);
- clauses.set(lastClause-1, jp);
- return;
- }
- case NodeConstants.Types.SOURCE:
- {
- if (Boolean.TRUE.equals(node.getProperty(NodeConstants.Info.INLINE_VIEW))) {
- PlanNode child = node.getFirstChild();
- QueryCommand newQuery = createQuery(metadata, capFinder, accessRoot, child);
-
- //ensure that the group is consistent
- GroupSymbol symbol = node.getGroups().iterator().next();
- SubqueryFromClause sfc = new SubqueryFromClause(symbol, newQuery);
- query.getFrom().addClause(sfc);
- return;
- }
- query.getFrom().addGroup(node.getGroups().iterator().next());
- break;
- }
- }
-
- for (PlanNode childNode : node.getChildren()) {
- buildQuery(accessRoot, childNode, query, metadata, capFinder);
- }
-
- switch(node.getType()) {
- case NodeConstants.Types.SELECT:
- {
- Criteria crit = (Criteria) node.getProperty(NodeConstants.Info.SELECT_CRITERIA);
- prepareSubqueries(node.getSubqueryContainers());
- if(!node.hasBooleanProperty(NodeConstants.Info.IS_HAVING)) {
- query.setCriteria( CompoundCriteria.combineCriteria(query.getCriteria(), crit) );
- } else {
- query.setHaving( CompoundCriteria.combineCriteria(query.getHaving(), crit) );
- }
- break;
- }
- case NodeConstants.Types.SORT:
- {
- processOrderBy(node, query);
- break;
- }
- case NodeConstants.Types.DUP_REMOVE:
- {
- query.getSelect().setDistinct(true);
- break;
- }
- case NodeConstants.Types.GROUP:
- {
- List groups = (List) node.getProperty(NodeConstants.Info.GROUP_COLS);
- if(groups != null && !groups.isEmpty()) {
- query.setGroupBy(new GroupBy(groups));
- }
- break;
- }
- case NodeConstants.Types.TUPLE_LIMIT:
- {
- processLimit(node, query, metadata);
- break;
- }
- }
- }
-
- private void prepareSubqueries(List<SubqueryContainer> containers) {
- for (SubqueryContainer container : containers) {
- prepareSubquery(container);
- }
- }
-
- public static void prepareSubquery(SubqueryContainer container) {
- RelationalPlan subqueryPlan = (RelationalPlan)container.getCommand().getProcessorPlan();
- QueryCommand command = CriteriaCapabilityValidatorVisitor.getQueryCommand(subqueryPlan);
- if (command == null) {
- return;
- }
- final SymbolMap map = container.getCommand().getCorrelatedReferences();
- if (map != null) {
- ExpressionMappingVisitor visitor = new RuleMergeCriteria.ReferenceReplacementVisitor(map);
- DeepPostOrderNavigator.doVisit(command, visitor);
- }
- command.setProcessorPlan(container.getCommand().getProcessorPlan());
- boolean removeLimit = false;
- if (container instanceof ExistsCriteria) {
- removeLimit = !((ExistsCriteria)container).shouldEvaluate();
- } else if (container instanceof ScalarSubquery) {
- removeLimit = !((ScalarSubquery)container).shouldEvaluate();
- }
- if (removeLimit && command.getLimit() != null && command.getLimit().isImplicit()) {
- command.setLimit(null);
- }
- container.setCommand(command);
- }
-
- private void processLimit(PlanNode node,
- QueryCommand query, QueryMetadataInterface metadata) {
-
- Expression limit = (Expression)node.getProperty(NodeConstants.Info.MAX_TUPLE_LIMIT);
- Expression offset = (Expression)node.getProperty(NodeConstants.Info.OFFSET_TUPLE_COUNT);
-
- PlanNode limitNode = NodeFactory.getNewNode(NodeConstants.Types.TUPLE_LIMIT);
- Expression childLimit = null;
- Expression childOffset = null;
- if (query.getLimit() != null) {
- childLimit = query.getLimit().getRowLimit();
- childOffset = query.getLimit().getOffset();
- }
- RulePushLimit.combineLimits(limitNode, metadata, limit, offset, childLimit, childOffset);
- Limit lim = new Limit((Expression)limitNode.getProperty(NodeConstants.Info.OFFSET_TUPLE_COUNT), (Expression)limitNode.getProperty(NodeConstants.Info.MAX_TUPLE_LIMIT));
- lim.setImplicit(node.hasBooleanProperty(Info.IS_IMPLICIT_LIMIT));
- query.setLimit(lim);
- }
-
- /**
- * Will combine the where criteria with the on criteria.
- *
- * A full rewrite call is not necessary here, but it will attempt to flatten the criteria.
- *
- * @param query
- * @param joinCrits
- */
- private void moveWhereClauseIntoOnClause(Query query,
- List joinCrits) {
- if (query.getCriteria() == null) {
- return;
- }
- LinkedHashSet combinedCrits = new LinkedHashSet();
- combinedCrits.addAll(joinCrits);
- combinedCrits.addAll(Criteria.separateCriteriaByAnd(query.getCriteria()));
- joinCrits.clear();
- joinCrits.addAll(combinedCrits);
- query.setCriteria(null);
- }
-
- private void processOrderBy(PlanNode node, QueryCommand query) {
- OrderBy orderBy = (OrderBy)node.getProperty(NodeConstants.Info.SORT_ORDER);
- query.setOrderBy(orderBy);
- if (query instanceof Query) {
- List<SingleElementSymbol> cols = query.getProjectedSymbols();
- for (OrderByItem item : orderBy.getOrderByItems()) {
- item.setExpressionPosition(cols.indexOf(item.getSymbol()));
- }
- QueryRewriter.rewriteOrderBy(query, orderBy, query.getProjectedSymbols(), new LinkedList<OrderByItem>());
- }
- }
-
- /**
- * Take the query, built straight from the subtree, and rebuild as a simple query
- * if possible.
- * @param query Query built from collapsing the source nodes
- * @return Same query with simplified from clause if possible
- */
- private void simplifyFromClause(Query query) {
- From from = query.getFrom();
- List clauses = from.getClauses();
- FromClause rootClause = (FromClause) 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());
- shredJoinTree(rootClause, query);
- } // else leave as is
- }
-
- /**
- * @param rootClause
- * @param query
- */
- private void shredJoinTree(FromClause clause, Query query) {
- if(clause instanceof UnaryFromClause || clause instanceof SubqueryFromClause) {
- query.getFrom().addClause(clause);
- } else {
- JoinPredicate jp = (JoinPredicate) clause;
-
- List<Criteria> crits = jp.getJoinCriteria();
- if(crits != null && crits.size() > 0) {
- Criteria joinCrit = null;
- if (crits.size() > 1) {
- joinCrit = new CompoundCriteria(crits);
- } else {
- joinCrit = crits.get(0);
- }
- query.setCriteria(CompoundCriteria.combineCriteria(joinCrit, query.getCriteria()));
- }
-
- // Recurse through tree
- shredJoinTree(jp.getLeftClause(), query);
- shredJoinTree(jp.getRightClause(), query);
- }
- }
-
- /**
- * @param clause Clause to check recursively
- * @return True if tree has outer joins, false otherwise
- */
- static boolean hasOuterJoins(FromClause clause) {
- if(clause instanceof UnaryFromClause || clause instanceof SubqueryFromClause) {
- return false;
- }
- JoinPredicate jp = (JoinPredicate) clause;
- if(jp.getJoinType().isOuter()) {
- return true;
- }
- // Walk children
- boolean childHasOuter = hasOuterJoins(jp.getLeftClause());
- if(childHasOuter) {
- return true;
- }
- return hasOuterJoins(jp.getRightClause());
- }
-
- public String toString() {
- return "CollapseSource"; //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleCollapseSource.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleCollapseSource.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleCollapseSource.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleCollapseSource.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,557 @@
+/*
+ * 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.relational.rules;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryPlannerException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.SupportConstants;
+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.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.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;
+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.ExistsCriteria;
+import org.teiid.query.sql.lang.From;
+import org.teiid.query.sql.lang.FromClause;
+import org.teiid.query.sql.lang.GroupBy;
+import org.teiid.query.sql.lang.Insert;
+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.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.Select;
+import org.teiid.query.sql.lang.SetQuery;
+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.lang.SetQuery.Operation;
+import org.teiid.query.sql.navigator.DeepPostOrderNavigator;
+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.ScalarSubquery;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
+import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
+import org.teiid.query.util.CommandContext;
+
+
+public final class RuleCollapseSource implements OptimizerRule {
+
+ public PlanNode execute(PlanNode plan, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, RuleStack rules, AnalysisRecord analysisRecord, CommandContext context)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ for (PlanNode accessNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.ACCESS)) {
+
+ // Get nested non-relational plan if there is one
+ ProcessorPlan nonRelationalPlan = FrameUtil.getNestedPlan(accessNode);
+ Command command = FrameUtil.getNonQueryCommand(accessNode);
+
+ if(nonRelationalPlan != null) {
+ accessNode.setProperty(NodeConstants.Info.PROCESSOR_PLAN, nonRelationalPlan);
+ } else if (RuleRaiseAccess.getModelIDFromAccess(accessNode, metadata) == null) {
+ //with query
+ accessNode.setProperty(NodeConstants.Info.IS_COMMON_TABLE, Boolean.TRUE);
+ } else if(command == null) {
+ PlanNode commandRoot = accessNode;
+ GroupSymbol intoGroup = (GroupSymbol)accessNode.getFirstChild().getProperty(NodeConstants.Info.INTO_GROUP);
+ if (intoGroup != null) {
+ commandRoot = NodeEditor.findNodePreOrder(accessNode, NodeConstants.Types.SOURCE).getFirstChild();
+ }
+ plan = removeUnnecessaryInlineView(plan, commandRoot);
+ QueryCommand queryCommand = createQuery(metadata, capFinder, accessNode, commandRoot);
+ addDistinct(metadata, capFinder, accessNode, queryCommand);
+ command = queryCommand;
+ if (intoGroup != null) {
+ Insert insertCommand = new Insert(intoGroup, ResolverUtil.resolveElementsInGroup(intoGroup, metadata), null);
+ insertCommand.setQueryExpression(queryCommand);
+ command = insertCommand;
+ }
+ }
+ if (command != null) {
+ accessNode.setProperty(NodeConstants.Info.ATOMIC_REQUEST, command);
+ }
+ accessNode.removeAllChildren();
+ }
+
+ return plan;
+ }
+
+ /**
+ * This functions as "RulePushDistinct", however we do not bother
+ * checking to see if a parent dup removal can actually be removed
+ * - which can only happen if there are sources/selects/simple projects/limits/order by
+ * between the access node and the parent dup removal.
+ *
+ * @param metadata
+ * @param capFinder
+ * @param accessNode
+ * @param queryCommand
+ * @throws QueryMetadataException
+ * @throws TeiidComponentException
+ */
+ private void addDistinct(QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder, PlanNode accessNode,
+ QueryCommand queryCommand) throws QueryMetadataException,
+ TeiidComponentException {
+ if (queryCommand.getLimit() != null) {
+ return; //TODO: could create an inline view
+ }
+ if (queryCommand.getOrderBy() == null) {
+ /*
+ * we're assuming that a pushed order by implies that the cost of the distinct operation
+ * will be marginal - which is not always true.
+ *
+ * TODO: we should add costing for the benefit of pushing distinct by itself
+ * cardinality without = c
+ * assume cost ~ c lg c for c' cardinality and a modification for associated bandwidth savings
+ * recompute cost of processing plan with c' and see if new cost + c lg c < original cost
+ */
+ return;
+ }
+ if (RuleRemoveOptionalJoins.useNonDistinctRows(accessNode.getParent())) {
+ return;
+ }
+ // ensure that all columns are comparable - they might not be if there is an intermediate project
+ for (SingleElementSymbol ses : queryCommand.getProjectedSymbols()) {
+ if (DataTypeManager.isNonComparable(DataTypeManager.getDataTypeName(ses.getType()))) {
+ return;
+ }
+ }
+ /*
+ * TODO: if we are under a grouping/union not-all, then we should also fully order the results
+ * and update the processing logic (this requires that we can guarantee null ordering) to assume sorted
+ */
+ if (queryCommand instanceof SetQuery) {
+ ((SetQuery)queryCommand).setAll(false);
+ } else if (CapabilitiesUtil.supports(Capability.QUERY_SELECT_DISTINCT, RuleRaiseAccess.getModelIDFromAccess(accessNode, metadata), metadata, capFinder)) {
+ Query query = (Query)queryCommand;
+ 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);
+ }
+ }
+ }
+
+ private PlanNode removeUnnecessaryInlineView(PlanNode root, PlanNode accessNode) {
+ PlanNode child = accessNode.getFirstChild();
+
+ if (child.hasBooleanProperty(NodeConstants.Info.INLINE_VIEW)) {
+ child.removeProperty(NodeConstants.Info.INLINE_VIEW);
+ root = RuleRaiseAccess.performRaise(root, child, accessNode);
+ //add the groups from the lower project
+ accessNode.getGroups().clear();
+ PlanNode sourceNode = FrameUtil.findJoinSourceNode(accessNode.getFirstChild());
+ if (sourceNode != null) {
+ accessNode.addGroups(sourceNode.getGroups());
+ }
+ accessNode.setProperty(Info.OUTPUT_COLS, accessNode.getFirstChild().getProperty(Info.OUTPUT_COLS));
+ }
+
+ return root;
+ }
+
+ private QueryCommand createQuery(QueryMetadataInterface metadata, CapabilitiesFinder capFinder, PlanNode accessRoot, PlanNode node) throws QueryMetadataException, TeiidComponentException, QueryPlannerException {
+ PlanNode setOpNode = NodeEditor.findNodePreOrder(node, NodeConstants.Types.SET_OP, NodeConstants.Types.SOURCE);
+ if (setOpNode != null) {
+ Operation setOp = (Operation)setOpNode.getProperty(NodeConstants.Info.SET_OPERATION);
+ SetQuery unionCommand = new SetQuery(setOp);
+ boolean unionAll = ((Boolean)setOpNode.getProperty(NodeConstants.Info.USE_ALL)).booleanValue();
+ unionCommand.setAll(unionAll);
+ PlanNode sort = NodeEditor.findNodePreOrder(node, NodeConstants.Types.SORT, NodeConstants.Types.SET_OP);
+ if (sort != null) {
+ processOrderBy(sort, unionCommand);
+ }
+ PlanNode limit = NodeEditor.findNodePreOrder(node, NodeConstants.Types.TUPLE_LIMIT, NodeConstants.Types.SET_OP);
+ if (limit != null) {
+ processLimit(limit, unionCommand, metadata);
+ }
+ int count = 0;
+ for (PlanNode child : setOpNode.getChildren()) {
+ QueryCommand command = createQuery(metadata, capFinder, accessRoot, child);
+ if (count == 0) {
+ unionCommand.setLeftQuery(command);
+ } else if (count == 1) {
+ unionCommand.setRightQuery(command);
+ } else {
+ unionCommand = new SetQuery(setOp, unionAll, unionCommand, command);
+ }
+ count++;
+ }
+ return unionCommand;
+ }
+ Query query = new Query();
+ Select select = new Select();
+ List<SingleElementSymbol> columns = (List<SingleElementSymbol>)node.getProperty(NodeConstants.Info.OUTPUT_COLS);
+ prepareSubqueries(ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(columns));
+ select.addSymbols(columns);
+ query.setSelect(select);
+ query.setFrom(new From());
+ buildQuery(accessRoot, node, query, metadata, capFinder);
+ if (query.getCriteria() instanceof CompoundCriteria) {
+ query.setCriteria(QueryRewriter.optimizeCriteria((CompoundCriteria)query.getCriteria(), metadata));
+ }
+ if (!CapabilitiesUtil.useAnsiJoin(RuleRaiseAccess.getModelIDFromAccess(accessRoot, metadata), metadata, capFinder)) {
+ simplifyFromClause(query);
+ }
+ if (columns.isEmpty()) {
+ if (CapabilitiesUtil.supports(Capability.QUERY_SELECT_EXPRESSION, RuleRaiseAccess.getModelIDFromAccess(accessRoot, metadata), metadata, capFinder)) {
+ select.addSymbol(new ExpressionSymbol("dummy", new Constant(1))); //$NON-NLS-1$
+ } else {
+ //TODO: need to ensure the type is consistent
+ //- should be rare as the source would typically support select expression if it supports union
+ select.addSymbol(selectOutputElement(query.getFrom().getGroups(), metadata));
+ }
+ }
+ return query;
+ }
+
+ /**
+ * Find a selectable element in the specified groups. This is a helper for fixing
+ * the "no elements" case.
+ *
+ * @param groups Bunch of groups
+ * @param metadata Metadata implementation
+ * @throws QueryPlannerException
+ */
+ private ElementSymbol selectOutputElement(Collection<GroupSymbol> groups, QueryMetadataInterface metadata)
+ throws QueryMetadataException, TeiidComponentException {
+
+ // Find a group with selectable elements and pick the first one
+ for (GroupSymbol group : groups) {
+ List<ElementSymbol> elements = (List<ElementSymbol>)ResolverUtil.resolveElementsInGroup(group, metadata);
+
+ for (ElementSymbol element : elements) {
+ if(metadata.elementSupports(element.getMetadataID(), SupportConstants.Element.SELECT)) {
+ element = (ElementSymbol)element.clone();
+ element.setGroupSymbol(group);
+ return element;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ void buildQuery(PlanNode accessRoot, PlanNode node, Query query, QueryMetadataInterface metadata, CapabilitiesFinder capFinder) throws QueryMetadataException, TeiidComponentException, QueryPlannerException {
+
+ //visit source and join nodes as they appear
+ switch(node.getType()) {
+ case NodeConstants.Types.JOIN:
+ {
+ prepareSubqueries(node.getSubqueryContainers());
+ JoinType joinType = (JoinType) node.getProperty(NodeConstants.Info.JOIN_TYPE);
+ List<Criteria> crits = (List<Criteria>) node.getProperty(NodeConstants.Info.JOIN_CRITERIA);
+
+ if (crits == null || crits.isEmpty()) {
+ crits = new ArrayList<Criteria>();
+ } else {
+ RuleChooseJoinStrategy.filterOptionalCriteria(crits);
+ if (crits.isEmpty() && joinType == JoinType.JOIN_INNER) {
+ joinType = JoinType.JOIN_CROSS;
+ }
+ }
+
+ PlanNode left = node.getFirstChild();
+ PlanNode right = node.getLastChild();
+
+ /* special handling is needed to determine criteria placement.
+ *
+ * if the join is a left outer join, criteria from the right side will be added to the on clause
+ */
+ Criteria savedCriteria = null;
+ buildQuery(accessRoot, left, query, metadata, capFinder);
+ if (joinType == JoinType.JOIN_LEFT_OUTER) {
+ savedCriteria = query.getCriteria();
+ query.setCriteria(null);
+ }
+ buildQuery(accessRoot, right, query, metadata, capFinder);
+ if (joinType == JoinType.JOIN_LEFT_OUTER) {
+ moveWhereClauseIntoOnClause(query, crits);
+ query.setCriteria(savedCriteria);
+ }
+
+ // Get last two clauses added to the FROM and combine them into a JoinPredicate
+ From from = query.getFrom();
+ List clauses = from.getClauses();
+ int lastClause = clauses.size()-1;
+ FromClause clause1 = (FromClause) clauses.get(lastClause-1);
+ FromClause clause2 = (FromClause) clauses.get(lastClause);
+
+ //correct the criteria or the join type if necessary
+ if (joinType != JoinType.JOIN_CROSS && crits.isEmpty()) {
+ crits.add(QueryRewriter.TRUE_CRITERIA);
+ } else if (joinType == JoinType.JOIN_CROSS && !crits.isEmpty()) {
+ joinType = JoinType.JOIN_INNER;
+ }
+
+ JoinPredicate jp = new JoinPredicate(clause1, clause2, joinType, crits);
+
+ // Replace last two clauses with new predicate
+ clauses.remove(lastClause);
+ clauses.set(lastClause-1, jp);
+ return;
+ }
+ case NodeConstants.Types.SOURCE:
+ {
+ if (Boolean.TRUE.equals(node.getProperty(NodeConstants.Info.INLINE_VIEW))) {
+ PlanNode child = node.getFirstChild();
+ QueryCommand newQuery = createQuery(metadata, capFinder, accessRoot, child);
+
+ //ensure that the group is consistent
+ GroupSymbol symbol = node.getGroups().iterator().next();
+ SubqueryFromClause sfc = new SubqueryFromClause(symbol, newQuery);
+ query.getFrom().addClause(sfc);
+ return;
+ }
+ query.getFrom().addGroup(node.getGroups().iterator().next());
+ break;
+ }
+ }
+
+ for (PlanNode childNode : node.getChildren()) {
+ buildQuery(accessRoot, childNode, query, metadata, capFinder);
+ }
+
+ switch(node.getType()) {
+ case NodeConstants.Types.SELECT:
+ {
+ Criteria crit = (Criteria) node.getProperty(NodeConstants.Info.SELECT_CRITERIA);
+ prepareSubqueries(node.getSubqueryContainers());
+ if(!node.hasBooleanProperty(NodeConstants.Info.IS_HAVING)) {
+ query.setCriteria( CompoundCriteria.combineCriteria(query.getCriteria(), crit) );
+ } else {
+ query.setHaving( CompoundCriteria.combineCriteria(query.getHaving(), crit) );
+ }
+ break;
+ }
+ case NodeConstants.Types.SORT:
+ {
+ processOrderBy(node, query);
+ break;
+ }
+ case NodeConstants.Types.DUP_REMOVE:
+ {
+ query.getSelect().setDistinct(true);
+ break;
+ }
+ case NodeConstants.Types.GROUP:
+ {
+ List groups = (List) node.getProperty(NodeConstants.Info.GROUP_COLS);
+ if(groups != null && !groups.isEmpty()) {
+ query.setGroupBy(new GroupBy(groups));
+ }
+ break;
+ }
+ case NodeConstants.Types.TUPLE_LIMIT:
+ {
+ processLimit(node, query, metadata);
+ break;
+ }
+ }
+ }
+
+ private void prepareSubqueries(List<SubqueryContainer> containers) {
+ for (SubqueryContainer container : containers) {
+ prepareSubquery(container);
+ }
+ }
+
+ public static void prepareSubquery(SubqueryContainer container) {
+ RelationalPlan subqueryPlan = (RelationalPlan)container.getCommand().getProcessorPlan();
+ AccessNode aNode = CriteriaCapabilityValidatorVisitor.getAccessNode(subqueryPlan);
+ QueryCommand command = CriteriaCapabilityValidatorVisitor.getQueryCommand(aNode);
+ if (command == null) {
+ return;
+ }
+ final SymbolMap map = container.getCommand().getCorrelatedReferences();
+ if (map != null) {
+ ExpressionMappingVisitor visitor = new RuleMergeCriteria.ReferenceReplacementVisitor(map);
+ DeepPostOrderNavigator.doVisit(command, visitor);
+ }
+ command.setProcessorPlan(container.getCommand().getProcessorPlan());
+ boolean removeLimit = false;
+ if (container instanceof ExistsCriteria) {
+ removeLimit = !((ExistsCriteria)container).shouldEvaluate();
+ } else if (container instanceof ScalarSubquery) {
+ removeLimit = !((ScalarSubquery)container).shouldEvaluate();
+ }
+ if (removeLimit && command.getLimit() != null && command.getLimit().isImplicit()) {
+ command.setLimit(null);
+ }
+ container.setCommand(command);
+ }
+
+ private void processLimit(PlanNode node,
+ QueryCommand query, QueryMetadataInterface metadata) {
+
+ Expression limit = (Expression)node.getProperty(NodeConstants.Info.MAX_TUPLE_LIMIT);
+ Expression offset = (Expression)node.getProperty(NodeConstants.Info.OFFSET_TUPLE_COUNT);
+
+ PlanNode limitNode = NodeFactory.getNewNode(NodeConstants.Types.TUPLE_LIMIT);
+ Expression childLimit = null;
+ Expression childOffset = null;
+ if (query.getLimit() != null) {
+ childLimit = query.getLimit().getRowLimit();
+ childOffset = query.getLimit().getOffset();
+ }
+ RulePushLimit.combineLimits(limitNode, metadata, limit, offset, childLimit, childOffset);
+ Limit lim = new Limit((Expression)limitNode.getProperty(NodeConstants.Info.OFFSET_TUPLE_COUNT), (Expression)limitNode.getProperty(NodeConstants.Info.MAX_TUPLE_LIMIT));
+ lim.setImplicit(node.hasBooleanProperty(Info.IS_IMPLICIT_LIMIT));
+ query.setLimit(lim);
+ }
+
+ /**
+ * Will combine the where criteria with the on criteria.
+ *
+ * A full rewrite call is not necessary here, but it will attempt to flatten the criteria.
+ *
+ * @param query
+ * @param joinCrits
+ */
+ private void moveWhereClauseIntoOnClause(Query query,
+ List joinCrits) {
+ if (query.getCriteria() == null) {
+ return;
+ }
+ LinkedHashSet combinedCrits = new LinkedHashSet();
+ combinedCrits.addAll(joinCrits);
+ combinedCrits.addAll(Criteria.separateCriteriaByAnd(query.getCriteria()));
+ joinCrits.clear();
+ joinCrits.addAll(combinedCrits);
+ query.setCriteria(null);
+ }
+
+ private void processOrderBy(PlanNode node, QueryCommand query) {
+ OrderBy orderBy = (OrderBy)node.getProperty(NodeConstants.Info.SORT_ORDER);
+ query.setOrderBy(orderBy);
+ if (query instanceof Query) {
+ List<SingleElementSymbol> cols = query.getProjectedSymbols();
+ for (OrderByItem item : orderBy.getOrderByItems()) {
+ item.setExpressionPosition(cols.indexOf(item.getSymbol()));
+ }
+ QueryRewriter.rewriteOrderBy(query, orderBy, query.getProjectedSymbols(), new LinkedList<OrderByItem>());
+ }
+ }
+
+ /**
+ * Take the query, built straight from the subtree, and rebuild as a simple query
+ * if possible.
+ * @param query Query built from collapsing the source nodes
+ * @return Same query with simplified from clause if possible
+ */
+ private void simplifyFromClause(Query query) {
+ From from = query.getFrom();
+ List clauses = from.getClauses();
+ FromClause rootClause = (FromClause) 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());
+ shredJoinTree(rootClause, query);
+ } // else leave as is
+ }
+
+ /**
+ * @param rootClause
+ * @param query
+ */
+ private void shredJoinTree(FromClause clause, Query query) {
+ if(clause instanceof UnaryFromClause || clause instanceof SubqueryFromClause) {
+ query.getFrom().addClause(clause);
+ } else {
+ JoinPredicate jp = (JoinPredicate) clause;
+
+ List<Criteria> crits = jp.getJoinCriteria();
+ if(crits != null && crits.size() > 0) {
+ Criteria joinCrit = null;
+ if (crits.size() > 1) {
+ joinCrit = new CompoundCriteria(crits);
+ } else {
+ joinCrit = crits.get(0);
+ }
+ query.setCriteria(CompoundCriteria.combineCriteria(joinCrit, query.getCriteria()));
+ }
+
+ // Recurse through tree
+ shredJoinTree(jp.getLeftClause(), query);
+ shredJoinTree(jp.getRightClause(), query);
+ }
+ }
+
+ /**
+ * @param clause Clause to check recursively
+ * @return True if tree has outer joins, false otherwise
+ */
+ static boolean hasOuterJoins(FromClause clause) {
+ if(clause instanceof UnaryFromClause || clause instanceof SubqueryFromClause) {
+ return false;
+ }
+ JoinPredicate jp = (JoinPredicate) clause;
+ if(jp.getJoinType().isOuter()) {
+ return true;
+ }
+ // Walk children
+ boolean childHasOuter = hasOuterJoins(jp.getLeftClause());
+ if(childHasOuter) {
+ return true;
+ }
+ return hasOuterJoins(jp.getRightClause());
+ }
+
+ public String toString() {
+ return "CollapseSource"; //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleImplementJoinStrategy.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleImplementJoinStrategy.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleImplementJoinStrategy.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,259 +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.optimizer.relational.rules;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedHashSet;
-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.query.analysis.AnalysisRecord;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.relational.OptimizerRule;
-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.processor.relational.JoinNode.JoinStrategyType;
-import org.teiid.query.processor.relational.MergeJoinStrategy.SortOption;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.OrderBy;
-import org.teiid.query.sql.symbol.ElementSymbol;
-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.GroupsUsedByElementsVisitor;
-import org.teiid.query.util.CommandContext;
-
-
-/**
- * Inserts sort nodes for specific join strategies.
- */
-public class RuleImplementJoinStrategy implements OptimizerRule {
-
- /**
- * @see org.teiid.query.optimizer.relational.OptimizerRule#execute(org.teiid.query.optimizer.relational.plantree.PlanNode, org.teiid.query.metadata.QueryMetadataInterface, org.teiid.query.optimizer.capabilities.CapabilitiesFinder, org.teiid.query.optimizer.relational.RuleStack, org.teiid.query.analysis.AnalysisRecord, org.teiid.query.util.CommandContext)
- */
- public PlanNode execute(PlanNode plan,
- QueryMetadataInterface metadata,
- CapabilitiesFinder capabilitiesFinder,
- RuleStack rules,
- AnalysisRecord analysisRecord,
- CommandContext context) throws QueryPlannerException,
- QueryMetadataException,
- TeiidComponentException {
-
- for (PlanNode sourceNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE, NodeConstants.Types.ACCESS)) {
- SymbolMap references = (SymbolMap)sourceNode.getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
- if (references != null) {
- Set<GroupSymbol> groups = GroupsUsedByElementsVisitor.getGroups(references.getValues());
- PlanNode joinNode = NodeEditor.findParent(sourceNode, NodeConstants.Types.JOIN, NodeConstants.Types.SOURCE);
- while (joinNode != null) {
- joinNode.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.NESTED_TABLE);
- if (joinNode.getProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE) != null) {
- //sanity check
- throw new AssertionError("Cannot use a depenedent join when the join involves a correlated nested table."); //$NON-NLS-1$
- }
- if (joinNode.getGroups().containsAll(groups)) {
- break;
- }
- joinNode = NodeEditor.findParent(joinNode, NodeConstants.Types.JOIN, NodeConstants.Types.SOURCE);
- }
- }
- }
-
- for (PlanNode joinNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.JOIN, NodeConstants.Types.ACCESS)) {
- JoinStrategyType stype = (JoinStrategyType) joinNode.getProperty(NodeConstants.Info.JOIN_STRATEGY);
- if (!JoinStrategyType.MERGE.equals(stype)) {
- continue;
- }
-
- /**
- * Don't push sorts for unbalanced inner joins, we prefer to use a processing time cost based decision
- */
- boolean pushLeft = true;
- boolean pushRight = true;
- if (joinNode.getProperty(NodeConstants.Info.JOIN_TYPE) == JoinType.JOIN_INNER && context != null) {
- float leftCost = NewCalculateCostUtil.computeCostForTree(joinNode.getFirstChild(), metadata);
- float rightCost = NewCalculateCostUtil.computeCostForTree(joinNode.getLastChild(), metadata);
- if (leftCost != NewCalculateCostUtil.UNKNOWN_VALUE && rightCost != NewCalculateCostUtil.UNKNOWN_VALUE
- && (leftCost > context.getProcessorBatchSize() || rightCost > context.getProcessorBatchSize())) {
- //we use a larger constant here to ensure that we don't unwisely prevent pushdown
- pushLeft = leftCost < context.getProcessorBatchSize() || leftCost / rightCost < 8;
- pushRight = rightCost < context.getProcessorBatchSize() || rightCost / leftCost < 8 || joinNode.getProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE) != null;
- }
- }
-
- List<SingleElementSymbol> leftExpressions = (List<SingleElementSymbol>) joinNode.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS);
- List<SingleElementSymbol> rightExpressions = (List<SingleElementSymbol>) joinNode.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS);
-
- //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
- Object key = null;
- boolean right = true;
- //we check the right first, since it should be larger
- if (joinNode.getLastChild().getType() == NodeConstants.Types.ACCESS && NewCalculateCostUtil.isSingleTable(joinNode.getLastChild())) {
- key = NewCalculateCostUtil.getKeyUsed(rightExpressions, null, metadata, null);
- }
- if (key == null && joinNode.getFirstChild().getType() == NodeConstants.Types.ACCESS && NewCalculateCostUtil.isSingleTable(joinNode.getFirstChild())) {
- key = NewCalculateCostUtil.getKeyUsed(leftExpressions, null, metadata, null);
- right = false;
- }
- if (key != null) {
- //redo the join predicates based upon the key alone
- List<Object> keyCols = metadata.getElementIDsInKey(key);
- int[] reorder = new int[keyCols.size()];
- List<Integer> toCriteria = new ArrayList<Integer>(rightExpressions.size() - keyCols.size());
- List<SingleElementSymbol> keyExpressions = right?rightExpressions:leftExpressions;
- for (int j = 0; j < keyExpressions.size(); j++) {
- SingleElementSymbol ses = keyExpressions.get(j);
- if (!(ses instanceof ElementSymbol)) {
- continue;
- }
- ElementSymbol es = (ElementSymbol)ses;
- boolean found = false;
- for (int i = 0; !found && i < keyCols.size(); i++) {
- if (es.getMetadataID().equals(keyCols.get(i))) {
- reorder[i] = j;
- found = true;
- }
- }
- if (!found) {
- toCriteria.add(j);
- }
- }
- List<Criteria> joinCriteria = (List<Criteria>) joinNode.getProperty(Info.JOIN_CRITERIA);
- for (int index : toCriteria) {
- SingleElementSymbol lses = leftExpressions.get(index);
- SingleElementSymbol rses = rightExpressions.get(index);
- CompareCriteria cc = new CompareCriteria(lses, CompareCriteria.EQ, rses);
- if (joinCriteria == null || joinCriteria.isEmpty()) {
- joinCriteria = new ArrayList<Criteria>();
- joinCriteria.add(cc);
- joinNode.setProperty(Info.JOIN_TYPE, JoinType.JOIN_INNER);
- }
- }
- joinNode.setProperty(Info.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)) {
- joinNode.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.ENHANCED_SORT);
- }
- }
-
- return plan;
- }
-
- /**
- * Insert a sort node under the merge join node. If necessary, also insert a project
- * node to handle function evaluation.
- * @param expressions The expressions that need to be sorted on
- * @param jnode The planner merge join node to attach to
- * @return returns true if a project node needs added
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- */
- static boolean insertSort(PlanNode childNode, List<SingleElementSymbol> expressions, PlanNode jnode, QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
- boolean attemptPush) throws QueryMetadataException, TeiidComponentException {
- Set<SingleElementSymbol> orderSymbols = new LinkedHashSet<SingleElementSymbol>(expressions);
-
- PlanNode sourceNode = FrameUtil.findJoinSourceNode(childNode);
- PlanNode joinNode = childNode.getParent();
-
- Set<SingleElementSymbol> outputSymbols = new LinkedHashSet<SingleElementSymbol>((List<SingleElementSymbol>)childNode.getProperty(NodeConstants.Info.OUTPUT_COLS));
-
- int oldSize = outputSymbols.size();
-
- outputSymbols.addAll(expressions);
-
- boolean needsCorrection = outputSymbols.size() > oldSize;
-
- PlanNode sortNode = createSortNode(new ArrayList<SingleElementSymbol>(orderSymbols), outputSymbols);
-
- if (sourceNode.getType() == NodeConstants.Types.ACCESS) {
- if (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)) {
- sourceNode.getFirstChild().addAsParent(sortNode);
-
- if (needsCorrection) {
- correctOutputElements(joinNode, outputSymbols, sortNode);
- }
- return true;
- }
- }
-
- 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));
- childNode.addAsParent(projectNode);
- correctOutputElements(joinNode, outputSymbols, projectNode);
- }
- return false;
- }
-
- private static PlanNode createSortNode(List<SingleElementSymbol> orderSymbols,
- Collection outputElements) {
- PlanNode sortNode = NodeFactory.getNewNode(NodeConstants.Types.SORT);
- sortNode.setProperty(NodeConstants.Info.SORT_ORDER, new OrderBy(orderSymbols));
- sortNode.setProperty(NodeConstants.Info.OUTPUT_COLS, new ArrayList(outputElements));
- return sortNode;
- }
-
- private static void correctOutputElements(PlanNode endNode,
- Collection outputElements,
- PlanNode startNode) {
- while (startNode != endNode) {
- startNode.setProperty(NodeConstants.Info.OUTPUT_COLS, new ArrayList(outputElements));
- startNode = startNode.getParent();
- }
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "ImplementJoinStrategy"; //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleImplementJoinStrategy.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleImplementJoinStrategy.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleImplementJoinStrategy.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleImplementJoinStrategy.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,292 @@
+/*
+ * 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.relational.rules;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+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.query.analysis.AnalysisRecord;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.relational.OptimizerRule;
+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.processor.relational.JoinNode.JoinStrategyType;
+import org.teiid.query.processor.relational.MergeJoinStrategy.SortOption;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.symbol.ElementSymbol;
+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.GroupsUsedByElementsVisitor;
+import org.teiid.query.util.CommandContext;
+
+
+/**
+ * Inserts sort nodes for specific join strategies.
+ */
+public class RuleImplementJoinStrategy implements OptimizerRule {
+
+ /**
+ * @see org.teiid.query.optimizer.relational.OptimizerRule#execute(org.teiid.query.optimizer.relational.plantree.PlanNode, org.teiid.query.metadata.QueryMetadataInterface, org.teiid.query.optimizer.capabilities.CapabilitiesFinder, org.teiid.query.optimizer.relational.RuleStack, org.teiid.query.analysis.AnalysisRecord, org.teiid.query.util.CommandContext)
+ */
+ public PlanNode execute(PlanNode plan,
+ QueryMetadataInterface metadata,
+ CapabilitiesFinder capabilitiesFinder,
+ RuleStack rules,
+ AnalysisRecord analysisRecord,
+ CommandContext context) throws QueryPlannerException,
+ QueryMetadataException,
+ TeiidComponentException {
+
+ for (PlanNode sourceNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE, NodeConstants.Types.ACCESS)) {
+ SymbolMap references = (SymbolMap)sourceNode.getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
+ if (references != null) {
+ Set<GroupSymbol> groups = GroupsUsedByElementsVisitor.getGroups(references.getValues());
+ PlanNode joinNode = NodeEditor.findParent(sourceNode, NodeConstants.Types.JOIN, NodeConstants.Types.SOURCE);
+ while (joinNode != null) {
+ joinNode.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.NESTED_TABLE);
+ if (joinNode.getProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE) != null) {
+ //sanity check
+ throw new AssertionError("Cannot use a depenedent join when the join involves a correlated nested table."); //$NON-NLS-1$
+ }
+ if (joinNode.getGroups().containsAll(groups)) {
+ break;
+ }
+ joinNode = NodeEditor.findParent(joinNode, NodeConstants.Types.JOIN, NodeConstants.Types.SOURCE);
+ }
+ }
+ }
+
+ for (PlanNode joinNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.JOIN, NodeConstants.Types.ACCESS)) {
+ JoinStrategyType stype = (JoinStrategyType) joinNode.getProperty(NodeConstants.Info.JOIN_STRATEGY);
+ if (!JoinStrategyType.MERGE.equals(stype)) {
+ continue;
+ }
+
+ /**
+ * Don't push sorts for unbalanced inner joins, we prefer to use a processing time cost based decision
+ */
+ boolean pushLeft = true;
+ boolean pushRight = true;
+ if (joinNode.getProperty(NodeConstants.Info.JOIN_TYPE) == JoinType.JOIN_INNER && context != null) {
+ float leftCost = NewCalculateCostUtil.computeCostForTree(joinNode.getFirstChild(), metadata);
+ float rightCost = NewCalculateCostUtil.computeCostForTree(joinNode.getLastChild(), metadata);
+ if (leftCost != NewCalculateCostUtil.UNKNOWN_VALUE && rightCost != NewCalculateCostUtil.UNKNOWN_VALUE
+ && (leftCost > context.getProcessorBatchSize() || rightCost > context.getProcessorBatchSize())) {
+ //we use a larger constant here to ensure that we don't unwisely prevent pushdown
+ pushLeft = leftCost < context.getProcessorBatchSize() || leftCost / rightCost < 8;
+ pushRight = rightCost < context.getProcessorBatchSize() || rightCost / leftCost < 8 || joinNode.getProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE) != null;
+ }
+ }
+
+ 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
+ Object key = null;
+ boolean right = true;
+ //we check the right first, since it should be larger
+ if (joinNode.getLastChild().getType() == NodeConstants.Types.ACCESS && NewCalculateCostUtil.isSingleTable(joinNode.getLastChild())) {
+ key = NewCalculateCostUtil.getKeyUsed(rightExpressions, null, metadata, null);
+ }
+ if (key == null && joinNode.getFirstChild().getType() == NodeConstants.Types.ACCESS && NewCalculateCostUtil.isSingleTable(joinNode.getFirstChild())) {
+ key = NewCalculateCostUtil.getKeyUsed(leftExpressions, null, metadata, null);
+ right = false;
+ }
+ if (key != null) {
+ //redo the join predicates based upon the key alone
+ List<Object> keyCols = metadata.getElementIDsInKey(key);
+ int[] reorder = new int[keyCols.size()];
+ List<Integer> toCriteria = new ArrayList<Integer>(rightExpressions.size() - keyCols.size());
+ List<SingleElementSymbol> keyExpressions = right?rightExpressions:leftExpressions;
+ for (int j = 0; j < keyExpressions.size(); j++) {
+ SingleElementSymbol ses = keyExpressions.get(j);
+ if (!(ses instanceof ElementSymbol)) {
+ continue;
+ }
+ ElementSymbol es = (ElementSymbol)ses;
+ boolean found = false;
+ for (int i = 0; !found && i < keyCols.size(); i++) {
+ if (es.getMetadataID().equals(keyCols.get(i))) {
+ reorder[i] = j;
+ found = true;
+ }
+ }
+ if (!found) {
+ toCriteria.add(j);
+ }
+ }
+ 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);
+ CompareCriteria cc = new CompareCriteria(lses, CompareCriteria.EQ, rses);
+ if (joinCriteria == null || joinCriteria.isEmpty()) {
+ joinCriteria = new ArrayList<Criteria>();
+ joinCriteria.add(cc);
+ joinNode.setProperty(Info.JOIN_TYPE, JoinType.JOIN_INNER);
+ }
+ }
+ 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);
+ }
+
+ Set<SingleElementSymbol> outputSymbols = new LinkedHashSet<SingleElementSymbol>((List<SingleElementSymbol>)joinNode.getProperty(NodeConstants.Info.OUTPUT_COLS));
+
+ boolean pushedLeft = insertSort(joinNode.getFirstChild(), leftExpressions, joinNode, metadata, capabilitiesFinder, pushLeft);
+
+ 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);
+ }
+ }
+
+ return plan;
+ }
+
+ /**
+ * Insert a sort node under the merge join node. If necessary, also insert a project
+ * node to handle function evaluation.
+ * @param expressions The expressions that need to be sorted on
+ * @param jnode The planner merge join node to attach to
+ * @return returns true if a project node needs added
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ */
+ static boolean insertSort(PlanNode childNode, List<SingleElementSymbol> expressions, PlanNode jnode, QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
+ boolean attemptPush) throws QueryMetadataException, TeiidComponentException {
+ Set<SingleElementSymbol> orderSymbols = new LinkedHashSet<SingleElementSymbol>(expressions);
+
+ PlanNode sourceNode = FrameUtil.findJoinSourceNode(childNode);
+ PlanNode joinNode = childNode.getParent();
+
+ Set<SingleElementSymbol> outputSymbols = new LinkedHashSet<SingleElementSymbol>((List<SingleElementSymbol>)childNode.getProperty(NodeConstants.Info.OUTPUT_COLS));
+
+ int oldSize = outputSymbols.size();
+
+ outputSymbols.addAll(expressions);
+
+ boolean needsCorrection = outputSymbols.size() > oldSize;
+
+ 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;
+ }
+ }
+
+ if (sourceNode.getType() == NodeConstants.Types.ACCESS) {
+ 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)) {
+ sourceNode.getFirstChild().addAsParent(sortNode);
+
+ if (needsCorrection) {
+ correctOutputElements(joinNode, outputSymbols, sortNode);
+ }
+ return true;
+ }
+ }
+
+ if (distinct) {
+ joinNode.setProperty(joinNode.getFirstChild() == childNode ? NodeConstants.Info.IS_LEFT_DISTINCT : NodeConstants.Info.IS_RIGHT_DISTINCT, true);
+ }
+
+ 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));
+ childNode.addAsParent(projectNode);
+ correctOutputElements(joinNode, outputSymbols, projectNode);
+ }
+ return false;
+ }
+
+ private static PlanNode createSortNode(List<SingleElementSymbol> orderSymbols,
+ Collection outputElements) {
+ PlanNode sortNode = NodeFactory.getNewNode(NodeConstants.Types.SORT);
+ sortNode.setProperty(NodeConstants.Info.SORT_ORDER, new OrderBy(orderSymbols));
+ sortNode.setProperty(NodeConstants.Info.OUTPUT_COLS, new ArrayList(outputElements));
+ return sortNode;
+ }
+
+ private static void correctOutputElements(PlanNode endNode,
+ Collection outputElements,
+ PlanNode startNode) {
+ while (startNode != endNode) {
+ startNode.setProperty(NodeConstants.Info.OUTPUT_COLS, new ArrayList(outputElements));
+ startNode = startNode.getParent();
+ }
+ }
+
+ /**
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ return "ImplementJoinStrategy"; //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeCriteria.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeCriteria.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeCriteria.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,621 +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.optimizer.relational.rules;
-
-import java.util.ArrayList;
-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.Set;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryPlannerException;
-import org.teiid.client.plan.Annotation;
-import org.teiid.client.plan.Annotation.Priority;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.id.IDGenerator;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.SupportConstants;
-import org.teiid.query.optimizer.QueryOptimizer;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.relational.OptimizerRule;
-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.processor.relational.RelationalPlan;
-import org.teiid.query.processor.relational.JoinNode.JoinStrategyType;
-import org.teiid.query.processor.relational.MergeJoinStrategy.SortOption;
-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.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.FromClause;
-import org.teiid.query.sql.lang.GroupBy;
-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.SubqueryCompareCriteria;
-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.GroupSymbol;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.symbol.ScalarSubquery;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-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.ExpressionMappingVisitor;
-import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
-import org.teiid.query.sql.visitor.ReferenceCollectorVisitor;
-import org.teiid.query.util.CommandContext;
-
-public final class RuleMergeCriteria implements OptimizerRule {
-
- public static final String UNNEST_DEFAULT = "org.teiid.subqueryUnnestDefault"; //$NON-NLS-1$
- private final boolean UNNEST = Boolean.getBoolean(UNNEST_DEFAULT);
-
- /**
- * Used to replace correlated references
- */
- protected static final class ReferenceReplacementVisitor extends
- ExpressionMappingVisitor {
- private final SymbolMap refs;
- private boolean replacedAny;
-
- ReferenceReplacementVisitor(SymbolMap refs) {
- super(null);
- this.refs = refs;
- }
-
- public Expression replaceExpression(Expression element) {
- if (element instanceof Reference) {
- Reference r = (Reference)element;
- Expression ex = refs.getMappedExpression(r.getExpression());
- if (ex != null) {
- if (ex instanceof ElementSymbol) {
- ElementSymbol es = (ElementSymbol) ex.clone();
- es.setIsExternalReference(false);
- ex = es;
- }
- replacedAny = true;
- return ex;
- }
- }
- return element;
- }
-
- }
-
- public static class PlannedResult {
- public List leftExpressions = new LinkedList();
- public List rightExpressions = new LinkedList();
- public Query query;
- public boolean not;
- public List<Criteria> nonEquiJoinCriteria = new LinkedList<Criteria>();
- public Criteria additionalCritieria;
- public Class<?> type;
- public boolean mergeJoin;
- public boolean madeDistinct;
- }
-
- private IDGenerator idGenerator;
- private CapabilitiesFinder capFinder;
- private AnalysisRecord analysisRecord;
- private CommandContext context;
- private QueryMetadataInterface metadata;
-
- public RuleMergeCriteria(IDGenerator idGenerator, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord, CommandContext context, QueryMetadataInterface metadata) {
- this.idGenerator = idGenerator;
- this.capFinder = capFinder;
- this.analysisRecord = analysisRecord;
- this.context = context;
- this.metadata = metadata;
- }
-
- /**
- * @see OptimizerRule#execute(PlanNode, QueryMetadataInterface, RuleStack)
- */
- public PlanNode execute(PlanNode plan, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, RuleStack rules, AnalysisRecord analysisRecord, CommandContext context)
- throws QueryPlannerException, TeiidComponentException {
-
- // Find strings of criteria and merge them, removing duplicates
- List<PlanNode> criteriaChains = new ArrayList<PlanNode>();
- findCriteriaChains(plan, criteriaChains, analysisRecord);
-
- // Merge chains
- for (PlanNode critNode : criteriaChains) {
- mergeChain(critNode, metadata);
- }
-
- return plan;
- }
-
- /**
- * Walk the tree pre-order, looking for any chains of criteria
- * @param node Root node to search
- * @param foundNodes Roots of criteria chains
- */
- void findCriteriaChains(PlanNode root, List<PlanNode> foundNodes, AnalysisRecord analysisRecord)
- throws QueryPlannerException, TeiidComponentException {
-
- PlanNode recurseRoot = root;
- if(root.getType() == NodeConstants.Types.SELECT) {
-
- // Walk to end of the chain and change recurse root
- while(recurseRoot.getType() == NodeConstants.Types.SELECT) {
- // Look for opportunities to replace with a semi-join
- recurseRoot = planMergeJoin(recurseRoot, root, analysisRecord);
- if (root.getChildCount() == 0) {
- root = recurseRoot.getFirstChild();
- if (root.getType() != NodeConstants.Types.SELECT) {
- root = root.getParent();
- }
- }
- recurseRoot = recurseRoot.getFirstChild();
- }
-
- // Ignore trivial 1-node case
- if(recurseRoot.getParent() != root) {
- // Found root for chain
- foundNodes.add(root);
- }
- }
-
- if (recurseRoot.getType() != NodeConstants.Types.ACCESS) {
- for (PlanNode child : recurseRoot.getChildren()) {
- findCriteriaChains(child, foundNodes, analysisRecord);
- }
- }
- }
-
- static void mergeChain(PlanNode chainRoot, QueryMetadataInterface metadata) {
- // Remove all of chain except root, collect crit from each
- CompoundCriteria critParts = new CompoundCriteria();
- LinkedList<Criteria> subqueryCriteria = new LinkedList<Criteria>();
- PlanNode current = chainRoot;
- boolean isDependentSet = false;
- while(current.getType() == NodeConstants.Types.SELECT) {
- if (!current.getCorrelatedReferenceElements().isEmpty()) {
- //add at the end for delayed evaluation
- subqueryCriteria.add(0, (Criteria)current.getProperty(NodeConstants.Info.SELECT_CRITERIA));
- } else {
- critParts.getCriteria().add(0, (Criteria)current.getProperty(NodeConstants.Info.SELECT_CRITERIA));
- }
-
- isDependentSet |= current.hasBooleanProperty(NodeConstants.Info.IS_DEPENDENT_SET);
-
- // Recurse
- PlanNode last = current;
- current = current.getLastChild();
-
- // Remove current
- if(last != chainRoot) {
- NodeEditor.removeChildNode(last.getParent(), last);
- }
- }
- critParts.getCriteria().addAll(subqueryCriteria);
- Criteria combinedCrit = QueryRewriter.optimizeCriteria(critParts, metadata);
-
- if (isDependentSet) {
- chainRoot.setProperty(NodeConstants.Info.IS_DEPENDENT_SET, Boolean.TRUE);
- }
-
- // Replace criteria at root with new combined criteria
- chainRoot.setProperty(NodeConstants.Info.SELECT_CRITERIA, combinedCrit);
-
- // Reset group for node based on combined criteria
- chainRoot.getGroups().clear();
-
- chainRoot.addGroups(GroupsUsedByElementsVisitor.getGroups(combinedCrit));
- chainRoot.addGroups(GroupsUsedByElementsVisitor.getGroups(chainRoot.getCorrelatedReferenceElements()));
- }
-
- /**
- * Look for:
- * [NOT] EXISTS ( )
- * IN ( ) / SOME ( )
- *
- * and replace with a semi join
- *
- * TODO: it would be good to have a hint to force
- */
- private PlanNode planMergeJoin(PlanNode current, PlanNode root, AnalysisRecord analysisRecord) throws QueryMetadataException,
- TeiidComponentException {
- float sourceCost = NewCalculateCostUtil.computeCostForTree(current.getFirstChild(), metadata);
- Criteria crit = (Criteria)current.getProperty(NodeConstants.Info.SELECT_CRITERIA);
-
- PlannedResult plannedResult = findSubquery(crit);
- if (plannedResult.query == null) {
- return current;
- }
- if (sourceCost != NewCalculateCostUtil.UNKNOWN_VALUE
- && sourceCost < RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY && !plannedResult.mergeJoin) {
- //TODO: see if a dependent join applies the other direction
- return current;
- }
-
- RelationalPlan originalPlan = (RelationalPlan)plannedResult.query.getProcessorPlan();
- Number originalCardinality = originalPlan.getRootNode().getEstimateNodeCardinality();
- if (!plannedResult.mergeJoin && originalCardinality.floatValue() == NewCalculateCostUtil.UNKNOWN_VALUE) {
- //TODO: this check isn't really accurate - exists and scalarsubqueries will always have cardinality 2/1
- //if it's currently unknown, removing criteria won't make it any better
- return current;
- }
-
- Collection<GroupSymbol> leftGroups = FrameUtil.findJoinSourceNode(current).getGroups();
-
- if (!planQuery(leftGroups, false, plannedResult)) {
- if (plannedResult.mergeJoin && analysisRecord != null && analysisRecord.recordAnnotations()) {
- this.analysisRecord.addAnnotation(new Annotation(Annotation.HINTS, "could not plan as a merge join: " + crit, "ignoring hint", Priority.MEDIUM)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return current;
- }
-
- //add an order by, which hopefully will get pushed down
- plannedResult.query.setOrderBy(new OrderBy(plannedResult.rightExpressions).clone());
- for (OrderByItem item : plannedResult.query.getOrderBy().getOrderByItems()) {
- int index = plannedResult.query.getProjectedSymbols().indexOf(item.getSymbol());
- item.setExpressionPosition(index);
- }
-
- try {
- //clone the symbols as they may change during planning
- List<SingleElementSymbol> projectedSymbols = LanguageObject.Util.deepClone(plannedResult.query.getProjectedSymbols(), SingleElementSymbol.class);
- //NOTE: we could tap into the relationalplanner at a lower level to get this in a plan node form,
- //the major benefit would be to reuse the dependent join planning logic if possible.
- if (analysisRecord != null && analysisRecord.recordDebug()) {
- analysisRecord.println("Attempting to plan " + crit + " as a merge join"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- RelationalPlan subPlan = (RelationalPlan)QueryOptimizer.optimizePlan(plannedResult.query, metadata, idGenerator, capFinder, analysisRecord, context);
- Number planCardinality = subPlan.getRootNode().getEstimateNodeCardinality();
-
- if (!plannedResult.mergeJoin) {
- //if we don't have a specific hint, then use costing
- if (planCardinality.floatValue() == NewCalculateCostUtil.UNKNOWN_VALUE
- || planCardinality.floatValue() > 10000000
- || (sourceCost == NewCalculateCostUtil.UNKNOWN_VALUE && planCardinality.floatValue() > 1000)
- || (sourceCost != NewCalculateCostUtil.UNKNOWN_VALUE && sourceCost * originalCardinality.floatValue() < planCardinality.floatValue() / (100 * Math.log(Math.max(4, sourceCost))))) {
- //bail-out if both are unknown or the new plan is too large
- if (analysisRecord != null && analysisRecord.recordDebug()) {
- analysisRecord.println("Failed to use mege join, as the cost was not favorable. Use the MJ hint to force."); //$NON-NLS-1$
- }
- return current;
- }
- }
-
- PlanNode semiJoin = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- semiJoin.addGroups(current.getGroups());
- semiJoin.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.MERGE);
- semiJoin.setProperty(NodeConstants.Info.JOIN_TYPE, plannedResult.not?JoinType.JOIN_ANTI_SEMI:JoinType.JOIN_SEMI);
- semiJoin.setProperty(NodeConstants.Info.NON_EQUI_JOIN_CRITERIA, plannedResult.nonEquiJoinCriteria);
-
- semiJoin.setProperty(NodeConstants.Info.LEFT_EXPRESSIONS, plannedResult.leftExpressions);
- semiJoin.setProperty(NodeConstants.Info.RIGHT_EXPRESSIONS, plannedResult.rightExpressions);
- semiJoin.setProperty(NodeConstants.Info.SORT_RIGHT, SortOption.ALREADY_SORTED);
- semiJoin.setProperty(NodeConstants.Info.OUTPUT_COLS, root.getProperty(NodeConstants.Info.OUTPUT_COLS));
-
- List childOutput = (List)current.getFirstChild().getProperty(NodeConstants.Info.OUTPUT_COLS);
- PlanNode toCorrect = root;
- while (toCorrect != current) {
- toCorrect.setProperty(NodeConstants.Info.OUTPUT_COLS, childOutput);
- toCorrect = toCorrect.getFirstChild();
- }
-
- PlanNode node = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- node.setProperty(NodeConstants.Info.PROCESSOR_PLAN, subPlan);
- node.setProperty(NodeConstants.Info.OUTPUT_COLS, projectedSymbols);
- node.setProperty(NodeConstants.Info.EST_CARDINALITY, planCardinality);
- root.addAsParent(semiJoin);
- semiJoin.addLastChild(node);
- PlanNode result = current.getParent();
- NodeEditor.removeChildNode(result, current);
- RuleImplementJoinStrategy.insertSort(semiJoin.getFirstChild(), (List<SingleElementSymbol>) plannedResult.leftExpressions, semiJoin, metadata, capFinder, true);
- return result;
- } catch (QueryPlannerException e) {
- //can't be done - probably access patterns - what about dependent
- return current;
- }
- }
-
- public PlannedResult findSubquery(Criteria crit) throws TeiidComponentException, QueryMetadataException {
- PlannedResult result = new PlannedResult();
- if (crit instanceof SubquerySetCriteria) {
- //convert to the quantified form
- SubquerySetCriteria ssc = (SubquerySetCriteria)crit;
- if (ssc.getSubqueryHint().isNoUnnest()) {
- return result;
- }
- result.not ^= ssc.isNegated();
- result.type = crit.getClass();
- result.mergeJoin = ssc.getSubqueryHint().isMergeJoin();
- if (!UNNEST && !result.mergeJoin) {
- return result;
- }
- crit = new SubqueryCompareCriteria(ssc.getExpression(), ssc.getCommand(), SubqueryCompareCriteria.EQ, SubqueryCompareCriteria.SOME);
- } else if (crit instanceof CompareCriteria) {
- if (!UNNEST) {
- return result;
- }
- //convert to the quantified form
- CompareCriteria cc = (CompareCriteria)crit;
- if (cc.getRightExpression() instanceof ScalarSubquery) {
- ScalarSubquery ss = (ScalarSubquery)cc.getRightExpression();
- result.type = ss.getClass();
- //we can only use a semi-join if we know that 1 row will be present
- if (ss.getCommand() instanceof Query) {
- Query query = (Query)ss.getCommand();
- if (query.getGroupBy() == null && query.hasAggregates()) {
- crit = new SubqueryCompareCriteria(cc.getLeftExpression(), ss.getCommand(), cc.getOperator(), SubqueryCompareCriteria.SOME);
- }
- }
- }
- }
- if (crit instanceof SubqueryCompareCriteria) {
- SubqueryCompareCriteria scc = (SubqueryCompareCriteria)crit;
-
- if (scc.getPredicateQuantifier() != SubqueryCompareCriteria.SOME
- //TODO: could add an inline view if not a query
- || !(scc.getCommand() instanceof Query)) {
- return result;
- }
-
- Query query = (Query)scc.getCommand();
- Expression rightExpr = SymbolMap.getExpression(query.getProjectedSymbols().get(0));
-
- if (result.not && !isNonNull(query, rightExpr)) {
- return result;
- }
- if (result.type == null) {
- result.type = scc.getClass();
- }
- result.query = query;
- result.additionalCritieria = (Criteria)new CompareCriteria(scc.getLeftExpression(), scc.getOperator(), rightExpr).clone();
- }
- if (crit instanceof ExistsCriteria) {
- ExistsCriteria exists = (ExistsCriteria)crit;
- if (exists.getSubqueryHint().isNoUnnest()) {
- return result;
- }
- if (!(exists.getCommand() instanceof Query)) {
- return result;
- }
- 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();
- if (!UNNEST && !result.mergeJoin) {
- return result;
- }
- }
- return result;
- }
-
- private boolean isNonNull(Query query, Expression rightExpr)
- throws TeiidComponentException, QueryMetadataException {
- if (rightExpr instanceof ElementSymbol) {
- ElementSymbol es = (ElementSymbol)rightExpr;
- if (metadata.elementSupports(es.getMetadataID(), SupportConstants.Element.NULL)) {
- return false;
- }
- if (!isSimpleJoin(query)) {
- return false;
- }
- } else if (rightExpr instanceof Constant) {
- if (((Constant)rightExpr).isNull()) {
- return false;
- }
- } else if (rightExpr instanceof AggregateSymbol) {
- AggregateSymbol as = (AggregateSymbol)rightExpr;
- if (as.getAggregateFunction() != Type.COUNT) {
- return false;
- }
- } else {
- return false;
- }
- return true;
- }
-
- private boolean isSimpleJoin(Query query) {
- if (query.getFrom() != null) {
- for (FromClause clause : (List<FromClause>)query.getFrom().getClauses()) {
- if (RuleCollapseSource.hasOuterJoins(clause)) {
- return false;
- }
- }
- }
- return true;
- }
-
- public boolean planQuery(Collection<GroupSymbol> leftGroups, boolean requireDistinct, PlannedResult plannedResult) throws QueryMetadataException, TeiidComponentException {
- if ((plannedResult.query.getLimit() != null && !plannedResult.query.getLimit().isImplicit()) || plannedResult.query.getFrom() == null) {
- return false;
- }
-
- if ((plannedResult.type == ExistsCriteria.class || plannedResult.type == ScalarSubquery.class) && plannedResult.query.getCorrelatedReferences() == null) {
- //we can't really improve on this case
- //TODO: do this check earlier
- return false;
- }
-
- plannedResult.query = (Query)plannedResult.query.clone();
- plannedResult.query.setLimit(null);
-
- List<GroupSymbol> rightGroups = plannedResult.query.getFrom().getGroups();
- Set<SingleElementSymbol> requiredExpressions = new LinkedHashSet<SingleElementSymbol>();
- final SymbolMap refs = plannedResult.query.getCorrelatedReferences();
- boolean addGroupBy = false;
- if (refs != null) {
- boolean hasAggregates = plannedResult.query.hasAggregates();
- Criteria where = plannedResult.query.getCriteria();
- if (plannedResult.query.getGroupBy() == null) {
- plannedResult.query.setCriteria(null);
- }
- Criteria having = plannedResult.query.getHaving();
- plannedResult.query.setHaving(null);
- if (hasCorrelatedReferences(plannedResult.query, refs)) {
- return false;
- }
- if (plannedResult.query.getGroupBy() == null) {
- processCriteria(leftGroups, plannedResult, rightGroups, requiredExpressions, refs, where, true);
- if (hasAggregates) {
- if (!plannedResult.nonEquiJoinCriteria.isEmpty()) {
- return false;
- }
- addGroupBy = true;
- }
- }
- processCriteria(leftGroups, plannedResult, rightGroups, requiredExpressions, refs, having, false);
- }
-
- if (plannedResult.additionalCritieria != null) {
- RuleChooseJoinStrategy.separateCriteria(leftGroups, rightGroups, plannedResult.leftExpressions, plannedResult.rightExpressions, Criteria.separateCriteriaByAnd(plannedResult.additionalCritieria), plannedResult.nonEquiJoinCriteria);
- }
-
- if (plannedResult.leftExpressions.isEmpty()) {
- return false;
- }
-
- plannedResult.leftExpressions = RuleChooseJoinStrategy.createExpressionSymbols(plannedResult.leftExpressions);
- plannedResult.rightExpressions = RuleChooseJoinStrategy.createExpressionSymbols(plannedResult.rightExpressions);
-
- if (requireDistinct && !addGroupBy && !isDistinct(plannedResult.query, plannedResult.rightExpressions, metadata)) {
- if (!requiredExpressions.isEmpty()) {
- return false;
- }
- plannedResult.query.getSelect().setDistinct(true);
- plannedResult.madeDistinct = true;
- }
-
- if (addGroupBy) {
- LinkedHashSet<SingleElementSymbol> groupingSymbols = new LinkedHashSet<SingleElementSymbol>();
- ArrayList<SingleElementSymbol> aggs = new ArrayList<SingleElementSymbol>();
- for (Expression expr : (List<Expression>)plannedResult.rightExpressions) {
- AggregateSymbolCollectorVisitor.getAggregates(expr, aggs, groupingSymbols);
- }
- if (!groupingSymbols.isEmpty()) {
- plannedResult.query.setGroupBy((GroupBy) new GroupBy(new ArrayList<SingleElementSymbol>(groupingSymbols)).clone());
- }
- }
- HashSet<SingleElementSymbol> projectedSymbols = new HashSet<SingleElementSymbol>();
- for (SingleElementSymbol ses : plannedResult.query.getProjectedSymbols()) {
- if (ses instanceof AliasSymbol) {
- ses = ((AliasSymbol)ses).getSymbol();
- }
- projectedSymbols.add(ses);
- }
- for (SingleElementSymbol ses : requiredExpressions) {
- if (projectedSymbols.add(ses)) {
- plannedResult.query.getSelect().addSymbol((SingleElementSymbol) ses.clone());
- }
- }
- for (SingleElementSymbol ses : (List<SingleElementSymbol>)plannedResult.rightExpressions) {
- if (projectedSymbols.add(ses)) {
- plannedResult.query.getSelect().addSymbol((SingleElementSymbol)ses.clone());
- }
- }
- return true;
- }
-
- private void processCriteria(Collection<GroupSymbol> leftGroups,
- PlannedResult plannedResult, List<GroupSymbol> rightGroups,
- Set<SingleElementSymbol> requiredExpressions, final SymbolMap refs,
- Criteria joinCriteria, boolean where) {
- if (joinCriteria == null) {
- return;
- }
- List<Criteria> crits = Criteria.separateCriteriaByAnd((Criteria)joinCriteria.clone());
-
- 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);
- ReferenceReplacementVisitor emv = new ReferenceReplacementVisitor(refs);
- DeepPostOrderNavigator.doVisit(conjunct, emv);
- if (!emv.replacedAny) {
- //if not correlated, then leave it on the query
- critIter.remove();
- if (where) {
- plannedResult.query.setCriteria(Criteria.combineCriteria(plannedResult.query.getCriteria(), conjunct));
- } else {
- plannedResult.query.setHaving(Criteria.combineCriteria(plannedResult.query.getHaving(), conjunct));
- }
- } else {
- requiredExpressions.addAll(aggregates);
- requiredExpressions.addAll(elements);
- }
- }
- RuleChooseJoinStrategy.separateCriteria(leftGroups, rightGroups, plannedResult.leftExpressions, plannedResult.rightExpressions, crits, plannedResult.nonEquiJoinCriteria);
- }
-
- public static boolean isDistinct(Query query, List<SingleElementSymbol> expressions, QueryMetadataInterface metadata)
- throws QueryMetadataException, TeiidComponentException {
- boolean distinct = false;
- if (query.getGroupBy() != null) {
- distinct = true;
- for (SingleElementSymbol groupByExpr : (List<SingleElementSymbol>)query.getGroupBy().getSymbols()) {
- if (!expressions.contains(groupByExpr)) {
- distinct = false;
- break;
- }
- }
- }
- if (distinct) {
- return true;
- }
- HashSet<GroupSymbol> keyPreservingGroups = new HashSet<GroupSymbol>();
- ResolverUtil.findKeyPreserved(query, keyPreservingGroups, metadata);
- return NewCalculateCostUtil.usesKey(expressions, keyPreservingGroups, metadata, true);
- }
-
- private boolean hasCorrelatedReferences(LanguageObject object, SymbolMap correlatedReferences) {
- Collection<Reference> references = ReferenceCollectorVisitor.getReferences(object);
- for (Reference reference : references) {
- if (correlatedReferences.asMap().containsKey(reference.getExpression())) {
- return true;
- }
- }
- return false;
- }
-
- public String toString() {
- return "MergeCriteria"; //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeCriteria.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeCriteria.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeCriteria.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeCriteria.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,623 @@
+/*
+ * 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.relational.rules;
+
+import java.util.ArrayList;
+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.Set;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryPlannerException;
+import org.teiid.client.plan.Annotation;
+import org.teiid.client.plan.Annotation.Priority;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.id.IDGenerator;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.SupportConstants;
+import org.teiid.query.optimizer.QueryOptimizer;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.relational.OptimizerRule;
+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.processor.relational.RelationalPlan;
+import org.teiid.query.processor.relational.JoinNode.JoinStrategyType;
+import org.teiid.query.processor.relational.MergeJoinStrategy.SortOption;
+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.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.FromClause;
+import org.teiid.query.sql.lang.GroupBy;
+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.SubqueryCompareCriteria;
+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.GroupSymbol;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.symbol.ScalarSubquery;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+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.ExpressionMappingVisitor;
+import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
+import org.teiid.query.sql.visitor.ReferenceCollectorVisitor;
+import org.teiid.query.util.CommandContext;
+
+public final class RuleMergeCriteria implements OptimizerRule {
+
+ public static final String UNNEST_DEFAULT = "org.teiid.subqueryUnnestDefault"; //$NON-NLS-1$
+ private final boolean UNNEST = Boolean.getBoolean(UNNEST_DEFAULT);
+
+ /**
+ * Used to replace correlated references
+ */
+ protected static final class ReferenceReplacementVisitor extends
+ ExpressionMappingVisitor {
+ private final SymbolMap refs;
+ private boolean replacedAny;
+
+ ReferenceReplacementVisitor(SymbolMap refs) {
+ super(null);
+ this.refs = refs;
+ }
+
+ public Expression replaceExpression(Expression element) {
+ if (element instanceof Reference) {
+ Reference r = (Reference)element;
+ Expression ex = refs.getMappedExpression(r.getExpression());
+ if (ex != null) {
+ if (ex instanceof ElementSymbol) {
+ ElementSymbol es = (ElementSymbol) ex.clone();
+ es.setIsExternalReference(false);
+ ex = es;
+ }
+ replacedAny = true;
+ return ex;
+ }
+ }
+ return element;
+ }
+
+ }
+
+ public static class PlannedResult {
+ public List leftExpressions = new LinkedList();
+ public List rightExpressions = new LinkedList();
+ public Query query;
+ public boolean not;
+ public List<Criteria> nonEquiJoinCriteria = new LinkedList<Criteria>();
+ public Criteria additionalCritieria;
+ public Class<?> type;
+ public boolean mergeJoin;
+ public boolean madeDistinct;
+ public boolean makeInd;
+ }
+
+ private IDGenerator idGenerator;
+ private CapabilitiesFinder capFinder;
+ private AnalysisRecord analysisRecord;
+ private CommandContext context;
+ private QueryMetadataInterface metadata;
+
+ public RuleMergeCriteria(IDGenerator idGenerator, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord, CommandContext context, QueryMetadataInterface metadata) {
+ this.idGenerator = idGenerator;
+ this.capFinder = capFinder;
+ this.analysisRecord = analysisRecord;
+ this.context = context;
+ this.metadata = metadata;
+ }
+
+ /**
+ * @see OptimizerRule#execute(PlanNode, QueryMetadataInterface, RuleStack)
+ */
+ public PlanNode execute(PlanNode plan, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, RuleStack rules, AnalysisRecord analysisRecord, CommandContext context)
+ throws QueryPlannerException, TeiidComponentException {
+
+ // Find strings of criteria and merge them, removing duplicates
+ List<PlanNode> criteriaChains = new ArrayList<PlanNode>();
+ findCriteriaChains(plan, criteriaChains, analysisRecord);
+
+ // Merge chains
+ for (PlanNode critNode : criteriaChains) {
+ mergeChain(critNode, metadata);
+ }
+
+ return plan;
+ }
+
+ /**
+ * Walk the tree pre-order, looking for any chains of criteria
+ * @param node Root node to search
+ * @param foundNodes Roots of criteria chains
+ */
+ void findCriteriaChains(PlanNode root, List<PlanNode> foundNodes, AnalysisRecord analysisRecord)
+ throws QueryPlannerException, TeiidComponentException {
+
+ PlanNode recurseRoot = root;
+ if(root.getType() == NodeConstants.Types.SELECT) {
+
+ // Walk to end of the chain and change recurse root
+ while(recurseRoot.getType() == NodeConstants.Types.SELECT) {
+ // Look for opportunities to replace with a semi-join
+ recurseRoot = planMergeJoin(recurseRoot, root, analysisRecord);
+ if (root.getChildCount() == 0) {
+ root = recurseRoot.getFirstChild();
+ if (root.getType() != NodeConstants.Types.SELECT) {
+ root = root.getParent();
+ }
+ }
+ recurseRoot = recurseRoot.getFirstChild();
+ }
+
+ // Ignore trivial 1-node case
+ if(recurseRoot.getParent() != root) {
+ // Found root for chain
+ foundNodes.add(root);
+ }
+ }
+
+ if (recurseRoot.getType() != NodeConstants.Types.ACCESS) {
+ for (PlanNode child : recurseRoot.getChildren()) {
+ findCriteriaChains(child, foundNodes, analysisRecord);
+ }
+ }
+ }
+
+ static void mergeChain(PlanNode chainRoot, QueryMetadataInterface metadata) {
+ // Remove all of chain except root, collect crit from each
+ CompoundCriteria critParts = new CompoundCriteria();
+ LinkedList<Criteria> subqueryCriteria = new LinkedList<Criteria>();
+ PlanNode current = chainRoot;
+ boolean isDependentSet = false;
+ while(current.getType() == NodeConstants.Types.SELECT) {
+ if (!current.getCorrelatedReferenceElements().isEmpty()) {
+ //add at the end for delayed evaluation
+ subqueryCriteria.add(0, (Criteria)current.getProperty(NodeConstants.Info.SELECT_CRITERIA));
+ } else {
+ critParts.getCriteria().add(0, (Criteria)current.getProperty(NodeConstants.Info.SELECT_CRITERIA));
+ }
+
+ isDependentSet |= current.hasBooleanProperty(NodeConstants.Info.IS_DEPENDENT_SET);
+
+ // Recurse
+ PlanNode last = current;
+ current = current.getLastChild();
+
+ // Remove current
+ if(last != chainRoot) {
+ NodeEditor.removeChildNode(last.getParent(), last);
+ }
+ }
+ critParts.getCriteria().addAll(subqueryCriteria);
+ Criteria combinedCrit = QueryRewriter.optimizeCriteria(critParts, metadata);
+
+ if (isDependentSet) {
+ chainRoot.setProperty(NodeConstants.Info.IS_DEPENDENT_SET, Boolean.TRUE);
+ }
+
+ // Replace criteria at root with new combined criteria
+ chainRoot.setProperty(NodeConstants.Info.SELECT_CRITERIA, combinedCrit);
+
+ // Reset group for node based on combined criteria
+ chainRoot.getGroups().clear();
+
+ chainRoot.addGroups(GroupsUsedByElementsVisitor.getGroups(combinedCrit));
+ chainRoot.addGroups(GroupsUsedByElementsVisitor.getGroups(chainRoot.getCorrelatedReferenceElements()));
+ }
+
+ /**
+ * Look for:
+ * [NOT] EXISTS ( )
+ * IN ( ) / SOME ( )
+ *
+ * and replace with a semi join
+ *
+ * TODO: it would be good to have a hint to force
+ */
+ private PlanNode planMergeJoin(PlanNode current, PlanNode root, AnalysisRecord analysisRecord) throws QueryMetadataException,
+ TeiidComponentException {
+ float sourceCost = NewCalculateCostUtil.computeCostForTree(current.getFirstChild(), metadata);
+ Criteria crit = (Criteria)current.getProperty(NodeConstants.Info.SELECT_CRITERIA);
+
+ PlannedResult plannedResult = findSubquery(crit);
+ if (plannedResult.query == null) {
+ return current;
+ }
+ if (sourceCost != NewCalculateCostUtil.UNKNOWN_VALUE
+ && sourceCost < RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY && !plannedResult.mergeJoin) {
+ //TODO: see if a dependent join applies the other direction
+ return current;
+ }
+
+ RelationalPlan originalPlan = (RelationalPlan)plannedResult.query.getProcessorPlan();
+ Number originalCardinality = originalPlan.getRootNode().getEstimateNodeCardinality();
+ if (!plannedResult.mergeJoin && originalCardinality.floatValue() == NewCalculateCostUtil.UNKNOWN_VALUE) {
+ //TODO: this check isn't really accurate - exists and scalarsubqueries will always have cardinality 2/1
+ //if it's currently unknown, removing criteria won't make it any better
+ return current;
+ }
+
+ Collection<GroupSymbol> leftGroups = FrameUtil.findJoinSourceNode(current).getGroups();
+
+ if (!planQuery(leftGroups, false, plannedResult)) {
+ if (plannedResult.mergeJoin && analysisRecord != null && analysisRecord.recordAnnotations()) {
+ this.analysisRecord.addAnnotation(new Annotation(Annotation.HINTS, "could not plan as a merge join: " + crit, "ignoring hint", Priority.MEDIUM)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return current;
+ }
+
+ //add an order by, which hopefully will get pushed down
+ plannedResult.query.setOrderBy(new OrderBy(plannedResult.rightExpressions).clone());
+ for (OrderByItem item : plannedResult.query.getOrderBy().getOrderByItems()) {
+ int index = plannedResult.query.getProjectedSymbols().indexOf(item.getSymbol());
+ item.setExpressionPosition(index);
+ }
+
+ try {
+ //clone the symbols as they may change during planning
+ List<SingleElementSymbol> projectedSymbols = LanguageObject.Util.deepClone(plannedResult.query.getProjectedSymbols(), SingleElementSymbol.class);
+ //NOTE: we could tap into the relationalplanner at a lower level to get this in a plan node form,
+ //the major benefit would be to reuse the dependent join planning logic if possible.
+ if (analysisRecord != null && analysisRecord.recordDebug()) {
+ analysisRecord.println("Attempting to plan " + crit + " as a merge join"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ RelationalPlan subPlan = (RelationalPlan)QueryOptimizer.optimizePlan(plannedResult.query, metadata, idGenerator, capFinder, analysisRecord, context);
+ Number planCardinality = subPlan.getRootNode().getEstimateNodeCardinality();
+
+ if (!plannedResult.mergeJoin) {
+ //if we don't have a specific hint, then use costing
+ if (planCardinality.floatValue() == NewCalculateCostUtil.UNKNOWN_VALUE
+ || planCardinality.floatValue() > 10000000
+ || (sourceCost == NewCalculateCostUtil.UNKNOWN_VALUE && planCardinality.floatValue() > 1000)
+ || (sourceCost != NewCalculateCostUtil.UNKNOWN_VALUE && sourceCost * originalCardinality.floatValue() < planCardinality.floatValue() / (100 * Math.log(Math.max(4, sourceCost))))) {
+ //bail-out if both are unknown or the new plan is too large
+ if (analysisRecord != null && analysisRecord.recordDebug()) {
+ analysisRecord.println("Failed to use mege join, as the cost was not favorable. Use the MJ hint to force."); //$NON-NLS-1$
+ }
+ return current;
+ }
+ }
+
+ PlanNode semiJoin = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+ semiJoin.addGroups(current.getGroups());
+ semiJoin.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.MERGE);
+ semiJoin.setProperty(NodeConstants.Info.JOIN_TYPE, plannedResult.not?JoinType.JOIN_ANTI_SEMI:JoinType.JOIN_SEMI);
+ semiJoin.setProperty(NodeConstants.Info.NON_EQUI_JOIN_CRITERIA, plannedResult.nonEquiJoinCriteria);
+
+ semiJoin.setProperty(NodeConstants.Info.LEFT_EXPRESSIONS, plannedResult.leftExpressions);
+ semiJoin.setProperty(NodeConstants.Info.RIGHT_EXPRESSIONS, plannedResult.rightExpressions);
+ semiJoin.setProperty(NodeConstants.Info.SORT_RIGHT, SortOption.ALREADY_SORTED);
+ semiJoin.setProperty(NodeConstants.Info.OUTPUT_COLS, root.getProperty(NodeConstants.Info.OUTPUT_COLS));
+
+ List childOutput = (List)current.getFirstChild().getProperty(NodeConstants.Info.OUTPUT_COLS);
+ PlanNode toCorrect = root;
+ while (toCorrect != current) {
+ toCorrect.setProperty(NodeConstants.Info.OUTPUT_COLS, childOutput);
+ toCorrect = toCorrect.getFirstChild();
+ }
+
+ PlanNode node = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ node.setProperty(NodeConstants.Info.PROCESSOR_PLAN, subPlan);
+ node.setProperty(NodeConstants.Info.OUTPUT_COLS, projectedSymbols);
+ node.setProperty(NodeConstants.Info.EST_CARDINALITY, planCardinality);
+ root.addAsParent(semiJoin);
+ semiJoin.addLastChild(node);
+ PlanNode result = current.getParent();
+ NodeEditor.removeChildNode(result, current);
+ RuleImplementJoinStrategy.insertSort(semiJoin.getFirstChild(), (List<SingleElementSymbol>) plannedResult.leftExpressions, semiJoin, metadata, capFinder, true);
+ return result;
+ } catch (QueryPlannerException e) {
+ //can't be done - probably access patterns - what about dependent
+ return current;
+ }
+ }
+
+ public PlannedResult findSubquery(Criteria crit) throws TeiidComponentException, QueryMetadataException {
+ PlannedResult result = new PlannedResult();
+ if (crit instanceof SubquerySetCriteria) {
+ //convert to the quantified form
+ SubquerySetCriteria ssc = (SubquerySetCriteria)crit;
+ if (ssc.getSubqueryHint().isNoUnnest()) {
+ return result;
+ }
+ result.not ^= ssc.isNegated();
+ result.type = crit.getClass();
+ result.mergeJoin = ssc.getSubqueryHint().isMergeJoin();
+ result.makeInd = ssc.getSubqueryHint().isDepJoin();
+ if (!UNNEST && !result.mergeJoin) {
+ return result;
+ }
+ crit = new SubqueryCompareCriteria(ssc.getExpression(), ssc.getCommand(), SubqueryCompareCriteria.EQ, SubqueryCompareCriteria.SOME);
+ } else if (crit instanceof CompareCriteria) {
+ if (!UNNEST) {
+ return result;
+ }
+ //convert to the quantified form
+ CompareCriteria cc = (CompareCriteria)crit;
+ if (cc.getRightExpression() instanceof ScalarSubquery) {
+ ScalarSubquery ss = (ScalarSubquery)cc.getRightExpression();
+ result.type = ss.getClass();
+ //we can only use a semi-join if we know that 1 row will be present
+ if (ss.getCommand() instanceof Query) {
+ Query query = (Query)ss.getCommand();
+ if (query.getGroupBy() == null && query.hasAggregates()) {
+ crit = new SubqueryCompareCriteria(cc.getLeftExpression(), ss.getCommand(), cc.getOperator(), SubqueryCompareCriteria.SOME);
+ }
+ }
+ }
+ }
+ if (crit instanceof SubqueryCompareCriteria) {
+ SubqueryCompareCriteria scc = (SubqueryCompareCriteria)crit;
+
+ if (scc.getPredicateQuantifier() != SubqueryCompareCriteria.SOME
+ //TODO: could add an inline view if not a query
+ || !(scc.getCommand() instanceof Query)) {
+ return result;
+ }
+
+ Query query = (Query)scc.getCommand();
+ Expression rightExpr = SymbolMap.getExpression(query.getProjectedSymbols().get(0));
+
+ if (result.not && !isNonNull(query, rightExpr)) {
+ return result;
+ }
+ if (result.type == null) {
+ result.type = scc.getClass();
+ }
+ result.query = query;
+ result.additionalCritieria = (Criteria)new CompareCriteria(scc.getLeftExpression(), scc.getOperator(), rightExpr).clone();
+ }
+ if (crit instanceof ExistsCriteria) {
+ ExistsCriteria exists = (ExistsCriteria)crit;
+ if (exists.getSubqueryHint().isNoUnnest()) {
+ return result;
+ }
+ if (!(exists.getCommand() instanceof Query)) {
+ return result;
+ }
+ 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();
+ if (!UNNEST && !result.mergeJoin) {
+ return result;
+ }
+ }
+ return result;
+ }
+
+ private boolean isNonNull(Query query, Expression rightExpr)
+ throws TeiidComponentException, QueryMetadataException {
+ if (rightExpr instanceof ElementSymbol) {
+ ElementSymbol es = (ElementSymbol)rightExpr;
+ if (metadata.elementSupports(es.getMetadataID(), SupportConstants.Element.NULL)) {
+ return false;
+ }
+ if (!isSimpleJoin(query)) {
+ return false;
+ }
+ } else if (rightExpr instanceof Constant) {
+ if (((Constant)rightExpr).isNull()) {
+ return false;
+ }
+ } else if (rightExpr instanceof AggregateSymbol) {
+ AggregateSymbol as = (AggregateSymbol)rightExpr;
+ if (as.getAggregateFunction() != Type.COUNT) {
+ return false;
+ }
+ } else {
+ return false;
+ }
+ return true;
+ }
+
+ private boolean isSimpleJoin(Query query) {
+ if (query.getFrom() != null) {
+ for (FromClause clause : (List<FromClause>)query.getFrom().getClauses()) {
+ if (RuleCollapseSource.hasOuterJoins(clause)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ public boolean planQuery(Collection<GroupSymbol> leftGroups, boolean requireDistinct, PlannedResult plannedResult) throws QueryMetadataException, TeiidComponentException {
+ if ((plannedResult.query.getLimit() != null && !plannedResult.query.getLimit().isImplicit()) || plannedResult.query.getFrom() == null) {
+ return false;
+ }
+
+ if ((plannedResult.type == ExistsCriteria.class || plannedResult.type == ScalarSubquery.class) && plannedResult.query.getCorrelatedReferences() == null) {
+ //we can't really improve on this case
+ //TODO: do this check earlier
+ return false;
+ }
+
+ plannedResult.query = (Query)plannedResult.query.clone();
+ plannedResult.query.setLimit(null);
+
+ List<GroupSymbol> rightGroups = plannedResult.query.getFrom().getGroups();
+ Set<SingleElementSymbol> requiredExpressions = new LinkedHashSet<SingleElementSymbol>();
+ final SymbolMap refs = plannedResult.query.getCorrelatedReferences();
+ boolean addGroupBy = false;
+ if (refs != null) {
+ boolean hasAggregates = plannedResult.query.hasAggregates();
+ Criteria where = plannedResult.query.getCriteria();
+ if (plannedResult.query.getGroupBy() == null) {
+ plannedResult.query.setCriteria(null);
+ }
+ Criteria having = plannedResult.query.getHaving();
+ plannedResult.query.setHaving(null);
+ if (hasCorrelatedReferences(plannedResult.query, refs)) {
+ return false;
+ }
+ if (plannedResult.query.getGroupBy() == null) {
+ processCriteria(leftGroups, plannedResult, rightGroups, requiredExpressions, refs, where, true);
+ if (hasAggregates) {
+ if (!plannedResult.nonEquiJoinCriteria.isEmpty()) {
+ return false;
+ }
+ addGroupBy = true;
+ }
+ }
+ processCriteria(leftGroups, plannedResult, rightGroups, requiredExpressions, refs, having, false);
+ }
+
+ if (plannedResult.additionalCritieria != null) {
+ RuleChooseJoinStrategy.separateCriteria(leftGroups, rightGroups, plannedResult.leftExpressions, plannedResult.rightExpressions, Criteria.separateCriteriaByAnd(plannedResult.additionalCritieria), plannedResult.nonEquiJoinCriteria);
+ }
+
+ if (plannedResult.leftExpressions.isEmpty()) {
+ return false;
+ }
+
+ plannedResult.leftExpressions = RuleChooseJoinStrategy.createExpressionSymbols(plannedResult.leftExpressions);
+ plannedResult.rightExpressions = RuleChooseJoinStrategy.createExpressionSymbols(plannedResult.rightExpressions);
+
+ if (requireDistinct && !addGroupBy && !isDistinct(plannedResult.query, plannedResult.rightExpressions, metadata)) {
+ if (!requiredExpressions.isEmpty()) {
+ return false;
+ }
+ plannedResult.query.getSelect().setDistinct(true);
+ plannedResult.madeDistinct = true;
+ }
+
+ if (addGroupBy) {
+ LinkedHashSet<SingleElementSymbol> groupingSymbols = new LinkedHashSet<SingleElementSymbol>();
+ ArrayList<SingleElementSymbol> aggs = new ArrayList<SingleElementSymbol>();
+ for (Expression expr : (List<Expression>)plannedResult.rightExpressions) {
+ AggregateSymbolCollectorVisitor.getAggregates(expr, aggs, groupingSymbols);
+ }
+ if (!groupingSymbols.isEmpty()) {
+ plannedResult.query.setGroupBy((GroupBy) new GroupBy(new ArrayList<SingleElementSymbol>(groupingSymbols)).clone());
+ }
+ }
+ HashSet<SingleElementSymbol> projectedSymbols = new HashSet<SingleElementSymbol>();
+ for (SingleElementSymbol ses : plannedResult.query.getProjectedSymbols()) {
+ if (ses instanceof AliasSymbol) {
+ ses = ((AliasSymbol)ses).getSymbol();
+ }
+ projectedSymbols.add(ses);
+ }
+ for (SingleElementSymbol ses : requiredExpressions) {
+ if (projectedSymbols.add(ses)) {
+ plannedResult.query.getSelect().addSymbol((SingleElementSymbol) ses.clone());
+ }
+ }
+ for (SingleElementSymbol ses : (List<SingleElementSymbol>)plannedResult.rightExpressions) {
+ if (projectedSymbols.add(ses)) {
+ plannedResult.query.getSelect().addSymbol((SingleElementSymbol)ses.clone());
+ }
+ }
+ return true;
+ }
+
+ private void processCriteria(Collection<GroupSymbol> leftGroups,
+ PlannedResult plannedResult, List<GroupSymbol> rightGroups,
+ Set<SingleElementSymbol> requiredExpressions, final SymbolMap refs,
+ Criteria joinCriteria, boolean where) {
+ if (joinCriteria == null) {
+ return;
+ }
+ List<Criteria> crits = Criteria.separateCriteriaByAnd((Criteria)joinCriteria.clone());
+
+ 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);
+ ReferenceReplacementVisitor emv = new ReferenceReplacementVisitor(refs);
+ DeepPostOrderNavigator.doVisit(conjunct, emv);
+ if (!emv.replacedAny) {
+ //if not correlated, then leave it on the query
+ critIter.remove();
+ if (where) {
+ plannedResult.query.setCriteria(Criteria.combineCriteria(plannedResult.query.getCriteria(), conjunct));
+ } else {
+ plannedResult.query.setHaving(Criteria.combineCriteria(plannedResult.query.getHaving(), conjunct));
+ }
+ } else {
+ requiredExpressions.addAll(aggregates);
+ requiredExpressions.addAll(elements);
+ }
+ }
+ RuleChooseJoinStrategy.separateCriteria(leftGroups, rightGroups, plannedResult.leftExpressions, plannedResult.rightExpressions, crits, plannedResult.nonEquiJoinCriteria);
+ }
+
+ public static boolean isDistinct(Query query, List<SingleElementSymbol> expressions, QueryMetadataInterface metadata)
+ throws QueryMetadataException, TeiidComponentException {
+ boolean distinct = false;
+ if (query.getGroupBy() != null) {
+ distinct = true;
+ for (SingleElementSymbol groupByExpr : (List<SingleElementSymbol>)query.getGroupBy().getSymbols()) {
+ if (!expressions.contains(groupByExpr)) {
+ distinct = false;
+ break;
+ }
+ }
+ }
+ if (distinct) {
+ return true;
+ }
+ HashSet<GroupSymbol> keyPreservingGroups = new HashSet<GroupSymbol>();
+ ResolverUtil.findKeyPreserved(query, keyPreservingGroups, metadata);
+ return NewCalculateCostUtil.usesKey(expressions, keyPreservingGroups, metadata, true);
+ }
+
+ private boolean hasCorrelatedReferences(LanguageObject object, SymbolMap correlatedReferences) {
+ Collection<Reference> references = ReferenceCollectorVisitor.getReferences(object);
+ for (Reference reference : references) {
+ if (correlatedReferences.asMap().containsKey(reference.getExpression())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public String toString() {
+ return "MergeCriteria"; //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlaceAccess.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlaceAccess.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlaceAccess.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,334 +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.optimizer.relational.rules;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-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.api.exception.query.QueryResolverException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.relational.OptimizerRule;
-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.resolver.util.ResolverUtil;
-import org.teiid.query.sql.lang.Insert;
-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.util.SymbolMap;
-import org.teiid.query.util.CommandContext;
-
-
-/**
- * This rule finds all SOURCE nodes and associates ACCESS patterns, ACCESS nodes, and aliases.
- */
-public final class RulePlaceAccess implements
- OptimizerRule {
-
- private static final String RECONTEXT_STRING = "__"; //$NON-NLS-1$
-
- public PlanNode execute(PlanNode plan,
- QueryMetadataInterface metadata,
- CapabilitiesFinder capFinder,
- RuleStack rules,
- AnalysisRecord analysisRecord,
- CommandContext context) throws QueryMetadataException,
- TeiidComponentException,
- QueryPlannerException {
-
- Set<String> groups = context.getGroups();
- if (groups == null) {
- groups = new HashSet<String>();
- context.setGroups(groups);
- }
-
- boolean[] addtionalRules = new boolean[2];
-
- for (PlanNode sourceNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE)) {
- addAccessNode(metadata, sourceNode, capFinder, addtionalRules);
- addAlias(sourceNode, groups, metadata);
- }
-
- if (addtionalRules[0]) {
- rules.addLast(RuleConstants.ACCESS_PATTERN_VALIDATION);
- }
- if (addtionalRules[1]) {
- rules.addLast(RuleConstants.VALIDATE_WHERE_ALL);
- }
- return plan;
- }
-
- /**
- * Adds a access node if the node is a source leaf node.
- *
- * @param metadata
- * @param sourceNode
- * @return true if the source node has an access pattern
- * @throws QueryMetadataException
- * @throws TeiidComponentException
- */
- private void addAccessNode(QueryMetadataInterface metadata,
- PlanNode sourceNode, CapabilitiesFinder finder, boolean[] additionalRules) throws QueryMetadataException,
- TeiidComponentException {
- boolean isInsert = false;
- Object req = sourceNode.getProperty(NodeConstants.Info.ATOMIC_REQUEST);
- if (req == null) {
- req = sourceNode.getProperty(NodeConstants.Info.NESTED_COMMAND);
- }
-
- if (sourceNode.getProperty(NodeConstants.Info.TABLE_FUNCTION) != null) {
- return;
- }
-
- if (req instanceof Insert) {
- isInsert = true;
- } else {
- PlanNode parent = sourceNode.getParent();
- if(parent.getType() == NodeConstants.Types.PROJECT && parent.getProperty(NodeConstants.Info.INTO_GROUP) != null) {
- isInsert = true;
- }
- }
-
- PlanNode apNode = sourceNode;
-
- if (sourceNode.getChildCount() == 0) {
- // Create the access node and insert
- PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- accessNode.addGroups(sourceNode.getGroups());
-
- copyDependentHints(sourceNode, accessNode);
-
- Object hint = sourceNode.removeProperty(NodeConstants.Info.IS_OPTIONAL);
- if (hint != null) {
- accessNode.setProperty(NodeConstants.Info.IS_OPTIONAL, hint);
- }
-
- Object modelId = sourceNode.removeProperty(NodeConstants.Info.MODEL_ID);
- if (modelId != null) {
- accessNode.setProperty(NodeConstants.Info.MODEL_ID, modelId);
- }
-
- // Insert
- sourceNode.addAsParent(accessNode);
-
- apNode = accessNode;
-
- // set hint as to if the model mandates a where clause
- for (GroupSymbol group : accessNode.getGroups()) {
- Object modelID = metadata.getModelID(group.getMetadataID());
- if (CapabilitiesUtil.requiresCriteria(modelID, metadata, finder)) {
- additionalRules[1] = true;
- break;
- }
- }
- }
-
- // Add access pattern(s), if any, as property of access node
- if (!isInsert && addAccessPatternsProperty(apNode, metadata)) {
- additionalRules[0] = true;
- }
- }
-
- /**
- * Ensures that the group is uniquely named within the current optimizer run
- *
- * @param sourceNode
- * @param groups
- * @param metadata
- * @throws QueryMetadataException
- * @throws TeiidComponentException
- * @throws QueryPlannerException
- */
- private void addAlias(PlanNode sourceNode,
- Set<String> groups,
- QueryMetadataInterface metadata) throws QueryMetadataException,
- TeiidComponentException,
- QueryPlannerException {
- // select with no from
- if (sourceNode.getGroups().isEmpty()) {
- return;
- }
-
- // insert, update, delete, create, etc.
- if (FrameUtil.getNonQueryCommand(sourceNode.getParent()) != null) {
- return;
- }
-
- PlanNode parentProject = NodeEditor.findParent(sourceNode, NodeConstants.Types.PROJECT);
-
- // the source over a project into cannot conflict with any other groups
- if (parentProject.hasProperty(NodeConstants.Info.INTO_GROUP)) {
- return;
- }
-
- GroupSymbol group = sourceNode.getGroups().iterator().next();
-
- if (groups.add(group.getName().toUpperCase())) {
- return; // this is the first instance of the group
- }
-
- List<PlanNode> childProjects = null;
- if (sourceNode.getChildCount() > 0) {
- childProjects = NodeEditor.findAllNodes(sourceNode.getFirstChild(),
- NodeConstants.Types.PROJECT,
- NodeConstants.Types.SOURCE);
- }
-
- GroupSymbol newGroup = recontextSymbol(group, groups);
-
- //the expressions in the map will all be element symbols
- Map<ElementSymbol, Expression> replacementSymbols = FrameUtil.buildSymbolMap(group, newGroup, metadata);
-
- FrameUtil.convertFrame(sourceNode, group, new HashSet<GroupSymbol>(Arrays.asList(newGroup)), replacementSymbols, metadata);
-
- // correct the lower symbol map
- if (childProjects != null) {
- SymbolMap symbolMap = (SymbolMap)sourceNode.getProperty(NodeConstants.Info.SYMBOL_MAP);
-
- SymbolMap replacementMap = new SymbolMap();
- for (Map.Entry<ElementSymbol, Expression> entry : symbolMap.asMap().entrySet()) {
- replacementMap.addMapping((ElementSymbol)replacementSymbols.get(entry.getKey()), entry.getValue());
- }
- sourceNode.setProperty(NodeConstants.Info.SYMBOL_MAP, replacementMap);
- }
-
- }
-
- /**
- * Creates a uniquely named group symbol given the old symbol
- *
- * @param oldSymbol
- * @param allUpperNames a set of all known groups in upper case
- * @return
- */
- public static GroupSymbol recontextSymbol(GroupSymbol oldSymbol,
- Set<String> allUpperNames) {
- // Create new unique name
- String oldName = oldSymbol.getName();
- int dotIndex = oldName.lastIndexOf("."); //$NON-NLS-1$
- if (dotIndex >= 0) {
- oldName = oldName.substring(dotIndex + 1);
- }
-
- int recontextNumber = 1;
- int recontextIndex = oldName.lastIndexOf(RECONTEXT_STRING);
- if (recontextIndex >= 0) {
- // Probably already been recontexted
- try {
- recontextNumber = Integer.parseInt(oldName.substring(recontextIndex + RECONTEXT_STRING.length())) + 1;
- oldName = oldName.substring(0, recontextIndex);
- } catch (Exception e) {
- // Ignore - ID must contain RECONTEXT_STRING already, so just append a new suffix
- }
- }
-
- // Ensure uniqueness within these frames
- String newName = null;
- do {
- newName = oldName + RECONTEXT_STRING + recontextNumber++;
- } while (!allUpperNames.add(newName.toUpperCase()));
-
- // Determine the definition
- String newDefinition = null;
- if (oldSymbol.getDefinition() == null) {
- newDefinition = oldSymbol.getName();
- } else {
- newDefinition = oldSymbol.getDefinition();
- }
-
- // Create the new symbol
- GroupSymbol newSymbol = oldSymbol.clone();
- newSymbol.setName(newName);
- newSymbol.setDefinition(newDefinition);
- return newSymbol;
- }
-
- static void copyDependentHints(PlanNode node,
- PlanNode copyTo) {
- // Copy the make dependent hint if necessary
- Object hint = node.getProperty(NodeConstants.Info.MAKE_DEP);
- if (hint != null) {
- copyTo.setProperty(NodeConstants.Info.MAKE_DEP, hint);
- }
- hint = node.getProperty(NodeConstants.Info.MAKE_NOT_DEP);
- if (hint != null) {
- copyTo.setProperty(NodeConstants.Info.MAKE_NOT_DEP, hint);
- }
- }
-
- /**
- * This method checks for access patterns and attaches those patterns as a property of the PlanNode. (The property will be a
- * Collection of Collections - each inner Collection will be the ElementSymbols comprising a single access pattern.)
- *
- * @param node
- * PlanNode
- * @param metadata
- * source of metadata
- * @throws QueryMetadataException
- * if there is an exception accessing metadata
- * @throws QueryResolverException
- * if the GroupSymbol of an atomic command cannot be resolved
- * @throws TeiidComponentException
- * indicating some unexpected non-business exception
- */
- static boolean addAccessPatternsProperty(final PlanNode node,
- final QueryMetadataInterface metadata) throws QueryMetadataException,
- TeiidComponentException {
-
- if (node.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
- return false;
- }
-
- // Each internal Collection is one access pattern
- List patternElements = ResolverUtil.getAccessPatternElementsInGroups(metadata, node.getGroups(), false);
-
- if (patternElements == null) {
- return false;
- }
- Collections.sort(patternElements);
- node.setProperty(NodeConstants.Info.ACCESS_PATTERNS, patternElements);
- return true;
- }
-
- /**
- * Return rule name
- *
- * @return Rule name
- */
- public String toString() {
- return "PlaceAccess"; //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlaceAccess.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlaceAccess.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlaceAccess.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlaceAccess.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,338 @@
+/*
+ * 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.relational.rules;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+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.api.exception.query.QueryResolverException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.relational.OptimizerRule;
+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.resolver.util.ResolverUtil;
+import org.teiid.query.sql.lang.Insert;
+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.util.SymbolMap;
+import org.teiid.query.util.CommandContext;
+
+
+/**
+ * This rule finds all SOURCE nodes and associates ACCESS patterns, ACCESS nodes, and aliases.
+ */
+public final class RulePlaceAccess implements
+ OptimizerRule {
+
+ private static final String RECONTEXT_STRING = "__"; //$NON-NLS-1$
+
+ public PlanNode execute(PlanNode plan,
+ QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder,
+ RuleStack rules,
+ AnalysisRecord analysisRecord,
+ CommandContext context) throws QueryMetadataException,
+ TeiidComponentException,
+ QueryPlannerException {
+
+ Set<String> groups = context.getGroups();
+ if (groups == null) {
+ groups = new HashSet<String>();
+ context.setGroups(groups);
+ }
+
+ boolean[] addtionalRules = new boolean[2];
+
+ for (PlanNode sourceNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE)) {
+ addAccessNode(metadata, sourceNode, capFinder, addtionalRules);
+ addAlias(sourceNode, groups, metadata);
+ }
+
+ if (addtionalRules[0]) {
+ rules.addLast(RuleConstants.ACCESS_PATTERN_VALIDATION);
+ }
+ if (addtionalRules[1]) {
+ rules.addLast(RuleConstants.VALIDATE_WHERE_ALL);
+ }
+ return plan;
+ }
+
+ /**
+ * Adds a access node if the node is a source leaf node.
+ *
+ * @param metadata
+ * @param sourceNode
+ * @return true if the source node has an access pattern
+ * @throws QueryMetadataException
+ * @throws TeiidComponentException
+ */
+ private void addAccessNode(QueryMetadataInterface metadata,
+ PlanNode sourceNode, CapabilitiesFinder finder, boolean[] additionalRules) throws QueryMetadataException,
+ TeiidComponentException {
+ boolean isInsert = false;
+ Object req = sourceNode.getProperty(NodeConstants.Info.ATOMIC_REQUEST);
+ if (req == null) {
+ req = sourceNode.getProperty(NodeConstants.Info.NESTED_COMMAND);
+ }
+
+ if (sourceNode.getProperty(NodeConstants.Info.TABLE_FUNCTION) != null) {
+ return;
+ }
+
+ if (req instanceof Insert) {
+ isInsert = true;
+ } else {
+ PlanNode parent = sourceNode.getParent();
+ if(parent.getType() == NodeConstants.Types.PROJECT && parent.getProperty(NodeConstants.Info.INTO_GROUP) != null) {
+ isInsert = true;
+ }
+ }
+
+ PlanNode apNode = sourceNode;
+
+ if (sourceNode.getChildCount() == 0) {
+ // Create the access node and insert
+ PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ accessNode.addGroups(sourceNode.getGroups());
+
+ copyDependentHints(sourceNode, accessNode);
+
+ Object hint = sourceNode.removeProperty(NodeConstants.Info.IS_OPTIONAL);
+ if (hint != null) {
+ accessNode.setProperty(NodeConstants.Info.IS_OPTIONAL, hint);
+ }
+
+ Object modelId = sourceNode.removeProperty(NodeConstants.Info.MODEL_ID);
+ if (modelId != null) {
+ accessNode.setProperty(NodeConstants.Info.MODEL_ID, modelId);
+ }
+
+ // Insert
+ sourceNode.addAsParent(accessNode);
+
+ apNode = accessNode;
+
+ // set hint as to if the model mandates a where clause
+ for (GroupSymbol group : accessNode.getGroups()) {
+ Object modelID = metadata.getModelID(group.getMetadataID());
+ if (CapabilitiesUtil.requiresCriteria(modelID, metadata, finder)) {
+ additionalRules[1] = true;
+ break;
+ }
+ }
+ }
+
+ // Add access pattern(s), if any, as property of access node
+ if (!isInsert && addAccessPatternsProperty(apNode, metadata)) {
+ additionalRules[0] = true;
+ }
+ }
+
+ /**
+ * Ensures that the group is uniquely named within the current optimizer run
+ *
+ * @param sourceNode
+ * @param groups
+ * @param metadata
+ * @throws QueryMetadataException
+ * @throws TeiidComponentException
+ * @throws QueryPlannerException
+ */
+ private void addAlias(PlanNode sourceNode,
+ Set<String> groups,
+ QueryMetadataInterface metadata) throws QueryMetadataException,
+ TeiidComponentException,
+ QueryPlannerException {
+ // select with no from
+ if (sourceNode.getGroups().isEmpty()) {
+ return;
+ }
+
+ // insert, update, delete, create, etc.
+ if (FrameUtil.getNonQueryCommand(sourceNode.getParent()) != null) {
+ return;
+ }
+
+ PlanNode parentProject = NodeEditor.findParent(sourceNode, NodeConstants.Types.PROJECT);
+
+ // the source over a project into cannot conflict with any other groups
+ if (parentProject.hasProperty(NodeConstants.Info.INTO_GROUP)) {
+ return;
+ }
+
+ GroupSymbol group = sourceNode.getGroups().iterator().next();
+
+ if (groups.add(group.getName().toUpperCase())) {
+ return; // this is the first instance of the group
+ }
+
+ List<PlanNode> childProjects = null;
+ if (sourceNode.getChildCount() > 0) {
+ childProjects = NodeEditor.findAllNodes(sourceNode.getFirstChild(),
+ NodeConstants.Types.PROJECT,
+ NodeConstants.Types.SOURCE);
+ }
+
+ GroupSymbol newGroup = recontextSymbol(group, groups);
+
+ //the expressions in the map will all be element symbols
+ Map<ElementSymbol, Expression> replacementSymbols = FrameUtil.buildSymbolMap(group, newGroup, metadata);
+
+ FrameUtil.convertFrame(sourceNode, group, new HashSet<GroupSymbol>(Arrays.asList(newGroup)), replacementSymbols, metadata);
+
+ // correct the lower symbol map
+ if (childProjects != null) {
+ SymbolMap symbolMap = (SymbolMap)sourceNode.getProperty(NodeConstants.Info.SYMBOL_MAP);
+
+ SymbolMap replacementMap = new SymbolMap();
+ for (Map.Entry<ElementSymbol, Expression> entry : symbolMap.asMap().entrySet()) {
+ replacementMap.addMapping((ElementSymbol)replacementSymbols.get(entry.getKey()), entry.getValue());
+ }
+ sourceNode.setProperty(NodeConstants.Info.SYMBOL_MAP, replacementMap);
+ }
+
+ }
+
+ /**
+ * Creates a uniquely named group symbol given the old symbol
+ *
+ * @param oldSymbol
+ * @param allUpperNames a set of all known groups in upper case
+ * @return
+ */
+ public static GroupSymbol recontextSymbol(GroupSymbol oldSymbol,
+ Set<String> allUpperNames) {
+ // Create new unique name
+ String oldName = oldSymbol.getName();
+ int dotIndex = oldName.lastIndexOf("."); //$NON-NLS-1$
+ if (dotIndex >= 0) {
+ oldName = oldName.substring(dotIndex + 1);
+ }
+
+ int recontextNumber = 1;
+ int recontextIndex = oldName.lastIndexOf(RECONTEXT_STRING);
+ if (recontextIndex >= 0) {
+ // Probably already been recontexted
+ try {
+ recontextNumber = Integer.parseInt(oldName.substring(recontextIndex + RECONTEXT_STRING.length())) + 1;
+ oldName = oldName.substring(0, recontextIndex);
+ } catch (Exception e) {
+ // Ignore - ID must contain RECONTEXT_STRING already, so just append a new suffix
+ }
+ }
+
+ // Ensure uniqueness within these frames
+ String newName = null;
+ do {
+ newName = oldName + RECONTEXT_STRING + recontextNumber++;
+ } while (!allUpperNames.add(newName.toUpperCase()));
+
+ // Determine the definition
+ String newDefinition = null;
+ if (oldSymbol.getDefinition() == null) {
+ newDefinition = oldSymbol.getName();
+ } else {
+ newDefinition = oldSymbol.getDefinition();
+ }
+
+ // Create the new symbol
+ GroupSymbol newSymbol = oldSymbol.clone();
+ newSymbol.setName(newName);
+ newSymbol.setDefinition(newDefinition);
+ return newSymbol;
+ }
+
+ static void copyDependentHints(PlanNode node,
+ PlanNode copyTo) {
+ // Copy the make dependent hint if necessary
+ Object hint = node.getProperty(NodeConstants.Info.MAKE_DEP);
+ if (hint != null) {
+ copyTo.setProperty(NodeConstants.Info.MAKE_DEP, hint);
+ }
+ hint = node.getProperty(NodeConstants.Info.MAKE_NOT_DEP);
+ 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);
+ }
+ }
+
+ /**
+ * This method checks for access patterns and attaches those patterns as a property of the PlanNode. (The property will be a
+ * Collection of Collections - each inner Collection will be the ElementSymbols comprising a single access pattern.)
+ *
+ * @param node
+ * PlanNode
+ * @param metadata
+ * source of metadata
+ * @throws QueryMetadataException
+ * if there is an exception accessing metadata
+ * @throws QueryResolverException
+ * if the GroupSymbol of an atomic command cannot be resolved
+ * @throws TeiidComponentException
+ * indicating some unexpected non-business exception
+ */
+ static boolean addAccessPatternsProperty(final PlanNode node,
+ final QueryMetadataInterface metadata) throws QueryMetadataException,
+ TeiidComponentException {
+
+ if (node.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
+ return false;
+ }
+
+ // Each internal Collection is one access pattern
+ List patternElements = ResolverUtil.getAccessPatternElementsInGroups(metadata, node.getGroups(), false);
+
+ if (patternElements == null) {
+ return false;
+ }
+ Collections.sort(patternElements);
+ node.setProperty(NodeConstants.Info.ACCESS_PATTERNS, patternElements);
+ return true;
+ }
+
+ /**
+ * Return rule name
+ *
+ * @return Rule name
+ */
+ public String toString() {
+ return "PlaceAccess"; //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanJoins.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanJoins.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanJoins.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,610 +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.optimizer.relational.rules;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-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.TeiidComponentException;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.relational.OptimizerRule;
-import org.teiid.query.optimizer.relational.RuleStack;
-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.processor.relational.JoinNode.JoinStrategyType;
-import org.teiid.query.resolver.util.AccessPattern;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
-import org.teiid.query.util.CommandContext;
-import org.teiid.query.util.Permutation;
-import org.teiid.translator.ExecutionFactory.SupportedJoinCriteria;
-
-
-/**
- * Determines join orderings based upon dependency and cost information
- *
- * The algorithm works as follows:
- *
- * Stage 1. Find join regions. A join region is an set of inner and cross joins
- * (with the join and intermediate criteria removed).
- *
- * Dependency Phase
- *
- * Stage 2. Determine if dependencies found can be satisfied.
- * a. Throw an exception if a quick check fails.
- *
- * Stage 3. A satisfying set of access patterns and join ordering will be found
- * for each join region.
- * a. If this is not possible, an exception will be thrown
- * b. only one possible set of access patterns will be considered
- *
- * Optimization Phase
- *
- * Stage 4. Heuristically push joins down. Join regions (with more than one join source) will be
- * exhaustively searched (bottom up) for join pairs that can be pushed to a source.
- * a. A join is eligible for pushing if the access node can be raised and
- * there is at least one join criteria that can also be pushed.
- * -- costing information is not considered at this point.
- * b. Once a pair has been pushed, they will be replaced in the join region
- * with a single access node.
- *
- * Stage 5. The remaining join regions will be ordered in a left linear tree based
- * upon a an exhaustive, or random, algorithm that considers costing and criteria information.
- *
- */
-public class RulePlanJoins implements OptimizerRule {
-
- public static final int EXHAUSTIVE_SEARCH_GROUPS = 6;
-
- /**
- * @see org.teiid.query.optimizer.relational.OptimizerRule#execute(org.teiid.query.optimizer.relational.plantree.PlanNode, org.teiid.query.metadata.QueryMetadataInterface, org.teiid.query.optimizer.capabilities.CapabilitiesFinder, org.teiid.query.optimizer.relational.RuleStack, org.teiid.query.analysis.AnalysisRecord, org.teiid.query.util.CommandContext)
- */
- public PlanNode execute(PlanNode plan,
- QueryMetadataInterface metadata,
- CapabilitiesFinder capabilitiesFinder,
- RuleStack rules,
- AnalysisRecord analysisRecord,
- CommandContext context) throws QueryPlannerException,
- QueryMetadataException,
- TeiidComponentException {
-
-
-
- List<JoinRegion> joinRegions = new LinkedList<JoinRegion>();
-
- findJoinRegions(plan, null, joinRegions);
-
- //dependency phase
-
- for (Iterator<JoinRegion> joinRegionIter = joinRegions.iterator(); joinRegionIter.hasNext();) {
- JoinRegion joinRegion = joinRegionIter.next();
-
- //skip regions that have nothing to plan
- if (joinRegion.getJoinSourceNodes().size() + joinRegion.getDependentJoinSourceNodes().size() < 2) {
- joinRegionIter.remove();
- continue;
- }
-
- joinRegion.initializeJoinInformation();
-
- //account for nested table correlations
- for (PlanNode joinSource : joinRegion.getJoinSourceNodes().keySet()) {
- SymbolMap map = (SymbolMap)joinSource.getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
- if (map !=null) {
- joinSource.setProperty(NodeConstants.Info.REQUIRED_ACCESS_PATTERN_GROUPS, GroupsUsedByElementsVisitor.getGroups(map.getValues()));
- joinRegion.setContainsNestedTable(true);
- }
- }
-
- //check for unsatisfied dependencies
- if (joinRegion.getUnsatisfiedAccessPatterns().isEmpty()) {
- continue;
- }
-
- //quick check for satisfiability
- if (!joinRegion.isSatisfiable()) {
- throw new QueryPlannerException(QueryPlugin.Util.getString("RulePlanJoins.cantSatisfy", joinRegion.getUnsatisfiedAccessPatterns())); //$NON-NLS-1$
- }
-
- planForDependencies(joinRegion);
- }
-
- //optimization phase
- for (JoinRegion joinRegion : joinRegions) {
- groupJoinsForPushing(metadata, capabilitiesFinder, joinRegion, context);
- }
-
- for (Iterator<JoinRegion> joinRegionIter = joinRegions.iterator(); joinRegionIter.hasNext();) {
- JoinRegion joinRegion = joinRegionIter.next();
-
- //move the dependent nodes back into all joinSources
- joinRegion.getJoinSourceNodes().putAll(joinRegion.getDependentJoinSourceNodes());
- joinRegion.getCriteriaNodes().addAll(joinRegion.getDependentCriteriaNodes());
- joinRegion.getDependentJoinSourceNodes().clear();
- joinRegion.getDependentCriteriaNodes().clear();
-
- if (joinRegion.getJoinSourceNodes().size() < 2) {
- joinRegion.reconstructJoinRegoin();
- joinRegionIter.remove();
- continue;
- }
-
- joinRegion.initializeCostingInformation(metadata);
-
- Object[] bestOrder = findBestJoinOrder(joinRegion, metadata, capabilitiesFinder, context);
-
- //if no best order was found, just stick with how the user entered the query
- if (bestOrder == null) {
- continue;
- }
-
- joinRegion.changeJoinOrder(bestOrder);
- joinRegion.reconstructJoinRegoin();
- }
-
- return plan;
- }
-
- /**
- * This is a heuristic that checks for joins that may be pushed so they can be removed
- * before considering the joins that must be evaluated in MetaMatrix.
- *
- * By running this, we eliminate the need for running RuleRaiseAccess during join ordering
- *
- * @param metadata
- * @param joinRegion
- * @throws QueryMetadataException
- * @throws TeiidComponentException
- * @throws QueryPlannerException
- */
- private void groupJoinsForPushing(QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
- JoinRegion joinRegion, CommandContext context) throws QueryMetadataException,
- TeiidComponentException, QueryPlannerException {
- //TODO: consider moving select criteria if it is preventing a join from being pushed down
- //TODO: make the criteria checks based upon a guess at selectivity
-
- Map accessMap = getAccessMap(metadata, capFinder, joinRegion);
-
- boolean structureChanged = false;
-
- //search for combinations of join sources that should be pushed down
- for (Iterator accessNodeIter = accessMap.entrySet().iterator(); accessNodeIter.hasNext();) {
- Map.Entry entry = (Map.Entry)accessNodeIter.next();
-
- List<PlanNode> accessNodes = (List)entry.getValue();
-
- if (accessNodes.size() < 2) {
- continue;
- }
-
- for (int i = accessNodes.size() - 1; i >= 0; i--) {
-
- PlanNode accessNode1 = accessNodes.get(i);
-
- for (int k = accessNodes.size() - 1; k >= 0; k--) {
- if (k == i) {
- continue;
- }
-
- PlanNode accessNode2 = accessNodes.get(k);
-
- List<PlanNode> criteriaNodes = joinRegion.getCriteriaNodes();
-
- List<PlanNode> joinCriteriaNodes = new LinkedList<PlanNode>();
-
- /* hasJoinCriteria will be true if
- * 1. there is criteria between accessNode1 and accessNode2 exclusively
- * 2. there is criteria between some other source (not the same logical connector) and accessNode1 or accessNode2
- *
- * Ideally we should be a little smarter in case 2
- * - pushing down a same source cross join can be done if we know that a dependent join will be performed
- */
- boolean hasJoinCriteria = false;
- LinkedList<Criteria> joinCriteria = new LinkedList<Criteria>();
- Object modelId = RuleRaiseAccess.getModelIDFromAccess(accessNode1, metadata);
- SupportedJoinCriteria sjc = CapabilitiesUtil.getSupportedJoinCriteria(modelId, metadata, capFinder);
- for (PlanNode critNode : criteriaNodes) {
- Set<PlanNode> sources = joinRegion.getCritieriaToSourceMap().get(critNode);
-
- if (sources == null) {
- continue;
- }
-
- if (sources.contains(accessNode1)) {
- if (sources.contains(accessNode2) && sources.size() == 2) {
- Criteria crit = (Criteria)critNode.getProperty(NodeConstants.Info.SELECT_CRITERIA);
- if (RuleRaiseAccess.isSupportedJoinCriteria(sjc, crit, modelId, metadata, capFinder, null)) {
- joinCriteriaNodes.add(critNode);
- joinCriteria.add(crit);
- }
- } else if (!accessNodes.containsAll(sources)) {
- hasJoinCriteria = true;
- }
- } else if (sources.contains(accessNode2) && !accessNodes.containsAll(sources)) {
- hasJoinCriteria = true;
- }
- }
-
- /*
- * If we failed to find direct criteria, a cross join may still be acceptable
- */
- if (joinCriteriaNodes.isEmpty() && (hasJoinCriteria || !canPushCrossJoin(metadata, context, accessNode1, accessNode2))) {
- continue;
- }
-
- List<PlanNode> toTest = Arrays.asList(accessNode1, accessNode2);
-
- JoinType joinType = joinCriteria.isEmpty()?JoinType.JOIN_CROSS:JoinType.JOIN_INNER;
-
- //try to push to the source
- if (RuleRaiseAccess.canRaiseOverJoin(toTest, metadata, capFinder, joinCriteria, joinType, null) == null) {
- continue;
- }
-
- structureChanged = true;
-
- //remove the information that is no longer relevant to the join region
- joinRegion.getCritieriaToSourceMap().keySet().removeAll(joinCriteriaNodes);
- joinRegion.getCriteriaNodes().removeAll(joinCriteriaNodes);
- joinRegion.getJoinSourceNodes().remove(accessNode1);
- joinRegion.getJoinSourceNodes().remove(accessNode2);
- accessNodes.remove(i);
- accessNodes.remove(k < i ? k : k - 1);
-
- //build a new join node
- PlanNode joinNode = createJoinNode();
- joinNode.getGroups().addAll(accessNode1.getGroups());
- joinNode.getGroups().addAll(accessNode2.getGroups());
- joinNode.addFirstChild(accessNode2);
- joinNode.addLastChild(accessNode1);
- joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, joinType);
- joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, joinCriteria);
-
- PlanNode newAccess = RuleRaiseAccess.raiseAccessOverJoin(joinNode, entry.getKey(), false);
- for (PlanNode critNode : joinCriteriaNodes) {
- critNode.removeFromParent();
- critNode.removeAllChildren();
- }
-
- //update with the new source
-
- for (Set<PlanNode> source : joinRegion.getCritieriaToSourceMap().values()) {
- if (source.remove(accessNode1) || source.remove(accessNode2)) {
- source.add(newAccess);
- }
- }
-
- joinRegion.getJoinSourceNodes().put(newAccess, newAccess);
- accessNodes.add(newAccess);
- i = accessNodes.size();
- k = accessNodes.size();
- break;
- }
- }
- }
-
- if (structureChanged) {
- joinRegion.reconstructJoinRegoin();
- }
- }
-
- private boolean canPushCrossJoin(QueryMetadataInterface metadata, CommandContext context,
- PlanNode accessNode1, PlanNode accessNode2)
- throws QueryMetadataException, TeiidComponentException {
- float cost1 = NewCalculateCostUtil.computeCostForTree(accessNode1, metadata);
- float cost2 = NewCalculateCostUtil.computeCostForTree(accessNode2, metadata);
- float acceptableCost = context == null? 45.0f : (float)Math.sqrt(context.getProcessorBatchSize());
- return !((cost1 == -1 || cost2 == -1 || (cost1 > acceptableCost && cost2 > acceptableCost)));
- }
-
- /**
- * Return a map of Access Nodes to JoinSources that may be eligible for pushdown as
- * joins.
- */
- private Map getAccessMap(QueryMetadataInterface metadata,
- CapabilitiesFinder capFinder,
- JoinRegion joinRegion) throws QueryMetadataException,
- TeiidComponentException {
- Map accessMap = new HashMap();
-
- for (PlanNode node : joinRegion.getJoinSourceNodes().values()) {
- /* check to see if we are directly over an access node. in the event that the join source root
- * looks like select->access, we still won't consider this node for pushing
- */
- if (node.getType() != NodeConstants.Types.ACCESS) {
- continue;
- }
- Object accessModelID = RuleRaiseAccess.getModelIDFromAccess(node, metadata);
-
- if (accessModelID == null || !CapabilitiesUtil.supportsJoin(accessModelID, JoinType.JOIN_INNER, metadata, capFinder)) {
- continue;
- }
-
- RulePlanUnions.buildModelMap(metadata, capFinder, accessMap, node, accessModelID);
- }
- return accessMap;
- }
-
- /**
- * Greedily choose the first set of access patterns that can be satisfied
- * TODO: this is greedy. the first access pattern that can be satisfied will be
- * TODO: order access patterns by number of dependent groups
- *
- * If we could flatten to a single set of dependencies, then a topological sort would be faster
- *
- * @param joinRegion
- * @throws QueryPlannerException
- */
- private void planForDependencies(JoinRegion joinRegion) throws QueryPlannerException {
-
- if (joinRegion.getJoinSourceNodes().isEmpty()) {
- throw new QueryPlannerException(QueryPlugin.Util.getString("RulePlanJoins.cantSatisfy", joinRegion.getUnsatisfiedAccessPatterns())); //$NON-NLS-1$
- }
-
- HashSet<GroupSymbol> currentGroups = new HashSet<GroupSymbol>();
-
- for (PlanNode joinSource : joinRegion.getJoinSourceNodes().keySet()) {
- currentGroups.addAll(joinSource.getGroups());
- }
-
- HashMap<PlanNode, PlanNode> dependentNodes = new HashMap<PlanNode, PlanNode>(joinRegion.getDependentJoinSourceNodes());
-
- boolean satisfiedAP = true;
-
- while (!dependentNodes.isEmpty() && satisfiedAP) {
-
- satisfiedAP = false;
-
- for (Iterator<Map.Entry<PlanNode, PlanNode>> joinSources = dependentNodes.entrySet().iterator(); joinSources.hasNext();) {
- Map.Entry<PlanNode, PlanNode> entry = joinSources.next();
- PlanNode joinSource = entry.getKey();
-
- Collection accessPatterns = (Collection)joinSource.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
- for (Iterator i = accessPatterns.iterator(); i.hasNext();) {
- AccessPattern ap = (AccessPattern)i.next();
-
- boolean foundGroups = true;
- HashSet<GroupSymbol> allRequiredGroups = new HashSet<GroupSymbol>();
- for (ElementSymbol symbol : ap.getUnsatisfied()) {
- Set<Collection<GroupSymbol>> requiredGroupsSet = joinRegion.getDependentCriteriaElements().get(symbol);
- boolean elementSatisfied = false;
- if (requiredGroupsSet != null) {
- for (Collection<GroupSymbol> requiredGroups : requiredGroupsSet) {
- if (currentGroups.containsAll(requiredGroups)) {
- elementSatisfied = true;
- allRequiredGroups.addAll(requiredGroups);
- break;
- }
- }
- }
- if (!elementSatisfied) {
- foundGroups = false;
- break;
- }
- }
-
- if (!foundGroups) {
- continue;
- }
-
- joinSources.remove();
- satisfiedAP = true;
- joinSource.setProperty(NodeConstants.Info.ACCESS_PATTERN_USED, ap.clone());
- joinSource.setProperty(NodeConstants.Info.REQUIRED_ACCESS_PATTERN_GROUPS, allRequiredGroups);
- break;
- }
- }
- }
-
- if (!dependentNodes.isEmpty()) {
- throw new QueryPlannerException(QueryPlugin.Util.getString("RulePlanJoins.cantSatisfy", joinRegion.getUnsatisfiedAccessPatterns())); //$NON-NLS-1$
- }
-
- }
-
- static PlanNode createJoinNode() {
- PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_CROSS);
- joinNode.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.NESTED_LOOP);
- return joinNode;
- }
-
- /**
- * Finds all regions of inner and cross joins
- *
- * Join regions have boundaries at source nodes, outer joins, and unsatisfied dependencies
- *
- * @param root
- * @param currentRegion
- * @param joinRegions
- */
- static void findJoinRegions(PlanNode root, JoinRegion currentRegion, List<JoinRegion> joinRegions) {
- switch (root.getType()) {
- case NodeConstants.Types.JOIN:
- {
- if (currentRegion == null) {
- currentRegion = new JoinRegion();
- joinRegions.add(currentRegion);
- }
- 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);
-
- if (treatJoinAsSource) {
- currentRegion.addJoinSourceNode(root);
- } else {
- currentRegion.addParentCriteria(root);
- currentRegion.addJoinCriteriaList((List)root.getProperty(NodeConstants.Info.JOIN_CRITERIA));
- }
-
- for (PlanNode child : root.getChildren()) {
- findJoinRegions(child, treatJoinAsSource?null:currentRegion, joinRegions);
- }
-
- return;
- }
- case NodeConstants.Types.SOURCE:
- {
- if (currentRegion != null) {
- currentRegion.addJoinSourceNode(root);
- }
- currentRegion = null;
- break;
- }
- case NodeConstants.Types.NULL:
- case NodeConstants.Types.ACCESS:
- {
- if (currentRegion != null) {
- currentRegion.addJoinSourceNode(root);
- }
- return;
- }
- }
- if (root.getChildCount() == 0) {
- return;
- }
- for (PlanNode child : root.getChildren()) {
- findJoinRegions(child, root.getChildCount()==1?currentRegion:null, joinRegions);
- }
- }
-
- /**
- * The scoring algorithm is partially exhaustive and partially greedy. For
- * regions up to the exhaustive search group size all possible left linear join
- * trees will be searched in O(n!) time.
- *
- * Beyond this number, every join will be determined greedily in O(n^2) time.
- *
- * TODO: this method together with scoreRegion have not been optimized
- *
- * @param region
- * @param metadata
- * @return
- * @throws QueryPlannerException
- */
- Object[] findBestJoinOrder(JoinRegion region, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, CommandContext context) throws QueryMetadataException, TeiidComponentException, QueryPlannerException {
- int regionCount = region.getJoinSourceNodes().size();
-
- List<Integer> orderList = new ArrayList<Integer>(regionCount);
- for(int i=0; i<regionCount; i++) {
- orderList.add(new Integer(i));
- }
-
- double bestSubScore = Double.MAX_VALUE;
- Object[] bestSubOrder = null;
-
- Permutation perms = new Permutation(orderList.toArray());
-
- int exhaustive = regionCount;
-
- //after 16 sources this will be completely greedy. before that it will try to strike a compromise between the exhaustive
- //and non-exhaustive searches
- if (regionCount > EXHAUSTIVE_SEARCH_GROUPS) {
- exhaustive = Math.max(2, EXHAUSTIVE_SEARCH_GROUPS - (int)Math.ceil(Math.sqrt((regionCount - EXHAUSTIVE_SEARCH_GROUPS))));
- }
-
- Iterator permIter = perms.generate(exhaustive);
-
- while(permIter.hasNext()) {
- Object[] order = (Object[]) permIter.next();
-
- double score = region.scoreRegion(order, 0, metadata, capFinder, context);
- if(score < bestSubScore) {
- bestSubScore = score;
- bestSubOrder = order;
- }
- }
-
- if (bestSubOrder == null) {
- return null;
- }
-
- if (regionCount <= exhaustive) {
- return bestSubOrder;
- }
-
- Integer[] result = new Integer[regionCount];
-
- //remove the joins that have already been placed
- for(int i=0; i<bestSubOrder.length; i++) {
- result[i] = (Integer)bestSubOrder[i];
- }
-
- while(!orderList.isEmpty()) {
-
- double bestPartialScore = Double.MAX_VALUE;
- List bestOrder = null;
-
- for (int i = 0; i < orderList.size(); i++) {
- Integer index = orderList.get(i);
-
- List order = new ArrayList(Arrays.asList(bestSubOrder));
- order.add(index);
-
- double partialScore = region.scoreRegion(order.toArray(), bestSubOrder.length, metadata, capFinder, context);
-
- if (partialScore < bestPartialScore) {
- bestPartialScore = partialScore;
- bestOrder = order;
- }
- }
-
- if (bestOrder == null) {
- return null;
- }
-
- Integer next = (Integer)bestOrder.get(bestOrder.size() - 1);
- result[regionCount - orderList.size()] = next;
- orderList.remove(next);
- bestSubOrder = bestOrder.toArray();
- }
-
- return result;
- }
-
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return "PlanJoins"; //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanJoins.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanJoins.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanJoins.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanJoins.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,610 @@
+/*
+ * 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.relational.rules;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+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.TeiidComponentException;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.relational.OptimizerRule;
+import org.teiid.query.optimizer.relational.RuleStack;
+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.processor.relational.JoinNode.JoinStrategyType;
+import org.teiid.query.resolver.util.AccessPattern;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
+import org.teiid.query.util.CommandContext;
+import org.teiid.query.util.Permutation;
+import org.teiid.translator.ExecutionFactory.SupportedJoinCriteria;
+
+
+/**
+ * Determines join orderings based upon dependency and cost information
+ *
+ * The algorithm works as follows:
+ *
+ * Stage 1. Find join regions. A join region is an set of inner and cross joins
+ * (with the join and intermediate criteria removed).
+ *
+ * Dependency Phase
+ *
+ * Stage 2. Determine if dependencies found can be satisfied.
+ * a. Throw an exception if a quick check fails.
+ *
+ * Stage 3. A satisfying set of access patterns and join ordering will be found
+ * for each join region.
+ * a. If this is not possible, an exception will be thrown
+ * b. only one possible set of access patterns will be considered
+ *
+ * Optimization Phase
+ *
+ * Stage 4. Heuristically push joins down. Join regions (with more than one join source) will be
+ * exhaustively searched (bottom up) for join pairs that can be pushed to a source.
+ * a. A join is eligible for pushing if the access node can be raised and
+ * there is at least one join criteria that can also be pushed.
+ * -- costing information is not considered at this point.
+ * b. Once a pair has been pushed, they will be replaced in the join region
+ * with a single access node.
+ *
+ * Stage 5. The remaining join regions will be ordered in a left linear tree based
+ * upon a an exhaustive, or random, algorithm that considers costing and criteria information.
+ *
+ */
+public class RulePlanJoins implements OptimizerRule {
+
+ public static final int EXHAUSTIVE_SEARCH_GROUPS = 6;
+
+ /**
+ * @see org.teiid.query.optimizer.relational.OptimizerRule#execute(org.teiid.query.optimizer.relational.plantree.PlanNode, org.teiid.query.metadata.QueryMetadataInterface, org.teiid.query.optimizer.capabilities.CapabilitiesFinder, org.teiid.query.optimizer.relational.RuleStack, org.teiid.query.analysis.AnalysisRecord, org.teiid.query.util.CommandContext)
+ */
+ public PlanNode execute(PlanNode plan,
+ QueryMetadataInterface metadata,
+ CapabilitiesFinder capabilitiesFinder,
+ RuleStack rules,
+ AnalysisRecord analysisRecord,
+ CommandContext context) throws QueryPlannerException,
+ QueryMetadataException,
+ TeiidComponentException {
+
+
+
+ List<JoinRegion> joinRegions = new LinkedList<JoinRegion>();
+
+ findJoinRegions(plan, null, joinRegions);
+
+ //dependency phase
+
+ for (Iterator<JoinRegion> joinRegionIter = joinRegions.iterator(); joinRegionIter.hasNext();) {
+ JoinRegion joinRegion = joinRegionIter.next();
+
+ //skip regions that have nothing to plan
+ if (joinRegion.getJoinSourceNodes().size() + joinRegion.getDependentJoinSourceNodes().size() < 2) {
+ joinRegionIter.remove();
+ continue;
+ }
+
+ joinRegion.initializeJoinInformation();
+
+ //account for nested table correlations
+ for (PlanNode joinSource : joinRegion.getJoinSourceNodes().keySet()) {
+ SymbolMap map = (SymbolMap)joinSource.getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
+ if (map !=null) {
+ joinSource.setProperty(NodeConstants.Info.REQUIRED_ACCESS_PATTERN_GROUPS, GroupsUsedByElementsVisitor.getGroups(map.getValues()));
+ joinRegion.setContainsNestedTable(true);
+ }
+ }
+
+ //check for unsatisfied dependencies
+ if (joinRegion.getUnsatisfiedAccessPatterns().isEmpty()) {
+ continue;
+ }
+
+ //quick check for satisfiability
+ if (!joinRegion.isSatisfiable()) {
+ throw new QueryPlannerException(QueryPlugin.Util.getString("RulePlanJoins.cantSatisfy", joinRegion.getUnsatisfiedAccessPatterns())); //$NON-NLS-1$
+ }
+
+ planForDependencies(joinRegion);
+ }
+
+ //optimization phase
+ for (JoinRegion joinRegion : joinRegions) {
+ groupJoinsForPushing(metadata, capabilitiesFinder, joinRegion, context);
+ }
+
+ for (Iterator<JoinRegion> joinRegionIter = joinRegions.iterator(); joinRegionIter.hasNext();) {
+ JoinRegion joinRegion = joinRegionIter.next();
+
+ //move the dependent nodes back into all joinSources
+ joinRegion.getJoinSourceNodes().putAll(joinRegion.getDependentJoinSourceNodes());
+ joinRegion.getCriteriaNodes().addAll(joinRegion.getDependentCriteriaNodes());
+ joinRegion.getDependentJoinSourceNodes().clear();
+ joinRegion.getDependentCriteriaNodes().clear();
+
+ if (joinRegion.getJoinSourceNodes().size() < 2) {
+ joinRegion.reconstructJoinRegoin();
+ joinRegionIter.remove();
+ continue;
+ }
+
+ joinRegion.initializeCostingInformation(metadata);
+
+ Object[] bestOrder = findBestJoinOrder(joinRegion, metadata, capabilitiesFinder, context);
+
+ //if no best order was found, just stick with how the user entered the query
+ if (bestOrder == null) {
+ continue;
+ }
+
+ joinRegion.changeJoinOrder(bestOrder);
+ joinRegion.reconstructJoinRegoin();
+ }
+
+ return plan;
+ }
+
+ /**
+ * This is a heuristic that checks for joins that may be pushed so they can be removed
+ * before considering the joins that must be evaluated in MetaMatrix.
+ *
+ * By running this, we eliminate the need for running RuleRaiseAccess during join ordering
+ *
+ * @param metadata
+ * @param joinRegion
+ * @throws QueryMetadataException
+ * @throws TeiidComponentException
+ * @throws QueryPlannerException
+ */
+ private void groupJoinsForPushing(QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
+ JoinRegion joinRegion, CommandContext context) throws QueryMetadataException,
+ TeiidComponentException, QueryPlannerException {
+ //TODO: consider moving select criteria if it is preventing a join from being pushed down
+ //TODO: make the criteria checks based upon a guess at selectivity
+
+ Map accessMap = getAccessMap(metadata, capFinder, joinRegion);
+
+ boolean structureChanged = false;
+
+ //search for combinations of join sources that should be pushed down
+ for (Iterator accessNodeIter = accessMap.entrySet().iterator(); accessNodeIter.hasNext();) {
+ Map.Entry entry = (Map.Entry)accessNodeIter.next();
+
+ List<PlanNode> accessNodes = (List)entry.getValue();
+
+ if (accessNodes.size() < 2) {
+ continue;
+ }
+
+ for (int i = accessNodes.size() - 1; i >= 0; i--) {
+
+ PlanNode accessNode1 = accessNodes.get(i);
+
+ for (int k = accessNodes.size() - 1; k >= 0; k--) {
+ if (k == i) {
+ continue;
+ }
+
+ PlanNode accessNode2 = accessNodes.get(k);
+
+ List<PlanNode> criteriaNodes = joinRegion.getCriteriaNodes();
+
+ List<PlanNode> joinCriteriaNodes = new LinkedList<PlanNode>();
+
+ /* hasJoinCriteria will be true if
+ * 1. there is criteria between accessNode1 and accessNode2 exclusively
+ * 2. there is criteria between some other source (not the same logical connector) and accessNode1 or accessNode2
+ *
+ * Ideally we should be a little smarter in case 2
+ * - pushing down a same source cross join can be done if we know that a dependent join will be performed
+ */
+ boolean hasJoinCriteria = false;
+ LinkedList<Criteria> joinCriteria = new LinkedList<Criteria>();
+ Object modelId = RuleRaiseAccess.getModelIDFromAccess(accessNode1, metadata);
+ SupportedJoinCriteria sjc = CapabilitiesUtil.getSupportedJoinCriteria(modelId, metadata, capFinder);
+ for (PlanNode critNode : criteriaNodes) {
+ Set<PlanNode> sources = joinRegion.getCritieriaToSourceMap().get(critNode);
+
+ if (sources == null) {
+ continue;
+ }
+
+ if (sources.contains(accessNode1)) {
+ if (sources.contains(accessNode2) && sources.size() == 2) {
+ Criteria crit = (Criteria)critNode.getProperty(NodeConstants.Info.SELECT_CRITERIA);
+ if (RuleRaiseAccess.isSupportedJoinCriteria(sjc, crit, modelId, metadata, capFinder, null)) {
+ joinCriteriaNodes.add(critNode);
+ joinCriteria.add(crit);
+ }
+ } else if (!accessNodes.containsAll(sources)) {
+ hasJoinCriteria = true;
+ }
+ } else if (sources.contains(accessNode2) && !accessNodes.containsAll(sources)) {
+ hasJoinCriteria = true;
+ }
+ }
+
+ /*
+ * If we failed to find direct criteria, a cross join may still be acceptable
+ */
+ if (joinCriteriaNodes.isEmpty() && (hasJoinCriteria || !canPushCrossJoin(metadata, context, accessNode1, accessNode2))) {
+ continue;
+ }
+
+ List<PlanNode> toTest = Arrays.asList(accessNode1, accessNode2);
+
+ JoinType joinType = joinCriteria.isEmpty()?JoinType.JOIN_CROSS:JoinType.JOIN_INNER;
+
+ //try to push to the source
+ if (RuleRaiseAccess.canRaiseOverJoin(toTest, metadata, capFinder, joinCriteria, joinType, null) == null) {
+ continue;
+ }
+
+ structureChanged = true;
+
+ //remove the information that is no longer relevant to the join region
+ joinRegion.getCritieriaToSourceMap().keySet().removeAll(joinCriteriaNodes);
+ joinRegion.getCriteriaNodes().removeAll(joinCriteriaNodes);
+ joinRegion.getJoinSourceNodes().remove(accessNode1);
+ joinRegion.getJoinSourceNodes().remove(accessNode2);
+ accessNodes.remove(i);
+ accessNodes.remove(k < i ? k : k - 1);
+
+ //build a new join node
+ PlanNode joinNode = createJoinNode();
+ joinNode.getGroups().addAll(accessNode1.getGroups());
+ joinNode.getGroups().addAll(accessNode2.getGroups());
+ joinNode.addFirstChild(accessNode2);
+ joinNode.addLastChild(accessNode1);
+ joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, joinType);
+ joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, joinCriteria);
+
+ PlanNode newAccess = RuleRaiseAccess.raiseAccessOverJoin(joinNode, entry.getKey(), false);
+ for (PlanNode critNode : joinCriteriaNodes) {
+ critNode.removeFromParent();
+ critNode.removeAllChildren();
+ }
+
+ //update with the new source
+
+ for (Set<PlanNode> source : joinRegion.getCritieriaToSourceMap().values()) {
+ if (source.remove(accessNode1) || source.remove(accessNode2)) {
+ source.add(newAccess);
+ }
+ }
+
+ joinRegion.getJoinSourceNodes().put(newAccess, newAccess);
+ accessNodes.add(newAccess);
+ i = accessNodes.size();
+ k = accessNodes.size();
+ break;
+ }
+ }
+ }
+
+ if (structureChanged) {
+ joinRegion.reconstructJoinRegoin();
+ }
+ }
+
+ private boolean canPushCrossJoin(QueryMetadataInterface metadata, CommandContext context,
+ PlanNode accessNode1, PlanNode accessNode2)
+ throws QueryMetadataException, TeiidComponentException {
+ float cost1 = NewCalculateCostUtil.computeCostForTree(accessNode1, metadata);
+ float cost2 = NewCalculateCostUtil.computeCostForTree(accessNode2, metadata);
+ float acceptableCost = context == null? 45.0f : (float)Math.sqrt(context.getProcessorBatchSize());
+ return !((cost1 == -1 || cost2 == -1 || (cost1 > acceptableCost && cost2 > acceptableCost)));
+ }
+
+ /**
+ * Return a map of Access Nodes to JoinSources that may be eligible for pushdown as
+ * joins.
+ */
+ private Map getAccessMap(QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder,
+ JoinRegion joinRegion) throws QueryMetadataException,
+ TeiidComponentException {
+ Map accessMap = new HashMap();
+
+ for (PlanNode node : joinRegion.getJoinSourceNodes().values()) {
+ /* check to see if we are directly over an access node. in the event that the join source root
+ * looks like select->access, we still won't consider this node for pushing
+ */
+ if (node.getType() != NodeConstants.Types.ACCESS) {
+ continue;
+ }
+ Object accessModelID = RuleRaiseAccess.getModelIDFromAccess(node, metadata);
+
+ if (accessModelID == null || !CapabilitiesUtil.supportsJoin(accessModelID, JoinType.JOIN_INNER, metadata, capFinder)) {
+ continue;
+ }
+
+ RulePlanUnions.buildModelMap(metadata, capFinder, accessMap, node, accessModelID);
+ }
+ return accessMap;
+ }
+
+ /**
+ * Greedily choose the first set of access patterns that can be satisfied
+ * TODO: this is greedy. the first access pattern that can be satisfied will be
+ * TODO: order access patterns by number of dependent groups
+ *
+ * If we could flatten to a single set of dependencies, then a topological sort would be faster
+ *
+ * @param joinRegion
+ * @throws QueryPlannerException
+ */
+ private void planForDependencies(JoinRegion joinRegion) throws QueryPlannerException {
+
+ if (joinRegion.getJoinSourceNodes().isEmpty()) {
+ throw new QueryPlannerException(QueryPlugin.Util.getString("RulePlanJoins.cantSatisfy", joinRegion.getUnsatisfiedAccessPatterns())); //$NON-NLS-1$
+ }
+
+ HashSet<GroupSymbol> currentGroups = new HashSet<GroupSymbol>();
+
+ for (PlanNode joinSource : joinRegion.getJoinSourceNodes().keySet()) {
+ currentGroups.addAll(joinSource.getGroups());
+ }
+
+ HashMap<PlanNode, PlanNode> dependentNodes = new HashMap<PlanNode, PlanNode>(joinRegion.getDependentJoinSourceNodes());
+
+ boolean satisfiedAP = true;
+
+ while (!dependentNodes.isEmpty() && satisfiedAP) {
+
+ satisfiedAP = false;
+
+ for (Iterator<Map.Entry<PlanNode, PlanNode>> joinSources = dependentNodes.entrySet().iterator(); joinSources.hasNext();) {
+ Map.Entry<PlanNode, PlanNode> entry = joinSources.next();
+ PlanNode joinSource = entry.getKey();
+
+ Collection accessPatterns = (Collection)joinSource.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
+ for (Iterator i = accessPatterns.iterator(); i.hasNext();) {
+ AccessPattern ap = (AccessPattern)i.next();
+
+ boolean foundGroups = true;
+ HashSet<GroupSymbol> allRequiredGroups = new HashSet<GroupSymbol>();
+ for (ElementSymbol symbol : ap.getUnsatisfied()) {
+ Set<Collection<GroupSymbol>> requiredGroupsSet = joinRegion.getDependentCriteriaElements().get(symbol);
+ boolean elementSatisfied = false;
+ if (requiredGroupsSet != null) {
+ for (Collection<GroupSymbol> requiredGroups : requiredGroupsSet) {
+ if (currentGroups.containsAll(requiredGroups)) {
+ elementSatisfied = true;
+ allRequiredGroups.addAll(requiredGroups);
+ break;
+ }
+ }
+ }
+ if (!elementSatisfied) {
+ foundGroups = false;
+ break;
+ }
+ }
+
+ if (!foundGroups) {
+ continue;
+ }
+
+ joinSources.remove();
+ satisfiedAP = true;
+ joinSource.setProperty(NodeConstants.Info.ACCESS_PATTERN_USED, ap.clone());
+ joinSource.setProperty(NodeConstants.Info.REQUIRED_ACCESS_PATTERN_GROUPS, allRequiredGroups);
+ break;
+ }
+ }
+ }
+
+ if (!dependentNodes.isEmpty()) {
+ throw new QueryPlannerException(QueryPlugin.Util.getString("RulePlanJoins.cantSatisfy", joinRegion.getUnsatisfiedAccessPatterns())); //$NON-NLS-1$
+ }
+
+ }
+
+ static PlanNode createJoinNode() {
+ PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+ joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_CROSS);
+ joinNode.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.NESTED_LOOP);
+ return joinNode;
+ }
+
+ /**
+ * Finds all regions of inner and cross joins
+ *
+ * Join regions have boundaries at source nodes, outer joins, and unsatisfied dependencies
+ *
+ * @param root
+ * @param currentRegion
+ * @param joinRegions
+ */
+ static void findJoinRegions(PlanNode root, JoinRegion currentRegion, List<JoinRegion> joinRegions) {
+ switch (root.getType()) {
+ case NodeConstants.Types.JOIN:
+ {
+ if (currentRegion == null) {
+ currentRegion = new JoinRegion();
+ joinRegions.add(currentRegion);
+ }
+ 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) || root.hasProperty(NodeConstants.Info.MAKE_IND);
+
+ if (treatJoinAsSource) {
+ currentRegion.addJoinSourceNode(root);
+ } else {
+ currentRegion.addParentCriteria(root);
+ currentRegion.addJoinCriteriaList((List)root.getProperty(NodeConstants.Info.JOIN_CRITERIA));
+ }
+
+ for (PlanNode child : root.getChildren()) {
+ findJoinRegions(child, treatJoinAsSource?null:currentRegion, joinRegions);
+ }
+
+ return;
+ }
+ case NodeConstants.Types.SOURCE:
+ {
+ if (currentRegion != null) {
+ currentRegion.addJoinSourceNode(root);
+ }
+ currentRegion = null;
+ break;
+ }
+ case NodeConstants.Types.NULL:
+ case NodeConstants.Types.ACCESS:
+ {
+ if (currentRegion != null) {
+ currentRegion.addJoinSourceNode(root);
+ }
+ return;
+ }
+ }
+ if (root.getChildCount() == 0) {
+ return;
+ }
+ for (PlanNode child : root.getChildren()) {
+ findJoinRegions(child, root.getChildCount()==1?currentRegion:null, joinRegions);
+ }
+ }
+
+ /**
+ * The scoring algorithm is partially exhaustive and partially greedy. For
+ * regions up to the exhaustive search group size all possible left linear join
+ * trees will be searched in O(n!) time.
+ *
+ * Beyond this number, every join will be determined greedily in O(n^2) time.
+ *
+ * TODO: this method together with scoreRegion have not been optimized
+ *
+ * @param region
+ * @param metadata
+ * @return
+ * @throws QueryPlannerException
+ */
+ Object[] findBestJoinOrder(JoinRegion region, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, CommandContext context) throws QueryMetadataException, TeiidComponentException, QueryPlannerException {
+ int regionCount = region.getJoinSourceNodes().size();
+
+ List<Integer> orderList = new ArrayList<Integer>(regionCount);
+ for(int i=0; i<regionCount; i++) {
+ orderList.add(new Integer(i));
+ }
+
+ double bestSubScore = Double.MAX_VALUE;
+ Object[] bestSubOrder = null;
+
+ Permutation perms = new Permutation(orderList.toArray());
+
+ int exhaustive = regionCount;
+
+ //after 16 sources this will be completely greedy. before that it will try to strike a compromise between the exhaustive
+ //and non-exhaustive searches
+ if (regionCount > EXHAUSTIVE_SEARCH_GROUPS) {
+ exhaustive = Math.max(2, EXHAUSTIVE_SEARCH_GROUPS - (int)Math.ceil(Math.sqrt((regionCount - EXHAUSTIVE_SEARCH_GROUPS))));
+ }
+
+ Iterator permIter = perms.generate(exhaustive);
+
+ while(permIter.hasNext()) {
+ Object[] order = (Object[]) permIter.next();
+
+ double score = region.scoreRegion(order, 0, metadata, capFinder, context);
+ if(score < bestSubScore) {
+ bestSubScore = score;
+ bestSubOrder = order;
+ }
+ }
+
+ if (bestSubOrder == null) {
+ return null;
+ }
+
+ if (regionCount <= exhaustive) {
+ return bestSubOrder;
+ }
+
+ Integer[] result = new Integer[regionCount];
+
+ //remove the joins that have already been placed
+ for(int i=0; i<bestSubOrder.length; i++) {
+ result[i] = (Integer)bestSubOrder[i];
+ }
+
+ while(!orderList.isEmpty()) {
+
+ double bestPartialScore = Double.MAX_VALUE;
+ List bestOrder = null;
+
+ for (int i = 0; i < orderList.size(); i++) {
+ Integer index = orderList.get(i);
+
+ List order = new ArrayList(Arrays.asList(bestSubOrder));
+ order.add(index);
+
+ double partialScore = region.scoreRegion(order.toArray(), bestSubOrder.length, metadata, capFinder, context);
+
+ if (partialScore < bestPartialScore) {
+ bestPartialScore = partialScore;
+ bestOrder = order;
+ }
+ }
+
+ if (bestOrder == null) {
+ return null;
+ }
+
+ Integer next = (Integer)bestOrder.get(bestOrder.size() - 1);
+ result[regionCount - orderList.size()] = next;
+ orderList.remove(next);
+ bestSubOrder = bestOrder.toArray();
+ }
+
+ return result;
+ }
+
+ /**
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ return "PlanJoins"; //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushAggregates.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushAggregates.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushAggregates.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,883 +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.optimizer.relational.rules;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-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;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryPlannerException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.core.TeiidComponentException;
-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.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.resolver.util.ResolverUtil;
-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;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.OrderBy;
-import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.lang.SetQuery.Operation;
-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.Function;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.SearchedCaseExpression;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-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.ExpressionMappingVisitor;
-import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
-import org.teiid.query.util.CommandContext;
-import org.teiid.translator.SourceSystemFunctions;
-
-
-/**
- * @since 4.2
- */
-public class RulePushAggregates implements
- OptimizerRule {
-
- /**
- * @see org.teiid.query.optimizer.relational.OptimizerRule#execute(org.teiid.query.optimizer.relational.plantree.PlanNode,
- * org.teiid.query.metadata.QueryMetadataInterface, org.teiid.query.optimizer.capabilities.CapabilitiesFinder,
- * org.teiid.query.optimizer.relational.RuleStack, AnalysisRecord, CommandContext)
- * @since 4.2
- */
- public PlanNode execute(PlanNode plan,
- QueryMetadataInterface metadata,
- CapabilitiesFinder capFinder,
- RuleStack rules,
- AnalysisRecord analysisRecord,
- CommandContext context) throws QueryPlannerException,
- QueryMetadataException,
- TeiidComponentException {
-
- 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);
-
- if (child.getType() == NodeConstants.Types.SOURCE) {
- PlanNode setOp = child.getFirstChild();
-
- try {
- pushGroupNodeOverUnion(plan, metadata, capFinder, groupNode, child, groupingExpressions, setOp, context);
- } catch (QueryResolverException e) {
- throw new TeiidComponentException(e);
- }
- continue;
- }
-
- if (child.getType() != NodeConstants.Types.JOIN) {
- continue;
- }
-
- Set<AggregateSymbol> aggregates = collectAggregates(groupNode);
-
- pushGroupNode(groupNode, groupingExpressions, aggregates, metadata, capFinder);
- }
-
- return plan;
- }
-
- /**
- * The plan tree looks like:
- * group [agg(x), {a, b}]
- * source
- * set op
- * child 1
- * ...
- *
- * we need to make it into
- *
- * group [agg(agg(x)), {a, b}]
- * source
- * set op
- * project
- * [select]
- * group [agg(x), {a, b}]
- * source
- * child 1
- * ...
- *
- * 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
- * ...
- *
- */
- private void pushGroupNodeOverUnion(PlanNode plan,
- QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
- PlanNode groupNode, PlanNode child,
- List<SingleElementSymbol> groupingExpressions, PlanNode setOp, CommandContext context)
- 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
- }
- LinkedHashSet<AggregateSymbol> aggregates = collectAggregates(groupNode);
-
- Map<ElementSymbol, List<Set<Constant>>> partitionInfo = (Map<ElementSymbol, List<Set<Constant>>>)child.getProperty(Info.PARTITION_INFO);
-
- //check to see if any aggregate is dependent upon cardinality
- boolean cardinalityDependent = AggregateSymbol.areAggregatesCardinalityDependent(aggregates);
-
- LinkedList<PlanNode> unionChildren = new LinkedList<PlanNode>();
- findUnionChildren(unionChildren, cardinalityDependent, setOp);
-
- SymbolMap parentMap = (SymbolMap)child.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);
- return;
- }
-
- /*
- * if there are no aggregates, this is just duplicate removal
- * mark the union as not all, which should be removed later but
- * serves as a hint to distribute a distinct to the union queries
- */
- if (aggregates.isEmpty()) {
- if (groupingExpressions != null && !groupingExpressions.isEmpty()) {
- setOp.setProperty(NodeConstants.Info.USE_ALL, Boolean.FALSE);
- }
- return;
- }
-
- //TODO: merge virtual, plan unions, raise null - change the partition information
-
- if (unionChildren.size() < 2) {
- 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);
- pushdownList.add(pushdown);
- shouldPushdown |= pushdown;
- }
-
- if (!shouldPushdown) {
- return;
- }
-
- Iterator<Boolean> pushdownIterator = pushdownList.iterator();
- for (PlanNode planNode : unionChildren) {
- addView(plan, planNode, pushdownIterator.next(), groupingExpressions, aggregates, virtualElements, metadata, capFinder);
- }
-
- //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);
-
- //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);
- }
- 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 (Expression expr : aggMap.values()) {
- ExpressionMappingVisitor.mapExpressions(expr, projectedMap);
- }
- mapExpressions(groupNode.getParent(), aggMap, metadata);
- }
-
- private void decomposeGroupBy(PlanNode groupNode, PlanNode sourceNode,
- List<SingleElementSymbol> groupingExpressions,
- LinkedHashSet<AggregateSymbol> aggregates,
- LinkedList<PlanNode> unionChildren, SymbolMap parentMap, CommandContext context, QueryMetadataInterface metadata, CapabilitiesFinder capFinder) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
- // 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
- }
- }
- }
- GroupSymbol modifiedGroup = group.clone();
- SymbolMap symbolMap = createSymbolMap(modifiedGroup, symbols, sourceNode, metadata);
- sourceNode.setProperty(Info.SYMBOL_MAP, symbolMap);
-
- FrameUtil.convertFrame(sourceNode, group, Collections.singleton(modifiedGroup), symbolMap.inserseMapping(), metadata);
- }
-
- private boolean canPushGroupByToUnionChild(QueryMetadataInterface metadata,
- CapabilitiesFinder capFinder,
- List<SingleElementSymbol> groupingExpressions,
- LinkedHashSet<AggregateSymbol> aggregates, PlanNode planNode)
- throws QueryMetadataException, TeiidComponentException {
- if (planNode.getType() != NodeConstants.Types.ACCESS) {
- return false;
- }
- Object modelId = RuleRaiseAccess.getModelIDFromAccess(planNode, metadata);
- if (!CapabilitiesUtil.supports(Capability.QUERY_FROM_INLINE_VIEWS, modelId, metadata, capFinder)
- || !CapabilitiesUtil.supports(Capability.QUERY_GROUP_BY, modelId, metadata, capFinder)) {
- return false;
- }
- for (AggregateSymbol aggregate : aggregates) {
- if (!CapabilitiesUtil.supportsAggregateFunction(modelId, aggregate, metadata, capFinder)) {
- 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;
- }
-
- /**
- * Recursively searches the union tree for all applicable source nodes
- */
- static PlanNode findUnionChildren(List<PlanNode> unionChildren, boolean carinalityDependent, PlanNode setOp) {
- if (setOp.getType() != NodeConstants.Types.SET_OP || setOp.getProperty(NodeConstants.Info.SET_OPERATION) != Operation.UNION) {
- return setOp;
- }
-
- if (!setOp.hasBooleanProperty(NodeConstants.Info.USE_ALL)) {
- if (carinalityDependent) {
- return setOp;
- }
- setOp.setProperty(NodeConstants.Info.USE_ALL, Boolean.TRUE);
- }
-
- for (PlanNode planNode : setOp.getChildren()) {
- PlanNode child = findUnionChildren(unionChildren, carinalityDependent, planNode);
- if (child != null) {
- unionChildren.add(child);
- }
- }
-
- 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,
- List<? extends SingleElementSymbol> virtualElements,
- PlanNode child, QueryMetadataInterface metadata)
- throws TeiidComponentException, QueryMetadataException {
- TempMetadataStore store = new TempMetadataStore();
- TempMetadataAdapter tma = new TempMetadataAdapter(metadata, store);
- try {
- group.setMetadataID(ResolverUtil.addTempGroup(tma, group, virtualElements, false));
- } catch (QueryResolverException e) {
- throw new TeiidComponentException(e);
- }
- List<ElementSymbol> projectedSymbols = ResolverUtil.resolveElementsInGroup(group, metadata);
- SymbolMap symbolMap = SymbolMap.createSymbolMap(projectedSymbols,
- (List<Expression>)NodeEditor.findNodePreOrder(child, NodeConstants.Types.PROJECT).getProperty(NodeConstants.Info.PROJECT_COLS));
- 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.
- *
- * @param groupNode
- * @return the set of aggregate symbols found
- * @since 4.2
- */
- static LinkedHashSet<AggregateSymbol> collectAggregates(PlanNode groupNode) {
- LinkedHashSet<AggregateSymbol> aggregates = new LinkedHashSet<AggregateSymbol>();
- PlanNode currentNode = groupNode.getParent();
- 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));
- }
- break;
- }
- if (currentNode.getType() == NodeConstants.Types.SELECT) {
- Criteria crit = (Criteria)currentNode.getProperty(NodeConstants.Info.SELECT_CRITERIA);
- aggregates.addAll(AggregateSymbolCollectorVisitor.getAggregates(crit, true));
- }
-
- currentNode = currentNode.getParent();
- }
- return aggregates;
- }
-
- /**
- * Attempt to push the group node below one or more joins, manipulating the parent plan as necessary. This may involve
- * modifying symbols in parent nodes (to account for staged aggregates).
- * @throws QueryPlannerException
- *
- * @since 4.2
- */
- private void pushGroupNode(PlanNode groupNode,
- List<SingleElementSymbol> groupingExpressions,
- Set<AggregateSymbol> allAggregates,
- QueryMetadataInterface metadata,
- CapabilitiesFinder capFinder) 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);
-
- Set<PlanNode> possibleTargetNodes = new HashSet<PlanNode>(aggregateMap.keySet());
- possibleTargetNodes.addAll(groupingMap.keySet());
-
- for (PlanNode planNode : possibleTargetNodes) {
- Set<SingleElementSymbol> stagedGroupingSymbols = new LinkedHashSet<SingleElementSymbol>();
- List<AggregateSymbol> aggregates = aggregateMap.get(planNode);
- List<SingleElementSymbol> groupBy = groupingMap.get(planNode);
-
- if (!canPush(groupNode, stagedGroupingSymbols, planNode)) {
- continue;
- }
-
- if (groupBy != null) {
- stagedGroupingSymbols.addAll(groupBy);
- }
-
- collectSymbolsFromOtherAggregates(allAggregates, aggregates, planNode, stagedGroupingSymbols);
-
- //perform a costing check, if there's not a significant reduction, then don't stage
- float cardinality = NewCalculateCostUtil.computeCostForTree(planNode, metadata);
- float ndv = NewCalculateCostUtil.getNDVEstimate(planNode, metadata, cardinality, stagedGroupingSymbols, false);
- if (ndv != NewCalculateCostUtil.UNKNOWN_VALUE && cardinality / ndv < 4) {
- continue;
- }
-
- if (aggregates != null) {
- stageAggregates(groupNode, metadata, stagedGroupingSymbols, aggregates);
- } else {
- aggregates = new ArrayList<AggregateSymbol>(1);
- }
-
- if (aggregates.isEmpty() && stagedGroupingSymbols.isEmpty()) {
- continue;
- }
- //TODO: if aggregates is empty, then could insert a dup remove node instead
-
- PlanNode stageGroup = addGroupBy(planNode, stagedGroupingSymbols, aggregates);
-
- //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);
- if (stagedGroupingSymbols.isEmpty()) {
- RuleRaiseAccess.performRaise(null, stageGroup.getParent(), stageGroup.getParent().getParent());
- }
- }
- }
- }
-
- private PlanNode addGroupBy(PlanNode planNode,
- Collection<SingleElementSymbol> stagedGroupingSymbols,
- Collection<AggregateSymbol> aggregates) {
- 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 {
- // 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$
- aggregates.add(count); //consider the count aggregate for the push down call below
- selectNode.setProperty(NodeConstants.Info.SELECT_CRITERIA, new CompareCriteria(count, CompareCriteria.GT,
- new Constant(new Integer(0))));
- selectNode.setProperty(NodeConstants.Info.IS_HAVING, Boolean.TRUE);
- stageGroup.addAsParent(selectNode);
- }
- return stageGroup;
- }
-
- static void stageAggregates(PlanNode groupNode,
- QueryMetadataInterface metadata,
- Collection<SingleElementSymbol> stagedGroupingSymbols,
- Collection<AggregateSymbol> aggregates) 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)) {
- 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);
- }
- }
- }
-
- private void collectSymbolsFromOtherAggregates(Collection<AggregateSymbol> allAggregates,
- Collection<AggregateSymbol> aggregates,
- PlanNode current,
- Set<SingleElementSymbol> stagedGroupingSymbols) {
- Set<AggregateSymbol> otherAggs = new HashSet<AggregateSymbol>(allAggregates);
- if (aggregates != null) {
- otherAggs.removeAll(aggregates);
- }
-
- PlanNode source = FrameUtil.findJoinSourceNode(current);
-
- for (AggregateSymbol aggregateSymbol : otherAggs) {
- for (ElementSymbol symbol : ElementCollectorVisitor.getElements(aggregateSymbol, true)) {
- if (source.getGroups().contains(symbol.getGroupSymbol())) {
- stagedGroupingSymbols.add(symbol);
- }
- }
- }
- }
-
- /**
- * 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,
- PlanNode planNode) {
- PlanNode parentJoin = planNode.getParent();
-
- Set<GroupSymbol> groups = FrameUtil.findJoinSourceNode(planNode).getGroups();
-
- while (parentJoin != groupNode) {
- if (parentJoin.getType() != NodeConstants.Types.JOIN
- || parentJoin.hasCollectionProperty(NodeConstants.Info.NON_EQUI_JOIN_CRITERIA)
- || ((JoinType)parentJoin.getProperty(NodeConstants.Info.JOIN_TYPE)).isOuter()) {
- return false;
- }
-
- if (planNode == parentJoin.getFirstChild()) {
- if (parentJoin.hasCollectionProperty(NodeConstants.Info.LEFT_EXPRESSIONS) && !filterJoinColumns(stagedGroupingSymbols, groups, (List<SingleElementSymbol>)parentJoin.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS))) {
- return false;
- }
- } else {
- if (parentJoin.hasCollectionProperty(NodeConstants.Info.RIGHT_EXPRESSIONS) && !filterJoinColumns(stagedGroupingSymbols, groups, (List<SingleElementSymbol>)parentJoin.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS))) {
- return false;
- }
- }
-
- planNode = parentJoin;
- parentJoin = parentJoin.getParent();
- }
- return true;
- }
-
- private boolean filterJoinColumns(Set<SingleElementSymbol> stagedGroupingSymbols,
- Set<GroupSymbol> groups,
- List<SingleElementSymbol> symbols) {
- for (SingleElementSymbol singleElementSymbol : symbols) {
- if (!(singleElementSymbol instanceof ElementSymbol)) {
- return false;
- }
- if (groups.contains(((ElementSymbol)singleElementSymbol).getGroupSymbol())) {
- stagedGroupingSymbols.add(singleElementSymbol);
- }
- }
- return true;
- }
-
- private <T extends SingleElementSymbol> Map<PlanNode, List<T>> createNodeMapping(PlanNode groupNode,
- Collection<T> expressions, boolean aggs) {
- Map<PlanNode, List<T>> result = new HashMap<PlanNode, List<T>>();
- if (expressions == null) {
- return result;
- }
- for (T aggregateSymbol : expressions) {
- 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
- }
- Set<GroupSymbol> groups = GroupsUsedByElementsVisitor.getGroups(aggregateSymbol);
- if (groups.isEmpty()) {
- continue;
- }
- PlanNode originatingNode = FrameUtil.findOriginatingNode(groupNode, groups);
- if (originatingNode == null) {
- if (aggs) {
- return null; //should never happen
- }
- continue;
- }
-
- PlanNode parentAccess = NodeEditor.findParent(originatingNode, NodeConstants.Types.ACCESS, NodeConstants.Types.GROUP);
-
- if (parentAccess != null) {
- while (parentAccess.getType() == NodeConstants.Types.SELECT) {
- parentAccess = parentAccess.getParent();
- }
- originatingNode = parentAccess;
- }
-
- if (originatingNode.getParent() == groupNode) {
- //anything logically applied after the join and is
- //dependent upon the cardinality prevents us from optimizing.
- if (aggs && ((AggregateSymbol)aggregateSymbol).isCardinalityDependent()) {
- return null;
- }
- continue;
- }
-
- if (aggs && ((AggregateSymbol)aggregateSymbol).isDistinct()) {
- //TODO: support distinct
- continue;
- }
-
- List<T> symbols = result.get(originatingNode);
- if (symbols == null) {
- symbols = new LinkedList<T>();
- result.put(originatingNode, symbols);
- }
- symbols.add(aggregateSymbol);
- }
- return result;
- }
-
- 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>();
- for (SingleElementSymbol symbol : aggregateExpressions) {
- AggregateSymbol partitionAgg = (AggregateSymbol)symbol;
-
- Expression newExpression = null;
-
- Type aggFunction = partitionAgg.getAggregateFunction();
- 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);
-
- newExpression = convertFunc;
- nestedAggregates.add(partitionAgg);
- } else if (aggFunction == Type.AVG) {
- //AVG(x) -> SUM(SUM(x)) / SUM(COUNT(x))
- AggregateSymbol countAgg = new AggregateSymbol("stagedAgg", NonReserved.COUNT, false, partitionAgg.getExpression()); //$NON-NLS-1$
- AggregateSymbol sumAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, partitionAgg.getExpression()); //$NON-NLS-1$
-
- AggregateSymbol sumSumAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, sumAgg); //$NON-NLS-1$
- AggregateSymbol sumCountAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, countAgg); //$NON-NLS-1$
-
- Expression convertedSum = new Function(FunctionLibrary.CONVERT, new Expression[] {sumSumAgg, new Constant(DataTypeManager.getDataTypeName(partitionAgg.getType()))});
- Expression convertCount = new Function(FunctionLibrary.CONVERT, new Expression[] {sumCountAgg, new Constant(DataTypeManager.getDataTypeName(partitionAgg.getType()))});
-
- Function divideFunc = new Function("/", new Expression[] {convertedSum, convertCount}); //$NON-NLS-1$
- ResolverVisitor.resolveLanguageObject(divideFunc, metadata);
-
- newExpression = divideFunc;
- nestedAggregates.add(countAgg);
- nestedAggregates.add(sumAgg);
- } else if (partitionAgg.isEnhancedNumeric()) {
- //e.g. STDDEV_SAMP := CASE WHEN COUNT(X) > 1 THEN SQRT((SUM(X^2) - SUM(X)^2/COUNT(X))/(COUNT(X) - 1))
- AggregateSymbol countAgg = new AggregateSymbol("stagedAgg", NonReserved.COUNT, false, partitionAgg.getExpression()); //$NON-NLS-1$
- AggregateSymbol sumAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, partitionAgg.getExpression()); //$NON-NLS-1$
- AggregateSymbol sumSqAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, new Function(SourceSystemFunctions.POWER, new Expression[] {partitionAgg.getExpression(), new Constant(2)})); //$NON-NLS-1$
-
- AggregateSymbol sumSumAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, sumAgg); //$NON-NLS-1$
- AggregateSymbol sumCountAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, countAgg); //$NON-NLS-1$
- AggregateSymbol sumSumSqAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, sumSqAgg); //$NON-NLS-1$
-
- Expression convertedSum = new Function(FunctionLibrary.CONVERT, new Expression[] {sumSumAgg, new Constant(DataTypeManager.DefaultDataTypes.DOUBLE)});
-
- Function divideFunc = new Function(SourceSystemFunctions.DIVIDE_OP, new Expression[] {new Function(SourceSystemFunctions.POWER, new Expression[] {convertedSum, new Constant(2)}), sumCountAgg});
-
- Function minusFunc = new Function(SourceSystemFunctions.SUBTRACT_OP, new Expression[] {sumSumSqAgg, divideFunc});
- Expression divisor = null;
- if (aggFunction == Type.STDDEV_SAMP || aggFunction == Type.VAR_SAMP) {
- divisor = new Function(SourceSystemFunctions.SUBTRACT_OP, new Expression[] {sumCountAgg, new Constant(1)});
- } else {
- divisor = sumCountAgg;
- }
- Expression result = new Function(SourceSystemFunctions.DIVIDE_OP, new Expression[] {minusFunc, divisor});
- if (aggFunction == Type.STDDEV_POP || aggFunction == Type.STDDEV_SAMP) {
- result = new Function(SourceSystemFunctions.SQRT, new Expression[] {result});
- } else {
- result = new Function(FunctionLibrary.CONVERT, new Expression[] {result, new Constant(DataTypeManager.DefaultDataTypes.DOUBLE)});
- }
- Expression n = new Constant(0);
- if (aggFunction == Type.STDDEV_SAMP || aggFunction == Type.VAR_SAMP) {
- n = new Constant(1);
- }
- result = new SearchedCaseExpression(Arrays.asList(new CompareCriteria(sumCountAgg, CompareCriteria.GT, n)), Arrays.asList(result));
- ResolverVisitor.resolveLanguageObject(result, metadata);
-
- newExpression = result;
- nestedAggregates.add(countAgg);
- nestedAggregates.add(sumAgg);
- nestedAggregates.add(sumSqAgg);
- } else if (aggFunction == Type.TEXTAGG) {
- continue;
- }
- else {
- //AGG(X) -> AGG(AGG(X))
- newExpression = new AggregateSymbol("stagedAgg", aggFunction.name(), false, partitionAgg); //$NON-NLS-1$
- nestedAggregates.add(partitionAgg);
- }
-
- aggMap.put(partitionAgg, newExpression);
- }
- 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
- */
- public String toString() {
- return "PushAggregates"; //$NON-NLS-1$
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushAggregates.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushAggregates.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushAggregates.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushAggregates.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,883 @@
+/*
+ * 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.relational.rules;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+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;
+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.api.exception.query.QueryResolverException;
+import org.teiid.core.TeiidComponentException;
+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.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.resolver.util.ResolverUtil;
+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;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.SetQuery.Operation;
+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.Function;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.SearchedCaseExpression;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+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.ExpressionMappingVisitor;
+import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
+import org.teiid.query.util.CommandContext;
+import org.teiid.translator.SourceSystemFunctions;
+
+
+/**
+ * @since 4.2
+ */
+public class RulePushAggregates implements
+ OptimizerRule {
+
+ /**
+ * @see org.teiid.query.optimizer.relational.OptimizerRule#execute(org.teiid.query.optimizer.relational.plantree.PlanNode,
+ * org.teiid.query.metadata.QueryMetadataInterface, org.teiid.query.optimizer.capabilities.CapabilitiesFinder,
+ * org.teiid.query.optimizer.relational.RuleStack, AnalysisRecord, CommandContext)
+ * @since 4.2
+ */
+ public PlanNode execute(PlanNode plan,
+ QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder,
+ RuleStack rules,
+ AnalysisRecord analysisRecord,
+ CommandContext context) throws QueryPlannerException,
+ QueryMetadataException,
+ TeiidComponentException {
+
+ 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);
+
+ if (child.getType() == NodeConstants.Types.SOURCE) {
+ PlanNode setOp = child.getFirstChild();
+
+ try {
+ pushGroupNodeOverUnion(plan, metadata, capFinder, groupNode, child, groupingExpressions, setOp, context);
+ } catch (QueryResolverException e) {
+ throw new TeiidComponentException(e);
+ }
+ continue;
+ }
+
+ if (child.getType() != NodeConstants.Types.JOIN) {
+ continue;
+ }
+
+ Set<AggregateSymbol> aggregates = collectAggregates(groupNode);
+
+ pushGroupNode(groupNode, groupingExpressions, aggregates, metadata, capFinder);
+ }
+
+ return plan;
+ }
+
+ /**
+ * The plan tree looks like:
+ * group [agg(x), {a, b}]
+ * source
+ * set op
+ * child 1
+ * ...
+ *
+ * we need to make it into
+ *
+ * group [agg(agg(x)), {a, b}]
+ * source
+ * set op
+ * project
+ * [select]
+ * group [agg(x), {a, b}]
+ * source
+ * child 1
+ * ...
+ *
+ * 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
+ * ...
+ *
+ */
+ private void pushGroupNodeOverUnion(PlanNode plan,
+ QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
+ PlanNode groupNode, PlanNode child,
+ List<SingleElementSymbol> groupingExpressions, PlanNode setOp, CommandContext context)
+ 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
+ }
+ LinkedHashSet<AggregateSymbol> aggregates = collectAggregates(groupNode);
+
+ Map<ElementSymbol, List<Set<Constant>>> partitionInfo = (Map<ElementSymbol, List<Set<Constant>>>)child.getProperty(Info.PARTITION_INFO);
+
+ //check to see if any aggregate is dependent upon cardinality
+ boolean cardinalityDependent = AggregateSymbol.areAggregatesCardinalityDependent(aggregates);
+
+ LinkedList<PlanNode> unionChildren = new LinkedList<PlanNode>();
+ findUnionChildren(unionChildren, cardinalityDependent, setOp);
+
+ SymbolMap parentMap = (SymbolMap)child.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);
+ return;
+ }
+
+ /*
+ * if there are no aggregates, this is just duplicate removal
+ * mark the union as not all, which should be removed later but
+ * serves as a hint to distribute a distinct to the union queries
+ */
+ if (aggregates.isEmpty()) {
+ if (groupingExpressions != null && !groupingExpressions.isEmpty()) {
+ setOp.setProperty(NodeConstants.Info.USE_ALL, Boolean.FALSE);
+ }
+ return;
+ }
+
+ //TODO: merge virtual, plan unions, raise null - change the partition information
+
+ if (unionChildren.size() < 2) {
+ 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);
+ pushdownList.add(pushdown);
+ shouldPushdown |= pushdown;
+ }
+
+ if (!shouldPushdown) {
+ return;
+ }
+
+ Iterator<Boolean> pushdownIterator = pushdownList.iterator();
+ for (PlanNode planNode : unionChildren) {
+ addView(plan, planNode, pushdownIterator.next(), groupingExpressions, aggregates, virtualElements, metadata, capFinder);
+ }
+
+ //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);
+
+ //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);
+ }
+ 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 (Expression expr : aggMap.values()) {
+ ExpressionMappingVisitor.mapExpressions(expr, projectedMap);
+ }
+ mapExpressions(groupNode.getParent(), aggMap, metadata);
+ }
+
+ private void decomposeGroupBy(PlanNode groupNode, PlanNode sourceNode,
+ List<SingleElementSymbol> groupingExpressions,
+ LinkedHashSet<AggregateSymbol> aggregates,
+ LinkedList<PlanNode> unionChildren, SymbolMap parentMap, CommandContext context, QueryMetadataInterface metadata, CapabilitiesFinder capFinder) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+ // 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.getProjectedSymbols();
+ }
+ 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
+ }
+ }
+ }
+ GroupSymbol modifiedGroup = group.clone();
+ SymbolMap symbolMap = createSymbolMap(modifiedGroup, symbols, sourceNode, metadata);
+ sourceNode.setProperty(Info.SYMBOL_MAP, symbolMap);
+
+ FrameUtil.convertFrame(sourceNode, group, Collections.singleton(modifiedGroup), symbolMap.inserseMapping(), metadata);
+ }
+
+ private boolean canPushGroupByToUnionChild(QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder,
+ List<SingleElementSymbol> groupingExpressions,
+ LinkedHashSet<AggregateSymbol> aggregates, PlanNode planNode)
+ throws QueryMetadataException, TeiidComponentException {
+ if (planNode.getType() != NodeConstants.Types.ACCESS) {
+ return false;
+ }
+ Object modelId = RuleRaiseAccess.getModelIDFromAccess(planNode, metadata);
+ if (!CapabilitiesUtil.supports(Capability.QUERY_FROM_INLINE_VIEWS, modelId, metadata, capFinder)
+ || !CapabilitiesUtil.supports(Capability.QUERY_GROUP_BY, modelId, metadata, capFinder)) {
+ return false;
+ }
+ for (AggregateSymbol aggregate : aggregates) {
+ if (!CapabilitiesUtil.supportsAggregateFunction(modelId, aggregate, metadata, capFinder)) {
+ 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;
+ }
+
+ /**
+ * Recursively searches the union tree for all applicable source nodes
+ */
+ static PlanNode findUnionChildren(List<PlanNode> unionChildren, boolean carinalityDependent, PlanNode setOp) {
+ if (setOp.getType() != NodeConstants.Types.SET_OP || setOp.getProperty(NodeConstants.Info.SET_OPERATION) != Operation.UNION) {
+ return setOp;
+ }
+
+ if (!setOp.hasBooleanProperty(NodeConstants.Info.USE_ALL)) {
+ if (carinalityDependent) {
+ return setOp;
+ }
+ setOp.setProperty(NodeConstants.Info.USE_ALL, Boolean.TRUE);
+ }
+
+ for (PlanNode planNode : setOp.getChildren()) {
+ PlanNode child = findUnionChildren(unionChildren, carinalityDependent, planNode);
+ if (child != null) {
+ unionChildren.add(child);
+ }
+ }
+
+ 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(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,
+ List<? extends SingleElementSymbol> virtualElements,
+ PlanNode child, QueryMetadataInterface metadata)
+ throws TeiidComponentException, QueryMetadataException {
+ TempMetadataStore store = new TempMetadataStore();
+ TempMetadataAdapter tma = new TempMetadataAdapter(metadata, store);
+ try {
+ group.setMetadataID(ResolverUtil.addTempGroup(tma, group, virtualElements, false));
+ } catch (QueryResolverException e) {
+ throw new TeiidComponentException(e);
+ }
+ List<ElementSymbol> projectedSymbols = ResolverUtil.resolveElementsInGroup(group, metadata);
+ SymbolMap symbolMap = SymbolMap.createSymbolMap(projectedSymbols,
+ (List<Expression>)NodeEditor.findNodePreOrder(child, NodeConstants.Types.PROJECT).getProperty(NodeConstants.Info.PROJECT_COLS));
+ 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.
+ *
+ * @param groupNode
+ * @return the set of aggregate symbols found
+ * @since 4.2
+ */
+ static LinkedHashSet<AggregateSymbol> collectAggregates(PlanNode groupNode) {
+ LinkedHashSet<AggregateSymbol> aggregates = new LinkedHashSet<AggregateSymbol>();
+ PlanNode currentNode = groupNode.getParent();
+ 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));
+ }
+ break;
+ }
+ if (currentNode.getType() == NodeConstants.Types.SELECT) {
+ Criteria crit = (Criteria)currentNode.getProperty(NodeConstants.Info.SELECT_CRITERIA);
+ aggregates.addAll(AggregateSymbolCollectorVisitor.getAggregates(crit, true));
+ }
+
+ currentNode = currentNode.getParent();
+ }
+ return aggregates;
+ }
+
+ /**
+ * Attempt to push the group node below one or more joins, manipulating the parent plan as necessary. This may involve
+ * modifying symbols in parent nodes (to account for staged aggregates).
+ * @throws QueryPlannerException
+ *
+ * @since 4.2
+ */
+ private void pushGroupNode(PlanNode groupNode,
+ List<SingleElementSymbol> groupingExpressions,
+ Set<AggregateSymbol> allAggregates,
+ QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder) 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);
+
+ Set<PlanNode> possibleTargetNodes = new LinkedHashSet<PlanNode>(aggregateMap.keySet());
+ possibleTargetNodes.addAll(groupingMap.keySet());
+
+ for (PlanNode planNode : possibleTargetNodes) {
+ Set<SingleElementSymbol> stagedGroupingSymbols = new LinkedHashSet<SingleElementSymbol>();
+ List<AggregateSymbol> aggregates = aggregateMap.get(planNode);
+
+ if (!canPush(groupNode, stagedGroupingSymbols, planNode)) {
+ continue;
+ }
+
+ if (groupingExpressions != null) {
+ filterJoinColumns(stagedGroupingSymbols, planNode.getGroups(), groupingExpressions);
+ }
+
+ collectSymbolsFromOtherAggregates(allAggregates, aggregates, planNode, stagedGroupingSymbols);
+
+ //perform a costing check, if there's not a significant reduction, then don't stage
+ float cardinality = NewCalculateCostUtil.computeCostForTree(planNode, metadata);
+ float ndv = NewCalculateCostUtil.getNDVEstimate(planNode, metadata, cardinality, stagedGroupingSymbols, false);
+ if (ndv != NewCalculateCostUtil.UNKNOWN_VALUE && cardinality / ndv < 4) {
+ continue;
+ }
+
+ if (aggregates != null) {
+ stageAggregates(groupNode, metadata, stagedGroupingSymbols, aggregates);
+ } else {
+ aggregates = new ArrayList<AggregateSymbol>(1);
+ }
+
+ if (aggregates.isEmpty() && stagedGroupingSymbols.isEmpty()) {
+ continue;
+ }
+ //TODO: if aggregates is empty, then could insert a dup remove node instead
+
+ PlanNode stageGroup = addGroupBy(planNode, stagedGroupingSymbols, aggregates);
+
+ //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);
+ if (stagedGroupingSymbols.isEmpty()) {
+ RuleRaiseAccess.performRaise(null, stageGroup.getParent(), stageGroup.getParent().getParent());
+ }
+ }
+ }
+ }
+
+ private PlanNode addGroupBy(PlanNode planNode,
+ Collection<SingleElementSymbol> stagedGroupingSymbols,
+ Collection<AggregateSymbol> aggregates) {
+ 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 {
+ // 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$
+ aggregates.add(count); //consider the count aggregate for the push down call below
+ selectNode.setProperty(NodeConstants.Info.SELECT_CRITERIA, new CompareCriteria(count, CompareCriteria.GT,
+ new Constant(new Integer(0))));
+ selectNode.setProperty(NodeConstants.Info.IS_HAVING, Boolean.TRUE);
+ stageGroup.addAsParent(selectNode);
+ }
+ return stageGroup;
+ }
+
+ static void stageAggregates(PlanNode groupNode,
+ QueryMetadataInterface metadata,
+ Collection<SingleElementSymbol> stagedGroupingSymbols,
+ Collection<AggregateSymbol> aggregates) 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)) {
+ 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);
+ }
+ }
+ }
+
+ private void collectSymbolsFromOtherAggregates(Collection<AggregateSymbol> allAggregates,
+ Collection<AggregateSymbol> aggregates,
+ PlanNode current,
+ Set<SingleElementSymbol> stagedGroupingSymbols) {
+ Set<AggregateSymbol> otherAggs = new HashSet<AggregateSymbol>(allAggregates);
+ if (aggregates != null) {
+ otherAggs.removeAll(aggregates);
+ }
+
+ PlanNode source = FrameUtil.findJoinSourceNode(current);
+
+ for (AggregateSymbol aggregateSymbol : otherAggs) {
+ for (ElementSymbol symbol : ElementCollectorVisitor.getElements(aggregateSymbol, true)) {
+ if (source.getGroups().contains(symbol.getGroupSymbol())) {
+ stagedGroupingSymbols.add(symbol);
+ }
+ }
+ }
+ }
+
+ /**
+ * 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,
+ PlanNode planNode) {
+ PlanNode parentJoin = planNode.getParent();
+
+ Set<GroupSymbol> groups = FrameUtil.findJoinSourceNode(planNode).getGroups();
+
+ while (parentJoin != groupNode) {
+ if (parentJoin.getType() != NodeConstants.Types.JOIN
+ || parentJoin.hasCollectionProperty(NodeConstants.Info.NON_EQUI_JOIN_CRITERIA)
+ || ((JoinType)parentJoin.getProperty(NodeConstants.Info.JOIN_TYPE)).isOuter()) {
+ return false;
+ }
+
+ if (planNode == parentJoin.getFirstChild()) {
+ if (parentJoin.hasCollectionProperty(NodeConstants.Info.LEFT_EXPRESSIONS) && !filterJoinColumns(stagedGroupingSymbols, groups, (List<SingleElementSymbol>)parentJoin.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS))) {
+ return false;
+ }
+ } else {
+ if (parentJoin.hasCollectionProperty(NodeConstants.Info.RIGHT_EXPRESSIONS) && !filterJoinColumns(stagedGroupingSymbols, groups, (List<SingleElementSymbol>)parentJoin.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS))) {
+ return false;
+ }
+ }
+
+ planNode = parentJoin;
+ parentJoin = parentJoin.getParent();
+ }
+ return true;
+ }
+
+ private boolean filterJoinColumns(Set<SingleElementSymbol> stagedGroupingSymbols,
+ Set<GroupSymbol> groups,
+ List<SingleElementSymbol> symbols) {
+ for (SingleElementSymbol singleElementSymbol : symbols) {
+ if (!(singleElementSymbol instanceof ElementSymbol)) {
+ return false;
+ }
+ if (groups.contains(((ElementSymbol)singleElementSymbol).getGroupSymbol())) {
+ stagedGroupingSymbols.add(singleElementSymbol);
+ }
+ }
+ return true;
+ }
+
+ private <T extends SingleElementSymbol> Map<PlanNode, List<T>> createNodeMapping(PlanNode groupNode,
+ Collection<T> expressions, boolean aggs) {
+ Map<PlanNode, List<T>> result = new LinkedHashMap<PlanNode, List<T>>();
+ if (expressions == null) {
+ return result;
+ }
+ for (T aggregateSymbol : expressions) {
+ 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
+ }
+ Set<GroupSymbol> groups = GroupsUsedByElementsVisitor.getGroups(aggregateSymbol);
+ if (groups.isEmpty()) {
+ continue;
+ }
+ PlanNode originatingNode = FrameUtil.findOriginatingNode(groupNode, groups);
+ if (originatingNode == null) {
+ if (aggs) {
+ return null; //should never happen
+ }
+ continue;
+ }
+
+ PlanNode parentAccess = NodeEditor.findParent(originatingNode, NodeConstants.Types.ACCESS, NodeConstants.Types.GROUP);
+
+ if (parentAccess != null) {
+ while (parentAccess.getType() == NodeConstants.Types.SELECT) {
+ parentAccess = parentAccess.getParent();
+ }
+ originatingNode = parentAccess;
+ }
+
+ if (originatingNode.getParent() == groupNode) {
+ //anything logically applied after the join and is
+ //dependent upon the cardinality prevents us from optimizing.
+ if (aggs && ((AggregateSymbol)aggregateSymbol).isCardinalityDependent()) {
+ return null;
+ }
+ continue;
+ }
+
+ if (aggs && ((AggregateSymbol)aggregateSymbol).isDistinct()) {
+ //TODO: support distinct
+ continue;
+ }
+
+ List<T> symbols = result.get(originatingNode);
+ if (symbols == null) {
+ symbols = new LinkedList<T>();
+ result.put(originatingNode, symbols);
+ }
+ symbols.add(aggregateSymbol);
+ }
+ return result;
+ }
+
+ 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>();
+ for (SingleElementSymbol symbol : aggregateExpressions) {
+ AggregateSymbol partitionAgg = (AggregateSymbol)symbol;
+
+ Expression newExpression = null;
+
+ Type aggFunction = partitionAgg.getAggregateFunction();
+ 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);
+
+ newExpression = convertFunc;
+ nestedAggregates.add(partitionAgg);
+ } else if (aggFunction == Type.AVG) {
+ //AVG(x) -> SUM(SUM(x)) / SUM(COUNT(x))
+ AggregateSymbol countAgg = new AggregateSymbol("stagedAgg", NonReserved.COUNT, false, partitionAgg.getExpression()); //$NON-NLS-1$
+ AggregateSymbol sumAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, partitionAgg.getExpression()); //$NON-NLS-1$
+
+ AggregateSymbol sumSumAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, sumAgg); //$NON-NLS-1$
+ AggregateSymbol sumCountAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, countAgg); //$NON-NLS-1$
+
+ Expression convertedSum = new Function(FunctionLibrary.CONVERT, new Expression[] {sumSumAgg, new Constant(DataTypeManager.getDataTypeName(partitionAgg.getType()))});
+ Expression convertCount = new Function(FunctionLibrary.CONVERT, new Expression[] {sumCountAgg, new Constant(DataTypeManager.getDataTypeName(partitionAgg.getType()))});
+
+ Function divideFunc = new Function("/", new Expression[] {convertedSum, convertCount}); //$NON-NLS-1$
+ ResolverVisitor.resolveLanguageObject(divideFunc, metadata);
+
+ newExpression = divideFunc;
+ nestedAggregates.add(countAgg);
+ nestedAggregates.add(sumAgg);
+ } else if (partitionAgg.isEnhancedNumeric()) {
+ //e.g. STDDEV_SAMP := CASE WHEN COUNT(X) > 1 THEN SQRT((SUM(X^2) - SUM(X)^2/COUNT(X))/(COUNT(X) - 1))
+ AggregateSymbol countAgg = new AggregateSymbol("stagedAgg", NonReserved.COUNT, false, partitionAgg.getExpression()); //$NON-NLS-1$
+ AggregateSymbol sumAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, partitionAgg.getExpression()); //$NON-NLS-1$
+ AggregateSymbol sumSqAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, new Function(SourceSystemFunctions.POWER, new Expression[] {partitionAgg.getExpression(), new Constant(2)})); //$NON-NLS-1$
+
+ AggregateSymbol sumSumAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, sumAgg); //$NON-NLS-1$
+ AggregateSymbol sumCountAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, countAgg); //$NON-NLS-1$
+ AggregateSymbol sumSumSqAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, sumSqAgg); //$NON-NLS-1$
+
+ Expression convertedSum = new Function(FunctionLibrary.CONVERT, new Expression[] {sumSumAgg, new Constant(DataTypeManager.DefaultDataTypes.DOUBLE)});
+
+ Function divideFunc = new Function(SourceSystemFunctions.DIVIDE_OP, new Expression[] {new Function(SourceSystemFunctions.POWER, new Expression[] {convertedSum, new Constant(2)}), sumCountAgg});
+
+ Function minusFunc = new Function(SourceSystemFunctions.SUBTRACT_OP, new Expression[] {sumSumSqAgg, divideFunc});
+ Expression divisor = null;
+ if (aggFunction == Type.STDDEV_SAMP || aggFunction == Type.VAR_SAMP) {
+ divisor = new Function(SourceSystemFunctions.SUBTRACT_OP, new Expression[] {sumCountAgg, new Constant(1)});
+ } else {
+ divisor = sumCountAgg;
+ }
+ Expression result = new Function(SourceSystemFunctions.DIVIDE_OP, new Expression[] {minusFunc, divisor});
+ if (aggFunction == Type.STDDEV_POP || aggFunction == Type.STDDEV_SAMP) {
+ result = new Function(SourceSystemFunctions.SQRT, new Expression[] {result});
+ } else {
+ result = new Function(FunctionLibrary.CONVERT, new Expression[] {result, new Constant(DataTypeManager.DefaultDataTypes.DOUBLE)});
+ }
+ Expression n = new Constant(0);
+ if (aggFunction == Type.STDDEV_SAMP || aggFunction == Type.VAR_SAMP) {
+ n = new Constant(1);
+ }
+ result = new SearchedCaseExpression(Arrays.asList(new CompareCriteria(sumCountAgg, CompareCriteria.GT, n)), Arrays.asList(result));
+ ResolverVisitor.resolveLanguageObject(result, metadata);
+
+ newExpression = result;
+ nestedAggregates.add(countAgg);
+ nestedAggregates.add(sumAgg);
+ nestedAggregates.add(sumSqAgg);
+ } else if (aggFunction == Type.TEXTAGG) {
+ continue;
+ }
+ else {
+ //AGG(X) -> AGG(AGG(X))
+ newExpression = new AggregateSymbol("stagedAgg", aggFunction.name(), false, partitionAgg); //$NON-NLS-1$
+ nestedAggregates.add(partitionAgg);
+ }
+
+ aggMap.put(partitionAgg, newExpression);
+ }
+ 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
+ */
+ public String toString() {
+ return "PushAggregates"; //$NON-NLS-1$
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,858 +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.optimizer.relational.rules;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-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.language.SortSpecification.NullOrdering;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.SupportConstants;
-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.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.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.Criteria;
-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.SetQuery.Operation;
-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.GroupSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.util.CommandContext;
-import org.teiid.translator.ExecutionFactory.NullOrder;
-import org.teiid.translator.ExecutionFactory.SupportedJoinCriteria;
-
-
-public final class RuleRaiseAccess implements OptimizerRule {
-
- public PlanNode execute(PlanNode plan, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, RuleStack rules, AnalysisRecord analysisRecord, CommandContext context)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- boolean afterJoinPlanning = !rules.contains(RuleConstants.PLAN_JOINS);
-
- // Loop until nothing has been raised - plan is then stable and can be returned
- boolean raisedNode = true;
- while(raisedNode) {
- raisedNode = false;
-
- for (PlanNode accessNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.ACCESS)) {
- PlanNode newRoot = raiseAccessNode(plan, accessNode, metadata, capFinder, afterJoinPlanning, analysisRecord);
- if(newRoot != null) {
- raisedNode = true;
- plan = newRoot;
- }
- }
- }
-
- return plan;
- }
-
- /**
- * @return null if nothing changed, and a new plan root if something changed
- */
- static PlanNode raiseAccessNode(PlanNode rootNode, PlanNode accessNode, QueryMetadataInterface metadata,
- CapabilitiesFinder capFinder, boolean afterJoinPlanning, AnalysisRecord record)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- PlanNode parentNode = accessNode.getParent();
- if(parentNode == null) {
- // Nothing to raise over
- return null;
- }
- Object modelID = getModelIDFromAccess(accessNode, metadata);
- if(modelID == null) {
- return null;
- }
-
- switch(parentNode.getType()) {
- case NodeConstants.Types.JOIN:
- {
- modelID = canRaiseOverJoin(modelID, parentNode, metadata, capFinder, afterJoinPlanning, record);
- if(modelID != null) {
- raiseAccessOverJoin(parentNode, modelID, true);
- return rootNode;
- }
- return null;
- }
- case NodeConstants.Types.PROJECT:
- {
- // Check that the PROJECT contains only functions that can be pushed
- List projectCols = (List) parentNode.getProperty(NodeConstants.Info.PROJECT_COLS);
-
- for (int i = 0; i < projectCols.size(); i++) {
- SingleElementSymbol symbol = (SingleElementSymbol)projectCols.get(i);
- if(! canPushSymbol(symbol, true, modelID, metadata, capFinder, record)) {
- return null;
- }
- }
-
- /*
- * TODO: this creates an extraneous project node in many circumstances.
- * However we don't actually support project in this case, so allowing it to be pushed
- * causes problems with stored procedures and the assumptions made for proc/relational
- * planning.
- */
- if (FrameUtil.isProcedure(parentNode)) {
- return null;
- }
-
- return performRaise(rootNode, accessNode, parentNode);
- }
- case NodeConstants.Types.DUP_REMOVE:
- {
- // If model supports the support constant parameter, then move access node
- if(!CapabilitiesUtil.supportsSelectDistinct(modelID, metadata, capFinder)) {
- recordDebug("cannot push dupremove, since distinct is not supported by source", parentNode, record); //$NON-NLS-1$
- return null;
- }
-
- //TODO: this check is too specific the columns could be used in expressions that are comparable
- if (!CapabilitiesUtil.checkElementsAreSearchable((List)NodeEditor.findNodePreOrder(parentNode, NodeConstants.Types.PROJECT).getProperty(NodeConstants.Info.PROJECT_COLS), metadata, SupportConstants.Element.SEARCHABLE_COMPARE)) {
- recordDebug("cannot push dupremove, since not all columns are comparable at the source", parentNode, record); //$NON-NLS-1$
- return null;
- }
-
- return performRaise(rootNode, accessNode, parentNode);
- }
- case NodeConstants.Types.SORT:
- {
- if (canRaiseOverSort(accessNode, metadata, capFinder, parentNode, record, false)) {
- return performRaise(rootNode, accessNode, parentNode);
- }
- return null;
- }
- case NodeConstants.Types.GROUP:
- {
- Set<AggregateSymbol> aggregates = RulePushAggregates.collectAggregates(parentNode);
- if (canRaiseOverGroupBy(parentNode, accessNode, aggregates, metadata, capFinder, record)) {
- return performRaise(rootNode, accessNode, parentNode);
- }
- return null;
- }
- case NodeConstants.Types.SET_OP:
- if (!canRaiseOverSetQuery(parentNode, metadata, capFinder)) {
- return null;
- }
-
- for (PlanNode node : new ArrayList<PlanNode>(parentNode.getChildren())) {
- if (node == accessNode) {
- continue;
- }
- NodeEditor.removeChildNode(parentNode, node);
- }
- accessNode.getGroups().clear();
- return performRaise(rootNode, accessNode, parentNode);
- case NodeConstants.Types.SELECT:
- {
- if (parentNode.hasBooleanProperty(NodeConstants.Info.IS_DEPENDENT_SET)) {
- return null;
- }
- if (canRaiseOverSelect(accessNode, metadata, capFinder, parentNode, record)) {
- RulePushSelectCriteria.satisfyAccessPatterns(parentNode, accessNode);
- return performRaise(rootNode, accessNode, parentNode);
- }
- //determine if we should push the select back up
- if (parentNode.getParent() == null) {
- return null;
- }
- PlanNode selectRoot = parentNode;
- while (selectRoot.getParent() != null && selectRoot.getParent().getType() == NodeConstants.Types.SELECT) {
- selectRoot = selectRoot.getParent();
- }
- if (selectRoot.getParent() == null || (selectRoot.getParent().getType() & (NodeConstants.Types.PROJECT|NodeConstants.Types.GROUP)) == selectRoot.getParent().getType()) {
- return null;
- }
- PlanNode grandParent = selectRoot.getParent();
- boolean isLeft = false;
- isLeft = grandParent.getFirstChild() == selectRoot;
- if (grandParent.getType() == NodeConstants.Types.JOIN) {
- JoinType jt = (JoinType)grandParent.getProperty(NodeConstants.Info.JOIN_TYPE);
- if (jt == JoinType.JOIN_FULL_OUTER || (jt == JoinType.JOIN_LEFT_OUTER && !isLeft)) {
- return null;
- }
- }
- grandParent.removeChild(selectRoot);
- if (isLeft) {
- grandParent.addFirstChild(accessNode);
- } else {
- grandParent.addLastChild(accessNode);
- }
- PlanNode newParent = grandParent.getParent();
- //TODO: use costing or heuristics instead of always raising
- PlanNode newRoot = raiseAccessNode(rootNode, accessNode, metadata, capFinder, afterJoinPlanning, record);
- if (newRoot == null) {
- //return the tree to its original state
- parentNode.addFirstChild(accessNode);
- if (isLeft) {
- grandParent.addFirstChild(selectRoot);
- } else {
- grandParent.addLastChild(selectRoot);
- }
- } else {
- //attach the select nodes above the access node
- accessNode = grandParent.getParent();
- if (newParent != null) {
- isLeft = newParent.getFirstChild() == accessNode;
- if (isLeft) {
- newParent.addFirstChild(selectRoot);
- } else {
- newParent.addLastChild(selectRoot);
- }
- } else {
- newRoot = selectRoot;
- }
- parentNode.addFirstChild(accessNode);
- return newRoot;
- }
- return null;
- }
- case NodeConstants.Types.SOURCE:
- {
- //if a source has access patterns that are unsatisfied, then the raise cannot occur
- if (parentNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
- return null;
- }
-
- SymbolMap references = (SymbolMap)parentNode.getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
- if (references != null) {
- return null;
- }
-
- //raise only if there is no intervening project into
- PlanNode parentProject = NodeEditor.findParent(parentNode, NodeConstants.Types.PROJECT);
- GroupSymbol intoGroup = (GroupSymbol)parentProject.getProperty(NodeConstants.Info.INTO_GROUP);
- if (intoGroup != null && parentProject.getParent() == null) {
- if (CapabilitiesUtil.supports(Capability.INSERT_WITH_QUERYEXPRESSION, modelID, metadata, capFinder) && CapabilitiesUtil.isSameConnector(modelID, metadata.getModelID(intoGroup.getMetadataID()), metadata, capFinder)) {
- rootNode = performRaise(rootNode, accessNode, parentNode);
- return performRaise(rootNode, accessNode, parentProject);
- }
- return null;
- } else if (!CapabilitiesUtil.supportsInlineView(modelID, metadata, capFinder)) {
- return null;
- }
-
- //is there another query that will be used with this source
- if (FrameUtil.getNonQueryCommand(accessNode) != null || FrameUtil.getNestedPlan(accessNode) != null) {
- return null;
- }
-
- //switch to inline view and change the group on the access to that of the source
- parentNode.setProperty(NodeConstants.Info.INLINE_VIEW, Boolean.TRUE);
- accessNode.getGroups().clear();
- accessNode.addGroups(parentNode.getGroups());
- RulePlaceAccess.copyDependentHints(parentNode, accessNode);
- return performRaise(rootNode, accessNode, parentNode);
- }
- case NodeConstants.Types.TUPLE_LIMIT:
- {
- return RulePushLimit.raiseAccessOverLimit(rootNode, accessNode, metadata, capFinder, parentNode);
- }
- default:
- {
- return null;
- }
- }
- }
-
- static boolean canRaiseOverGroupBy(PlanNode groupNode,
- PlanNode accessNode,
- Collection<? extends SingleElementSymbol> aggregates,
- QueryMetadataInterface metadata,
- CapabilitiesFinder capFinder, AnalysisRecord record) throws QueryMetadataException,
- TeiidComponentException {
- Object modelID = getModelIDFromAccess(accessNode, metadata);
- if(modelID == null) {
- return false;
- }
- List<SingleElementSymbol> groupCols = (List<SingleElementSymbol>)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)) {
- return false;
- }
- }
- }
- if (aggregates != null) {
- for (SingleElementSymbol aggregateSymbol : aggregates) {
- if(! CriteriaCapabilityValidatorVisitor.canPushLanguageObject(aggregateSymbol, modelID, metadata, capFinder, record)) {
- return false;
- }
- }
- }
- return CapabilitiesUtil.checkElementsAreSearchable(groupCols, metadata, SupportConstants.Element.SEARCHABLE_COMPARE);
- }
-
- private static void recordDebug(String message, PlanNode node, AnalysisRecord record) {
- if (record != null && record.recordDebug()) {
- record.println(message + " " + node.nodeToString()); //$NON-NLS-1$
- }
- }
-
- static boolean canRaiseOverSort(PlanNode accessNode,
- QueryMetadataInterface metadata,
- CapabilitiesFinder capFinder,
- PlanNode parentNode, AnalysisRecord record, boolean compensateForUnrelated) throws QueryMetadataException,
- TeiidComponentException {
- // Find the model for this node by getting ACCESS node's model
- Object modelID = getModelIDFromAccess(accessNode, metadata);
- if(modelID == null) {
- // Couldn't determine model ID, so give up
- return false;
- }
-
- 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;
- }
- boolean supportsNullOrdering = CapabilitiesUtil.supports(Capability.QUERY_ORDERBY_NULL_ORDERING, modelID, metadata, capFinder);
- NullOrder defaultNullOrder = CapabilitiesUtil.getDefaultNullOrder(modelID, metadata, capFinder);
- if (symbol.getNullOrdering() != null) {
- if (!supportsNullOrdering) {
- if (symbol.getNullOrdering() == NullOrdering.FIRST) {
- if (defaultNullOrder != NullOrder.FIRST && !(symbol.isAscending() && defaultNullOrder == NullOrder.LOW)
- && !(!symbol.isAscending() && defaultNullOrder == NullOrder.HIGH)) {
- return false;
- }
- } else if (defaultNullOrder != NullOrder.LAST && !(symbol.isAscending() && defaultNullOrder == NullOrder.HIGH)
- && !(!symbol.isAscending() && defaultNullOrder == NullOrder.LOW)) {
- return false;
- }
- symbol.setNullOrdering(null);
- }
- } else if (supportsNullOrdering && defaultNullOrder != NullOrder.LOW) {
- //try to match the expected default of low
- if (symbol.isAscending()) {
- if (defaultNullOrder != NullOrder.FIRST) {
- symbol.setNullOrdering(NullOrdering.FIRST);
- }
- } else if (defaultNullOrder != NullOrder.LAST) {
- symbol.setNullOrdering(NullOrdering.LAST);
- }
- }
- }
-
- if (accessNode.getLastChild() != null) {
- //check to see if the sort applies to a union
- if (accessNode.getLastChild().getType() == NodeConstants.Types.SET_OP) {
- return CapabilitiesUtil.supportsSetQueryOrderBy(modelID, metadata, capFinder);
- }
- //check to see the plan is not in a consistent state to have a sort applied
- if (accessNode.getLastChild().getType() == NodeConstants.Types.TUPLE_LIMIT) {
- return false;
- }
- }
-
- if (!CapabilitiesUtil.checkElementsAreSearchable(sortCols, metadata, SupportConstants.Element.SEARCHABLE_COMPARE)) {
- return false;
- }
-
- // If model supports the support constant parameter, then move access node
- if (!CapabilitiesUtil.supportsOrderBy(modelID, metadata, capFinder)) {
- return false;
- }
-
- if (parentNode.hasBooleanProperty(NodeConstants.Info.UNRELATED_SORT)
- && !CapabilitiesUtil.supports(Capability.QUERY_ORDERBY_UNRELATED, modelID, metadata, capFinder)
- && NodeEditor.findParent(accessNode, NodeConstants.Types.PROJECT, NodeConstants.Types.SOURCE) == null
- && !compensateForUnrelated) {
- return false;
- }
-
- return true;
- }
-
- /**
- * @param accessNode
- * @param metadata
- * @param capFinder
- * @param parentNode
- * @return
- * @throws QueryMetadataException
- * @throws TeiidComponentException
- * @throws QueryPlannerException
- */
- static boolean canRaiseOverSelect(PlanNode accessNode,
- QueryMetadataInterface metadata,
- CapabilitiesFinder capFinder,
- PlanNode parentNode, AnalysisRecord record) throws QueryMetadataException,
- TeiidComponentException,
- QueryPlannerException {
- if (parentNode.hasBooleanProperty(NodeConstants.Info.IS_PHANTOM)) {
- return true;
- }
-
- // Find the model for this node by getting ACCESS node's model
- Object modelID = getModelIDFromAccess(accessNode, metadata);
- if(modelID == null) {
- // Couldn't determine model ID, so give up
- return false;
- }
-
- if (parentNode.hasBooleanProperty(NodeConstants.Info.IS_HAVING) && !CapabilitiesUtil.supports(Capability.QUERY_HAVING, modelID, metadata, capFinder)) {
- recordDebug("cannot push having, since having is not supported by source", parentNode, record); //$NON-NLS-1$
- return false;
- }
-
- //don't push criteria into an invalid location above an ordered limit - shouldn't happen
- PlanNode limitNode = NodeEditor.findNodePreOrder(accessNode, NodeConstants.Types.TUPLE_LIMIT, NodeConstants.Types.SOURCE);
- if (limitNode != null && FrameUtil.isOrderedLimit(limitNode)) {
- return false;
- }
-
- Criteria crit = (Criteria) parentNode.getProperty(NodeConstants.Info.SELECT_CRITERIA);
-
- if(!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(crit, modelID, metadata, capFinder, record) ) {
- return false;
- }
-
- if (accessNode.getFirstChild() != null && accessNode.getFirstChild().getType() == NodeConstants.Types.SET_OP) {
- return false; //inconsistent select position - RulePushSelectCriteria is too greedy
- }
-
- return true;
- }
-
- /**
- *
- * @param symbol Symbol to check
- * @param inSelectClause True if evaluating in the context of a SELECT clause
- * @param modelID Model
- * @param metadata Metadata
- * @param capFinder Capabilities finder
- * @return True if can push symbol to source
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- * @since 4.1.2
- */
- private static boolean canPushSymbol(SingleElementSymbol symbol, boolean inSelectClause, Object modelID,
- QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord record)
- throws TeiidComponentException, QueryMetadataException {
-
- Expression expr = SymbolMap.getExpression(symbol);
-
- // Do the normal checks
- if(! CriteriaCapabilityValidatorVisitor.canPushLanguageObject(expr, modelID, metadata, capFinder, record)) {
- return false;
- }
-
- if(inSelectClause && !(expr instanceof ElementSymbol || expr instanceof AggregateSymbol)
- && !CapabilitiesUtil.supportsSelectExpression(modelID, metadata, capFinder)) {
- return false;
- }
-
- // By default, no reason we can't push
- return true;
- }
-
- static PlanNode performRaise(PlanNode rootNode, PlanNode accessNode, PlanNode parentNode) {
- accessNode.removeProperty(NodeConstants.Info.EST_CARDINALITY);
- NodeEditor.removeChildNode(parentNode, accessNode);
- parentNode.addAsParent(accessNode);
- PlanNode grandparentNode = accessNode.getParent();
- if(grandparentNode != null) {
- return rootNode;
- }
- return accessNode;
- }
-
- /**
- * Determine whether an access node can be raised over the specified join node.
- *
- * This method can also be used to determine if a join node "A", parent of another join
- * node "B", will have it's access raised. This is needed to help determine if node
- * "B" will have access raised over it. In this scenario, the parameter will be true.
- * When this method is called normally from the "execute" method, that param will be false.
- *
- * @param joinNode Join node that might be pushed underneath the access node
- * @param metadata Metadata information
- * @param capFinder CapabilitiesFinder
- * @return The modelID if the raise can proceed and what common model these combined
- * nodes will be sent to
- */
- private static Object canRaiseOverJoin(Object modelId, PlanNode joinNode, QueryMetadataInterface metadata,
- CapabilitiesFinder capFinder, boolean afterJoinPlanning, AnalysisRecord record)
- throws QueryMetadataException, TeiidComponentException {
-
- List crits = (List) joinNode.getProperty(NodeConstants.Info.JOIN_CRITERIA);
- JoinType type = (JoinType) joinNode.getProperty(NodeConstants.Info.JOIN_TYPE);
-
- //let ruleplanjoins handle this case
- if (!afterJoinPlanning && type == JoinType.JOIN_CROSS && joinNode.getParent().getType() == NodeConstants.Types.JOIN) {
- JoinType jt = (JoinType)joinNode.getParent().getProperty(NodeConstants.Info.JOIN_TYPE);
- if (!jt.isOuter()) {
- return null;
- }
- }
-
- if (joinNode.getProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE) != null) {
- return null;
- }
-
- //if a join has access patterns that are unsatisfied, then the raise cannot occur
- if (joinNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
- return null;
- }
-
- //if I'm on the inner side of an outer join, then and we have a criteria restriction, then I can't be pushed
- if (type.isOuter() && CapabilitiesUtil.getSupportedJoinCriteria(modelId, metadata, capFinder) != SupportedJoinCriteria.ANY) {
- PlanNode critNode = NodeEditor.findNodePreOrder(joinNode.getLastChild(), NodeConstants.Types.SELECT, NodeConstants.Types.SOURCE);
- if (critNode != null) {
- return null;
- }
- if (type == JoinType.JOIN_FULL_OUTER) {
- critNode = NodeEditor.findNodePreOrder(joinNode.getFirstChild(), NodeConstants.Types.SELECT, NodeConstants.Types.SOURCE);
- if (critNode != null) {
- return null;
- }
- }
- }
-
- return canRaiseOverJoin(joinNode.getChildren(), metadata, capFinder, crits, type, record);
- }
-
- static Object canRaiseOverJoin(List<PlanNode> children,
- QueryMetadataInterface metadata,
- CapabilitiesFinder capFinder,
- List<Criteria> crits,
- JoinType type, AnalysisRecord record) throws QueryMetadataException,
- TeiidComponentException {
- //we only want to consider binary joins
- if (children.size() != 2) {
- return null;
- }
-
- Object modelID = null;
- Set<Object> groupIDs = new HashSet<Object>();
- int groupCount = 0;
- LinkedList<CompareCriteria> thetaCriteria = new LinkedList<CompareCriteria>();
- SupportedJoinCriteria sjc = null;
-
- for (PlanNode childNode : children) {
- if(childNode.getType() != NodeConstants.Types.ACCESS
- || childNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
- return null;
- }
- Object accessModelID = getModelIDFromAccess(childNode, metadata);
- if(accessModelID == null) {
- return null;
- }
-
- groupCount += childNode.getGroups().size();
-
- // Add all group metadata IDs to the list but check before each to make
- // sure group hasn't already been seen - if so, bail out - this is a self join
- // Unless model supports self joins, in which case, don't bail out.
-
- boolean supportsSelfJoins = CapabilitiesUtil.supportsSelfJoins(accessModelID, metadata, capFinder);
-
- if (!supportsSelfJoins) {
- for (GroupSymbol groupSymbol : childNode.getGroups()) {
- Object groupID = groupSymbol.getMetadataID();
- if(!groupIDs.add(groupID)) {
- // Already seen group - can't raise access over self join
- return null;
- }
- }
- }
-
- //check the join criteria now that we know the model
- if(modelID == null) {
-
- if (!CapabilitiesUtil.supportsJoin(accessModelID, type, metadata, capFinder)) {
- return null;
- }
- sjc = CapabilitiesUtil.getSupportedJoinCriteria(accessModelID, metadata, capFinder);
-
- /*
- * Key joins must be left linear
- */
- if (sjc == SupportedJoinCriteria.KEY && children.get(0).getGroups().size() != 1) {
- return null;
- }
-
- if(crits != null && !crits.isEmpty()) {
- for (Criteria crit : crits) {
- if (!isSupportedJoinCriteria(sjc, crit, accessModelID, metadata, capFinder, record)) {
- if (crit instanceof CompareCriteria) {
- CompareCriteria cc = (CompareCriteria) crit;
- if (cc.isOptional()) {
- cc.setOptional(true);
- continue;
- }
- }
- return null;
- } else if (crit instanceof CompareCriteria) {
- thetaCriteria.add((CompareCriteria)crit);
- }
- }
- if (sjc == SupportedJoinCriteria.KEY) {
- LinkedList<Expression> leftExpressions = new LinkedList<Expression>();
- LinkedList<Expression> rightExpressions = new LinkedList<Expression>();
- RuleChooseJoinStrategy.separateCriteria(children.get(0).getGroups(), children.get(1).getGroups(), leftExpressions, rightExpressions, crits, new LinkedList<Criteria>());
- ArrayList<Object> leftIds = new ArrayList<Object>(leftExpressions.size());
- ArrayList<Object> rightIds = new ArrayList<Object>(rightExpressions.size());
- for (Expression expr : leftExpressions) {
- if (expr instanceof ElementSymbol) {
- leftIds.add(((ElementSymbol) expr).getMetadataID());
- }
- }
- GroupSymbol rightGroup = null;
- for (Expression expr : rightExpressions) {
- if (expr instanceof ElementSymbol) {
- ElementSymbol es = (ElementSymbol) expr;
- if (rightGroup == null) {
- rightGroup = es.getGroupSymbol();
- } else if (!rightGroup.equals(es.getGroupSymbol())) {
- return null;
- }
- rightIds.add(es.getMetadataID());
- }
- }
- if (rightGroup == null) {
- return null;
- }
- if (!matchesForeignKey(metadata, leftIds, rightIds, children.get(0).getGroups().iterator().next(), true)
- && !matchesForeignKey(metadata, rightIds, leftIds, rightGroup, true)) {
- return null;
- }
- }
- } else if (sjc != SupportedJoinCriteria.ANY) {
- return null; //cross join not supported
- }
-
- modelID = accessModelID;
-
- } else if(!CapabilitiesUtil.isSameConnector(modelID, accessModelID, metadata, capFinder)) {
- return null;
- }
- } // end walking through join node's children
-
- int maxGroups = CapabilitiesUtil.getMaxFromGroups(modelID, metadata, capFinder);
-
- if (maxGroups != -1 && maxGroups < groupCount) {
- return null;
- }
-
- if (sjc == SupportedJoinCriteria.KEY) {
- for (CompareCriteria criteria : thetaCriteria) {
- criteria.setOptional(false);
- }
- } else {
- //TODO: this should be done in a less arbitrary way, and what about composite keys?
- boolean hasCriteria = false;
- for (CompareCriteria criteria : thetaCriteria) {
- if (criteria.getIsOptional() == null || (!hasCriteria && criteria.getIsOptional())) {
- criteria.setOptional(false);
- }
- hasCriteria = true;
- }
- }
-
- return modelID;
- }
-
- /**
- * Checks criteria one predicate at a time. Only tests up to the equi restriction.
- */
- static boolean isSupportedJoinCriteria(SupportedJoinCriteria sjc, Criteria crit, Object accessModelID,
- QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord record)
- throws QueryMetadataException, TeiidComponentException {
- if(!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(crit, accessModelID, metadata, capFinder, record) ) {
- return false;
- }
- if (sjc == SupportedJoinCriteria.ANY) {
- return true;
- }
- //theta join must be between elements with a compare predicate
- if (!(crit instanceof CompareCriteria)) {
- return false;
- }
- CompareCriteria cc = (CompareCriteria)crit;
- if (!(cc.getLeftExpression() instanceof ElementSymbol)) {
- return false;
- }
- if (!(cc.getRightExpression() instanceof ElementSymbol)) {
- return false;
- }
- if (sjc == SupportedJoinCriteria.THETA) {
- return true;
- }
- //equi must use the equality operator
- if (cc.getOperator() != CompareCriteria.EQ) {
- return false;
- }
- return true;
- }
-
- public static boolean matchesForeignKey(QueryMetadataInterface metadata,
- Collection<Object> leftIds, Collection<Object> rightIds, GroupSymbol leftGroup, boolean exact)
- throws TeiidComponentException, QueryMetadataException {
- Collection fks = metadata.getForeignKeysInGroup(leftGroup.getMetadataID());
- for (Object fk : fks) {
- List fkColumns = metadata.getElementIDsInKey(fk);
- if ((exact && leftIds.size() != fkColumns.size()) || !leftIds.containsAll(fkColumns)) {
- continue;
- }
- Object pk = metadata.getPrimaryKeyIDForForeignKeyID(fk);
- List pkColumns = metadata.getElementIDsInKey(pk);
- if ((!exact || rightIds.size() == pkColumns.size()) && rightIds.containsAll(pkColumns)) {
- return true;
- }
- }
- return false;
- }
-
- static PlanNode raiseAccessOverJoin(PlanNode joinNode, Object modelID, boolean insert) {
- PlanNode leftAccess = joinNode.getFirstChild();
- PlanNode rightAccess = joinNode.getLastChild();
-
- // Remove old access nodes - this will automatically add children of access nodes to join node
- NodeEditor.removeChildNode(joinNode, leftAccess);
- NodeEditor.removeChildNode(joinNode, rightAccess);
-
- //Set for later possible use, even though this isn't an access node
- joinNode.setProperty(NodeConstants.Info.MODEL_ID, modelID);
-
- // Insert new access node above join node
- PlanNode newAccess = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- newAccess.setProperty(NodeConstants.Info.MODEL_ID, modelID);
- newAccess.addGroups(rightAccess.getGroups());
- 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);
- }
- }
- RulePlaceAccess.copyDependentHints(leftAccess, newAccess);
- RulePlaceAccess.copyDependentHints(rightAccess, newAccess);
- RulePlaceAccess.copyDependentHints(joinNode, newAccess);
-
- if (insert) {
- joinNode.addAsParent(newAccess);
- } else {
- newAccess.addFirstChild(joinNode);
- }
-
- return newAccess;
- }
-
- /**
- * Get modelID for Access node and cache the result in the Access node.
- * @param accessNode Access node
- * @param metadata Metadata access
- * @return Object Model ID or null if not found.
- * @throws QueryMetadataException
- * @throws TeiidComponentException
- */
- static Object getModelIDFromAccess(PlanNode accessNode, QueryMetadataInterface metadata)
- throws QueryMetadataException, TeiidComponentException {
-
- Object accessModelID = accessNode.getProperty(NodeConstants.Info.MODEL_ID);
- if(accessModelID == null && accessNode.getGroups().size() > 0) {
- GroupSymbol group = accessNode.getGroups().iterator().next();
- if(metadata.isVirtualGroup(group.getMetadataID())) {
- return null;
- }
- accessModelID = metadata.getModelID(group.getMetadataID());
-
- accessNode.setProperty(NodeConstants.Info.MODEL_ID, accessModelID);
- }
-
- return accessModelID;
- }
-
- private static boolean canRaiseOverSetQuery(PlanNode setOpNode,
- QueryMetadataInterface metadata,
- CapabilitiesFinder capFinder) throws QueryMetadataException, TeiidComponentException {
-
- Object modelID = null;
-
- for (PlanNode childNode : setOpNode.getChildren()) {
- if(childNode.getType() != NodeConstants.Types.ACCESS) {
- return false;
- }
-
- if (FrameUtil.getNonQueryCommand(childNode) != null || FrameUtil.getNestedPlan(childNode) != null) {
- return false;
- }
-
- // Get model and check that it exists
- Object accessModelID = getModelIDFromAccess(childNode, metadata);
- if(accessModelID == null) {
- return false;
- }
-
- // Reconcile this access node's model ID with existing
- if(modelID == null) {
- modelID = accessModelID;
-
- if(! CapabilitiesUtil.supportsSetOp(accessModelID, (Operation)setOpNode.getProperty(NodeConstants.Info.SET_OPERATION), metadata, capFinder)) {
- return false;
- }
- } else if(!CapabilitiesUtil.isSameConnector(modelID, accessModelID, metadata, capFinder)) {
- return false;
- }
- if (!setOpNode.hasBooleanProperty(NodeConstants.Info.USE_ALL)
- && !CapabilitiesUtil.checkElementsAreSearchable((List)NodeEditor.findNodePreOrder(childNode, NodeConstants.Types.PROJECT).getProperty(NodeConstants.Info.PROJECT_COLS), metadata, SupportConstants.Element.SEARCHABLE_COMPARE)) {
- return false;
- }
-
- }
- return true;
- }
-
- public String toString() {
- return "RaiseAccess"; //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,864 @@
+/*
+ * 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.relational.rules;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+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.language.SortSpecification.NullOrdering;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.SupportConstants;
+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.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.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.Criteria;
+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.SetQuery.Operation;
+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.GroupSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.util.CommandContext;
+import org.teiid.translator.ExecutionFactory.NullOrder;
+import org.teiid.translator.ExecutionFactory.SupportedJoinCriteria;
+
+
+public final class RuleRaiseAccess implements OptimizerRule {
+
+ public PlanNode execute(PlanNode plan, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, RuleStack rules, AnalysisRecord analysisRecord, CommandContext context)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ boolean afterJoinPlanning = !rules.contains(RuleConstants.PLAN_JOINS);
+
+ // Loop until nothing has been raised - plan is then stable and can be returned
+ boolean raisedNode = true;
+ while(raisedNode) {
+ raisedNode = false;
+
+ for (PlanNode accessNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.ACCESS)) {
+ PlanNode newRoot = raiseAccessNode(plan, accessNode, metadata, capFinder, afterJoinPlanning, analysisRecord);
+ if(newRoot != null) {
+ raisedNode = true;
+ plan = newRoot;
+ }
+ }
+ }
+
+ return plan;
+ }
+
+ /**
+ * @return null if nothing changed, and a new plan root if something changed
+ */
+ static PlanNode raiseAccessNode(PlanNode rootNode, PlanNode accessNode, QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder, boolean afterJoinPlanning, AnalysisRecord record)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ PlanNode parentNode = accessNode.getParent();
+ if(parentNode == null) {
+ // Nothing to raise over
+ return null;
+ }
+ Object modelID = getModelIDFromAccess(accessNode, metadata);
+ if(modelID == null) {
+ return null;
+ }
+
+ switch(parentNode.getType()) {
+ case NodeConstants.Types.JOIN:
+ {
+ modelID = canRaiseOverJoin(modelID, parentNode, metadata, capFinder, afterJoinPlanning, record);
+ if(modelID != null) {
+ raiseAccessOverJoin(parentNode, modelID, true);
+ return rootNode;
+ }
+ return null;
+ }
+ case NodeConstants.Types.PROJECT:
+ {
+ // Check that the PROJECT contains only functions that can be pushed
+ List projectCols = (List) parentNode.getProperty(NodeConstants.Info.PROJECT_COLS);
+
+ for (int i = 0; i < projectCols.size(); i++) {
+ SingleElementSymbol symbol = (SingleElementSymbol)projectCols.get(i);
+ if(! canPushSymbol(symbol, true, modelID, metadata, capFinder, record)) {
+ return null;
+ }
+ }
+
+ /*
+ * TODO: this creates an extraneous project node in many circumstances.
+ * However we don't actually support project in this case, so allowing it to be pushed
+ * causes problems with stored procedures and the assumptions made for proc/relational
+ * planning.
+ */
+ if (FrameUtil.isProcedure(parentNode)) {
+ return null;
+ }
+
+ return performRaise(rootNode, accessNode, parentNode);
+ }
+ case NodeConstants.Types.DUP_REMOVE:
+ {
+ // If model supports the support constant parameter, then move access node
+ if(!CapabilitiesUtil.supportsSelectDistinct(modelID, metadata, capFinder)) {
+ recordDebug("cannot push dupremove, since distinct is not supported by source", parentNode, record); //$NON-NLS-1$
+ return null;
+ }
+
+ //TODO: this check is too specific the columns could be used in expressions that are comparable
+ if (!CapabilitiesUtil.checkElementsAreSearchable((List)NodeEditor.findNodePreOrder(parentNode, NodeConstants.Types.PROJECT).getProperty(NodeConstants.Info.PROJECT_COLS), metadata, SupportConstants.Element.SEARCHABLE_COMPARE)) {
+ recordDebug("cannot push dupremove, since not all columns are comparable at the source", parentNode, record); //$NON-NLS-1$
+ return null;
+ }
+
+ return performRaise(rootNode, accessNode, parentNode);
+ }
+ case NodeConstants.Types.SORT:
+ {
+ if (canRaiseOverSort(accessNode, metadata, capFinder, parentNode, record, false)) {
+ return performRaise(rootNode, accessNode, parentNode);
+ }
+ return null;
+ }
+ case NodeConstants.Types.GROUP:
+ {
+ Set<AggregateSymbol> aggregates = RulePushAggregates.collectAggregates(parentNode);
+ if (canRaiseOverGroupBy(parentNode, accessNode, aggregates, metadata, capFinder, record)) {
+ return performRaise(rootNode, accessNode, parentNode);
+ }
+ return null;
+ }
+ case NodeConstants.Types.SET_OP:
+ if (!canRaiseOverSetQuery(parentNode, metadata, capFinder)) {
+ return null;
+ }
+
+ for (PlanNode node : new ArrayList<PlanNode>(parentNode.getChildren())) {
+ if (node == accessNode) {
+ continue;
+ }
+ NodeEditor.removeChildNode(parentNode, node);
+ }
+ accessNode.getGroups().clear();
+ return performRaise(rootNode, accessNode, parentNode);
+ case NodeConstants.Types.SELECT:
+ {
+ if (parentNode.hasBooleanProperty(NodeConstants.Info.IS_DEPENDENT_SET)) {
+ return null;
+ }
+ if (canRaiseOverSelect(accessNode, metadata, capFinder, parentNode, record)) {
+ RulePushSelectCriteria.satisfyAccessPatterns(parentNode, accessNode);
+ return performRaise(rootNode, accessNode, parentNode);
+ }
+ //determine if we should push the select back up
+ if (parentNode.getParent() == null) {
+ return null;
+ }
+ PlanNode selectRoot = parentNode;
+ while (selectRoot.getParent() != null && selectRoot.getParent().getType() == NodeConstants.Types.SELECT) {
+ selectRoot = selectRoot.getParent();
+ }
+ if (selectRoot.getParent() == null || (selectRoot.getParent().getType() & (NodeConstants.Types.PROJECT|NodeConstants.Types.GROUP)) == selectRoot.getParent().getType()) {
+ return null;
+ }
+ PlanNode grandParent = selectRoot.getParent();
+ boolean isLeft = false;
+ isLeft = grandParent.getFirstChild() == selectRoot;
+ if (grandParent.getType() == NodeConstants.Types.JOIN) {
+ JoinType jt = (JoinType)grandParent.getProperty(NodeConstants.Info.JOIN_TYPE);
+ if (jt == JoinType.JOIN_FULL_OUTER || (jt == JoinType.JOIN_LEFT_OUTER && !isLeft)) {
+ return null;
+ }
+ }
+ grandParent.removeChild(selectRoot);
+ if (isLeft) {
+ grandParent.addFirstChild(accessNode);
+ } else {
+ grandParent.addLastChild(accessNode);
+ }
+ PlanNode newParent = grandParent.getParent();
+ //TODO: use costing or heuristics instead of always raising
+ PlanNode newRoot = raiseAccessNode(rootNode, accessNode, metadata, capFinder, afterJoinPlanning, record);
+ if (newRoot == null) {
+ //return the tree to its original state
+ parentNode.addFirstChild(accessNode);
+ if (isLeft) {
+ grandParent.addFirstChild(selectRoot);
+ } else {
+ grandParent.addLastChild(selectRoot);
+ }
+ } else {
+ //attach the select nodes above the access node
+ accessNode = grandParent.getParent();
+ if (newParent != null) {
+ isLeft = newParent.getFirstChild() == accessNode;
+ if (isLeft) {
+ newParent.addFirstChild(selectRoot);
+ } else {
+ newParent.addLastChild(selectRoot);
+ }
+ } else {
+ newRoot = selectRoot;
+ }
+ parentNode.addFirstChild(accessNode);
+ return newRoot;
+ }
+ return null;
+ }
+ case NodeConstants.Types.SOURCE:
+ {
+ //if a source has access patterns that are unsatisfied, then the raise cannot occur
+ if (parentNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
+ return null;
+ }
+
+ SymbolMap references = (SymbolMap)parentNode.getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
+ if (references != null) {
+ return null;
+ }
+
+ //raise only if there is no intervening project into
+ PlanNode parentProject = NodeEditor.findParent(parentNode, NodeConstants.Types.PROJECT);
+ GroupSymbol intoGroup = (GroupSymbol)parentProject.getProperty(NodeConstants.Info.INTO_GROUP);
+ if (intoGroup != null && parentProject.getParent() == null) {
+ if (CapabilitiesUtil.supports(Capability.INSERT_WITH_QUERYEXPRESSION, modelID, metadata, capFinder) && CapabilitiesUtil.isSameConnector(modelID, metadata.getModelID(intoGroup.getMetadataID()), metadata, capFinder)) {
+ rootNode = performRaise(rootNode, accessNode, parentNode);
+ return performRaise(rootNode, accessNode, parentProject);
+ }
+ return null;
+ } else if (!CapabilitiesUtil.supportsInlineView(modelID, metadata, capFinder)) {
+ return null;
+ }
+
+ //is there another query that will be used with this source
+ if (FrameUtil.getNonQueryCommand(accessNode) != null || FrameUtil.getNestedPlan(accessNode) != null) {
+ return null;
+ }
+
+ //switch to inline view and change the group on the access to that of the source
+ parentNode.setProperty(NodeConstants.Info.INLINE_VIEW, Boolean.TRUE);
+ accessNode.getGroups().clear();
+ accessNode.addGroups(parentNode.getGroups());
+ RulePlaceAccess.copyDependentHints(parentNode, accessNode);
+ return performRaise(rootNode, accessNode, parentNode);
+ }
+ case NodeConstants.Types.TUPLE_LIMIT:
+ {
+ return RulePushLimit.raiseAccessOverLimit(rootNode, accessNode, metadata, capFinder, parentNode);
+ }
+ default:
+ {
+ return null;
+ }
+ }
+ }
+
+ static boolean canRaiseOverGroupBy(PlanNode groupNode,
+ PlanNode accessNode,
+ Collection<? extends SingleElementSymbol> aggregates,
+ QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder, AnalysisRecord record) throws QueryMetadataException,
+ TeiidComponentException {
+ Object modelID = getModelIDFromAccess(accessNode, metadata);
+ if(modelID == null) {
+ return false;
+ }
+ List<SingleElementSymbol> groupCols = (List<SingleElementSymbol>)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)) {
+ return false;
+ }
+ }
+ }
+ if (aggregates != null) {
+ for (SingleElementSymbol aggregateSymbol : aggregates) {
+ if(! CriteriaCapabilityValidatorVisitor.canPushLanguageObject(aggregateSymbol, modelID, metadata, capFinder, record)) {
+ return false;
+ }
+ }
+ }
+ return CapabilitiesUtil.checkElementsAreSearchable(groupCols, metadata, SupportConstants.Element.SEARCHABLE_COMPARE);
+ }
+
+ private static void recordDebug(String message, PlanNode node, AnalysisRecord record) {
+ if (record != null && record.recordDebug()) {
+ record.println(message + " " + node.nodeToString()); //$NON-NLS-1$
+ }
+ }
+
+ static boolean canRaiseOverSort(PlanNode accessNode,
+ QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder,
+ PlanNode parentNode, AnalysisRecord record, boolean compensateForUnrelated) throws QueryMetadataException,
+ TeiidComponentException {
+ // Find the model for this node by getting ACCESS node's model
+ Object modelID = getModelIDFromAccess(accessNode, metadata);
+ if(modelID == null) {
+ // Couldn't determine model ID, so give up
+ return false;
+ }
+
+ 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;
+ }
+ boolean supportsNullOrdering = CapabilitiesUtil.supports(Capability.QUERY_ORDERBY_NULL_ORDERING, modelID, metadata, capFinder);
+ NullOrder defaultNullOrder = CapabilitiesUtil.getDefaultNullOrder(modelID, metadata, capFinder);
+ if (symbol.getNullOrdering() != null) {
+ if (!supportsNullOrdering) {
+ if (symbol.getNullOrdering() == NullOrdering.FIRST) {
+ if (defaultNullOrder != NullOrder.FIRST && !(symbol.isAscending() && defaultNullOrder == NullOrder.LOW)
+ && !(!symbol.isAscending() && defaultNullOrder == NullOrder.HIGH)) {
+ return false;
+ }
+ } else if (defaultNullOrder != NullOrder.LAST && !(symbol.isAscending() && defaultNullOrder == NullOrder.HIGH)
+ && !(!symbol.isAscending() && defaultNullOrder == NullOrder.LOW)) {
+ return false;
+ }
+ symbol.setNullOrdering(null);
+ }
+ } else if (supportsNullOrdering && defaultNullOrder != NullOrder.LOW) {
+ //try to match the expected default of low
+ if (symbol.isAscending()) {
+ if (defaultNullOrder != NullOrder.FIRST) {
+ symbol.setNullOrdering(NullOrdering.FIRST);
+ }
+ } else if (defaultNullOrder != NullOrder.LAST) {
+ symbol.setNullOrdering(NullOrdering.LAST);
+ }
+ }
+ }
+
+ if (accessNode.getLastChild() != null) {
+ //check to see if the sort applies to a union
+ if (accessNode.getLastChild().getType() == NodeConstants.Types.SET_OP) {
+ return CapabilitiesUtil.supportsSetQueryOrderBy(modelID, metadata, capFinder);
+ }
+ //check to see the plan is not in a consistent state to have a sort applied
+ if (accessNode.getLastChild().getType() == NodeConstants.Types.TUPLE_LIMIT) {
+ return false;
+ }
+ }
+
+ if (!CapabilitiesUtil.checkElementsAreSearchable(sortCols, metadata, SupportConstants.Element.SEARCHABLE_COMPARE)) {
+ return false;
+ }
+
+ // If model supports the support constant parameter, then move access node
+ if (!CapabilitiesUtil.supportsOrderBy(modelID, metadata, capFinder)) {
+ return false;
+ }
+
+ if (parentNode.hasBooleanProperty(NodeConstants.Info.UNRELATED_SORT)
+ && !CapabilitiesUtil.supports(Capability.QUERY_ORDERBY_UNRELATED, modelID, metadata, capFinder)
+ && NodeEditor.findParent(accessNode, NodeConstants.Types.PROJECT, NodeConstants.Types.SOURCE) == null
+ && !compensateForUnrelated) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * @param accessNode
+ * @param metadata
+ * @param capFinder
+ * @param parentNode
+ * @return
+ * @throws QueryMetadataException
+ * @throws TeiidComponentException
+ * @throws QueryPlannerException
+ */
+ static boolean canRaiseOverSelect(PlanNode accessNode,
+ QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder,
+ PlanNode parentNode, AnalysisRecord record) throws QueryMetadataException,
+ TeiidComponentException,
+ QueryPlannerException {
+ if (parentNode.hasBooleanProperty(NodeConstants.Info.IS_PHANTOM)) {
+ return true;
+ }
+
+ // Find the model for this node by getting ACCESS node's model
+ Object modelID = getModelIDFromAccess(accessNode, metadata);
+ if(modelID == null) {
+ // Couldn't determine model ID, so give up
+ return false;
+ }
+
+ if (parentNode.hasBooleanProperty(NodeConstants.Info.IS_HAVING) && !CapabilitiesUtil.supports(Capability.QUERY_HAVING, modelID, metadata, capFinder)) {
+ recordDebug("cannot push having, since having is not supported by source", parentNode, record); //$NON-NLS-1$
+ return false;
+ }
+
+ //don't push criteria into an invalid location above an ordered limit - shouldn't happen
+ PlanNode limitNode = NodeEditor.findNodePreOrder(accessNode, NodeConstants.Types.TUPLE_LIMIT, NodeConstants.Types.SOURCE);
+ if (limitNode != null && FrameUtil.isOrderedLimit(limitNode)) {
+ return false;
+ }
+
+ Criteria crit = (Criteria) parentNode.getProperty(NodeConstants.Info.SELECT_CRITERIA);
+
+ if(!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(crit, modelID, metadata, capFinder, record) ) {
+ return false;
+ }
+
+ if (accessNode.getFirstChild() != null && accessNode.getFirstChild().getType() == NodeConstants.Types.SET_OP) {
+ return false; //inconsistent select position - RulePushSelectCriteria is too greedy
+ }
+
+ return true;
+ }
+
+ /**
+ *
+ * @param symbol Symbol to check
+ * @param inSelectClause True if evaluating in the context of a SELECT clause
+ * @param modelID Model
+ * @param metadata Metadata
+ * @param capFinder Capabilities finder
+ * @return True if can push symbol to source
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ * @since 4.1.2
+ */
+ private static boolean canPushSymbol(SingleElementSymbol symbol, boolean inSelectClause, Object modelID,
+ QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord record)
+ throws TeiidComponentException, QueryMetadataException {
+
+ Expression expr = SymbolMap.getExpression(symbol);
+
+ // Do the normal checks
+ if(! CriteriaCapabilityValidatorVisitor.canPushLanguageObject(expr, modelID, metadata, capFinder, record)) {
+ return false;
+ }
+
+ if(inSelectClause && !(expr instanceof ElementSymbol || expr instanceof AggregateSymbol)
+ && !CapabilitiesUtil.supportsSelectExpression(modelID, metadata, capFinder)) {
+ return false;
+ }
+
+ // By default, no reason we can't push
+ return true;
+ }
+
+ static PlanNode performRaise(PlanNode rootNode, PlanNode accessNode, PlanNode parentNode) {
+ accessNode.removeProperty(NodeConstants.Info.EST_CARDINALITY);
+ NodeEditor.removeChildNode(parentNode, accessNode);
+ parentNode.addAsParent(accessNode);
+ PlanNode grandparentNode = accessNode.getParent();
+ if(grandparentNode != null) {
+ return rootNode;
+ }
+ return accessNode;
+ }
+
+ /**
+ * Determine whether an access node can be raised over the specified join node.
+ *
+ * This method can also be used to determine if a join node "A", parent of another join
+ * node "B", will have it's access raised. This is needed to help determine if node
+ * "B" will have access raised over it. In this scenario, the parameter will be true.
+ * When this method is called normally from the "execute" method, that param will be false.
+ *
+ * @param joinNode Join node that might be pushed underneath the access node
+ * @param metadata Metadata information
+ * @param capFinder CapabilitiesFinder
+ * @return The modelID if the raise can proceed and what common model these combined
+ * nodes will be sent to
+ */
+ private static Object canRaiseOverJoin(Object modelId, PlanNode joinNode, QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder, boolean afterJoinPlanning, AnalysisRecord record)
+ throws QueryMetadataException, TeiidComponentException {
+
+ List crits = (List) joinNode.getProperty(NodeConstants.Info.JOIN_CRITERIA);
+ JoinType type = (JoinType) joinNode.getProperty(NodeConstants.Info.JOIN_TYPE);
+
+ //let ruleplanjoins handle this case
+ if (!afterJoinPlanning && type == JoinType.JOIN_CROSS && joinNode.getParent().getType() == NodeConstants.Types.JOIN) {
+ JoinType jt = (JoinType)joinNode.getParent().getProperty(NodeConstants.Info.JOIN_TYPE);
+ if (!jt.isOuter()) {
+ return null;
+ }
+ }
+
+ if (joinNode.getProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE) != null) {
+ return null;
+ }
+
+ //if a join has access patterns that are unsatisfied, then the raise cannot occur
+ if (joinNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
+ return null;
+ }
+
+ //if I'm on the inner side of an outer join, then and we have a criteria restriction, then I can't be pushed
+ if (type.isOuter() && CapabilitiesUtil.getSupportedJoinCriteria(modelId, metadata, capFinder) != SupportedJoinCriteria.ANY) {
+ PlanNode critNode = NodeEditor.findNodePreOrder(joinNode.getLastChild(), NodeConstants.Types.SELECT, NodeConstants.Types.SOURCE);
+ if (critNode != null) {
+ return null;
+ }
+ if (type == JoinType.JOIN_FULL_OUTER) {
+ critNode = NodeEditor.findNodePreOrder(joinNode.getFirstChild(), NodeConstants.Types.SELECT, NodeConstants.Types.SOURCE);
+ if (critNode != null) {
+ return null;
+ }
+ }
+ }
+
+ return canRaiseOverJoin(joinNode.getChildren(), metadata, capFinder, crits, type, record);
+ }
+
+ static Object canRaiseOverJoin(List<PlanNode> children,
+ QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder,
+ List<Criteria> crits,
+ JoinType type, AnalysisRecord record) throws QueryMetadataException,
+ TeiidComponentException {
+ //we only want to consider binary joins
+ if (children.size() != 2) {
+ return null;
+ }
+
+ Object modelID = null;
+ Set<Object> groupIDs = new HashSet<Object>();
+ int groupCount = 0;
+ LinkedList<CompareCriteria> thetaCriteria = new LinkedList<CompareCriteria>();
+ SupportedJoinCriteria sjc = null;
+
+ for (PlanNode childNode : children) {
+ if(childNode.getType() != NodeConstants.Types.ACCESS
+ || childNode.hasCollectionProperty(NodeConstants.Info.ACCESS_PATTERNS)) {
+ return null;
+ }
+ Object accessModelID = getModelIDFromAccess(childNode, metadata);
+ if(accessModelID == null) {
+ return null;
+ }
+
+ groupCount += childNode.getGroups().size();
+
+ // Add all group metadata IDs to the list but check before each to make
+ // sure group hasn't already been seen - if so, bail out - this is a self join
+ // Unless model supports self joins, in which case, don't bail out.
+
+ boolean supportsSelfJoins = CapabilitiesUtil.supportsSelfJoins(accessModelID, metadata, capFinder);
+
+ if (!supportsSelfJoins) {
+ for (GroupSymbol groupSymbol : childNode.getGroups()) {
+ Object groupID = groupSymbol.getMetadataID();
+ if(!groupIDs.add(groupID)) {
+ // Already seen group - can't raise access over self join
+ return null;
+ }
+ }
+ }
+
+ //check the join criteria now that we know the model
+ if(modelID == null) {
+
+ if (!CapabilitiesUtil.supportsJoin(accessModelID, type, metadata, capFinder)) {
+ return null;
+ }
+ sjc = CapabilitiesUtil.getSupportedJoinCriteria(accessModelID, metadata, capFinder);
+
+ /*
+ * Key joins must be left linear
+ */
+ if (sjc == SupportedJoinCriteria.KEY && children.get(0).getGroups().size() != 1) {
+ return null;
+ }
+
+ if(crits != null && !crits.isEmpty()) {
+ for (Criteria crit : crits) {
+ if (!isSupportedJoinCriteria(sjc, crit, accessModelID, metadata, capFinder, record)) {
+ if (crit instanceof CompareCriteria) {
+ CompareCriteria cc = (CompareCriteria) crit;
+ if (cc.isOptional()) {
+ cc.setOptional(true);
+ continue;
+ }
+ }
+ return null;
+ } else if (crit instanceof CompareCriteria) {
+ thetaCriteria.add((CompareCriteria)crit);
+ }
+ }
+ if (sjc == SupportedJoinCriteria.KEY) {
+ LinkedList<Expression> leftExpressions = new LinkedList<Expression>();
+ LinkedList<Expression> rightExpressions = new LinkedList<Expression>();
+ RuleChooseJoinStrategy.separateCriteria(children.get(0).getGroups(), children.get(1).getGroups(), leftExpressions, rightExpressions, crits, new LinkedList<Criteria>());
+ ArrayList<Object> leftIds = new ArrayList<Object>(leftExpressions.size());
+ ArrayList<Object> rightIds = new ArrayList<Object>(rightExpressions.size());
+ for (Expression expr : leftExpressions) {
+ if (expr instanceof ElementSymbol) {
+ leftIds.add(((ElementSymbol) expr).getMetadataID());
+ }
+ }
+ GroupSymbol rightGroup = null;
+ for (Expression expr : rightExpressions) {
+ if (expr instanceof ElementSymbol) {
+ ElementSymbol es = (ElementSymbol) expr;
+ if (rightGroup == null) {
+ rightGroup = es.getGroupSymbol();
+ } else if (!rightGroup.equals(es.getGroupSymbol())) {
+ return null;
+ }
+ rightIds.add(es.getMetadataID());
+ }
+ }
+ if (rightGroup == null) {
+ return null;
+ }
+ if (!matchesForeignKey(metadata, leftIds, rightIds, children.get(0).getGroups().iterator().next(), true)
+ && !matchesForeignKey(metadata, rightIds, leftIds, rightGroup, true)) {
+ return null;
+ }
+ }
+ } else if (sjc != SupportedJoinCriteria.ANY) {
+ return null; //cross join not supported
+ }
+
+ modelID = accessModelID;
+
+ } else if(!CapabilitiesUtil.isSameConnector(modelID, accessModelID, metadata, capFinder)) {
+ return null;
+ }
+ } // end walking through join node's children
+
+ int maxGroups = CapabilitiesUtil.getMaxFromGroups(modelID, metadata, capFinder);
+
+ if (maxGroups != -1 && maxGroups < groupCount) {
+ return null;
+ }
+
+ if (sjc == SupportedJoinCriteria.KEY) {
+ for (CompareCriteria criteria : thetaCriteria) {
+ criteria.setOptional(false);
+ }
+ } else {
+ //TODO: this should be done in a less arbitrary way, and what about composite keys?
+ boolean hasCriteria = false;
+ for (CompareCriteria criteria : thetaCriteria) {
+ if (criteria.getIsOptional() == null || (!hasCriteria && criteria.getIsOptional())) {
+ criteria.setOptional(false);
+ }
+ hasCriteria = true;
+ }
+ }
+
+ return modelID;
+ }
+
+ /**
+ * Checks criteria one predicate at a time. Only tests up to the equi restriction.
+ */
+ static boolean isSupportedJoinCriteria(SupportedJoinCriteria sjc, Criteria crit, Object accessModelID,
+ QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord record)
+ throws QueryMetadataException, TeiidComponentException {
+ if(!CriteriaCapabilityValidatorVisitor.canPushLanguageObject(crit, accessModelID, metadata, capFinder, record) ) {
+ return false;
+ }
+ if (sjc == SupportedJoinCriteria.ANY) {
+ return true;
+ }
+ //theta join must be between elements with a compare predicate
+ if (!(crit instanceof CompareCriteria)) {
+ return false;
+ }
+ CompareCriteria cc = (CompareCriteria)crit;
+ if (!(cc.getLeftExpression() instanceof ElementSymbol)) {
+ return false;
+ }
+ if (!(cc.getRightExpression() instanceof ElementSymbol)) {
+ return false;
+ }
+ if (sjc == SupportedJoinCriteria.THETA) {
+ return true;
+ }
+ //equi must use the equality operator
+ if (cc.getOperator() != CompareCriteria.EQ) {
+ return false;
+ }
+ return true;
+ }
+
+ public static boolean matchesForeignKey(QueryMetadataInterface metadata,
+ Collection<Object> leftIds, Collection<Object> rightIds, GroupSymbol leftGroup, boolean exact)
+ throws TeiidComponentException, QueryMetadataException {
+ Collection fks = metadata.getForeignKeysInGroup(leftGroup.getMetadataID());
+ for (Object fk : fks) {
+ List fkColumns = metadata.getElementIDsInKey(fk);
+ if ((exact && leftIds.size() != fkColumns.size()) || !leftIds.containsAll(fkColumns)) {
+ continue;
+ }
+ Object pk = metadata.getPrimaryKeyIDForForeignKeyID(fk);
+ List pkColumns = metadata.getElementIDsInKey(pk);
+ if ((!exact || rightIds.size() == pkColumns.size()) && rightIds.containsAll(pkColumns)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ static PlanNode raiseAccessOverJoin(PlanNode joinNode, Object modelID, boolean insert) {
+ PlanNode leftAccess = joinNode.getFirstChild();
+ PlanNode rightAccess = joinNode.getLastChild();
+
+ // Remove old access nodes - this will automatically add children of access nodes to join node
+ NodeEditor.removeChildNode(joinNode, leftAccess);
+ NodeEditor.removeChildNode(joinNode, rightAccess);
+
+ //Set for later possible use, even though this isn't an access node
+ joinNode.setProperty(NodeConstants.Info.MODEL_ID, modelID);
+
+ // Insert new access node above join node
+ PlanNode newAccess = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ newAccess.setProperty(NodeConstants.Info.MODEL_ID, modelID);
+ newAccess.addGroups(rightAccess.getGroups());
+ newAccess.addGroups(leftAccess.getGroups());
+
+ // Combine hints if necessary
+ 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);
+
+ if (insert) {
+ joinNode.addAsParent(newAccess);
+ } else {
+ newAccess.addFirstChild(joinNode);
+ }
+
+ 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
+ * @param metadata Metadata access
+ * @return Object Model ID or null if not found.
+ * @throws QueryMetadataException
+ * @throws TeiidComponentException
+ */
+ static Object getModelIDFromAccess(PlanNode accessNode, QueryMetadataInterface metadata)
+ throws QueryMetadataException, TeiidComponentException {
+
+ Object accessModelID = accessNode.getProperty(NodeConstants.Info.MODEL_ID);
+ if(accessModelID == null && accessNode.getGroups().size() > 0) {
+ GroupSymbol group = accessNode.getGroups().iterator().next();
+ if(metadata.isVirtualGroup(group.getMetadataID())) {
+ return null;
+ }
+ accessModelID = metadata.getModelID(group.getMetadataID());
+
+ accessNode.setProperty(NodeConstants.Info.MODEL_ID, accessModelID);
+ }
+
+ return accessModelID;
+ }
+
+ private static boolean canRaiseOverSetQuery(PlanNode setOpNode,
+ QueryMetadataInterface metadata,
+ CapabilitiesFinder capFinder) throws QueryMetadataException, TeiidComponentException {
+
+ Object modelID = null;
+
+ for (PlanNode childNode : setOpNode.getChildren()) {
+ if(childNode.getType() != NodeConstants.Types.ACCESS) {
+ return false;
+ }
+
+ if (FrameUtil.getNonQueryCommand(childNode) != null || FrameUtil.getNestedPlan(childNode) != null) {
+ return false;
+ }
+
+ // Get model and check that it exists
+ Object accessModelID = getModelIDFromAccess(childNode, metadata);
+ if(accessModelID == null) {
+ return false;
+ }
+
+ // Reconcile this access node's model ID with existing
+ if(modelID == null) {
+ modelID = accessModelID;
+
+ if(! CapabilitiesUtil.supportsSetOp(accessModelID, (Operation)setOpNode.getProperty(NodeConstants.Info.SET_OPERATION), metadata, capFinder)) {
+ return false;
+ }
+ } else if(!CapabilitiesUtil.isSameConnector(modelID, accessModelID, metadata, capFinder)) {
+ return false;
+ }
+ if (!setOpNode.hasBooleanProperty(NodeConstants.Info.USE_ALL)
+ && !CapabilitiesUtil.checkElementsAreSearchable((List)NodeEditor.findNodePreOrder(childNode, NodeConstants.Types.PROJECT).getProperty(NodeConstants.Info.PROJECT_COLS), metadata, SupportConstants.Element.SEARCHABLE_COMPARE)) {
+ return false;
+ }
+
+ }
+ return true;
+ }
+
+ public String toString() {
+ return "RaiseAccess"; //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ContextReplacerVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/xml/ContextReplacerVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ContextReplacerVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,90 +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.optimizer.xml;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.navigator.PreOrderNavigator;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
-
-
-/**
- * <p>Walk a tree of language objects and replaces any usage of 'context' syntax
- * (implemented as a Function) with it's right argument. The stripped-off
- * 'context' Functions can be gotten as a Collection afterward.</p>
- */
-class ContextReplacerVisitor extends ExpressionMappingVisitor {
-
- private Collection contextFunctions = new LinkedList(); //contains Function objects
-
- /**
- * Construct a new visitor
- */
- ContextReplacerVisitor() {
- super(Collections.EMPTY_MAP);
- }
-
- /**
- * Get the Collection of Function objects representing context operators
- * which were stripped out of the language object by this visitor
- * @return Collection of Function
- */
- Collection getContextFunctions(){
- return this.contextFunctions;
- }
-
- /**
- * @see org.teiid.query.sql.visitor.ExpressionMappingVisitor#replaceExpression(org.teiid.query.sql.symbol.Expression)
- */
- public Expression replaceExpression(Expression exp) {
- if (exp instanceof Function){
- Function function = (Function)exp;
- if (function.getName().equalsIgnoreCase(FunctionLibrary.CONTEXT)){
- this.contextFunctions.add(function);
- //return 2nd argument to 'context'
- return function.getArg(1);
- }
- }
- return exp;
- }
-
- /**
- * Helper to quickly replace 'context'
- * @param obj Language object
- */
- static final Collection replaceContextFunctions(LanguageObject obj) {
- if (obj == null){
- return Collections.EMPTY_SET;
- }
- ContextReplacerVisitor visitor = new ContextReplacerVisitor();
- PreOrderNavigator.doVisit(obj, visitor);
- return visitor.getContextFunctions();
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ContextReplacerVisitor.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/xml/ContextReplacerVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ContextReplacerVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ContextReplacerVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,90 @@
+/*
+ * 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.Collection;
+import java.util.Collections;
+import java.util.LinkedList;
+
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.navigator.PreOrderNavigator;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.Function;
+import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
+
+
+/**
+ * <p>Walk a tree of language objects and replaces any usage of 'context' syntax
+ * (implemented as a Function) with it's right argument. The stripped-off
+ * 'context' Functions can be gotten as a Collection afterward.</p>
+ */
+class ContextReplacerVisitor extends ExpressionMappingVisitor {
+
+ private Collection<Function> contextFunctions = new LinkedList<Function>(); //contains Function objects
+
+ /**
+ * Construct a new visitor
+ */
+ ContextReplacerVisitor() {
+ super(Collections.EMPTY_MAP);
+ }
+
+ /**
+ * Get the Collection of Function objects representing context operators
+ * which were stripped out of the language object by this visitor
+ * @return Collection of Function
+ */
+ Collection<Function> getContextFunctions(){
+ return this.contextFunctions;
+ }
+
+ /**
+ * @see org.teiid.query.sql.visitor.ExpressionMappingVisitor#replaceExpression(org.teiid.query.sql.symbol.Expression)
+ */
+ public Expression replaceExpression(Expression exp) {
+ if (exp instanceof Function){
+ Function function = (Function)exp;
+ if (function.getName().equalsIgnoreCase(FunctionLibrary.CONTEXT)){
+ this.contextFunctions.add(function);
+ //return 2nd argument to 'context'
+ return function.getArg(1);
+ }
+ }
+ return exp;
+ }
+
+ /**
+ * Helper to quickly replace 'context'
+ * @param obj Language object
+ */
+ static final Collection<Function> replaceContextFunctions(LanguageObject obj) {
+ if (obj == null){
+ return Collections.emptySet();
+ }
+ ContextReplacerVisitor visitor = new ContextReplacerVisitor();
+ PreOrderNavigator.doVisit(obj, visitor);
+ return visitor.getContextFunctions();
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/CriteriaPlanner.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/xml/CriteriaPlanner.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/CriteriaPlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,343 +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.optimizer.xml;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-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.query.QueryPlugin;
-import org.teiid.query.function.FunctionLibrary;
-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.ResultSetInfo;
-import org.teiid.query.metadata.QueryMetadataInterface;
-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.Function;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-
-
-public class CriteriaPlanner {
-
- /**
- * Take the criteria from the user's command and break it into pieces applicable to each
- * mapping class result set in the mapping document
- *
- * Assumes that criteria is in CNF where each conjunct applies to only a single context.
- *
- * The post condition of this method is that each result set with
- *
- * @param criteria Criteria from user's command
- * @throws QueryPlannerException for any logical exception detected during planning
- * @throws QueryMetadataException if metadata encounters exception
- * @throws TeiidComponentException unexpected exception
- */
- static void placeUserCriteria(Criteria criteria, XMLPlannerEnvironment planEnv)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- for (Iterator conjunctIter = Criteria.separateCriteriaByAnd(criteria).iterator(); conjunctIter.hasNext();) {
-
- Criteria conjunct = (Criteria) conjunctIter.next();
-
- if (planStagingTableCriteria(conjunct, planEnv)) {
- continue;
- }
-
- //this is a gross hack, these should not be criteria
- if (planRowLimitFunction(conjunct, criteria, planEnv)) {
- continue;
- }
-
- MappingNode context = null;
-
- Collection 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();
- MappingNode otherContext = getContext(planEnv, contextFunction);
- if (context == null) {
- context = otherContext;
- } else if (context != otherContext){
- throw new QueryPlannerException("ERR.015.004.0068", QueryPlugin.Util.getString("ERR.015.004.0068", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- //search up to find the source node
- MappingNode contextRsNode = context.getSourceNode();
- if (contextRsNode != null) {
- context = contextRsNode;
- }
-
- } else {
- context = planEnv.mappingDoc;
- }
-
- Set sourceNodes = collectSourceNodesInConjunct(conjunct, context, planEnv.mappingDoc);
-
- //TODO: this can be replaced with method on the source node?
- MappingSourceNode criteriaRs = findRootResultSetNode(context, sourceNodes, criteria);
-
- Criteria convertedCrit = XMLNodeMappingVisitor.convertCriteria(conjunct, planEnv.mappingDoc, planEnv.getGlobalMetadata());
-
- ResultSetInfo rs = criteriaRs.getResultSetInfo();
- rs.setCriteria(Criteria.combineCriteria(rs.getCriteria(), convertedCrit));
- rs.addToCriteriaResultSets(sourceNodes);
- }
- }
-
- /**
- * This method collects all the MappingSourceNode(s) at or below the context given.
- */
- private static Set collectSourceNodesInConjunct(Criteria conjunct, MappingNode context, MappingDocument mappingDoc)
- throws QueryPlannerException {
-
- Collection elements = ElementCollectorVisitor.getElements(conjunct, true);
- Set resultSets = new HashSet();
-
- 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();
-
- String elementFullName = elementSymbol.getCanonicalName();
-
- MappingNode node = MappingNode.findNode(mappingDoc, elementFullName);
-
- MappingNode elementRsNode = node.getSourceNode();
- if (elementRsNode == null) {
- throw new QueryPlannerException(QueryPlugin.Util.getString("CriteriaPlanner.invalid_element", elementSymbol)); //$NON-NLS-1$
- }
-
- String elementRsFullName = elementRsNode.getFullyQualifiedName().toUpperCase();
-
- //check for a match at or below the context
- if (contextFullName.equals(elementRsFullName) ||
- elementRsFullName.startsWith(contextFullName + ElementSymbol.SEPARATOR)) {
- resultSets.add(elementRsNode);
- continue;
- }
-
- //check for match above the context
- if (contextFullName.startsWith(elementRsFullName + ElementSymbol.SEPARATOR)) {
- continue;
- }
-
- throw new QueryPlannerException(QueryPlugin.Util.getString("CriteriaPlanner.invalid_context", elementSymbol, context.getFullyQualifiedName())); //$NON-NLS-1$
- }
- return resultSets;
- }
-
- private static MappingSourceNode findRootResultSetNode(MappingNode context, Set resultSets, Criteria criteria)
- throws QueryPlannerException {
-
- if (context instanceof MappingSourceNode) {
- return (MappingSourceNode)context;
- }
-
- Set criteriaResultSets = new HashSet();
- // 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();
-
- MappingNode root = node;
-
- while (node != null) {
- if (node instanceof MappingSourceNode) {
- root = node;
- }
- node = node.getParent();
- }
- criteriaResultSets.add(root);
- }
-
- if (criteriaResultSets.size() != 1) {
- //TODO: this assumption could be relaxed if we allow context to be from a document perspective, rather than from a result set
- throw new QueryPlannerException(QueryPlugin.Util.getString("CriteriaPlanner.no_context", criteria)); //$NON-NLS-1$
- }
- return (MappingSourceNode)criteriaResultSets.iterator().next();
- }
-
- /**
- * Removes non-inferred staging table criteria. Places it directly onto the contextCriteria
- */
- static boolean planStagingTableCriteria(Criteria criteria, XMLPlannerEnvironment planEnv) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- String rootTempGroupName = getStagingTableForConjunct(criteria, planEnv.getGlobalMetadata());
- if (rootTempGroupName == null){
- return false;
- }
-
- // Defect 13172 - be careful to check for previously found root staging table
- // conjuncts and combine that with current conjunct
- ResultSetInfo rs = planEnv.getStagingTableResultsInfo(rootTempGroupName);
-
- rs.setCriteria(Criteria.combineCriteria(rs.getCriteria(), criteria));
-
- return true;
- }
-
- static boolean planRowLimitFunction(Criteria conjunct, Criteria wholeCrit, XMLPlannerEnvironment planEnv)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- // Check for "rowlimit" or "rowlimitexception" pseudo-function:
- // Restrictions
- // -Single arg must be any xml doc node that is within the scope of a mapping class
- // -Can't have conflicting row limits on the same mapping class
- // (Query Validator enforces additional restrictions.)
-
- Function rowLimitFunction = null;
- Constant rowLimitConstant = null;
- boolean exceptionOnRowLimit = false;
-
- if (conjunct instanceof CompareCriteria) {
- CompareCriteria crit = (CompareCriteria)conjunct;
- if (crit.getLeftExpression() instanceof Function) {
- Function function = (Function)crit.getLeftExpression();
- if (function.getName().equalsIgnoreCase(FunctionLibrary.ROWLIMIT)) {
- rowLimitFunction = function;
- rowLimitConstant = (Constant)crit.getRightExpression();
- } else if (function.getName().equalsIgnoreCase(FunctionLibrary.ROWLIMITEXCEPTION)) {
- rowLimitFunction = function;
- rowLimitConstant = (Constant)crit.getRightExpression();
- exceptionOnRowLimit = true;
- }
- }
- if (rowLimitFunction == null && crit.getRightExpression() instanceof Function) {
- Function function = (Function)crit.getRightExpression();
- if (function.getName().equalsIgnoreCase(FunctionLibrary.ROWLIMIT)) {
- rowLimitFunction = function;
- rowLimitConstant = (Constant)crit.getLeftExpression();
- } else if (function.getName().equalsIgnoreCase(FunctionLibrary.ROWLIMITEXCEPTION)) {
- rowLimitFunction = function;
- rowLimitConstant = (Constant)crit.getLeftExpression();
- exceptionOnRowLimit = true;
- }
- }
- }
-
- if (rowLimitFunction == null) {
- return false;
- }
- int rowLimit = ((Integer)rowLimitConstant.getValue()).intValue();
-
- String fullyQualifiedNodeName = planEnv.getGlobalMetadata().getFullName(((ElementSymbol)rowLimitFunction.getArg(0)).getMetadataID());
-
- MappingNode node = MappingNode.findNode(planEnv.mappingDoc, fullyQualifiedNodeName.toUpperCase());
- MappingSourceNode sourceNode = node.getSourceNode();
- if (sourceNode == null) {
- String msg = QueryPlugin.Util.getString("XMLPlanner.The_rowlimit_parameter_{0}_is_not_in_the_scope_of_any_mapping_class", fullyQualifiedNodeName); //$NON-NLS-1$
- throw new QueryPlannerException(msg);
- }
-
- ResultSetInfo criteriaRsInfo = sourceNode.getResultSetInfo();
-
- // Check for conflicting row limits on the same mapping class
- int existingLimit = criteriaRsInfo.getUserRowLimit();
- if (existingLimit > 0 && existingLimit != rowLimit) {
- String msg = QueryPlugin.Util.getString("XMLPlanner.Criteria_{0}_contains_conflicting_row_limits", wholeCrit); //$NON-NLS-1$
- throw new QueryPlannerException(msg);
- }
-
- criteriaRsInfo.setUserRowLimit(rowLimit, exceptionOnRowLimit);
-
- // No further processing on this conjunct
- return true;
- }
-
- /**
- * Validate that all elements within a conjunct are either referring to a temp table
- * or NOT referring to a temp table. Can't mix element types within a conjunct.
- * @param conjunct Conjunct to validate
- * @return String name of temporary result set, if conjunct is for the root temp table;
- * or return null if the conjunct is for XML document node(s)
- * @throws QueryPlannerException if conjunct has mixed types
- */
- static String getStagingTableForConjunct(Criteria conjunct, QueryMetadataInterface metadata)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- Collection 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();
- GroupSymbol group = element.getGroupSymbol();
- //assumes that all non-xml group elements are temp elements
- boolean hasTempElement = !metadata.isXMLGroup(group.getMetadataID());
- if(!first && hasTempElement && resultSet == null) {
- throw new QueryPlannerException("ERR.015.004.0035", QueryPlugin.Util.getString("ERR.015.004.0035", conjunct)); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (hasTempElement) {
- String currentResultSet = metadata.getFullName(element.getGroupSymbol().getMetadataID());
- if (resultSet != null && !resultSet.equalsIgnoreCase(currentResultSet)) {
- throw new QueryPlannerException(QueryPlugin.Util.getString("CriteriaPlanner.multiple_staging", conjunct)); //$NON-NLS-1$
- }
- resultSet = currentResultSet;
- }
- first = false;
- }
-
- if (resultSet != null) {
- Collection functions = ContextReplacerVisitor.replaceContextFunctions(conjunct);
- if (!functions.isEmpty()) {
- throw new QueryPlannerException(QueryPlugin.Util.getString("CriteriaPlanner.staging_context")); //$NON-NLS-1$
- }
-
- //should also throw an exception if it contains a row limit function
- }
-
- return resultSet;
- }
-
- /**
- * Returns the context for a given context function
- */
- static MappingNode getContext(XMLPlannerEnvironment planEnv, Function contextFunction)
- throws QueryPlannerException {
-
- ElementSymbol targetContext = (ElementSymbol)contextFunction.getArg(0);
-
- MappingNode contextNode = MappingNode.findNode(planEnv.mappingDoc, targetContext.getCanonicalName());
- if (contextNode == null){
- throw new QueryPlannerException("ERR.015.004.0037", QueryPlugin.Util.getString("ERR.015.004.0037", targetContext)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return contextNode;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/CriteriaPlanner.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/xml/CriteriaPlanner.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/CriteriaPlanner.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/CriteriaPlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,335 @@
+/*
+ * 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.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+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.query.QueryPlugin;
+import org.teiid.query.function.FunctionLibrary;
+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.ResultSetInfo;
+import org.teiid.query.metadata.QueryMetadataInterface;
+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.Function;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+
+
+public class CriteriaPlanner {
+
+ /**
+ * Take the criteria from the user's command and break it into pieces applicable to each
+ * mapping class result set in the mapping document
+ *
+ * Assumes that criteria is in CNF where each conjunct applies to only a single context.
+ *
+ * The post condition of this method is that each result set with
+ *
+ * @param criteria Criteria from user's command
+ * @throws QueryPlannerException for any logical exception detected during planning
+ * @throws QueryMetadataException if metadata encounters exception
+ * @throws TeiidComponentException unexpected exception
+ */
+ static void placeUserCriteria(Criteria criteria, XMLPlannerEnvironment planEnv)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ for (Iterator<Criteria> conjunctIter = Criteria.separateCriteriaByAnd(criteria).iterator(); conjunctIter.hasNext();) {
+
+ Criteria conjunct = conjunctIter.next();
+
+ if (planStagingTableCriteria(conjunct, planEnv)) {
+ continue;
+ }
+
+ //this is a gross hack, these should not be criteria
+ if (planRowLimitFunction(conjunct, criteria, planEnv)) {
+ continue;
+ }
+
+ MappingNode context = null;
+
+ Collection<Function> contextFunctions = ContextReplacerVisitor.replaceContextFunctions(conjunct);
+ if (!contextFunctions.isEmpty()) {
+ //ensure that every part of the conjunct is to the same context
+ for (Function contextFunction : contextFunctions) {
+ MappingNode otherContext = getContext(planEnv, contextFunction);
+ if (context == null) {
+ context = otherContext;
+ } else if (context != otherContext){
+ throw new QueryPlannerException("ERR.015.004.0068", QueryPlugin.Util.getString("ERR.015.004.0068", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ //search up to find the source node
+ MappingNode contextRsNode = context.getSourceNode();
+ if (contextRsNode != null) {
+ context = contextRsNode;
+ }
+
+ } else {
+ 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);
+
+ Criteria convertedCrit = XMLNodeMappingVisitor.convertCriteria(conjunct, planEnv.mappingDoc, planEnv.getGlobalMetadata());
+
+ ResultSetInfo rs = criteriaRs.getResultSetInfo();
+ rs.setCriteria(Criteria.combineCriteria(rs.getCriteria(), convertedCrit));
+ rs.addToCriteriaResultSets(sourceNodes);
+ }
+ }
+
+ /**
+ * This method collects all the MappingSourceNode(s) at or below the context given.
+ */
+ private static Set<MappingSourceNode> collectSourceNodesInConjunct(Criteria conjunct, MappingNode context, MappingDocument mappingDoc)
+ throws QueryPlannerException {
+
+ 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 (ElementSymbol elementSymbol : elements) {
+ String elementFullName = elementSymbol.getCanonicalName();
+
+ MappingNode node = MappingNode.findNode(mappingDoc, elementFullName);
+
+ MappingSourceNode elementRsNode = node.getSourceNode();
+ if (elementRsNode == null) {
+ throw new QueryPlannerException(QueryPlugin.Util.getString("CriteriaPlanner.invalid_element", elementSymbol)); //$NON-NLS-1$
+ }
+
+ String elementRsFullName = elementRsNode.getFullyQualifiedName().toUpperCase();
+
+ //check for a match at or below the context
+ if (contextFullName.equals(elementRsFullName) ||
+ elementRsFullName.startsWith(contextFullName + ElementSymbol.SEPARATOR)) {
+ resultSets.add(elementRsNode);
+ continue;
+ }
+
+ //check for match above the context
+ if (contextFullName.startsWith(elementRsFullName + ElementSymbol.SEPARATOR)) {
+ continue;
+ }
+
+ throw new QueryPlannerException(QueryPlugin.Util.getString("CriteriaPlanner.invalid_context", elementSymbol, context.getFullyQualifiedName())); //$NON-NLS-1$
+ }
+ return resultSets;
+ }
+
+ private static MappingSourceNode findRootResultSetNode(MappingNode context, Set<MappingSourceNode> resultSets, Criteria criteria)
+ throws QueryPlannerException {
+
+ if (context instanceof MappingSourceNode) {
+ return (MappingSourceNode)context;
+ }
+
+ 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 (MappingNode node : resultSets) {
+ MappingNode root = node;
+
+ while (node != null) {
+ if (node instanceof MappingSourceNode) {
+ root = node;
+ }
+ node = node.getParent();
+ }
+ criteriaResultSets.add(root);
+ }
+
+ if (criteriaResultSets.size() != 1) {
+ //TODO: this assumption could be relaxed if we allow context to be from a document perspective, rather than from a result set
+ throw new QueryPlannerException(QueryPlugin.Util.getString("CriteriaPlanner.no_context", criteria)); //$NON-NLS-1$
+ }
+ return (MappingSourceNode)criteriaResultSets.iterator().next();
+ }
+
+ /**
+ * Removes non-inferred staging table criteria. Places it directly onto the contextCriteria
+ */
+ static boolean planStagingTableCriteria(Criteria criteria, XMLPlannerEnvironment planEnv) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ String rootTempGroupName = getStagingTableForConjunct(criteria, planEnv.getGlobalMetadata());
+ if (rootTempGroupName == null){
+ return false;
+ }
+
+ // Defect 13172 - be careful to check for previously found root staging table
+ // conjuncts and combine that with current conjunct
+ ResultSetInfo rs = planEnv.getStagingTableResultsInfo(rootTempGroupName);
+
+ rs.setCriteria(Criteria.combineCriteria(rs.getCriteria(), criteria));
+
+ return true;
+ }
+
+ static boolean planRowLimitFunction(Criteria conjunct, Criteria wholeCrit, XMLPlannerEnvironment planEnv)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ // Check for "rowlimit" or "rowlimitexception" pseudo-function:
+ // Restrictions
+ // -Single arg must be any xml doc node that is within the scope of a mapping class
+ // -Can't have conflicting row limits on the same mapping class
+ // (Query Validator enforces additional restrictions.)
+
+ Function rowLimitFunction = null;
+ Constant rowLimitConstant = null;
+ boolean exceptionOnRowLimit = false;
+
+ if (conjunct instanceof CompareCriteria) {
+ CompareCriteria crit = (CompareCriteria)conjunct;
+ if (crit.getLeftExpression() instanceof Function) {
+ Function function = (Function)crit.getLeftExpression();
+ if (function.getName().equalsIgnoreCase(FunctionLibrary.ROWLIMIT)) {
+ rowLimitFunction = function;
+ rowLimitConstant = (Constant)crit.getRightExpression();
+ } else if (function.getName().equalsIgnoreCase(FunctionLibrary.ROWLIMITEXCEPTION)) {
+ rowLimitFunction = function;
+ rowLimitConstant = (Constant)crit.getRightExpression();
+ exceptionOnRowLimit = true;
+ }
+ }
+ if (rowLimitFunction == null && crit.getRightExpression() instanceof Function) {
+ Function function = (Function)crit.getRightExpression();
+ if (function.getName().equalsIgnoreCase(FunctionLibrary.ROWLIMIT)) {
+ rowLimitFunction = function;
+ rowLimitConstant = (Constant)crit.getLeftExpression();
+ } else if (function.getName().equalsIgnoreCase(FunctionLibrary.ROWLIMITEXCEPTION)) {
+ rowLimitFunction = function;
+ rowLimitConstant = (Constant)crit.getLeftExpression();
+ exceptionOnRowLimit = true;
+ }
+ }
+ }
+
+ if (rowLimitFunction == null) {
+ return false;
+ }
+ int rowLimit = ((Integer)rowLimitConstant.getValue()).intValue();
+
+ String fullyQualifiedNodeName = planEnv.getGlobalMetadata().getFullName(((ElementSymbol)rowLimitFunction.getArg(0)).getMetadataID());
+
+ MappingNode node = MappingNode.findNode(planEnv.mappingDoc, fullyQualifiedNodeName.toUpperCase());
+ MappingSourceNode sourceNode = node.getSourceNode();
+ if (sourceNode == null) {
+ String msg = QueryPlugin.Util.getString("XMLPlanner.The_rowlimit_parameter_{0}_is_not_in_the_scope_of_any_mapping_class", fullyQualifiedNodeName); //$NON-NLS-1$
+ throw new QueryPlannerException(msg);
+ }
+
+ ResultSetInfo criteriaRsInfo = sourceNode.getResultSetInfo();
+
+ // Check for conflicting row limits on the same mapping class
+ int existingLimit = criteriaRsInfo.getUserRowLimit();
+ if (existingLimit > 0 && existingLimit != rowLimit) {
+ String msg = QueryPlugin.Util.getString("XMLPlanner.Criteria_{0}_contains_conflicting_row_limits", wholeCrit); //$NON-NLS-1$
+ throw new QueryPlannerException(msg);
+ }
+
+ criteriaRsInfo.setUserRowLimit(rowLimit, exceptionOnRowLimit);
+
+ // No further processing on this conjunct
+ return true;
+ }
+
+ /**
+ * Validate that all elements within a conjunct are either referring to a temp table
+ * or NOT referring to a temp table. Can't mix element types within a conjunct.
+ * @param conjunct Conjunct to validate
+ * @return String name of temporary result set, if conjunct is for the root temp table;
+ * or return null if the conjunct is for XML document node(s)
+ * @throws QueryPlannerException if conjunct has mixed types
+ */
+ static String getStagingTableForConjunct(Criteria conjunct, QueryMetadataInterface metadata)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(conjunct, true);
+
+ boolean first = true;
+ String resultSet = null;
+
+ // Check each remaining element to make sure it matches
+ for (ElementSymbol element : elements) {
+ GroupSymbol group = element.getGroupSymbol();
+ //assumes that all non-xml group elements are temp elements
+ boolean hasTempElement = !metadata.isXMLGroup(group.getMetadataID());
+ if(!first && hasTempElement && resultSet == null) {
+ throw new QueryPlannerException("ERR.015.004.0035", QueryPlugin.Util.getString("ERR.015.004.0035", conjunct)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ if (hasTempElement) {
+ String currentResultSet = metadata.getFullName(element.getGroupSymbol().getMetadataID());
+ if (resultSet != null && !resultSet.equalsIgnoreCase(currentResultSet)) {
+ throw new QueryPlannerException(QueryPlugin.Util.getString("CriteriaPlanner.multiple_staging", conjunct)); //$NON-NLS-1$
+ }
+ resultSet = currentResultSet;
+ }
+ first = false;
+ }
+
+ if (resultSet != null) {
+ Collection<Function> functions = ContextReplacerVisitor.replaceContextFunctions(conjunct);
+ if (!functions.isEmpty()) {
+ throw new QueryPlannerException(QueryPlugin.Util.getString("CriteriaPlanner.staging_context")); //$NON-NLS-1$
+ }
+
+ //should also throw an exception if it contains a row limit function
+ }
+
+ return resultSet;
+ }
+
+ /**
+ * Returns the context for a given context function
+ */
+ static MappingNode getContext(XMLPlannerEnvironment planEnv, Function contextFunction)
+ throws QueryPlannerException {
+
+ ElementSymbol targetContext = (ElementSymbol)contextFunction.getArg(0);
+
+ MappingNode contextNode = MappingNode.findNode(planEnv.mappingDoc, targetContext.getCanonicalName());
+ if (contextNode == null){
+ throw new QueryPlannerException("ERR.015.004.0037", QueryPlugin.Util.getString("ERR.015.004.0037", targetContext)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return contextNode;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/MarkExcludeVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/xml/MarkExcludeVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/MarkExcludeVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.query.optimizer.xml;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.teiid.query.mapping.xml.MappingAllNode;
-import org.teiid.query.mapping.xml.MappingAttribute;
-import org.teiid.query.mapping.xml.MappingBaseNode;
-import org.teiid.query.mapping.xml.MappingChoiceNode;
-import org.teiid.query.mapping.xml.MappingDocument;
-import org.teiid.query.mapping.xml.MappingElement;
-import org.teiid.query.mapping.xml.MappingRecursiveElement;
-import org.teiid.query.mapping.xml.MappingSequenceNode;
-import org.teiid.query.mapping.xml.MappingSourceNode;
-import org.teiid.query.mapping.xml.MappingVisitor;
-import org.teiid.query.mapping.xml.Navigator;
-
-
-/**
- * This vistor marks all the nodes in the Mapping Document to
- * "exclude".
- */
-public class MarkExcludeVisitor extends MappingVisitor{
- HashSet keepNodes;
-
- public MarkExcludeVisitor(HashSet keppNodes) {
- this.keepNodes = keppNodes;
- }
-
- // User non-selectable node; just exclude
- public void visit(MappingAllNode all) {
- all.setExclude(true);
- }
-
- // User non-selectable node; just exclude
- public void visit(MappingSourceNode element) {
- element.setExclude(true);
- }
-
- // User non-selectable node; just exclude
- public void visit(MappingChoiceNode choice) {
- choice.setExclude(true);
- }
- // User non-selectable node; just exclude
- public void visit(MappingRecursiveElement element) {
- element.setExclude(true);
- }
- // User non-selectable node; just exclude
- public void visit(MappingSequenceNode sequence) {
- sequence.setExclude(true);
- }
-
- public void visit(MappingAttribute attribute) {
- String name = attribute.getCanonicalName();
- if (keepNodes.contains(name)) {
- // we need to keep this; if not already excluded
- if (!attribute.isExcluded()) {
- includeSelf(attribute.getParentNode());
- includeAncestors(attribute.getParentNode());
- }
- }
- else {
- if (!attribute.isAlwaysInclude()) {
- attribute.setExclude(true);
- }
- }
- }
-
- public void visit(MappingElement element) {
- String name = element.getCanonicalName();
- if (keepNodes.contains(name)) {
- // we need to keep this; if not already excluded
- if (!element.isExcluded()) {
- includeSelf(element);
- includeAncestors(element);
- }
- }
- else {
- if (!element.isAlwaysInclude()) {
- element.setExclude(true);
- }
- }
- }
-
- void includeSelf(MappingBaseNode element) {
- element.setExclude(false);
-
- // if this element has any attributes which are "must have" then
- // turn the exclude off on them.
- if (element instanceof MappingElement) {
- MappingElement elem = (MappingElement)element;
- List attributes = elem.getAttributes();
- if (attributes != null && !attributes.isEmpty()) {
- for (Iterator i = attributes.iterator(); i.hasNext();) {
- MappingAttribute attribute = (MappingAttribute)i.next();
- if (attribute.isAlwaysInclude()) {
- attribute.setExclude(false);
- }
- }
- }
- }
- }
-
- void includeAncestors(MappingBaseNode element) {
- MappingBaseNode parent = element.getParentNode();
- if (parent != null) {
- includeSelf(parent);
- includeAncestors(parent);
- }
- }
-
- public static MappingDocument markExcludedNodes(MappingDocument doc, HashSet keepNodes) {
- MarkExcludeVisitor visitor = new MarkExcludeVisitor(keepNodes);
- doc.acceptVisitor(new Navigator(true, visitor));
- return doc;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/MarkExcludeVisitor.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/xml/MarkExcludeVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/MarkExcludeVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/MarkExcludeVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.query.optimizer.xml;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+
+import org.teiid.query.mapping.xml.MappingAllNode;
+import org.teiid.query.mapping.xml.MappingAttribute;
+import org.teiid.query.mapping.xml.MappingBaseNode;
+import org.teiid.query.mapping.xml.MappingChoiceNode;
+import org.teiid.query.mapping.xml.MappingDocument;
+import org.teiid.query.mapping.xml.MappingElement;
+import org.teiid.query.mapping.xml.MappingRecursiveElement;
+import org.teiid.query.mapping.xml.MappingSequenceNode;
+import org.teiid.query.mapping.xml.MappingSourceNode;
+import org.teiid.query.mapping.xml.MappingVisitor;
+import org.teiid.query.mapping.xml.Navigator;
+
+
+/**
+ * This visitor marks all the nodes in the Mapping Document to
+ * "exclude".
+ */
+public class MarkExcludeVisitor extends MappingVisitor{
+ HashSet<String> keepNodes;
+
+ public MarkExcludeVisitor(HashSet<String> keppNodes) {
+ this.keepNodes = keppNodes;
+ }
+
+ // User non-selectable node; just exclude
+ public void visit(MappingAllNode all) {
+ all.setExclude(true);
+ }
+
+ // User non-selectable node; just exclude
+ public void visit(MappingSourceNode element) {
+ element.setExclude(true);
+ }
+
+ // User non-selectable node; just exclude
+ public void visit(MappingChoiceNode choice) {
+ choice.setExclude(true);
+ }
+ // User non-selectable node; just exclude
+ public void visit(MappingRecursiveElement element) {
+ element.setExclude(true);
+ }
+ // User non-selectable node; just exclude
+ public void visit(MappingSequenceNode sequence) {
+ sequence.setExclude(true);
+ }
+
+ public void visit(MappingAttribute attribute) {
+ String name = attribute.getCanonicalName();
+ if (keepNodes.contains(name)) {
+ // we need to keep this; if not already excluded
+ if (!attribute.isExcluded()) {
+ includeSelf(attribute.getParentNode());
+ includeAncestors(attribute.getParentNode());
+ }
+ }
+ else {
+ if (!attribute.isAlwaysInclude()) {
+ attribute.setExclude(true);
+ }
+ }
+ }
+
+ public void visit(MappingElement element) {
+ String name = element.getCanonicalName();
+ if (keepNodes.contains(name)) {
+ // we need to keep this; if not already excluded
+ if (!element.isExcluded()) {
+ includeSelf(element);
+ includeAncestors(element);
+ }
+ }
+ else {
+ if (!element.isAlwaysInclude()) {
+ element.setExclude(true);
+ }
+ }
+ }
+
+ void includeSelf(MappingBaseNode element) {
+ element.setExclude(false);
+
+ // if this element has any attributes which are "must have" then
+ // turn the exclude off on them.
+ if (element instanceof MappingElement) {
+ MappingElement elem = (MappingElement)element;
+ List attributes = elem.getAttributes();
+ if (attributes != null && !attributes.isEmpty()) {
+ for (Iterator i = attributes.iterator(); i.hasNext();) {
+ MappingAttribute attribute = (MappingAttribute)i.next();
+ if (attribute.isAlwaysInclude()) {
+ attribute.setExclude(false);
+ }
+ }
+ }
+ }
+ }
+
+ void includeAncestors(MappingBaseNode element) {
+ MappingBaseNode parent = element.getParentNode();
+ if (parent != null) {
+ includeSelf(parent);
+ includeAncestors(parent);
+ }
+ }
+
+ public static MappingDocument markExcludedNodes(MappingDocument doc, HashSet<String> keepNodes) {
+ MarkExcludeVisitor visitor = new MarkExcludeVisitor(keepNodes);
+ doc.acceptVisitor(new Navigator(true, visitor));
+ return doc;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/NameInSourceResolverVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/xml/NameInSourceResolverVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/NameInSourceResolverVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,164 +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.optimizer.xml;
-
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.core.types.DataTypeManager;
-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.MappingSourceNode;
-import org.teiid.query.mapping.xml.MappingVisitor;
-import org.teiid.query.mapping.xml.Navigator;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.GroupSymbol;
-
-
-
-/**
- * This visitor resolves the "element" names on the mapping nodes to the planned
- * sources defined at same or parent nodes.
- */
-public class NameInSourceResolverVisitor extends MappingVisitor {
- XMLPlannerEnvironment planEnv;
-
- NameInSourceResolverVisitor(XMLPlannerEnvironment planEnv) {
- this.planEnv = planEnv;
- }
-
- public void visit(MappingSourceNode element) {
- if (element.getAliasResultName() == null) {
- return;
- }
-
- Map symbols = element.getSymbolMap();
-
- List elements = new LinkedList();
-
- for (Iterator i = symbols.values().iterator(); i.hasNext();) {
- Object symbol = i.next();
- if (symbol instanceof ElementSymbol) {
- elements.add(symbol);
- }
- }
-
- //fix recusive references
- Map fixedMap = QueryUtil.createSymbolMap(new GroupSymbol(element.getActualResultSetName()), element.getAliasResultName(), elements);
-
- updateSymbolMap(element, fixedMap);
-
- symbols.putAll(fixedMap);
- }
-
- public void visit(MappingAttribute attribute) {
- String nameInSource = attribute.getNameInSource();
- if (nameInSource != null) {
-
- MappingSourceNode sourceNode = attribute.getSourceNode();
- ElementSymbol symbol = resolveElementSymbol(nameInSource, sourceNode);
-
- attribute.setElementSymbol(symbol);
- }
- }
-
- public void visit(MappingElement element) {
- String nameInSource = element.getNameInSource();
- if (nameInSource != null) {
- MappingSourceNode sourceNode = element.getSourceNode();
- ElementSymbol symbol = resolveElementSymbol(nameInSource, sourceNode);
-
- element.setElementSymbol(symbol);
- }
- }
-
- private ElementSymbol resolveElementSymbol(String elementName, MappingSourceNode sourceNode) {
- try {
- QueryMetadataInterface metadata = this.planEnv.getGlobalMetadata();
-
- ElementSymbol symbol = sourceNode.getMappedSymbol(new ElementSymbol(elementName));
-
- Object elementID = metadata.getElementID(symbol.getName());
- symbol.setMetadataID(elementID);
-
- Object groupID = metadata.getGroupIDForElementID(elementID);
- String groupName = metadata.getFullName(groupID);
- GroupSymbol groupSymbol = new GroupSymbol(groupName);
- groupSymbol.setMetadataID(groupID);
-
- symbol.setGroupSymbol(groupSymbol);
- symbol.setType(DataTypeManager.getDataTypeClass(metadata.getElementType(symbol.getMetadataID())));
- return symbol;
- } catch (QueryMetadataException e) {
- throw new TeiidRuntimeException(e);
- } catch (TeiidComponentException e) {
- throw new TeiidRuntimeException(e);
- }
- }
-
- /**
- * Resolve all the "NameInSource" property nodes (element names), with the their results
- * set queries.
- * @param doc
- * @param planEnv
- */
- public static void resolveElements(MappingDocument doc, XMLPlannerEnvironment planEnv)
- throws QueryMetadataException, TeiidComponentException {
-
- NameInSourceResolverVisitor real = new NameInSourceResolverVisitor(planEnv);
-
- try {
- MappingVisitor visitor = new Navigator(true, real);
- doc.acceptVisitor(visitor);
- } catch (TeiidRuntimeException e) {
- if (e.getCause() instanceof QueryMetadataException) {
- throw (QueryMetadataException)e.getCause();
- }
- else if (e.getCause() instanceof TeiidComponentException) {
- throw (TeiidComponentException)e.getCause();
- }
- throw e;
- }
- }
-
- static void updateSymbolMap(MappingSourceNode source,
- Map target) {
- for (Iterator i = source.getSymbolMap().entrySet().iterator(); i.hasNext();) {
- Map.Entry entry = (Map.Entry)i.next();
- Object newValue = target.get(entry.getValue());
-
- if (newValue != null) {
- entry.setValue(newValue);
- }
- }
-
- source.updateSymbolMapDependentValues();
-}
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/NameInSourceResolverVisitor.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/xml/NameInSourceResolverVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/NameInSourceResolverVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/NameInSourceResolverVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,164 @@
+/*
+ * 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.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.core.types.DataTypeManager;
+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.MappingSourceNode;
+import org.teiid.query.mapping.xml.MappingVisitor;
+import org.teiid.query.mapping.xml.Navigator;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.GroupSymbol;
+
+
+
+/**
+ * This visitor resolves the "element" names on the mapping nodes to the planned
+ * sources defined at same or parent nodes.
+ */
+public class NameInSourceResolverVisitor extends MappingVisitor {
+ XMLPlannerEnvironment planEnv;
+
+ NameInSourceResolverVisitor(XMLPlannerEnvironment planEnv) {
+ this.planEnv = planEnv;
+ }
+
+ public void visit(MappingSourceNode element) {
+ if (element.getAliasResultName() == null) {
+ return;
+ }
+
+ Map symbols = element.getSymbolMap();
+
+ List<ElementSymbol> elements = new LinkedList<ElementSymbol>();
+
+ for (Iterator i = symbols.values().iterator(); i.hasNext();) {
+ Object symbol = i.next();
+ if (symbol instanceof ElementSymbol) {
+ elements.add((ElementSymbol)symbol);
+ }
+ }
+
+ //fix recusive references
+ Map fixedMap = QueryUtil.createSymbolMap(new GroupSymbol(element.getActualResultSetName()), element.getAliasResultName(), elements);
+
+ updateSymbolMap(element, fixedMap);
+
+ symbols.putAll(fixedMap);
+ }
+
+ public void visit(MappingAttribute attribute) {
+ String nameInSource = attribute.getNameInSource();
+ if (nameInSource != null) {
+
+ MappingSourceNode sourceNode = attribute.getSourceNode();
+ ElementSymbol symbol = resolveElementSymbol(nameInSource, sourceNode);
+
+ attribute.setElementSymbol(symbol);
+ }
+ }
+
+ public void visit(MappingElement element) {
+ String nameInSource = element.getNameInSource();
+ if (nameInSource != null) {
+ MappingSourceNode sourceNode = element.getSourceNode();
+ ElementSymbol symbol = resolveElementSymbol(nameInSource, sourceNode);
+
+ element.setElementSymbol(symbol);
+ }
+ }
+
+ private ElementSymbol resolveElementSymbol(String elementName, MappingSourceNode sourceNode) {
+ try {
+ QueryMetadataInterface metadata = this.planEnv.getGlobalMetadata();
+
+ ElementSymbol symbol = sourceNode.getMappedSymbol(new ElementSymbol(elementName));
+
+ Object elementID = metadata.getElementID(symbol.getName());
+ symbol.setMetadataID(elementID);
+
+ Object groupID = metadata.getGroupIDForElementID(elementID);
+ String groupName = metadata.getFullName(groupID);
+ GroupSymbol groupSymbol = new GroupSymbol(groupName);
+ groupSymbol.setMetadataID(groupID);
+
+ symbol.setGroupSymbol(groupSymbol);
+ symbol.setType(DataTypeManager.getDataTypeClass(metadata.getElementType(symbol.getMetadataID())));
+ return symbol;
+ } catch (QueryMetadataException e) {
+ throw new TeiidRuntimeException(e);
+ } catch (TeiidComponentException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+
+ /**
+ * Resolve all the "NameInSource" property nodes (element names), with the their results
+ * set queries.
+ * @param doc
+ * @param planEnv
+ */
+ public static void resolveElements(MappingDocument doc, XMLPlannerEnvironment planEnv)
+ throws QueryMetadataException, TeiidComponentException {
+
+ NameInSourceResolverVisitor real = new NameInSourceResolverVisitor(planEnv);
+
+ try {
+ MappingVisitor visitor = new Navigator(true, real);
+ doc.acceptVisitor(visitor);
+ } catch (TeiidRuntimeException e) {
+ if (e.getCause() instanceof QueryMetadataException) {
+ throw (QueryMetadataException)e.getCause();
+ }
+ else if (e.getCause() instanceof TeiidComponentException) {
+ throw (TeiidComponentException)e.getCause();
+ }
+ throw e;
+ }
+ }
+
+ static void updateSymbolMap(MappingSourceNode source,
+ Map target) {
+ for (Iterator i = source.getSymbolMap().entrySet().iterator(); i.hasNext();) {
+ Map.Entry entry = (Map.Entry)i.next();
+ Object newValue = target.get(entry.getValue());
+
+ if (newValue != null) {
+ entry.setValue(newValue);
+ }
+ }
+
+ source.updateSymbolMapDependentValues();
+}
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/SourceNodePlannerVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/xml/SourceNodePlannerVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/SourceNodePlannerVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,453 +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.optimizer.xml;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryPlannerException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.query.mapping.relational.QueryNode;
-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.TempMetadataAdapter;
-import org.teiid.query.metadata.TempMetadataStore;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.SubqueryFromClause;
-import org.teiid.query.sql.lang.UnaryFromClause;
-import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
-import org.teiid.query.sql.visitor.SQLStringVisitor;
-
-
-
-/**
- * This visitor will take source node's QueryNode, move the the inputset criteria
- * specified on the QueryNode on to the Source Node's query.
- */
-public class SourceNodePlannerVisitor extends MappingVisitor {
- private XMLPlannerEnvironment planEnv;
-
- public SourceNodePlannerVisitor(XMLPlannerEnvironment planEnv) {
- this.planEnv = planEnv;
- }
-
- public void visit(MappingSourceNode sourceNode) {
-
- try {
- // create a basic query for the mapping class.
- String groupName = sourceNode.getResultName();
- GroupSymbol groupSymbol = null;
- GroupSymbol newGroupSymbol = null;
-
- try {
- groupSymbol = QueryUtil.createResolvedGroup(groupName, planEnv.getGlobalMetadata());
- newGroupSymbol = createAlternateGroup(groupSymbol, sourceNode);
- } catch (QueryMetadataException e) {
- /*
- * JIRA JBEDSP-531 if a node is excluded and has no transformation, then it matches the
- * designer notion of an incomplete document. we'll allow this by removing everything
- * starting at this point
- */
- MappingNode current = sourceNode;
- boolean isExcluded = false;
- while (current != null) {
- if (current.isExcluded()) {
- isExcluded = true;
- break;
- }
- current = current.getParent();
- }
- if (!isExcluded) {
- throw e;
- }
- //cut me and everything below me from the tree
- sourceNode.getParent().getChildren().remove(sourceNode);
- sourceNode.getChildren().clear();
- return;
- }
- String newGroup = newGroupSymbol.getName();
-
- ResultSetInfo rsInfo = sourceNode.getResultSetInfo();
- //create the command off of the unresolved group symbol
- Query baseQuery = QueryUtil.wrapQuery(new UnaryFromClause(new GroupSymbol(newGroup)), newGroup);
- baseQuery.getSelect().clearSymbols();
- for (Iterator<ElementSymbol> i = ResolverUtil.resolveElementsInGroup(groupSymbol, planEnv.getGlobalMetadata()).iterator(); i.hasNext();) {
- ElementSymbol ses = i.next();
- baseQuery.getSelect().addSymbol(new ElementSymbol(newGroup + SingleElementSymbol.SEPARATOR + ses.getShortName()));
- }
-
- rsInfo.setCommand(baseQuery);
-
- QueryNode modifiedNode = QueryUtil.getQueryNode(newGroup, planEnv.getGlobalMetadata());
- Command command = QueryUtil.getQuery(newGroup, modifiedNode, planEnv);
-
- MappingSourceNode parent = sourceNode.getParentSourceNode();
- Collection<ElementSymbol> bindings = QueryUtil.getBindingElements(modifiedNode);
- // 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)) {
- return;
- }
-
- // now get the criteria set at the design time; and walk and remove any inputset
- // criteria.
- Query transformationQuery = (Query)command;
-
- Criteria criteria = transformationQuery.getCriteria();
- Criteria nonInputsetCriteria = null;
- Criteria inputSetCriteria = null;
-
- for (Iterator<Criteria> i = Criteria.separateCriteriaByAnd(criteria).iterator(); i.hasNext();) {
- Criteria conjunct = i.next();
-
- // collect references in the criteria; if there are references; then this is
- // set by inputset criteria
- Collection<ElementSymbol> references = QueryUtil.getBindingsReferences(conjunct, bindings);
- if (references.isEmpty()) {
- nonInputsetCriteria = Criteria.combineCriteria(nonInputsetCriteria, conjunct);
- }
- else {
- inputSetCriteria = Criteria.combineCriteria(inputSetCriteria, conjunct);
- }
- }
-
- // Keep the criteria which is not reference based.
- transformationQuery.setCriteria(nonInputsetCriteria);
-
- // check and map/convert the inputset criteria elements to groupName, so that
- // this criteria mapped on the baseQuery;
-
- boolean addedProjectedSymbol = convertCriteria(newGroupSymbol, transformationQuery, inputSetCriteria, planEnv.getGlobalMetadata(), sourceNode.getSymbolMap());
- if (addedProjectedSymbol && transformationQuery.getSelect().isDistinct()) {
- transformationQuery.getSelect().setDistinct(false);
- baseQuery.getSelect().setDistinct(true);
- }
-
- String inlineViewName = planEnv.getAliasName(newGroup);
- transformationQuery = QueryUtil.wrapQuery(new SubqueryFromClause(inlineViewName, transformationQuery), inlineViewName);
-
- // Now that we have the modified Query Node for the group name
- // we need to update the metadata.
- QueryNode relationalNode = new QueryNode(SQLStringVisitor.getSQLString(transformationQuery));
- planEnv.addQueryNodeToMetadata(newGroupSymbol.getMetadataID(), relationalNode);
-
- QueryUtil.markBindingsAsNonExternal(inputSetCriteria, bindings);
-
- baseQuery.setCriteria(inputSetCriteria);
- rsInfo.setCriteriaRaised(true);
- } catch (Exception e) {
- throw new TeiidRuntimeException(e);
- }
- }
-
- /**
- * check to make sure that given query nodes bindings are only to the node provided,
- * if they are returns true; false otherwise
- */
- private boolean areBindingsOnlyToNode(QueryNode modifiedNode, MappingSourceNode sourceNode)
- throws TeiidComponentException {
-
- List<SingleElementSymbol> bindings = QueryResolver.parseBindings(modifiedNode);
-
- String nodeStr = (sourceNode.getActualResultSetName() + ElementSymbol.SEPARATOR).toUpperCase();
-
- for (Iterator<SingleElementSymbol> i = bindings.iterator(); i.hasNext();) {
- SingleElementSymbol ses = i.next();
- if (ses instanceof AliasSymbol) {
- ses = ((AliasSymbol)ses).getSymbol();
- }
- ElementSymbol binding = (ElementSymbol)ses;
-
- if (!binding.getCanonicalName().startsWith(nodeStr)) {
- return false;
- }
- }
-
- return true;
- }
-
- static String getNewName(String groupName, TempMetadataStore store) {
- int index = 1;
- String newGroup = null;
- while (true) {
- newGroup = (groupName + "_" + index++).toUpperCase(); //$NON-NLS-1$
- if (!store.getData().containsKey(newGroup)) {
- break;
- }
- }
- return newGroup;
- }
-
- /**
- * In mapping document, sometimes sibiling nodes might share the mapping class defination,
- * however during the runtime depending upon where they are used their criteria may be
- * different on different path of execution (choice nodes), so here we alias all the result
- * set names in a mapping document.
- */
- private GroupSymbol createAlternateGroup(GroupSymbol oldSymbol, MappingSourceNode sourceNode)
- throws QueryMetadataException, TeiidComponentException, QueryPlannerException {
-
- // get elements in the old group
- List elements = ResolverUtil.resolveElementsInGroup(oldSymbol, planEnv.getGlobalMetadata());
-
- TempMetadataStore store = planEnv.getGlobalMetadata().getMetadataStore();
-
- // create a new group name and to the temp store
- String newGroup = getNewName(oldSymbol.getName(), store);
- GroupSymbol newGroupSymbol = new GroupSymbol(newGroup);
- newGroupSymbol.setMetadataID(store.addTempGroup(newGroup, elements));
-
- // create a symbol map; so that all the others who refer by the old name can use this map
- // to convert to new group.
- sourceNode.setSymbolMap(QueryUtil.createSymbolMap(oldSymbol, newGroup, elements));
-
- // now that we created a new group; now define the query node for this new group based
- // on the old one.
- QueryNode oldQueryNode = QueryUtil.getQueryNode(oldSymbol.getName(), planEnv.getGlobalMetadata());
-
- // move the query and its bindings
- QueryNode modifiedNode = new QueryNode(oldQueryNode.getQuery());
- mapBindings(sourceNode, oldQueryNode, modifiedNode);
-
- // add the query node for the new group into metadata.
- planEnv.addQueryNodeToMetadata(newGroupSymbol.getMetadataID(), modifiedNode);
-
- return newGroupSymbol;
- }
-
- static void mapBindings(MappingSourceNode sourceNode,
- QueryNode oldQueryNode,
- QueryNode modifiedNode) throws TeiidComponentException {
- if (oldQueryNode.getBindings() != null) {
- List<String> bindings = new ArrayList<String>();
- for (Iterator<SingleElementSymbol> i = QueryResolver.parseBindings(oldQueryNode).iterator(); i.hasNext();) {
- SingleElementSymbol ses = i.next();
- String name = ses.getName();
- boolean useName = false;
- if (ses instanceof AliasSymbol) {
- ses = ((AliasSymbol)ses).getSymbol();
- useName = true;
- }
- ElementSymbol es = (ElementSymbol)ses;
- if (!useName) {
- bindings.add(sourceNode.getMappedSymbol(es).toString());
- } else {
- bindings.add(new AliasSymbol(name, sourceNode.getMappedSymbol(es)).toString());
- }
- }
- modifiedNode.setBindings(bindings);
- }
- }
-
- private boolean canRaiseInputset(Command command, Collection<ElementSymbol> bindings) throws TeiidComponentException {
- // check to see if this is query.
- if (!(command instanceof Query)) {
- return false;
- }
-
- Query query = (Query)command;
- Criteria crit = query.getCriteria();
-
- if (crit != null && (query.getGroupBy() != null || query.getHaving() != null || query.getLimit() != null)) {
- return false;
- }
- //temporarily remove the criteria
- query.setCriteria(null);
- //just throw away order by
- query.setOrderBy(null);
-
- List<ElementSymbol> references = QueryUtil.getBindingsReferences(query, bindings);
-
- query.setCriteria(crit);
-
- //if there are any input set bindings in the rest of the command, don't convert
- return references.isEmpty();
- }
-
- /**
- * Convert the critria group elements from its native group to supplied group.
- * @param newGroupSymbol - group to which the criterial elements to be modified
- * @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 {
-
- String groupName = newGroupSymbol.getName();
- Collection<ElementSymbol> elementsInCriteria = ElementCollectorVisitor.getElements(criteria, true);
- Map mappedElements = new HashMap();
-
- List projectedSymbols = transformationQuery.getProjectedSymbols();
-
- boolean addedProjectedSymbol = false;
-
- for (Iterator<ElementSymbol> i = elementsInCriteria.iterator(); i.hasNext();) {
-
- final ElementSymbol symbol = i.next();
-
- if (symbol.isExternalReference()) {
- continue;
- }
-
- if (projectedSymbols.contains(symbol)) {
- mappedElements.put(symbol, new ElementSymbol(groupName + ElementSymbol.SEPARATOR + symbol.getShortName()));
- continue;
- }
- AliasSymbol alias = getMachingAlias(projectedSymbols, symbol);
- if (alias != null) {
- mappedElements.put(symbol, new ElementSymbol(groupName + ElementSymbol.SEPARATOR + alias.getShortName()));
- continue;
- }
- // this means that the criteria symbol, is not projected, so add the element symbol
- // to query node, so that it is projected.
-
- String name = getNewSymbolName(newGroupSymbol.getName(), symbol, symbolMap);
-
- AliasSymbol selectSymbol = new AliasSymbol(name, symbol);
-
- transformationQuery.getSelect().addSymbol(selectSymbol);
- addedProjectedSymbol = true;
-
- // also add to the projected elements on the temp group.
- metadata.getMetadataStore().addElementSymbolToTempGroup(newGroupSymbol.getName(), selectSymbol);
-
- ElementSymbol upperSymbol = new ElementSymbol(groupName + ElementSymbol.SEPARATOR + selectSymbol.getShortName());
- mappedElements.put(symbol, upperSymbol);
-
- //add to the symbol map. the base symbol is not to the original group, since it doesn't really project this element
- symbolMap.put(upperSymbol, upperSymbol);
- }
-
- // now that we have resolved criteria elements; map them correctly
- ExpressionMappingVisitor.mapExpressions(criteria, mappedElements);
- return addedProjectedSymbol;
- }
-
- static String getNewSymbolName(String newGroupName,
- ElementSymbol elementSymbol,
- Map symbolMap) {
-
- int index = 1;
-
- String newSymbolName = elementSymbol.getShortName();
-
- while (symbolMap.values().contains(new ElementSymbol(newGroupName + ElementSymbol.SEPARATOR + newSymbolName))) {
- newSymbolName = elementSymbol.getShortName() + "_" + index++; //$NON-NLS-1$
- }
-
- return newSymbolName;
- }
-
- /**
- * 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();
- if (element instanceof AliasSymbol) {
- AliasSymbol alias = (AliasSymbol)element;
- if (alias.getSymbol().equals(symbol)) {
- return alias;
- }
- }
- }
- return null;
- }
-
- /**
- * try to split the criteria based on if that is inputset criteria or not.
- * @param doc
- * @param planEnv
- * @return
- */
- public static MappingDocument raiseInputSet(MappingDocument doc, XMLPlannerEnvironment planEnv)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
- SourceNodePlannerVisitor real = new SourceNodePlannerVisitor(planEnv);
- planWalk(doc, real);
- return doc;
- }
-
- private static void planWalk(MappingDocument doc, MappingVisitor visitor)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- try {
- Navigator walker = new Navigator(true, visitor) {
-
- /*
- * Special walking of children so that we can safely remove nodes
- */
- @Override
- protected void walkChildNodes(MappingNode element) {
- List children = new ArrayList(element.getNodeChildren());
- for(Iterator i=children.iterator(); i.hasNext();) {
-
- if (shouldAbort()) {
- break;
- }
-
- MappingNode node = (MappingNode)i.next();
- node.acceptVisitor(this);
- }
- }
- };
-
- doc.acceptVisitor(walker);
- } catch (TeiidRuntimeException e) {
- if (e.getCause() instanceof QueryPlannerException) {
- throw (QueryPlannerException)e.getCause();
- }
- else if (e.getCause() instanceof QueryMetadataException) {
- throw (QueryMetadataException)e.getCause();
- }
- else if (e.getCause() instanceof TeiidComponentException) {
- throw (TeiidComponentException)e.getCause();
- }
- else {
- throw e;
- }
- }
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/SourceNodePlannerVisitor.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/xml/SourceNodePlannerVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/SourceNodePlannerVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/SourceNodePlannerVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,450 @@
+/*
+ * 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.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryPlannerException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.query.mapping.relational.QueryNode;
+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.TempMetadataAdapter;
+import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.SubqueryFromClause;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.symbol.AliasSymbol;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
+import org.teiid.query.sql.visitor.SQLStringVisitor;
+
+
+
+/**
+ * This visitor will take source node's QueryNode, move the the inputset criteria
+ * specified on the QueryNode on to the Source Node's query.
+ */
+public class SourceNodePlannerVisitor extends MappingVisitor {
+ private XMLPlannerEnvironment planEnv;
+
+ public SourceNodePlannerVisitor(XMLPlannerEnvironment planEnv) {
+ this.planEnv = planEnv;
+ }
+
+ public void visit(MappingSourceNode sourceNode) {
+
+ try {
+ // create a basic query for the mapping class.
+ String groupName = sourceNode.getResultName();
+ GroupSymbol groupSymbol = null;
+ GroupSymbol newGroupSymbol = null;
+
+ try {
+ groupSymbol = QueryUtil.createResolvedGroup(groupName, planEnv.getGlobalMetadata());
+ newGroupSymbol = createAlternateGroup(groupSymbol, sourceNode);
+ } catch (QueryMetadataException e) {
+ /*
+ * JIRA JBEDSP-531 if a node is excluded and has no transformation, then it matches the
+ * designer notion of an incomplete document. we'll allow this by removing everything
+ * starting at this point
+ */
+ MappingNode current = sourceNode;
+ boolean isExcluded = false;
+ while (current != null) {
+ if (current.isExcluded()) {
+ isExcluded = true;
+ break;
+ }
+ current = current.getParent();
+ }
+ if (!isExcluded) {
+ throw e;
+ }
+ //cut me and everything below me from the tree
+ sourceNode.getParent().getChildren().remove(sourceNode);
+ sourceNode.getChildren().clear();
+ return;
+ }
+ String newGroup = newGroupSymbol.getName();
+
+ ResultSetInfo rsInfo = sourceNode.getResultSetInfo();
+ //create the command off of the unresolved group symbol
+ Query baseQuery = QueryUtil.wrapQuery(new UnaryFromClause(new GroupSymbol(newGroup)), newGroup);
+ baseQuery.getSelect().clearSymbols();
+ for (Iterator<ElementSymbol> i = ResolverUtil.resolveElementsInGroup(groupSymbol, planEnv.getGlobalMetadata()).iterator(); i.hasNext();) {
+ ElementSymbol ses = i.next();
+ baseQuery.getSelect().addSymbol(new ElementSymbol(newGroup + SingleElementSymbol.SEPARATOR + ses.getShortName()));
+ }
+
+ rsInfo.setCommand(baseQuery);
+
+ QueryNode modifiedNode = QueryUtil.getQueryNode(newGroup, planEnv.getGlobalMetadata());
+ Command command = QueryUtil.getQuery(newGroup, modifiedNode, planEnv);
+
+ MappingSourceNode parent = sourceNode.getParentSourceNode();
+ Collection<ElementSymbol> bindings = QueryUtil.getBindingElements(modifiedNode);
+ // 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 sure bindings are only to parent.
+ if (parent == null || !canRaiseInputset(command, bindings) || !areBindingsOnlyToNode(modifiedNode, parent)) {
+ return;
+ }
+
+ // now get the criteria set at the design time; and walk and remove any inputset
+ // criteria.
+ Query transformationQuery = (Query)command;
+
+ Criteria criteria = transformationQuery.getCriteria();
+ Criteria nonInputsetCriteria = null;
+ Criteria inputSetCriteria = null;
+
+ for (Iterator<Criteria> i = Criteria.separateCriteriaByAnd(criteria).iterator(); i.hasNext();) {
+ Criteria conjunct = i.next();
+
+ // collect references in the criteria; if there are references; then this is
+ // set by inputset criteria
+ Collection<ElementSymbol> references = QueryUtil.getBindingsReferences(conjunct, bindings);
+ if (references.isEmpty()) {
+ nonInputsetCriteria = Criteria.combineCriteria(nonInputsetCriteria, conjunct);
+ }
+ else {
+ inputSetCriteria = Criteria.combineCriteria(inputSetCriteria, conjunct);
+ }
+ }
+
+ // Keep the criteria which is not reference based.
+ transformationQuery.setCriteria(nonInputsetCriteria);
+
+ // check and map/convert the inputset criteria elements to groupName, so that
+ // this criteria mapped on the baseQuery;
+
+ boolean addedProjectedSymbol = convertCriteria(newGroupSymbol, transformationQuery, inputSetCriteria, planEnv.getGlobalMetadata(), sourceNode.getSymbolMap());
+ if (addedProjectedSymbol && transformationQuery.getSelect().isDistinct()) {
+ transformationQuery.getSelect().setDistinct(false);
+ baseQuery.getSelect().setDistinct(true);
+ }
+
+ String inlineViewName = planEnv.getAliasName(newGroup);
+ transformationQuery = QueryUtil.wrapQuery(new SubqueryFromClause(inlineViewName, transformationQuery), inlineViewName);
+
+ // Now that we have the modified Query Node for the group name
+ // we need to update the metadata.
+ QueryNode relationalNode = new QueryNode(SQLStringVisitor.getSQLString(transformationQuery));
+ planEnv.addQueryNodeToMetadata(newGroupSymbol.getMetadataID(), relationalNode);
+
+ QueryUtil.markBindingsAsNonExternal(inputSetCriteria, bindings);
+
+ baseQuery.setCriteria(inputSetCriteria);
+ rsInfo.setCriteriaRaised(true);
+ } catch (Exception e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+
+ /**
+ * check to make sure that given query nodes bindings are only to the node provided,
+ * if they are returns true; false otherwise
+ */
+ private boolean areBindingsOnlyToNode(QueryNode modifiedNode, MappingSourceNode sourceNode)
+ throws TeiidComponentException {
+
+ List<SingleElementSymbol> bindings = QueryResolver.parseBindings(modifiedNode);
+
+ String nodeStr = (sourceNode.getActualResultSetName() + ElementSymbol.SEPARATOR).toUpperCase();
+
+ for (Iterator<SingleElementSymbol> i = bindings.iterator(); i.hasNext();) {
+ SingleElementSymbol ses = i.next();
+ if (ses instanceof AliasSymbol) {
+ ses = ((AliasSymbol)ses).getSymbol();
+ }
+ ElementSymbol binding = (ElementSymbol)ses;
+
+ if (!binding.getCanonicalName().startsWith(nodeStr)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ static String getNewName(String groupName, TempMetadataStore store) {
+ int index = 1;
+ String newGroup = null;
+ while (true) {
+ newGroup = (groupName + "_" + index++).toUpperCase(); //$NON-NLS-1$
+ if (!store.getData().containsKey(newGroup)) {
+ break;
+ }
+ }
+ return newGroup;
+ }
+
+ /**
+ * In mapping document, sometimes sibiling nodes might share the mapping class defination,
+ * however during the runtime depending upon where they are used their criteria may be
+ * different on different path of execution (choice nodes), so here we alias all the result
+ * set names in a mapping document.
+ */
+ private GroupSymbol createAlternateGroup(GroupSymbol oldSymbol, MappingSourceNode sourceNode)
+ throws QueryMetadataException, TeiidComponentException, QueryPlannerException {
+
+ // get elements in the old group
+ List<ElementSymbol> elements = ResolverUtil.resolveElementsInGroup(oldSymbol, planEnv.getGlobalMetadata());
+
+ TempMetadataStore store = planEnv.getGlobalMetadata().getMetadataStore();
+
+ // create a new group name and to the temp store
+ String newGroup = getNewName(oldSymbol.getName(), store);
+ GroupSymbol newGroupSymbol = new GroupSymbol(newGroup);
+ newGroupSymbol.setMetadataID(store.addTempGroup(newGroup, elements));
+
+ // create a symbol map; so that all the others who refer by the old name can use this map
+ // to convert to new group.
+ sourceNode.setSymbolMap(QueryUtil.createSymbolMap(oldSymbol, newGroup, elements));
+
+ // now that we created a new group; now define the query node for this new group based
+ // on the old one.
+ QueryNode oldQueryNode = QueryUtil.getQueryNode(oldSymbol.getName(), planEnv.getGlobalMetadata());
+
+ // move the query and its bindings
+ QueryNode modifiedNode = new QueryNode(oldQueryNode.getQuery());
+ mapBindings(sourceNode, oldQueryNode, modifiedNode);
+
+ // add the query node for the new group into metadata.
+ planEnv.addQueryNodeToMetadata(newGroupSymbol.getMetadataID(), modifiedNode);
+
+ return newGroupSymbol;
+ }
+
+ static void mapBindings(MappingSourceNode sourceNode,
+ QueryNode oldQueryNode,
+ QueryNode modifiedNode) throws TeiidComponentException {
+ if (oldQueryNode.getBindings() != null) {
+ List<String> bindings = new ArrayList<String>();
+ for (Iterator<SingleElementSymbol> i = QueryResolver.parseBindings(oldQueryNode).iterator(); i.hasNext();) {
+ SingleElementSymbol ses = i.next();
+ String name = ses.getName();
+ boolean useName = false;
+ if (ses instanceof AliasSymbol) {
+ ses = ((AliasSymbol)ses).getSymbol();
+ useName = true;
+ }
+ ElementSymbol es = (ElementSymbol)ses;
+ if (!useName) {
+ bindings.add(sourceNode.getMappedSymbol(es).toString());
+ } else {
+ bindings.add(new AliasSymbol(name, sourceNode.getMappedSymbol(es)).toString());
+ }
+ }
+ modifiedNode.setBindings(bindings);
+ }
+ }
+
+ private boolean canRaiseInputset(Command command, Collection<ElementSymbol> bindings) {
+ // check to see if this is query.
+ if (!(command instanceof Query)) {
+ return false;
+ }
+
+ Query query = (Query)command;
+ Criteria crit = query.getCriteria();
+
+ if (crit != null && (query.getGroupBy() != null || query.getHaving() != null || query.getLimit() != null)) {
+ return false;
+ }
+ //temporarily remove the criteria
+ query.setCriteria(null);
+ //just throw away order by
+ query.setOrderBy(null);
+
+ List<ElementSymbol> references = QueryUtil.getBindingsReferences(query, bindings);
+
+ query.setCriteria(crit);
+
+ //if there are any input set bindings in the rest of the command, don't convert
+ return references.isEmpty();
+ }
+
+ /**
+ * Convert the critria group elements from its native group to supplied group.
+ * @param newGroupSymbol - group to which the criterial elements to be modified
+ * @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) {
+
+ String groupName = newGroupSymbol.getName();
+ Collection<ElementSymbol> elementsInCriteria = ElementCollectorVisitor.getElements(criteria, true);
+ Map<ElementSymbol, ElementSymbol> mappedElements = new HashMap<ElementSymbol, ElementSymbol>();
+
+ List<SingleElementSymbol> projectedSymbols = transformationQuery.getProjectedSymbols();
+
+ boolean addedProjectedSymbol = false;
+
+ for (Iterator<ElementSymbol> i = elementsInCriteria.iterator(); i.hasNext();) {
+
+ final ElementSymbol symbol = i.next();
+
+ if (symbol.isExternalReference()) {
+ continue;
+ }
+
+ if (projectedSymbols.contains(symbol)) {
+ mappedElements.put(symbol, new ElementSymbol(groupName + ElementSymbol.SEPARATOR + symbol.getShortName()));
+ continue;
+ }
+ AliasSymbol alias = getMachingAlias(projectedSymbols, symbol);
+ if (alias != null) {
+ mappedElements.put(symbol, new ElementSymbol(groupName + ElementSymbol.SEPARATOR + alias.getShortName()));
+ continue;
+ }
+ // this means that the criteria symbol, is not projected, so add the element symbol
+ // to query node, so that it is projected.
+
+ String name = getNewSymbolName(newGroupSymbol.getName(), symbol, symbolMap);
+
+ AliasSymbol selectSymbol = new AliasSymbol(name, symbol);
+
+ transformationQuery.getSelect().addSymbol(selectSymbol);
+ addedProjectedSymbol = true;
+
+ // also add to the projected elements on the temp group.
+ metadata.getMetadataStore().addElementSymbolToTempGroup(newGroupSymbol.getName(), selectSymbol);
+
+ ElementSymbol upperSymbol = new ElementSymbol(groupName + ElementSymbol.SEPARATOR + selectSymbol.getShortName());
+ mappedElements.put(symbol, upperSymbol);
+
+ //add to the symbol map. the base symbol is not to the original group, since it doesn't really project this element
+ symbolMap.put(upperSymbol, upperSymbol);
+ }
+
+ // now that we have resolved criteria elements; map them correctly
+ ExpressionMappingVisitor.mapExpressions(criteria, mappedElements);
+ return addedProjectedSymbol;
+ }
+
+ static String getNewSymbolName(String newGroupName,
+ ElementSymbol elementSymbol,
+ Map symbolMap) {
+
+ int index = 1;
+
+ String newSymbolName = elementSymbol.getShortName();
+
+ while (symbolMap.values().contains(new ElementSymbol(newGroupName + ElementSymbol.SEPARATOR + newSymbolName))) {
+ newSymbolName = elementSymbol.getShortName() + "_" + index++; //$NON-NLS-1$
+ }
+
+ return newSymbolName;
+ }
+
+ /**
+ * If the element has alias wrapping, then return the matching alias element.
+ * @return matched alias symbol; null otherwise.
+ */
+ 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)) {
+ return alias;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * try to split the criteria based on if that is inputset criteria or not.
+ * @param doc
+ * @param planEnv
+ * @return
+ */
+ public static MappingDocument raiseInputSet(MappingDocument doc, XMLPlannerEnvironment planEnv)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+ SourceNodePlannerVisitor real = new SourceNodePlannerVisitor(planEnv);
+ planWalk(doc, real);
+ return doc;
+ }
+
+ private static void planWalk(MappingDocument doc, MappingVisitor visitor)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ try {
+ Navigator walker = new Navigator(true, visitor) {
+
+ /*
+ * Special walking of children so that we can safely remove nodes
+ */
+ @Override
+ protected void walkChildNodes(MappingNode element) {
+ List<MappingNode> children = new ArrayList<MappingNode>(element.getNodeChildren());
+ for(Iterator<MappingNode> i=children.iterator(); i.hasNext();) {
+
+ if (shouldAbort()) {
+ break;
+ }
+
+ MappingNode node = i.next();
+ node.acceptVisitor(this);
+ }
+ }
+ };
+
+ doc.acceptVisitor(walker);
+ } catch (TeiidRuntimeException e) {
+ if (e.getCause() instanceof QueryPlannerException) {
+ throw (QueryPlannerException)e.getCause();
+ }
+ else if (e.getCause() instanceof QueryMetadataException) {
+ throw (QueryMetadataException)e.getCause();
+ }
+ else if (e.getCause() instanceof TeiidComponentException) {
+ throw (TeiidComponentException)e.getCause();
+ }
+ else {
+ throw e;
+ }
+ }
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ValidateMappedCriteriaVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/xml/ValidateMappedCriteriaVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ValidateMappedCriteriaVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,124 +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.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;
-import org.teiid.api.exception.query.QueryPlannerException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.query.mapping.xml.MappingCriteriaNode;
-import org.teiid.query.mapping.xml.MappingDocument;
-import org.teiid.query.mapping.xml.MappingRecursiveElement;
-import org.teiid.query.mapping.xml.MappingVisitor;
-import org.teiid.query.mapping.xml.Navigator;
-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;
-
-
-/**
- * Validate the criteria specified on the elements.
- */
-public class ValidateMappedCriteriaVisitor extends MappingVisitor {
- XMLPlannerEnvironment planEnv;
-
- public ValidateMappedCriteriaVisitor( XMLPlannerEnvironment planEnv) {
- this.planEnv = planEnv;
- }
-
- public void visit(MappingCriteriaNode element) {
- String criteriaStr = element.getCriteria();
- Map symbolMap = element.getSourceNode().buildFullSymbolMap();
- Criteria criteria = resolveCriteria(criteriaStr, symbolMap);
- if (criteria != null) {
- List groupNames = getCriteriaGroups(criteria);
- element.setCriteriaNode(criteria);
- element.setGroupsInCriteria(groupNames);
- }
- }
-
- public void visit(MappingRecursiveElement element) {
- String criteriaStr = element.getCriteria();
- Map symbolMap = element.getSourceNode().buildFullSymbolMap();
- Criteria criteria = resolveCriteria(criteriaStr, symbolMap);
- if (criteria != null) {
- List groupNames = getCriteriaGroups(criteria);
- element.setCriteriaNode(criteria);
- element.setGroupsInCriteria(groupNames);
- }
- }
-
- Criteria resolveCriteria(String criteriaString, Map symbolMap) {
- if (criteriaString != null && criteriaString.length() > 0) {
- try {
- Criteria crit = QueryParser.getQueryParser().parseCriteria(criteriaString);
- StaticSymbolMappingVisitor.mapSymbols(crit, symbolMap);
- ResolverVisitor.resolveLanguageObject(crit, null, planEnv.getGlobalMetadata());
- return crit;
- } catch (Exception e) {
- throw new TeiidRuntimeException(e);
- }
- }
- 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 {
-
- try {
- ValidateMappedCriteriaVisitor visitor = new ValidateMappedCriteriaVisitor(planEnv);
- doc.acceptVisitor(new Navigator(true, visitor));
- } catch (TeiidRuntimeException e) {
- if (e.getCause() instanceof QueryPlannerException) {
- throw (QueryPlannerException)e.getCause();
- }
- else if (e.getCause() instanceof QueryMetadataException) {
- throw (QueryMetadataException)e.getCause();
- }
- else if (e.getCause() instanceof TeiidComponentException) {
- throw (TeiidComponentException)e.getCause();
- }
- throw e;
- }
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ValidateMappedCriteriaVisitor.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/xml/ValidateMappedCriteriaVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ValidateMappedCriteriaVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/ValidateMappedCriteriaVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,103 @@
+/*
+ * 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.Map;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryPlannerException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.query.mapping.xml.MappingCriteriaNode;
+import org.teiid.query.mapping.xml.MappingDocument;
+import org.teiid.query.mapping.xml.MappingRecursiveElement;
+import org.teiid.query.mapping.xml.MappingVisitor;
+import org.teiid.query.mapping.xml.Navigator;
+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.visitor.StaticSymbolMappingVisitor;
+
+
+/**
+ * Validate the criteria specified on the elements.
+ */
+public class ValidateMappedCriteriaVisitor extends MappingVisitor {
+ XMLPlannerEnvironment planEnv;
+
+ public ValidateMappedCriteriaVisitor( XMLPlannerEnvironment planEnv) {
+ this.planEnv = planEnv;
+ }
+
+ public void visit(MappingCriteriaNode element) {
+ String criteriaStr = element.getCriteria();
+ Map symbolMap = element.getSourceNode().buildFullSymbolMap();
+ Criteria criteria = resolveCriteria(criteriaStr, symbolMap);
+ if (criteria != null) {
+ element.setCriteriaNode(criteria);
+ }
+ }
+
+ public void visit(MappingRecursiveElement element) {
+ String criteriaStr = element.getCriteria();
+ Map symbolMap = element.getSourceNode().buildFullSymbolMap();
+ Criteria criteria = resolveCriteria(criteriaStr, symbolMap);
+ if (criteria != null) {
+ element.setCriteriaNode(criteria);
+ }
+ }
+
+ Criteria resolveCriteria(String criteriaString, Map symbolMap) {
+ if (criteriaString != null && criteriaString.length() > 0) {
+ try {
+ Criteria crit = QueryParser.getQueryParser().parseCriteria(criteriaString);
+ StaticSymbolMappingVisitor.mapSymbols(crit, symbolMap);
+ ResolverVisitor.resolveLanguageObject(crit, null, planEnv.getGlobalMetadata());
+ return crit;
+ } catch (Exception e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+ return null;
+ }
+
+ public static void validateAndCollectCriteriaElements(MappingDocument doc, XMLPlannerEnvironment planEnv)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ try {
+ ValidateMappedCriteriaVisitor visitor = new ValidateMappedCriteriaVisitor(planEnv);
+ doc.acceptVisitor(new Navigator(true, visitor));
+ } catch (TeiidRuntimeException e) {
+ if (e.getCause() instanceof QueryPlannerException) {
+ throw (QueryPlannerException)e.getCause();
+ }
+ else if (e.getCause() instanceof QueryMetadataException) {
+ throw (QueryMetadataException)e.getCause();
+ }
+ else if (e.getCause() instanceof TeiidComponentException) {
+ throw (TeiidComponentException)e.getCause();
+ }
+ throw e;
+ }
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLNodeMappingVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/xml/XMLNodeMappingVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLNodeMappingVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.query.optimizer.xml;
-
-import java.util.Collection;
-
-import org.teiid.api.exception.query.QueryPlannerException;
-import org.teiid.core.TeiidComponentException;
-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.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.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Symbol;
-import org.teiid.query.sql.visitor.AbstractSymbolMappingVisitor;
-
-
-/**
- * This visitor is able to map symbols based on the XML document model:
- * given a symbol representing one of the nodes of the document which is
- * mapped, this object will find the Symbol representing the relational
- * element it is mapped to.
- */
-public class XMLNodeMappingVisitor extends AbstractSymbolMappingVisitor {
-
- private MappingNode rootNode;
- private QueryMetadataInterface metadata;
-
- /**
- * Constructor for XMLNodeMappingVisitor.
- */
- public XMLNodeMappingVisitor(MappingDocument rootNode, QueryMetadataInterface metadata) {
- this.rootNode = rootNode;
- this.metadata = metadata;
- }
-
- /**
- * @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();
-
- // Find mapping node for specified path
- MappingNode elementNode = MappingNode.findNode(rootNode, path);
- if(elementNode == null) {
- return null;
- }
-
- // Construct a new element node based on mapping node reference
- String symbolName = elementNode.getNameInSource();
- if (symbolName == null){
- return null;
- }
- return elementNode.getSourceNode().getMappedSymbol(new ElementSymbol(symbolName));
- } catch (TeiidComponentException err) {
- throw new TeiidRuntimeException(err);
- }
- }
-
- /**
- * Convert the criteria from names using document identifiers to names using
- * result set (i.e. mapping class) identifiers.
- * @param simpleCrit Criteria to convert
- * @param rootNode Root of mapping node tree
- * @return Criteria Converted criteria
- * @throws QueryPlannerException if simpleCrit has a XML document model element
- * that is not mapped to data in a mapping class
- */
- public static Criteria convertCriteria(Criteria simpleCrit, MappingDocument rootNode, QueryMetadataInterface metadata)
- throws QueryPlannerException, TeiidComponentException{
- return (Criteria)convertObject(simpleCrit, rootNode, metadata);
- }
-
- public static LanguageObject convertObject(LanguageObject object, MappingDocument rootNode, QueryMetadataInterface metadata)
- 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);
- } catch (TeiidRuntimeException e) {
- Throwable child = e.getChild();
-
- if (child instanceof TeiidComponentException) {
- throw (TeiidComponentException)child;
- }
-
- throw new TeiidComponentException(child);
- }
-
- Collection unmappedSymbols = mappingVisitor.getUnmappedSymbols();
- if (unmappedSymbols != null && unmappedSymbols.size() > 0){
- 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;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLNodeMappingVisitor.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/xml/XMLNodeMappingVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLNodeMappingVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLNodeMappingVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,154 @@
+/*
+ * 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.Collection;
+
+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.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;
+
+
+/**
+ * This visitor is able to map symbols based on the XML document model:
+ * given a symbol representing one of the nodes of the document which is
+ * mapped, this object will find the Symbol representing the relational
+ * element it is mapped to.
+ */
+public class XMLNodeMappingVisitor extends AbstractSymbolMappingVisitor {
+
+ private MappingNode rootNode;
+ private QueryMetadataInterface metadata;
+
+ /**
+ * Constructor for XMLNodeMappingVisitor.
+ */
+ public XMLNodeMappingVisitor(MappingDocument rootNode, QueryMetadataInterface metadata) {
+ this.rootNode = rootNode;
+ 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) {
+ try {
+ 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 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 = node.getNameInSource();
+ if (symbolName == null){
+ return null;
+ }
+ ElementSymbol es = msn.getMappedSymbol(new ElementSymbol(symbolName));
+ return es;
+ } catch (TeiidException err) {
+ throw new TeiidRuntimeException(err);
+ }
+ }
+
+ /**
+ * Convert the criteria from names using document identifiers to names using
+ * result set (i.e. mapping class) identifiers.
+ * @param simpleCrit Criteria to convert
+ * @param rootNode Root of mapping node tree
+ * @return Criteria Converted criteria
+ * @throws QueryPlannerException if simpleCrit has a XML document model element
+ * that is not mapped to data in a mapping class
+ */
+ public static Criteria convertCriteria(Criteria simpleCrit, MappingDocument rootNode, QueryMetadataInterface metadata)
+ throws QueryPlannerException, TeiidComponentException{
+ return convertObject((Criteria)simpleCrit.clone(), rootNode, metadata, true);
+ }
+
+ public static <T extends LanguageObject> T convertObject(T object, MappingDocument rootNode, QueryMetadataInterface metadata, boolean deep)
+ throws QueryPlannerException, TeiidComponentException{
+ //Don't want to do deep visiting
+ XMLNodeMappingVisitor mappingVisitor = new XMLNodeMappingVisitor(rootNode, metadata);
+ try {
+ PreOrPostOrderNavigator.doVisit(object, mappingVisitor, PreOrPostOrderNavigator.POST_ORDER, deep);
+ } catch (TeiidRuntimeException e) {
+ Throwable child = e.getChild();
+
+ if (child instanceof TeiidComponentException) {
+ throw (TeiidComponentException)child;
+ }
+
+ throw new TeiidComponentException(child);
+ }
+
+ Collection unmappedSymbols = mappingVisitor.getUnmappedSymbols();
+ if (unmappedSymbols != null && unmappedSymbols.size() > 0){
+ 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 object;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanToProcessVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanToProcessVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanToProcessVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,412 +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.optimizer.xml;
-
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Stack;
-
-import org.teiid.query.mapping.xml.InterceptingVisitor;
-import org.teiid.query.mapping.xml.MappingAllNode;
-import org.teiid.query.mapping.xml.MappingAttribute;
-import org.teiid.query.mapping.xml.MappingBaseNode;
-import org.teiid.query.mapping.xml.MappingChoiceNode;
-import org.teiid.query.mapping.xml.MappingCommentNode;
-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.MappingInterceptor;
-import org.teiid.query.mapping.xml.MappingRecursiveElement;
-import org.teiid.query.mapping.xml.MappingSequenceNode;
-import org.teiid.query.mapping.xml.MappingSourceNode;
-import org.teiid.query.mapping.xml.ResultSetInfo;
-import org.teiid.query.processor.xml.AbortProcessingInstruction;
-import org.teiid.query.processor.xml.AddNodeInstruction;
-import org.teiid.query.processor.xml.BlockInstruction;
-import org.teiid.query.processor.xml.Condition;
-import org.teiid.query.processor.xml.CriteriaCondition;
-import org.teiid.query.processor.xml.DefaultCondition;
-import org.teiid.query.processor.xml.EndBlockInstruction;
-import org.teiid.query.processor.xml.EndDocumentInstruction;
-import org.teiid.query.processor.xml.ExecSqlInstruction;
-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;
-import org.teiid.query.processor.xml.Program;
-import org.teiid.query.processor.xml.RecurseProgramCondition;
-import org.teiid.query.processor.xml.WhileInstruction;
-
-
-
-/**
- * This class converts the MappingDocument to a Program which can be executed using the
- * Query Processor
- */
-public class XMLPlanToProcessVisitor implements MappingInterceptor {
-
- Stack programStack = new Stack();
- XMLPlannerEnvironment planEnv;
- Program originalProgram ;
- Program cleanupProgram = new Program();
-
- public XMLPlanToProcessVisitor(XMLPlannerEnvironment env) {
- this.planEnv = env;
- }
-
- public void start(MappingDocument doc, Map context) {
- Program currentProgram = new Program();
- this.programStack.push(currentProgram);
- }
-
- public void end(MappingDocument doc, Map context) {
- // remove the current program from the stack; we no longer need this
- originalProgram=(Program)this.programStack.pop();
-
- // cleanup program will have instructions to unload the staging table.
- originalProgram.addInstructions(cleanupProgram);
- }
-
- public void start(MappingAttribute attribute, Map context){
- Program currentProgram = (Program)this.programStack.peek();
- ProcessorInstruction tagInst = TagBuilderVisitor.buildTag(attribute);
- if (tagInst != null) {
- currentProgram.addInstruction(tagInst);
- }
- }
-
- public void end(MappingAttribute attribute, Map context){
- }
-
- public void start(MappingCommentNode comment, Map context){
- Program currentProgram = (Program)this.programStack.peek();
- ProcessorInstruction tagInst = TagBuilderVisitor.buildTag(comment);
- if (tagInst != null) {
- currentProgram.addInstruction(tagInst);
- }
- }
-
- public void end(MappingCommentNode comment, Map context){
- // nothing to do
- }
-
- public void start(MappingAllNode all, Map context){
- commonStart(all, context);
- }
-
- public void end(MappingAllNode all, Map context){
- commonEnd(all, context);
- }
-
- public void start(MappingChoiceNode choice, Map context){
- IfInstruction ifInst = new IfInstruction();
- // if an exception should be thrown as the default choice, then add a sub program to that
- if (choice.throwExceptionOnDefault()) {
- Program subProgram = new Program();
- subProgram.addInstruction(new AbortProcessingInstruction());
- DefaultCondition defCondition = new DefaultCondition(subProgram);
- ifInst.setDefaultCondition(defCondition);
- }
-
- // to be used by the criteria nodes.
- context.put(choice, ifInst);
-
- // 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();
- currentProgram.addInstruction(ifInst);
- }
-
- public void end(MappingChoiceNode choice, Map context){
- commonEnd(choice, context);
-
- // what we put in must go..
- context.remove(choice);
- }
-
- public void start(MappingCriteriaNode node, Map context){
-
- // every criteria node has its own program..
- Program childProgram = new Program();
- IfInstruction ifInst = (IfInstruction)context.get(node.getParentNode());
-
- if (node.getCriteria() != null) {
- Condition condition = new CriteriaCondition(node.getCriteriaNode(), childProgram);
- ifInst.addCondition(condition);
- }
-
- if (node.isDefault()) {
- DefaultCondition defCondition = new DefaultCondition(childProgram);
- ifInst.setDefaultCondition(defCondition);
- }
-
- // now push the child program
- this.programStack.push(childProgram);
-
- // now call code for the common node element
- commonStart(node, context);
- }
-
- public void end(MappingCriteriaNode element, Map context){
-
- // do the common end..
- commonEnd(element, context);
-
- // pop the child program created in the begin of the node.
- this.programStack.pop();
- }
-
- public void start(MappingSequenceNode sequence, Map context){
- commonStart(sequence, context);
- }
-
- public void end(MappingSequenceNode sequence, Map context){
- commonEnd(sequence, context);
- }
-
- private void startRootRecursive(MappingBaseNode node, Map context) {
- Program childProgram = new Program();
- context.put(node.getRecursionId(), childProgram);
- this.programStack.push(childProgram);
- }
-
- private void endRootRecursive(MappingBaseNode node, Map context) {
- // add the recursive program to the main program.
- Program recursiveProgram = (Program)programStack.pop();
-
- // this is the main program
- Program currentProgram = (Program)this.programStack.peek();
- currentProgram.addInstructions(recursiveProgram);
- context.remove(node.getRecursionId());
-
- // defect 17575; In case of recursive node the top most element
- // name could be different from original; so take it it out, so that
- // recursive node can put what ever it needs as head.
- ProcessorInstruction firstInst = recursiveProgram.getInstructionAt(0);
- if (firstInst instanceof AddNodeInstruction) {
- recursiveProgram.removeInstructionAt(0);
- }
- }
-
- public void start(MappingElement element, Map context){
- //commonStart(element, context);
- Program currentProgram = (Program)programStack.peek();
-
- // if we are dealing with multiple documents
- startFragment(currentProgram, element);
-
- ProcessorInstruction tagInst = TagBuilderVisitor.buildTag(element);
- currentProgram.addInstruction(tagInst);
-
- commonStart(element, context);
-
- // 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.addInstruction(new MoveDocInstruction(MoveDocInstruction.DOWN));
- }
- }
-
- public void end(MappingElement element, Map context){
- Program currentProgram = (Program)this.programStack.peek();
-
- // If there were more children under this node move the cursor up
- if (!element.getChildren().isEmpty()) {
- currentProgram.addInstruction(new MoveDocInstruction(MoveDocInstruction.UP));
- }
-
- commonEnd(element, context);
-
- // update the program pointer
- currentProgram = (Program)programStack.peek();
-
- // if we are dealing with multiple documents
- endFragment(currentProgram, element);
- }
-
- public void start(MappingSourceNode node, Map context) {
- Program currentProgram = (Program)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);
-
- BlockInstruction blockInst = new BlockInstruction(source);
- currentProgram.addInstruction(blockInst);
-
- // Add instruction to read the first row in
- MoveCursorInstruction moveCursor = new MoveCursorInstruction(source);
- currentProgram.addInstruction(moveCursor);
-
- // set up while instruction, add sub Program
- WhileInstruction whileInst = new WhileInstruction(source);
- currentProgram.addInstruction(whileInst);
-
- Program childProgram = new Program();
- whileInst.setBlockProgram(childProgram);
-
- // when while is done close the resultset(note that the child program will
- // have all the statements.
- EndBlockInstruction closeInst = new EndBlockInstruction(source);
- currentProgram.addInstruction(closeInst);
-
- // push the new child program on to stack so that all the children use this
- // program; this must be at end of this block, as the once we exit here we
- // are going to loop for children with new program
- programStack.push(childProgram);
- }
-
- public void end(MappingSourceNode node, Map context) {
- Program currentProgram = (Program)programStack.peek();
-
- String source = node.getActualResultSetName();
- ResultSetInfo info= node.getResultSetInfo();
-
- if (!info.isJoinRoot()) {
- // 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
- this.programStack.pop();
-
- commonEnd(node, context);
- }
-
- private void startFragment(Program program, MappingBaseNode element) {
- // In the case that we are returning the multiple documents; we are going to treat them as
- // fragments, so do not add the header information
- if (element.isTagRoot()) {
- MappingDocument doc = element.getDocument();
- ProcessorInstruction header = new InitializeDocumentInstruction(doc.getDocumentEncoding(), doc.isFormatted());
- program.addInstruction(header);
- }
- }
-
- private void endFragment(Program program, MappingBaseNode element) {
- // In the case that we are returning the multiple documents; we are going to treat them as
- // fragments, so do not add the header information
- if (element.isTagRoot()) {
- program.addInstruction(new EndDocumentInstruction());
- }
- }
-
- private void commonStart(MappingBaseNode node, Map context) {
- // if this node is root of some recursive node then do below
- if (node.isRootRecursiveNode()) {
- // start recording the program.
- 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();
-
- // load staging
- currentProgram.addInstruction(new ExecStagingTableInstruction(table, planEnv.getStagingTableResultsInfo(table)));
-
- // unload sttaging
- String unloadName = planEnv.unLoadResultName(table);
- cleanupProgram.addInstruction(new ExecStagingTableInstruction(unloadName, planEnv.getStagingTableResultsInfo(unloadName)));
- } // for
- }
-
- private void commonEnd(MappingBaseNode node, Map context) {
- if (node.isRootRecursiveNode()) {
- // stop recording and update the program
- endRootRecursive(node, context);
- }
- }
-
- public void start(final MappingRecursiveElement element, Map context){
- Program currentProgram = (Program)programStack.peek();
-
- // if we are dealing with multiple documents
- startFragment(currentProgram, element);
-
- ProcessorInstruction tagInst = TagBuilderVisitor.buildTag(element);
- currentProgram.addInstruction(tagInst);
-
- // this is set by root recursive node. Note that the MappingClass on recursive
- // node is same as the source on the root recursive node.
- Program recursiveProgram = (Program)context.get(element.getMappingClass().toUpperCase());
- IfInstruction ifInst = new IfInstruction();
- RecurseProgramCondition recurseCondition = buildRecurseCondition(element, recursiveProgram);
- ifInst.addCondition(recurseCondition);
- ifInst.setDefaultCondition(new DefaultCondition(new Program()));
-
- currentProgram.addInstruction(ifInst);
- }
-
- public void end(final MappingRecursiveElement element, Map context){
- Program currentProgram = (Program)programStack.peek();
-
- // if we are dealing with multiple documents
- endFragment(currentProgram, element);
- }
-
- private static RecurseProgramCondition buildRecurseCondition(MappingRecursiveElement element, Program subProgram) {
- String criteriaString = element.getCriteria();
- RecurseProgramCondition condition = null;
-
- if (criteriaString == null || criteriaString.trim().length() == 0){
- condition = new RecurseProgramCondition(subProgram, null, element.getRecursionLimit(), element.throwExceptionOnRecurrsionLimit());
- }
- else {
- condition = new RecurseProgramCondition(subProgram, element.getCriteriaNode(), element.getRecursionLimit(), element.throwExceptionOnRecurrsionLimit());
- }
- return condition;
- }
-
- public static Program planProgram(MappingDocument doc, XMLPlannerEnvironment env) {
- XMLPlanToProcessVisitor visitor = new XMLPlanToProcessVisitor(env);
- doc.acceptVisitor(new InterceptingVisitor(visitor));
- return visitor.originalProgram;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanToProcessVisitor.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanToProcessVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanToProcessVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanToProcessVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.query.optimizer.xml;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Stack;
+
+import org.teiid.query.mapping.xml.InterceptingVisitor;
+import org.teiid.query.mapping.xml.MappingAllNode;
+import org.teiid.query.mapping.xml.MappingAttribute;
+import org.teiid.query.mapping.xml.MappingBaseNode;
+import org.teiid.query.mapping.xml.MappingChoiceNode;
+import org.teiid.query.mapping.xml.MappingCommentNode;
+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.MappingInterceptor;
+import org.teiid.query.mapping.xml.MappingRecursiveElement;
+import org.teiid.query.mapping.xml.MappingSequenceNode;
+import org.teiid.query.mapping.xml.MappingSourceNode;
+import org.teiid.query.mapping.xml.ResultSetInfo;
+import org.teiid.query.processor.xml.AbortProcessingInstruction;
+import org.teiid.query.processor.xml.AddNodeInstruction;
+import org.teiid.query.processor.xml.BlockInstruction;
+import org.teiid.query.processor.xml.Condition;
+import org.teiid.query.processor.xml.CriteriaCondition;
+import org.teiid.query.processor.xml.DefaultCondition;
+import org.teiid.query.processor.xml.EndBlockInstruction;
+import org.teiid.query.processor.xml.EndDocumentInstruction;
+import org.teiid.query.processor.xml.ExecSqlInstruction;
+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.MoveCursorInstruction;
+import org.teiid.query.processor.xml.MoveDocInstruction;
+import org.teiid.query.processor.xml.ProcessorInstruction;
+import org.teiid.query.processor.xml.Program;
+import org.teiid.query.processor.xml.RecurseProgramCondition;
+import org.teiid.query.processor.xml.WhileInstruction;
+
+
+
+/**
+ * This class converts the MappingDocument to a Program which can be executed using the
+ * Query Processor
+ */
+public class XMLPlanToProcessVisitor implements MappingInterceptor {
+
+ Stack<Program> programStack = new Stack<Program>();
+ XMLPlannerEnvironment planEnv;
+ Program originalProgram ;
+ Program cleanupProgram = new Program();
+
+ public XMLPlanToProcessVisitor(XMLPlannerEnvironment env) {
+ this.planEnv = env;
+ }
+
+ public void start(MappingDocument doc, Map context) {
+ Program currentProgram = new Program();
+ this.programStack.push(currentProgram);
+ }
+
+ public void end(MappingDocument doc, Map context) {
+ // remove the current program from the stack; we no longer need this
+ originalProgram=this.programStack.pop();
+
+ // cleanup program will have instructions to unload the staging table.
+ originalProgram.addInstructions(cleanupProgram);
+ }
+
+ public void start(MappingAttribute attribute, Map context){
+ Program currentProgram = this.programStack.peek();
+ ProcessorInstruction tagInst = TagBuilderVisitor.buildTag(attribute);
+ if (tagInst != null) {
+ currentProgram.addInstruction(tagInst);
+ }
+ }
+
+ public void end(MappingAttribute attribute, Map context){
+ }
+
+ public void start(MappingCommentNode comment, Map context){
+ Program currentProgram = this.programStack.peek();
+ ProcessorInstruction tagInst = TagBuilderVisitor.buildTag(comment);
+ if (tagInst != null) {
+ currentProgram.addInstruction(tagInst);
+ }
+ }
+
+ public void end(MappingCommentNode comment, Map context){
+ // nothing to do
+ }
+
+ public void start(MappingAllNode all, Map context){
+ commonStart(all, context);
+ }
+
+ public void end(MappingAllNode all, Map context){
+ commonEnd(all, context);
+ }
+
+ public void start(MappingChoiceNode choice, Map context){
+ IfInstruction ifInst = new IfInstruction();
+ // if an exception should be thrown as the default choice, then add a sub program to that
+ if (choice.throwExceptionOnDefault()) {
+ Program subProgram = new Program();
+ subProgram.addInstruction(new AbortProcessingInstruction());
+ DefaultCondition defCondition = new DefaultCondition(subProgram);
+ ifInst.setDefaultCondition(defCondition);
+ }
+
+ // to be used by the criteria nodes.
+ context.put(choice, ifInst);
+
+ // process the node as others (if see we have not done anything for this node yet..)
+ commonStart(choice, context);
+
+ Program currentProgram = this.programStack.peek();
+ currentProgram.addInstruction(ifInst);
+ }
+
+ public void end(MappingChoiceNode choice, Map context){
+ commonEnd(choice, context);
+
+ // what we put in must go..
+ context.remove(choice);
+ }
+
+ public void start(MappingCriteriaNode node, Map context){
+
+ // every criteria node has its own program..
+ Program childProgram = new Program();
+ IfInstruction ifInst = (IfInstruction)context.get(node.getParentNode());
+
+ if (node.getCriteria() != null) {
+ Condition condition = new CriteriaCondition(node.getCriteriaNode(), childProgram);
+ ifInst.addCondition(condition);
+ }
+
+ if (node.isDefault()) {
+ DefaultCondition defCondition = new DefaultCondition(childProgram);
+ ifInst.setDefaultCondition(defCondition);
+ }
+
+ // now push the child program
+ this.programStack.push(childProgram);
+
+ // now call code for the common node element
+ commonStart(node, context);
+ }
+
+ public void end(MappingCriteriaNode element, Map context){
+
+ // do the common end..
+ commonEnd(element, context);
+
+ // pop the child program created in the begin of the node.
+ this.programStack.pop();
+ }
+
+ public void start(MappingSequenceNode sequence, Map context){
+ commonStart(sequence, context);
+ }
+
+ public void end(MappingSequenceNode sequence, Map context){
+ commonEnd(sequence, context);
+ }
+
+ private void startRootRecursive(MappingBaseNode node, Map context) {
+ Program childProgram = new Program();
+ context.put(node.getRecursionId(), childProgram);
+ this.programStack.push(childProgram);
+ }
+
+ private void endRootRecursive(MappingBaseNode node, Map context) {
+ // add the recursive program to the main program.
+ Program recursiveProgram = programStack.pop();
+
+ // this is the main program
+ Program currentProgram = this.programStack.peek();
+ currentProgram.addInstructions(recursiveProgram);
+ context.remove(node.getRecursionId());
+
+ // defect 17575; In case of recursive node the top most element
+ // name could be different from original; so take it it out, so that
+ // recursive node can put what ever it needs as head.
+ ProcessorInstruction firstInst = recursiveProgram.getInstructionAt(0);
+ if (firstInst instanceof AddNodeInstruction) {
+ recursiveProgram.removeInstructionAt(0);
+ }
+ }
+
+ public void start(MappingElement element, Map context){
+ //commonStart(element, context);
+ Program currentProgram = programStack.peek();
+
+ // if we are dealing with multiple documents
+ startFragment(currentProgram, element);
+
+ ProcessorInstruction tagInst = TagBuilderVisitor.buildTag(element);
+ currentProgram.addInstruction(tagInst);
+
+ commonStart(element, context);
+
+ // If there are more children under this node move the cursor down
+ if (!element.getChildren().isEmpty()) {
+ // update the program pointer
+ currentProgram = programStack.peek();
+ currentProgram.addInstruction(new MoveDocInstruction(MoveDocInstruction.DOWN));
+ }
+ }
+
+ public void end(MappingElement element, Map context){
+ Program currentProgram = this.programStack.peek();
+
+ // If there were more children under this node move the cursor up
+ if (!element.getChildren().isEmpty()) {
+ currentProgram.addInstruction(new MoveDocInstruction(MoveDocInstruction.UP));
+ }
+
+ commonEnd(element, context);
+
+ // update the program pointer
+ currentProgram = programStack.peek();
+
+ // if we are dealing with multiple documents
+ endFragment(currentProgram, element);
+ }
+
+ public void start(MappingSourceNode node, Map context) {
+ Program currentProgram = programStack.peek();
+
+ commonStart(node, context);
+
+ String source = node.getActualResultSetName();
+ ResultSetInfo info= node.getResultSetInfo();
+
+ // Add instruction to execute relational query
+ ExecSqlInstruction sqlInst = new ExecSqlInstruction(source, info);
+ currentProgram.addInstruction(sqlInst);
+
+ BlockInstruction blockInst = new BlockInstruction(source);
+ currentProgram.addInstruction(blockInst);
+
+ // Add instruction to read the first row in
+ MoveCursorInstruction moveCursor = new MoveCursorInstruction(source);
+ currentProgram.addInstruction(moveCursor);
+
+ // set up while instruction, add sub Program
+ WhileInstruction whileInst = new WhileInstruction(source);
+ currentProgram.addInstruction(whileInst);
+
+ Program childProgram = new Program();
+ whileInst.setBlockProgram(childProgram);
+
+ // when while is done close the resultset(note that the child program will
+ // have all the statements.
+ EndBlockInstruction closeInst = new EndBlockInstruction(source);
+ currentProgram.addInstruction(closeInst);
+
+ // push the new child program on to stack so that all the children use this
+ // program; this must be at end of this block, as the once we exit here we
+ // are going to loop for children with new program
+ programStack.push(childProgram);
+ }
+
+ public void end(MappingSourceNode node, Map context) {
+ Program currentProgram = programStack.peek();
+
+ String source = node.getActualResultSetName();
+ ResultSetInfo info= node.getResultSetInfo();
+
+ // 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
+ this.programStack.pop();
+
+ commonEnd(node, context);
+ }
+
+ private void startFragment(Program program, MappingBaseNode element) {
+ // In the case that we are returning the multiple documents; we are going to treat them as
+ // fragments, so do not add the header information
+ if (element.isTagRoot()) {
+ MappingDocument doc = element.getDocument();
+ ProcessorInstruction header = new InitializeDocumentInstruction(doc.getDocumentEncoding(), doc.isFormatted());
+ program.addInstruction(header);
+ }
+ }
+
+ private void endFragment(Program program, MappingBaseNode element) {
+ // In the case that we are returning the multiple documents; we are going to treat them as
+ // fragments, so do not add the header information
+ if (element.isTagRoot()) {
+ program.addInstruction(new EndDocumentInstruction());
+ }
+ }
+
+ private void commonStart(MappingBaseNode node, Map context) {
+ // if this node is root of some recursive node then do below
+ if (node.isRootRecursiveNode()) {
+ // start recording the program.
+ startRootRecursive(node, context);
+ }
+
+ List<String> stagingTables = node.getStagingTables();
+ for (String table : stagingTables) {
+ Program currentProgram = programStack.peek();
+
+ // load staging
+ currentProgram.addInstruction(new ExecStagingTableInstruction(table, planEnv.getStagingTableResultsInfo(table)));
+
+ // unload staging
+ String unloadName = planEnv.unLoadResultName(table);
+ cleanupProgram.addInstruction(new ExecStagingTableInstruction(unloadName, planEnv.getStagingTableResultsInfo(unloadName)));
+ } // for
+ }
+
+ private void commonEnd(MappingBaseNode node, Map context) {
+ if (node.isRootRecursiveNode()) {
+ // stop recording and update the program
+ endRootRecursive(node, context);
+ }
+ }
+
+ public void start(final MappingRecursiveElement element, Map context){
+ Program currentProgram = programStack.peek();
+
+ // if we are dealing with multiple documents
+ startFragment(currentProgram, element);
+
+ ProcessorInstruction tagInst = TagBuilderVisitor.buildTag(element);
+ currentProgram.addInstruction(tagInst);
+
+ // this is set by root recursive node. Note that the MappingClass on recursive
+ // node is same as the source on the root recursive node.
+ Program recursiveProgram = (Program)context.get(element.getMappingClass().toUpperCase());
+ IfInstruction ifInst = new IfInstruction();
+ RecurseProgramCondition recurseCondition = buildRecurseCondition(element, recursiveProgram);
+ ifInst.addCondition(recurseCondition);
+ ifInst.setDefaultCondition(new DefaultCondition(new Program()));
+
+ currentProgram.addInstruction(ifInst);
+ }
+
+ public void end(final MappingRecursiveElement element, Map context){
+ Program currentProgram = programStack.peek();
+
+ // if we are dealing with multiple documents
+ endFragment(currentProgram, element);
+ }
+
+ private static RecurseProgramCondition buildRecurseCondition(MappingRecursiveElement element, Program subProgram) {
+ String criteriaString = element.getCriteria();
+ RecurseProgramCondition condition = null;
+
+ if (criteriaString == null || criteriaString.trim().length() == 0){
+ condition = new RecurseProgramCondition(subProgram, null, element.getRecursionLimit(), element.throwExceptionOnRecurrsionLimit());
+ }
+ else {
+ condition = new RecurseProgramCondition(subProgram, element.getCriteriaNode(), element.getRecursionLimit(), element.throwExceptionOnRecurrsionLimit());
+ }
+ return condition;
+ }
+
+ public static Program planProgram(MappingDocument doc, XMLPlannerEnvironment env) {
+ XMLPlanToProcessVisitor visitor = new XMLPlanToProcessVisitor(env);
+ doc.acceptVisitor(new InterceptingVisitor(visitor));
+ return visitor.originalProgram;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanner.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanner.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,309 +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.optimizer.xml;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryPlannerException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.id.IDGenerator;
-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.mapping.xml.MappingDocument;
-import org.teiid.query.mapping.xml.MappingNode;
-import org.teiid.query.mapping.xml.MappingNodeLogger;
-import org.teiid.query.mapping.xml.MappingRecursiveElement;
-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.CommandPlanner;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.xml.Program;
-import org.teiid.query.processor.xml.XMLPlan;
-import org.teiid.query.processor.xml.XMLProcessorEnvironment;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.Criteria;
-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.SelectSymbol;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.util.CommandContext;
-
-
-/**
- * <p> This prepares an {@link org.teiid.query.processor.xml.XMLPlan XMLPlan} from
- * a Mapping Document structure of {@link org.teiid.query.mapping.xml.MappingNode MappingNodes}.
- * </p>
- */
-public final class XMLPlanner implements CommandPlanner{
-
- /**
- * Default constructor. Since this object is stateless the constructor
- * has nothing to do.
- */
- public XMLPlanner() {}
-
- /**
- * @see org.teiid.query.optimizer.CommandPlanner#optimize
- */
- public ProcessorPlan optimize(Command command,IDGenerator idGenerator,QueryMetadataInterface metadata,CapabilitiesFinder capFinder,AnalysisRecord analysisRecord,CommandContext context)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- XMLPlannerEnvironment env = new XMLPlannerEnvironment(metadata);
-
- return XMLPlanner.preparePlan(command, metadata, analysisRecord, env, idGenerator, capFinder, context);
- }
-
- /**
- * This method takes in a Command object of the user's query and returns a XML plan
- * as a XMLNode object.
- * @param command The Command object for which query plan is to be returned
- * @param metadata The metadata needed for planning
- * @param planEnv XMLPlanner.XMLPlannerEnvironment object which holds various data
- * @return The XML plan returned as an XMLPlan object
- * @throws QueryPlannerException
- * @throws QueryMetadataException
- * @throws TeiidComponentException
- */
- static XMLPlan preparePlan(Command command, QueryMetadataInterface metadata, AnalysisRecord analysisRecord, XMLPlannerEnvironment planEnv, IDGenerator idGenerator, CapabilitiesFinder capFinder, CommandContext context)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- Query xmlQuery = (Query) command;
- boolean debug = analysisRecord.recordDebug();
- if(debug) {
- analysisRecord.println("============================================================================"); //$NON-NLS-1$
- analysisRecord.println("XML COMMAND: " + xmlQuery); //$NON-NLS-1$
- }
-
- // lookup mapping node for the user command
- GroupSymbol group = xmlQuery.getFrom().getGroups().iterator().next();
-
- MappingDocument doc = (MappingDocument)metadata.getMappingNode(group.getMetadataID());
- doc = (MappingDocument)doc.clone();
-
- // make a copy of the document
- planEnv.mappingDoc = doc;
- planEnv.documentGroup = group;
- planEnv.xmlCommand = (Query) command;
- planEnv.analysisRecord = analysisRecord;
- planEnv.capFinder = capFinder;
- planEnv.idGenerator = idGenerator;
- planEnv.context = context;
-
- LogManager.logTrace(LogConstants.CTX_XML_PLANNER, new Object[]{"Mapping document tree", new MappingNodeLogger(planEnv.mappingDoc)}); //$NON-NLS-1$
- if(debug) {
- debugDocumentInfo("Start", planEnv); //$NON-NLS-1$
- }
-
- prePlan(planEnv, debug);
-
- // Generate program to create document
- Program programPlan = XMLPlanToProcessVisitor.planProgram(planEnv.mappingDoc, planEnv);
-
- // create plan from program and initialized environment
- XMLProcessorEnvironment env = planEnv.createProcessorEnvironment(programPlan);
- XMLPlan plan = new XMLPlan(env);
- plan.setXMLSchemas(metadata.getXMLSchemas(group.getMetadataID()));
- if(debug) {
- analysisRecord.println(""); //$NON-NLS-1$
- analysisRecord.println(plan.toString());
- analysisRecord.println("============================================================================"); //$NON-NLS-1$
- }
-
- return plan;
- }
-
- private static void debugDocumentInfo(String msgTag, XMLPlannerEnvironment planEnv) {
- planEnv.analysisRecord.println("\n"+msgTag+":============================================================================"); //$NON-NLS-1$ //$NON-NLS-2$
- planEnv.analysisRecord.println("MAPPING DOCUMENT:\n" + MappingNode.toStringNodeTree(planEnv.mappingDoc)); //$NON-NLS-1$
- }
-
-
- /**
- * Pre planning - steps that occur before planning of the XML Query plan.
- * @param root root of mapping document
- * @param rsCrits Map of String mapping class result set name to Criteria object
- * @param rsOrderBy Map of String mapping class result set name to OrderBy clause
- * @param planEnv an instance of XMLPlannerEnvironment for passing around information
- * @param metadata QueryMetadataInterface instance
- * @throws QueryPlannerException for any logical exception detected during planning
- * @throws QueryMetadataException if metadata encounters exception
- * @throws TeiidComponentException unexpected exception
- */
- private static void prePlan(XMLPlannerEnvironment planEnv, boolean debug)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- //extract source nodes
- planEnv.mappingDoc = SourceNodeGenaratorVisitor.extractSourceNodes(planEnv.mappingDoc);
-
- if (debug) {
- debugDocumentInfo("After Source Node Generation", planEnv); //$NON-NLS-1$
- }
-
- //raise input set criteria if possible
- SourceNodePlannerVisitor.raiseInputSet(planEnv.mappingDoc, planEnv);
-
- //Place the orderbys
- placeOrderBys(planEnv.xmlCommand.getOrderBy(), planEnv);
-
- //prepare any user-specified criteria in command
- Criteria crit = planEnv.xmlCommand.getCriteria();
- CriteriaPlanner.placeUserCriteria(crit, planEnv);
-
- //Plan the various relational result sets along with criteria and order by
- XMLQueryPlanner.prePlanQueries(planEnv.mappingDoc, planEnv);
-
- if (debug) {
- debugDocumentInfo("After Pre Plan Queries", planEnv); //$NON-NLS-1$
- }
-
- preMarkExcluded(planEnv.xmlCommand, planEnv.mappingDoc);
-
- if (debug) {
- debugDocumentInfo("After Mark Exclude", planEnv); //$NON-NLS-1$
- }
-
- //Remove excluded document subtrees
- removeExcluded(planEnv.mappingDoc);
-
- if (debug) {
- debugDocumentInfo("After Exclude", 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();
- if (!(node instanceof MappingRecursiveElement) && child.isExcluded()) {
- i.remove();
- } else {
- removeExcluded(child);
- }
- }
- }
-
- /**
- * Is selection is not "select *", then mark all those un used nodes as excluded. The way
- * we do this mark the nodes selected and their parents as selected, then we sweep to mark
- * everybody who is not marked "included" as excluded.
- * @param xmlCommand
- */
- static MappingDocument preMarkExcluded(Query xmlCommand, MappingDocument doc) {
- Select select = xmlCommand.getSelect();
- SelectSymbol firstSymbol = select.getSymbol(0);
-
- // 0. mark the nodes to be excluded
- if(firstSymbol instanceof AllSymbol) {
- 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();
- elements.add(element.getCanonicalName());
- }
-
- // keep the nodes given mark the rest of the nodes to be elementated
- return MarkExcludeVisitor.markExcludedNodes(doc, elements);
- }
-
-
- /**
- * Get the result sets of all orderby's elements
- * @param orderBy The fully resolved order by clause
- * @param planEnv XMLPlannerEnvironment
- * @param metadata QueryMetadataInterface
- * @return Map The hash map of result sets and corresponding order by clauses
- * @throws QueryPlannerException
- * @throws QueryMetadataException
- * @throws TeiidComponentException
- */
- private static void placeOrderBys(OrderBy orderBy, XMLPlannerEnvironment planEnv)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
- //prepare fully resolved Order By elements
-
- if (orderBy == null) {
- return;
- }
-
- List elements = orderBy.getSortKeys();
- List types = orderBy.getTypes();
-
- for (int i = 0; i< elements.size(); i++) {
- ElementSymbol elemSymbol = (ElementSymbol) elements.get(i);
-
- String nodeName = planEnv.getGlobalMetadata().getFullName(elemSymbol.getMetadataID()).toUpperCase();
- MappingNode elementNode = MappingNode.findNode(planEnv.mappingDoc, nodeName);
-
- // make sure that the name in source is defined for this node, so that it can be used
- // in the orderby. static nodes do not qualify for ordering.
- if (elementNode.getNameInSource() == null){
- Object[] params = new Object[] {elementNode, orderBy};
- String msg = QueryPlugin.Util.getString("XMLPlanner.The_XML_document_element_{0}_is_not_mapped_to_data_and_cannot_be_used_in_the_ORDER_BY_clause__{1}_1", params); //$NON-NLS-1$
- throw new QueryPlannerException(msg);
- }
-
- MappingSourceNode sourceNode = elementNode.getSourceNode();
- ResultSetInfo rs = sourceNode.getResultSetInfo();
- OrderBy by = rs.getOrderBy();
- if (by == null) {
- by = new OrderBy();
- }
- ElementSymbol mappedSymbol = (ElementSymbol)sourceNode.getSymbolMap().get(new ElementSymbol(elementNode.getNameInSource()));
- by.addVariable((ElementSymbol)mappedSymbol.clone(), ((Boolean)types.get(i)).booleanValue());
- rs.setOrderBy(by);
- }
- }
-
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanner.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanner.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanner.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,313 @@
+/*
+ * 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.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryPlannerException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.id.IDGenerator;
+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.mapping.xml.MappingDocument;
+import org.teiid.query.mapping.xml.MappingNode;
+import org.teiid.query.mapping.xml.MappingNodeLogger;
+import org.teiid.query.mapping.xml.MappingRecursiveElement;
+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.CommandPlanner;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.xml.Program;
+import org.teiid.query.processor.xml.XMLPlan;
+import org.teiid.query.processor.xml.XMLProcessorEnvironment;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.Criteria;
+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.SelectSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.util.CommandContext;
+
+
+/**
+ * <p> This prepares an {@link org.teiid.query.processor.xml.XMLPlan XMLPlan} from
+ * a Mapping Document structure of {@link org.teiid.query.mapping.xml.MappingNode MappingNodes}.
+ * </p>
+ */
+public final class XMLPlanner implements CommandPlanner{
+
+ /**
+ * Default constructor. Since this object is stateless the constructor
+ * has nothing to do.
+ */
+ public XMLPlanner() {}
+
+ /**
+ * @see org.teiid.query.optimizer.CommandPlanner#optimize
+ */
+ public ProcessorPlan optimize(Command command,IDGenerator idGenerator,QueryMetadataInterface metadata,CapabilitiesFinder capFinder,AnalysisRecord analysisRecord,CommandContext context)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ XMLPlannerEnvironment env = new XMLPlannerEnvironment(metadata);
+
+ return XMLPlanner.preparePlan(command, metadata, analysisRecord, env, idGenerator, capFinder, context);
+ }
+
+ /**
+ * This method takes in a Command object of the user's query and returns a XML plan
+ * as a XMLNode object.
+ * @param command The Command object for which query plan is to be returned
+ * @param metadata The metadata needed for planning
+ * @param planEnv XMLPlanner.XMLPlannerEnvironment object which holds various data
+ * @return The XML plan returned as an XMLPlan object
+ * @throws QueryPlannerException
+ * @throws QueryMetadataException
+ * @throws TeiidComponentException
+ */
+ static XMLPlan preparePlan(Command command, QueryMetadataInterface metadata, AnalysisRecord analysisRecord, XMLPlannerEnvironment planEnv, IDGenerator idGenerator, CapabilitiesFinder capFinder, CommandContext context)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ Query xmlQuery = (Query) command;
+ boolean debug = analysisRecord.recordDebug();
+ if(debug) {
+ analysisRecord.println("============================================================================"); //$NON-NLS-1$
+ analysisRecord.println("XML COMMAND: " + xmlQuery); //$NON-NLS-1$
+ }
+
+ // lookup mapping node for the user command
+ GroupSymbol group = xmlQuery.getFrom().getGroups().iterator().next();
+
+ MappingDocument doc = (MappingDocument)metadata.getMappingNode(group.getMetadataID());
+ doc = doc.clone();
+
+ // make a copy of the document
+ planEnv.mappingDoc = doc;
+ planEnv.documentGroup = group;
+ planEnv.xmlCommand = (Query) command;
+ planEnv.analysisRecord = analysisRecord;
+ planEnv.capFinder = capFinder;
+ planEnv.idGenerator = idGenerator;
+ planEnv.context = context;
+
+ LogManager.logTrace(LogConstants.CTX_XML_PLANNER, new Object[]{"Mapping document tree", new MappingNodeLogger(planEnv.mappingDoc)}); //$NON-NLS-1$
+ if(debug) {
+ debugDocumentInfo("Start", planEnv); //$NON-NLS-1$
+ }
+
+ prePlan(planEnv, debug);
+
+ // Generate program to create document
+ Program programPlan = XMLPlanToProcessVisitor.planProgram(planEnv.mappingDoc, planEnv);
+
+ // create plan from program and initialized environment
+ XMLProcessorEnvironment env = planEnv.createProcessorEnvironment(programPlan);
+ XMLPlan plan = new XMLPlan(env);
+ plan.setXMLSchemas(metadata.getXMLSchemas(group.getMetadataID()));
+ if(debug) {
+ analysisRecord.println(""); //$NON-NLS-1$
+ analysisRecord.println(plan.toString());
+ analysisRecord.println("============================================================================"); //$NON-NLS-1$
+ }
+
+ return plan;
+ }
+
+ private static void debugDocumentInfo(String msgTag, XMLPlannerEnvironment planEnv) {
+ planEnv.analysisRecord.println("\n"+msgTag+":============================================================================"); //$NON-NLS-1$ //$NON-NLS-2$
+ planEnv.analysisRecord.println("MAPPING DOCUMENT:\n" + MappingNode.toStringNodeTree(planEnv.mappingDoc)); //$NON-NLS-1$
+ }
+
+
+ /**
+ * Pre planning - steps that occur before planning of the XML Query plan.
+ * @param root root of mapping document
+ * @param rsCrits Map of String mapping class result set name to Criteria object
+ * @param rsOrderBy Map of String mapping class result set name to OrderBy clause
+ * @param planEnv an instance of XMLPlannerEnvironment for passing around information
+ * @param metadata QueryMetadataInterface instance
+ * @throws QueryPlannerException for any logical exception detected during planning
+ * @throws QueryMetadataException if metadata encounters exception
+ * @throws TeiidComponentException unexpected exception
+ */
+ private static void prePlan(XMLPlannerEnvironment planEnv, boolean debug)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ //extract source nodes
+ planEnv.mappingDoc = SourceNodeGenaratorVisitor.extractSourceNodes(planEnv.mappingDoc);
+
+ if (debug) {
+ debugDocumentInfo("After Source Node Generation", planEnv); //$NON-NLS-1$
+ }
+
+ //raise input set criteria if possible
+ SourceNodePlannerVisitor.raiseInputSet(planEnv.mappingDoc, planEnv);
+
+ //Place the orderbys
+ placeOrderBys(planEnv.xmlCommand.getOrderBy(), planEnv);
+
+ //prepare any user-specified criteria in command
+ Criteria crit = planEnv.xmlCommand.getCriteria();
+ CriteriaPlanner.placeUserCriteria(crit, planEnv);
+
+ //Plan the various relational result sets along with criteria and order by
+ XMLQueryPlanner.prePlanQueries(planEnv.mappingDoc, planEnv);
+
+ if (debug) {
+ debugDocumentInfo("After Pre Plan Queries", planEnv); //$NON-NLS-1$
+ }
+
+ preMarkExcluded(planEnv.xmlCommand, planEnv.mappingDoc);
+
+ if (debug) {
+ debugDocumentInfo("After Mark Exclude", planEnv); //$NON-NLS-1$
+ }
+
+ //Remove excluded document subtrees
+ removeExcluded(planEnv.mappingDoc);
+
+ 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);
+
+ //Plan the various relational result sets
+ XMLQueryPlanner.optimizeQueries(planEnv.mappingDoc, planEnv);
+
+ //Handle nillable nodes
+ planEnv.mappingDoc = HandleNillableVisitor.execute(planEnv.mappingDoc);
+ }
+
+ static void removeExcluded(MappingNode node) {
+ for (Iterator i = node.getChildren().iterator(); i.hasNext();) {
+ MappingNode child = (MappingNode)i.next();
+ if (!(node instanceof MappingRecursiveElement) && child.isExcluded()) {
+ i.remove();
+ } else {
+ removeExcluded(child);
+ }
+ }
+ }
+
+ /**
+ * Is selection is not "select *", then mark all those un used nodes as excluded. The way
+ * we do this mark the nodes selected and their parents as selected, then we sweep to mark
+ * everybody who is not marked "included" as excluded.
+ * @param xmlCommand
+ */
+ static MappingDocument preMarkExcluded(Query xmlCommand, MappingDocument doc) {
+ Select select = xmlCommand.getSelect();
+ SelectSymbol firstSymbol = select.getSymbol(0);
+
+ // 0. mark the nodes to be excluded
+ if(firstSymbol instanceof AllSymbol) {
+ return doc;
+ }
+
+ // Get all the valid nodes to be marked as included.
+ Collection<ElementSymbol> validElements = ElementCollectorVisitor.getElements(select, true);
+ HashSet<String> elements = new HashSet<String>(validElements.size());
+ for (ElementSymbol element : validElements) {
+ elements.add(element.getCanonicalName());
+ }
+
+ // keep the nodes given mark the rest of the nodes to be elementated
+ return MarkExcludeVisitor.markExcludedNodes(doc, elements);
+ }
+
+
+ /**
+ * Get the result sets of all orderby's elements
+ * @param orderBy The fully resolved order by clause
+ * @param planEnv XMLPlannerEnvironment
+ * @param metadata QueryMetadataInterface
+ * @return Map The hash map of result sets and corresponding order by clauses
+ * @throws QueryPlannerException
+ * @throws QueryMetadataException
+ * @throws TeiidComponentException
+ */
+ private static void placeOrderBys(OrderBy orderBy, XMLPlannerEnvironment planEnv)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+ //prepare fully resolved Order By elements
+
+ if (orderBy == null) {
+ return;
+ }
+
+ List<SingleElementSymbol> elements = orderBy.getSortKeys();
+ List<Boolean> types = orderBy.getTypes();
+
+ for (int i = 0; i< elements.size(); i++) {
+ ElementSymbol elemSymbol = (ElementSymbol) elements.get(i);
+
+ String nodeName = planEnv.getGlobalMetadata().getFullName(elemSymbol.getMetadataID()).toUpperCase();
+ MappingNode elementNode = MappingNode.findNode(planEnv.mappingDoc, nodeName);
+
+ // make sure that the name in source is defined for this node, so that it can be used
+ // in the orderby. static nodes do not qualify for ordering.
+ if (elementNode.getNameInSource() == null){
+ Object[] params = new Object[] {elementNode, orderBy};
+ String msg = QueryPlugin.Util.getString("XMLPlanner.The_XML_document_element_{0}_is_not_mapped_to_data_and_cannot_be_used_in_the_ORDER_BY_clause__{1}_1", params); //$NON-NLS-1$
+ throw new QueryPlannerException(msg);
+ }
+
+ MappingSourceNode sourceNode = elementNode.getSourceNode();
+ ResultSetInfo rs = sourceNode.getResultSetInfo();
+ OrderBy by = rs.getOrderBy();
+ if (by == null) {
+ by = new OrderBy();
+ }
+ ElementSymbol mappedSymbol = (ElementSymbol)sourceNode.getSymbolMap().get(new ElementSymbol(elementNode.getNameInSource()));
+ by.addVariable(mappedSymbol.clone(), ((Boolean)types.get(i)).booleanValue());
+ rs.setOrderBy(by);
+ }
+ }
+
+}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLProjectionMinimizer.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/xml/XMLProjectionMinimizer.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLProjectionMinimizer.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLProjectionMinimizer.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLQueryPlanner.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/xml/XMLQueryPlanner.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLQueryPlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,516 +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.optimizer.xml;
-
-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;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-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.query.QueryPlugin;
-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.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.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.metadata.TempMetadataID;
-import org.teiid.query.optimizer.QueryOptimizer;
-import org.teiid.query.optimizer.relational.rules.NewCalculateCostUtil;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.relational.RelationalNode;
-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;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.FromClause;
-import org.teiid.query.sql.lang.GroupContext;
-import org.teiid.query.sql.lang.Into;
-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.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-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.GroupSymbol;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.visitor.StaticSymbolMappingVisitor;
-
-
-public class XMLQueryPlanner {
-
- static void prePlanQueries(MappingDocument doc, final XMLPlannerEnvironment planEnv)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- MappingVisitor queryPlanVisitor = new MappingVisitor() {
-
- 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();
- planStagingTable(tableName, planEnv);
- }
-
- // now if this is of they source node plan; all other nodes
- // do not need query planning.
- if (baseNode instanceof MappingSourceNode) {
- planQueries((MappingSourceNode)baseNode, planEnv);
- }
-
- } catch (Exception e) {
- throw new TeiidRuntimeException(e);
- }
- }
-
- };
- planWalk(doc, queryPlanVisitor);
- }
-
- static void optimizeQueries(MappingDocument doc, final XMLPlannerEnvironment planEnv)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- MappingVisitor queryPlanVisitor = new MappingVisitor() {
- public void visit(MappingSourceNode sourceNode) {
- 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);
-
- // Plan the result set.
- ProcessorPlan queryPlan = optimizePlan(command, planEnv);
- rsInfo.setPlan(queryPlan);
- } catch (Exception e) {
- throw new TeiidRuntimeException(e);
- }
- }
- };
- planWalk(doc, queryPlanVisitor);
- }
-
- private static void planWalk(MappingDocument doc, MappingVisitor visitor)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- try {
- Navigator walker = new Navigator(true, visitor);
- doc.acceptVisitor(walker);
- } catch (TeiidRuntimeException e) {
- if (e.getCause() instanceof QueryPlannerException) {
- throw (QueryPlannerException)e.getCause();
- }
- else if (e.getCause() instanceof QueryMetadataException) {
- throw (QueryMetadataException)e.getCause();
- }
- else if (e.getCause() instanceof TeiidComponentException) {
- throw (TeiidComponentException)e.getCause();
- }
- else {
- throw e;
- }
- }
- }
-
- static void planQueries(MappingSourceNode sourceNode, XMLPlannerEnvironment planEnv)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- ResultSetInfo rsInfo = sourceNode.getResultSetInfo();
-
- // Create sql: SELECT * FROM rsName
- Query rsQuery = (Query)rsInfo.getCommand();
-
- // add user order by to base query
- rsQuery.setOrderBy(rsInfo.getOrderBy());
-
- // add user criteria to base query from model
- Criteria crit = rsInfo.getCriteria();
- try {
- if(crit != null) {
- planQueryWithCriteria(sourceNode, planEnv);
- }
- } catch (QueryResolverException e) {
- throw new TeiidComponentException(e);
- }
-
- if (rsInfo.getUserRowLimit() != -1) {
- int limit = rsInfo.getUserRowLimit();
- if (rsInfo.exceptionOnRowlimit()) {
- limit++;
- }
- 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);
- }
-
- static ProcessorPlan optimizePlan(Command query, XMLPlannerEnvironment planEnv)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- TempMetadataAdapter metadata = planEnv.getGlobalMetadata();
- ProcessorPlan plan = QueryOptimizer.optimizePlan(query, metadata, planEnv.idGenerator, planEnv.capFinder, planEnv.analysisRecord, planEnv.context);
-
- return plan;
- }
-
- static void prepareQuery(MappingSourceNode sourceNode, XMLPlannerEnvironment planEnv, QueryCommand rsQuery)
- throws TeiidComponentException, QueryResolverException {
-
- Collection externalGroups = getExternalGroups(sourceNode);
-
- rsQuery.setExternalGroupContexts(new GroupContext(null, externalGroups));
-
- QueryResolver.resolveCommand(rsQuery, planEnv.getGlobalMetadata());
- }
-
- private static Collection getExternalGroups(MappingSourceNode sourceNode) {
- Collection externalGroups = new HashSet();
-
- MappingSourceNode parentSource = sourceNode.getParentSourceNode();
- while (parentSource != null) {
- externalGroups.add(new GroupSymbol(parentSource.getActualResultSetName()));
- parentSource = parentSource.getParentSourceNode();
- }
- return externalGroups;
- }
-
-
- /**
- * The Criteria Source nodes are source nodes underneath the context Node.
- */
- private static boolean getResultSets(MappingSourceNode contextNode, Set criteriaSourceNodes, LinkedHashSet allResultSets) {
-
- boolean singleParentage = true;
-
- for (Iterator i = criteriaSourceNodes.iterator(); i.hasNext();) {
- MappingSourceNode node = (MappingSourceNode)i.next();
-
- List rsStack = getResultSetStack(contextNode, node);
-
- if (allResultSets.containsAll(rsStack)) {
- continue;
- }
- if (!rsStack.containsAll(allResultSets)) {
- singleParentage = false;
- }
- allResultSets.addAll(rsStack);
- }
-
- return singleParentage;
- }
-
- private static LinkedList getResultSetStack(MappingSourceNode contextNode, MappingBaseNode node) {
- LinkedList rsStack = new LinkedList();
-
- while (node != null && node != contextNode) {
- if (node instanceof MappingSourceNode) {
- rsStack.add(0, node);
- }
- node = node.getParentNode();
- }
- return rsStack;
- }
-
- private static void planQueryWithCriteria(MappingSourceNode contextNode, XMLPlannerEnvironment planEnv)
- throws QueryPlannerException, TeiidComponentException, QueryMetadataException, QueryResolverException {
-
- Map symbolMap = new HashMap();
-
- ResultSetInfo rsInfo = contextNode.getResultSetInfo();
-
- // this list of all the source nodes below the context, which are directly ro indirectly
- // involved in the criteria
- LinkedHashSet resultSets = new LinkedHashSet();
-
- boolean singleParentage = getResultSets(contextNode, rsInfo.getCriteriaResultSets(), resultSets);
-
- Query contextQuery = null;
-
- if (rsInfo.isCriteriaRaised()) {
- contextQuery = (Query)QueryUtil.getQueryFromQueryNode(rsInfo.getResultSetName(), planEnv);
- String inlineViewName = planEnv.getAliasName(rsInfo.getResultSetName());
- updateSymbolMap(symbolMap, rsInfo.getResultSetName(), inlineViewName, planEnv.getGlobalMetadata());
- } else {
- contextQuery = (Query)rsInfo.getCommand();
- }
-
- Query currentQuery = contextQuery;
-
- for (Iterator i = resultSets.iterator(); i.hasNext();) {
- MappingSourceNode rsNode = (MappingSourceNode)i.next();
-
- ResultSetInfo childRsInfo = rsNode.getResultSetInfo();
-
- QueryNode planNode = QueryUtil.getQueryNode(childRsInfo.getResultSetName(), planEnv.getGlobalMetadata());
- Command command = QueryUtil.getQuery(childRsInfo.getResultSetName(), planNode, planEnv);
-
- String inlineViewName = planEnv.getAliasName(childRsInfo.getResultSetName());
-
- 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()) {
- 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);
-
- JoinPredicate join = null;
-
- 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);
-
- continue;
- }
-
- if (!singleParentage) {
- throw new QueryPlannerException(QueryPlugin.Util.getString("XMLQueryPlanner.cannot_plan", rsInfo.getCriteria())); //$NON-NLS-1$
- }
-
- Query subQuery = QueryUtil.wrapQuery(new SubqueryFromClause(inlineViewName, command), inlineViewName);
-
- currentQuery.setCriteria(Criteria.combineCriteria(currentQuery.getCriteria(), new ExistsCriteria(subQuery)));
-
- currentQuery = subQuery;
- }
-
- Criteria userCrit = (Criteria)rsInfo.getCriteria().clone();
-
- currentQuery.setCriteria(Criteria.combineCriteria(currentQuery.getCriteria(), userCrit));
-
- StaticSymbolMappingVisitor.mapSymbols(contextQuery, symbolMap);
-
- if (rsInfo.isCriteriaRaised()) {
- //if allowing ancestor bindings, we need to update the bindings for the query node...
- prepareQuery(contextNode, planEnv, contextQuery);
- QueryUtil.rewriteQuery(contextQuery, planEnv.getGlobalMetadata(), planEnv.context);
-
- //selectively replace correlated references with their actual element symbols
- List<Reference> bindings = QueryUtil.getReferences(contextQuery);
-
- QueryNode modifiedNode = new QueryNode(null);
- modifiedNode.setCommand(contextQuery);
-
- for (Iterator<Reference> i = bindings.iterator(); i.hasNext();) {
- Reference ref = i.next();
- modifiedNode.addBinding(ref.getExpression().toString());
- }
-
- GroupSymbol groupSymbol = QueryUtil.createResolvedGroup(rsInfo.getResultSetName(), planEnv.getGlobalMetadata());
- planEnv.addQueryNodeToMetadata(groupSymbol.getMetadataID(), modifiedNode);
- }
- }
-
- private 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));
-
- symbolMap.putAll(QueryUtil.createSymbolMap(oldGroupSymbol, newGroup, projectedElements));
- }
-
- /**
- * Currently any virtual/physical table can be planned as a staged table. A Staged
- * table only means that is has been preped to load the data into a temp table; when the other
- * transformations use this staged table, they will be redirected to use the temp table instead.
- * however note that it is still up to the plan to make sure the temp table is loaded.
- * @param groupName
- * @param planEnv
- * @return {@link GroupSymbol} the temptable which has been planned.
- * @throws QueryResolverException
- */
- static void planStagingTable(String groupName, XMLPlannerEnvironment planEnv)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException, QueryResolverException {
-
- ResultSetInfo rsInfo = planEnv.getStagingTableResultsInfo(groupName);
-
- FromClause fromClause = new UnaryFromClause(new GroupSymbol(groupName));
- Query query = QueryUtil.wrapQuery(fromClause, groupName);
- if (rsInfo.getCriteria() != null) {
- query.setCriteria(rsInfo.getCriteria());
- }
- planStagaingQuery(false, groupName, groupName, query, planEnv);
- }
- /**
- * This method takes given query and adds the "into" symbol to query and resoves it
- * and registers it with planner env as the staging table. Also, builds a unload query
- * to unload the staging table.
- * @throws QueryResolverException
- */
- static boolean planStagaingQuery(boolean implicit, String srcGroupName, String stageGroupName, Query query, XMLPlannerEnvironment planEnv)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException, QueryResolverException {
-
- GroupSymbol srcGroup = QueryUtil.createResolvedGroup(srcGroupName, planEnv.getGlobalMetadata());
-
- String intoGroupName = "#"+stageGroupName.replace('.', '_'); //$NON-NLS-1$
- GroupSymbol intoGroupSymbol = new GroupSymbol(intoGroupName);
-
- query.setInto(new Into(intoGroupSymbol));
-
- QueryResolver.resolveCommand(query, planEnv.getGlobalMetadata());
-
- Command cmd = QueryUtil.rewriteQuery(query, planEnv.getGlobalMetadata(), planEnv.context);
-
- ProcessorPlan plan = null;
-
- boolean debug = planEnv.analysisRecord.recordDebug();
-
- if (debug) {
- planEnv.analysisRecord.println("Attempting to create plan for staging table " + srcGroupName); //$NON-NLS-1$
- }
-
- try {
- // register with env
- plan = optimizePlan(cmd, planEnv);
- } catch (QueryPlannerException e) {
- if (implicit) {
- if (debug) {
- planEnv.analysisRecord.println("Failed to create plan for staging table " + srcGroupName + " due to " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return false;
- }
- throw e;
- }
-
- int cardinality = QueryMetadataInterface.UNKNOWN_CARDINALITY;
-
- if (plan instanceof RelationalPlan) {
- RelationalPlan relationalPlan = (RelationalPlan)plan;
- RelationalNode root = relationalPlan.getRootNode();
- //since the root will be a project into node, get the cost from its child
- if (root.getChildren()[0] != null) {
- root = root.getChildren()[0];
- }
- Number planCardinality = root.getEstimateNodeCardinality();
-
- if (planCardinality == null || planCardinality.floatValue() == NewCalculateCostUtil.UNKNOWN_VALUE) {
- //don't stage unknown cost without criteria
- if (implicit && query.getCriteria() == null) {
- return false;
- }
- } else if (planCardinality.floatValue() < planEnv.context.getProcessorBatchSize()) {
- //the staging table seems small
- cardinality = planCardinality.intValue();
- } else if (implicit) {
- return false;
- }
- }
-
- // since this was staging table; this adds some temp metadata to the query node; extract
- // that metadata and inject into global metadata store for rest of the queries to use.
- Map tempMetadata = query.getTemporaryMetadata();
- if (tempMetadata != null && !tempMetadata.isEmpty()) {
- planEnv.addToGlobalMetadata(tempMetadata);
- }
-
- ResultSetInfo rsInfo = planEnv.getStagingTableResultsInfo(stageGroupName);
- rsInfo.setCommand(cmd);
- rsInfo.setPlan(plan);
-
- //set the carinality on the temp group.
- TempMetadataID intoGroupID = (TempMetadataID)intoGroupSymbol.getMetadataID();
- intoGroupID.setCardinality(cardinality);
-
- // add the meterialization hook for the staged table to original one.
- //GroupSymbol groupSymbol = (GroupSymbol)query.getFrom().getGroups().get(0);
- planEnv.addStagingTable(srcGroup.getMetadataID(), intoGroupID);
-
- // plan the unload of the staging table
- String unloadName = planEnv.unLoadResultName(stageGroupName);
- ResultSetInfo rsUnloadInfo = planEnv.getStagingTableResultsInfo(unloadName);
- Command command = wrapStagingTableUnloadQuery(intoGroupSymbol);
- QueryResolver.resolveCommand(command, planEnv.getGlobalMetadata());
- command = QueryUtil.rewriteQuery(command, planEnv.getGlobalMetadata(), planEnv.context);
-
- plan = optimizePlan(command, planEnv);
- rsUnloadInfo.setCommand(command);
- rsUnloadInfo.setPlan(plan);
-
- return true;
- }
-
- /**
- * This builds a command in the following form; If staging table name is "FOO"
- * the command built is "Delete FROM #FOO"
- */
- private static Command wrapStagingTableUnloadQuery(GroupSymbol intoGroupSymbol) {
- Drop drop = new Drop();
- drop.setTable(intoGroupSymbol);
- return drop;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLQueryPlanner.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/xml/XMLQueryPlanner.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLQueryPlanner.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLQueryPlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,602 @@
+/*
+ * 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.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;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+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.query.QueryPlugin;
+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.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.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.metadata.TempMetadataID;
+import org.teiid.query.optimizer.QueryOptimizer;
+import org.teiid.query.optimizer.relational.rules.NewCalculateCostUtil;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.relational.RelationalNode;
+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;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.FromClause;
+import org.teiid.query.sql.lang.GroupContext;
+import org.teiid.query.sql.lang.Into;
+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.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 {
+
+ 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() {
+
+ public void visit(MappingBaseNode baseNode) {
+ try {
+ // first if there are any explicit staging tables plan them first
+ List<String> stagingTables = baseNode.getStagingTables();
+ for (String tableName : stagingTables) {
+ planStagingTable(tableName, planEnv);
+ }
+
+ // now if this is of they source node plan; all other nodes
+ // do not need query planning.
+ if (baseNode instanceof MappingSourceNode) {
+ planQueries((MappingSourceNode)baseNode, planEnv);
+ }
+
+ } catch (Exception e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+
+ };
+ planWalk(doc, queryPlanVisitor);
+ }
+
+ static void optimizeQueries(MappingDocument doc, final XMLPlannerEnvironment planEnv)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ MappingVisitor queryPlanVisitor = new MappingVisitor() {
+ public void visit(MappingSourceNode sourceNode) {
+ try {
+ ResultSetInfo rsInfo = sourceNode.getResultSetInfo();
+
+ Query command = (Query)rsInfo.getCommand();
+
+ prepareQuery(sourceNode, planEnv, command);
+
+ QueryUtil.rewriteQuery(command, planEnv.getGlobalMetadata(), planEnv.context);
+
+ // Plan the result set.
+ ProcessorPlan queryPlan = optimizePlan(command, planEnv);
+ rsInfo.setPlan(queryPlan);
+ } catch (Exception e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+ };
+ planWalk(doc, queryPlanVisitor);
+ }
+
+ private static void planWalk(MappingDocument doc, MappingVisitor visitor)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ try {
+ Navigator walker = new Navigator(true, visitor);
+ doc.acceptVisitor(walker);
+ } catch (TeiidRuntimeException e) {
+ if (e.getCause() instanceof QueryPlannerException) {
+ throw (QueryPlannerException)e.getCause();
+ }
+ else if (e.getCause() instanceof QueryMetadataException) {
+ throw (QueryMetadataException)e.getCause();
+ }
+ else if (e.getCause() instanceof TeiidComponentException) {
+ throw (TeiidComponentException)e.getCause();
+ }
+ else {
+ throw e;
+ }
+ }
+ }
+
+ static void planQueries(final MappingSourceNode sourceNode, XMLPlannerEnvironment planEnv)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ ResultSetInfo rsInfo = sourceNode.getResultSetInfo();
+
+ // Create sql: SELECT * FROM rsName
+ Query rsQuery = (Query)rsInfo.getCommand();
+
+ // add user order by to base query
+ rsQuery.setOrderBy(rsInfo.getOrderBy());
+
+ // add user criteria to base query from model
+ Criteria crit = rsInfo.getCriteria();
+ try {
+ if(crit != null) {
+ planQueryWithCriteria(sourceNode, planEnv);
+ }
+ } catch (QueryResolverException e) {
+ throw new TeiidComponentException(e);
+ }
+
+ if (rsInfo.getUserRowLimit() != -1) {
+ int limit = rsInfo.getUserRowLimit();
+ if (rsInfo.exceptionOnRowlimit()) {
+ limit++;
+ }
+ rsQuery.setLimit(new Limit(null, new Constant(new Integer(limit))));
+ }
+
+ // this query is not eligible for staging; proceed normally.
+ rsInfo.setCommand(rsQuery);
+ }
+
+ static ProcessorPlan optimizePlan(Command query, XMLPlannerEnvironment planEnv)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ TempMetadataAdapter metadata = planEnv.getGlobalMetadata();
+ ProcessorPlan plan = QueryOptimizer.optimizePlan(query, metadata, planEnv.idGenerator, planEnv.capFinder, planEnv.analysisRecord, planEnv.context);
+
+ return plan;
+ }
+
+ static void prepareQuery(MappingSourceNode sourceNode, XMLPlannerEnvironment planEnv, QueryCommand rsQuery)
+ throws TeiidComponentException, QueryResolverException {
+
+ Collection<GroupSymbol> externalGroups = getExternalGroups(sourceNode);
+
+ rsQuery.setExternalGroupContexts(new GroupContext(null, externalGroups));
+
+ QueryResolver.resolveCommand(rsQuery, planEnv.getGlobalMetadata());
+ }
+
+ private static Collection<GroupSymbol> getExternalGroups(MappingSourceNode sourceNode) {
+ Collection<GroupSymbol> externalGroups = new HashSet<GroupSymbol>();
+
+ MappingSourceNode parentSource = sourceNode.getParentSourceNode();
+ while (parentSource != null) {
+ externalGroups.add(new GroupSymbol(parentSource.getActualResultSetName()));
+ parentSource = parentSource.getParentSourceNode();
+ }
+ return externalGroups;
+ }
+
+
+ /**
+ * The Criteria Source nodes are source nodes underneath the context Node.
+ */
+ private static boolean getResultSets(MappingSourceNode contextNode, Set<MappingSourceNode> criteriaSourceNodes, LinkedHashSet<MappingSourceNode> allResultSets) {
+
+ boolean singleParentage = true;
+
+ for (Iterator<MappingSourceNode> i = criteriaSourceNodes.iterator(); i.hasNext();) {
+ MappingSourceNode node = i.next();
+
+ List<MappingSourceNode> rsStack = getResultSetStack(contextNode, node);
+
+ if (allResultSets.containsAll(rsStack)) {
+ continue;
+ }
+ if (!rsStack.containsAll(allResultSets)) {
+ singleParentage = false;
+ }
+ allResultSets.addAll(rsStack);
+ }
+
+ return singleParentage;
+ }
+
+ 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, (MappingSourceNode)node);
+ }
+ node = node.getParentNode();
+ }
+ return rsStack;
+ }
+
+ private static void planQueryWithCriteria(MappingSourceNode contextNode, XMLPlannerEnvironment planEnv)
+ throws QueryPlannerException, TeiidComponentException, QueryMetadataException, QueryResolverException {
+
+ Map symbolMap = new HashMap();
+
+ ResultSetInfo rsInfo = contextNode.getResultSetInfo();
+
+ // this list of all the source nodes below the context, which are directly ro indirectly
+ // involved in the criteria
+ LinkedHashSet<MappingSourceNode> resultSets = new LinkedHashSet<MappingSourceNode>();
+
+ boolean singleParentage = getResultSets(contextNode, rsInfo.getCriteriaResultSets(), resultSets);
+
+ Query contextQuery = null;
+
+ if (rsInfo.isCriteriaRaised()) {
+ contextQuery = (Query)QueryUtil.getQueryFromQueryNode(rsInfo.getResultSetName(), planEnv);
+ String inlineViewName = planEnv.getAliasName(rsInfo.getResultSetName());
+ updateSymbolMap(symbolMap, rsInfo.getResultSetName(), inlineViewName, planEnv.getGlobalMetadata());
+ } else {
+ contextQuery = (Query)rsInfo.getCommand();
+ }
+
+ Query currentQuery = contextQuery;
+
+ for (Iterator i = resultSets.iterator(); i.hasNext();) {
+ MappingSourceNode rsNode = (MappingSourceNode)i.next();
+
+ ResultSetInfo childRsInfo = rsNode.getResultSetInfo();
+
+ QueryNode planNode = QueryUtil.getQueryNode(childRsInfo.getResultSetName(), planEnv.getGlobalMetadata());
+ Command command = QueryUtil.getQuery(childRsInfo.getResultSetName(), planNode, planEnv);
+
+ String inlineViewName = planEnv.getAliasName(childRsInfo.getResultSetName());
+
+ 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()) {
+ 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 = currentQuery.getFrom().getClauses().remove(0);
+
+ JoinPredicate join = null;
+
+ 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);
+
+ continue;
+ }
+
+ if (!singleParentage) {
+ throw new QueryPlannerException(QueryPlugin.Util.getString("XMLQueryPlanner.cannot_plan", rsInfo.getCriteria())); //$NON-NLS-1$
+ }
+
+ Query subQuery = QueryUtil.wrapQuery(new SubqueryFromClause(inlineViewName, command), inlineViewName);
+
+ currentQuery.setCriteria(Criteria.combineCriteria(currentQuery.getCriteria(), new ExistsCriteria(subQuery)));
+
+ currentQuery = subQuery;
+ }
+
+ Criteria userCrit = (Criteria)rsInfo.getCriteria().clone();
+
+ currentQuery.setCriteria(Criteria.combineCriteria(currentQuery.getCriteria(), userCrit));
+
+ StaticSymbolMappingVisitor.mapSymbols(contextQuery, symbolMap);
+
+ if (rsInfo.isCriteriaRaised()) {
+ //if allowing ancestor bindings, we need to update the bindings for the query node...
+ prepareQuery(contextNode, planEnv, contextQuery);
+ QueryUtil.rewriteQuery(contextQuery, planEnv.getGlobalMetadata(), planEnv.context);
+
+ //selectively replace correlated references with their actual element symbols
+ List<Reference> bindings = QueryUtil.getReferences(contextQuery);
+
+ QueryNode modifiedNode = new QueryNode(null);
+ modifiedNode.setCommand(contextQuery);
+
+ for (Iterator<Reference> i = bindings.iterator(); i.hasNext();) {
+ Reference ref = i.next();
+ modifiedNode.addBinding(ref.getExpression().toString());
+ }
+
+ 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 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;
+ }
+
+ private 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<ElementSymbol> projectedElements = new HashSet<ElementSymbol>(ResolverUtil.resolveElementsInGroup(oldGroupSymbol, metadata));
+
+ symbolMap.putAll(QueryUtil.createSymbolMap(oldGroupSymbol, newGroup, projectedElements));
+ }
+
+ /**
+ * Currently any virtual/physical table can be planned as a staged table. A Staged
+ * table only means that is has been preped to load the data into a temp table; when the other
+ * transformations use this staged table, they will be redirected to use the temp table instead.
+ * however note that it is still up to the plan to make sure the temp table is loaded.
+ * @param groupName
+ * @param planEnv
+ * @return {@link GroupSymbol} the temptable which has been planned.
+ * @throws QueryResolverException
+ */
+ static void planStagingTable(String groupName, XMLPlannerEnvironment planEnv)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException, QueryResolverException {
+
+ ResultSetInfo rsInfo = planEnv.getStagingTableResultsInfo(groupName);
+
+ FromClause fromClause = new UnaryFromClause(new GroupSymbol(groupName));
+ Query query = QueryUtil.wrapQuery(fromClause, groupName);
+ if (rsInfo.getCriteria() != null) {
+ query.setCriteria(rsInfo.getCriteria());
+ }
+ planStagaingQuery(false, groupName, groupName, query, planEnv);
+ }
+ /**
+ * This method takes given query and adds the "into" symbol to query and resoves it
+ * and registers it with planner env as the staging table. Also, builds a unload query
+ * to unload the staging table.
+ * @throws QueryResolverException
+ */
+ static boolean planStagaingQuery(boolean implicit, String srcGroupName, String stageGroupName, Query query, XMLPlannerEnvironment planEnv)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException, QueryResolverException {
+
+ GroupSymbol srcGroup = QueryUtil.createResolvedGroup(srcGroupName, planEnv.getGlobalMetadata());
+
+ String intoGroupName = "#"+stageGroupName.replace('.', '_'); //$NON-NLS-1$
+ GroupSymbol intoGroupSymbol = new GroupSymbol(intoGroupName);
+
+ query.setInto(new Into(intoGroupSymbol));
+
+ QueryResolver.resolveCommand(query, planEnv.getGlobalMetadata());
+
+ Command cmd = QueryUtil.rewriteQuery(query, planEnv.getGlobalMetadata(), planEnv.context);
+
+ ProcessorPlan plan = null;
+
+ boolean debug = planEnv.analysisRecord.recordDebug();
+
+ if (debug) {
+ planEnv.analysisRecord.println("Attempting to create plan for staging table " + srcGroupName); //$NON-NLS-1$
+ }
+
+ try {
+ // register with env
+ plan = optimizePlan(cmd, planEnv);
+ } catch (QueryPlannerException e) {
+ if (implicit) {
+ if (debug) {
+ planEnv.analysisRecord.println("Failed to create plan for staging table " + srcGroupName + " due to " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return false;
+ }
+ throw e;
+ }
+
+ int cardinality = QueryMetadataInterface.UNKNOWN_CARDINALITY;
+
+ if (plan instanceof RelationalPlan) {
+ RelationalPlan relationalPlan = (RelationalPlan)plan;
+ RelationalNode root = relationalPlan.getRootNode();
+ //since the root will be a project into node, get the cost from its child
+ if (root.getChildren()[0] != null) {
+ root = root.getChildren()[0];
+ }
+ Number planCardinality = root.getEstimateNodeCardinality();
+
+ if (planCardinality == null || planCardinality.floatValue() == NewCalculateCostUtil.UNKNOWN_VALUE) {
+ //don't stage unknown cost without criteria
+ if (implicit && query.getCriteria() == null) {
+ return false;
+ }
+ } else if (planCardinality.floatValue() < planEnv.context.getProcessorBatchSize()) {
+ //the staging table seems small
+ cardinality = planCardinality.intValue();
+ } else if (implicit) {
+ return false;
+ }
+ }
+
+ // since this was staging table; this adds some temp metadata to the query node; extract
+ // that metadata and inject into global metadata store for rest of the queries to use.
+ Map tempMetadata = query.getTemporaryMetadata();
+ if (tempMetadata != null && !tempMetadata.isEmpty()) {
+ planEnv.addToGlobalMetadata(tempMetadata);
+ }
+
+ ResultSetInfo rsInfo = planEnv.getStagingTableResultsInfo(stageGroupName);
+ rsInfo.setCommand(cmd);
+ rsInfo.setPlan(plan);
+
+ //set the cardinality on the temp group.
+ TempMetadataID intoGroupID = (TempMetadataID)intoGroupSymbol.getMetadataID();
+ intoGroupID.setCardinality(cardinality);
+
+ // add the materialization hook for the staged table to original one.
+ //GroupSymbol groupSymbol = (GroupSymbol)query.getFrom().getGroups().get(0);
+ planEnv.addStagingTable(srcGroup.getMetadataID(), intoGroupID);
+
+ // plan the unload of the staging table
+ String unloadName = planEnv.unLoadResultName(stageGroupName);
+ ResultSetInfo rsUnloadInfo = planEnv.getStagingTableResultsInfo(unloadName);
+ Command command = wrapStagingTableUnloadQuery(intoGroupSymbol);
+ QueryResolver.resolveCommand(command, planEnv.getGlobalMetadata());
+ command = QueryUtil.rewriteQuery(command, planEnv.getGlobalMetadata(), planEnv.context);
+
+ plan = optimizePlan(command, planEnv);
+ rsUnloadInfo.setCommand(command);
+ rsUnloadInfo.setPlan(plan);
+
+ return true;
+ }
+
+ /**
+ * This builds a command in the following form; If staging table name is "FOO"
+ * the command built is "Delete FROM #FOO"
+ */
+ private static Command wrapStagingTableUnloadQuery(GroupSymbol intoGroupSymbol) {
+ Drop drop = new Drop();
+ drop.setTable(intoGroupSymbol);
+ return drop;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLStagaingQueryPlanner.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/xml/XMLStagaingQueryPlanner.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLStagaingQueryPlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.optimizer.xml;
-
-import java.util.Collection;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-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.query.mapping.relational.QueryNode;
-import org.teiid.query.mapping.xml.MappingDocument;
-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.optimizer.relational.RelationalPlanner;
-import org.teiid.query.sql.lang.Option;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-
-
-/**
- * This class has code to with planning the automatic XML staging queries.
- */
-public class XMLStagaingQueryPlanner {
-
-
- static void stageQueries(MappingDocument doc, final XMLPlannerEnvironment planEnv)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- MappingVisitor queryPlanVisitor = new MappingVisitor() {
- public void visit(MappingSourceNode sourceNode) {
- try {
- stagePlannedQuery(sourceNode, planEnv);
- } catch (Exception e) {
- throw new TeiidRuntimeException(e);
- }
- }
- };
- planWalk(doc, queryPlanVisitor);
- }
-
- private static void planWalk(MappingDocument doc, MappingVisitor visitor)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- try {
- Navigator walker = new Navigator(true, visitor);
- doc.acceptVisitor(walker);
- } catch (TeiidRuntimeException e) {
- if (e.getCause() instanceof QueryPlannerException) {
- throw (QueryPlannerException)e.getCause();
- }
- else if (e.getCause() instanceof QueryMetadataException) {
- throw (QueryMetadataException)e.getCause();
- }
- else if (e.getCause() instanceof TeiidComponentException) {
- throw (TeiidComponentException)e.getCause();
- }
- else {
- throw e;
- }
- }
- }
-
- static boolean stagePlannedQuery(MappingSourceNode sourceNode, XMLPlannerEnvironment planEnv)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException, QueryResolverException {
-
- Option option = planEnv.xmlCommand.getOption();
-
- // make sure we do not plan staging table for root mapping class.
- if (sourceNode.isRootSourceNode()) {
- return false;
- }
-
- //TODO: if this source is source for a recursive node, we do not want to stage
- if (sourceNode.getAliasResultName() != null) {
- return false;
- }
-
- String groupName = sourceNode.getActualResultSetName();
- ResultSetInfo rsInfo = sourceNode.getResultSetInfo();
-
- // If this node has been eligible for raising, it will be eligible for staging.
- if (!rsInfo.isCriteriaRaised()) {
- return false;
- }
-
- // no bindings - no references
- QueryNode queryNode = QueryUtil.getQueryNode(groupName, planEnv.getGlobalMetadata());
- if (queryNode.getBindings() != null && !queryNode.getBindings().isEmpty()) {
- 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);
-
- Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroupsIgnoreInlineViews(stagableQuery, false);
-
- //check for already staged queries
- if (groups.size() == 1) {
- GroupSymbol group = groups.iterator().next();
- group = QueryUtil.createResolvedGroup((GroupSymbol)group.clone(), planEnv.getGlobalMetadata());
- if (planEnv.isStagingTable(group.getMetadataID()) && stagableQuery.getCriteria() == null) {
- 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);
-
- return true;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLStagaingQueryPlanner.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/optimizer/xml/XMLStagaingQueryPlanner.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLStagaingQueryPlanner.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/xml/XMLStagaingQueryPlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,157 @@
+/*
+ * 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.Collection;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+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.query.mapping.relational.QueryNode;
+import org.teiid.query.mapping.xml.MappingDocument;
+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.optimizer.relational.RelationalPlanner;
+import org.teiid.query.sql.lang.Option;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.visitor.GroupCollectorVisitor;
+
+
+/**
+ * This class has code to with planning the automatic XML staging queries.
+ */
+public class XMLStagaingQueryPlanner {
+
+
+ static void stageQueries(MappingDocument doc, final XMLPlannerEnvironment planEnv)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ MappingVisitor queryPlanVisitor = new MappingVisitor() {
+ public void visit(MappingSourceNode sourceNode) {
+ try {
+ stagePlannedQuery(sourceNode, planEnv);
+ } catch (Exception e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+ };
+ planWalk(doc, queryPlanVisitor);
+ }
+
+ private static void planWalk(MappingDocument doc, MappingVisitor visitor)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ try {
+ Navigator walker = new Navigator(true, visitor);
+ doc.acceptVisitor(walker);
+ } catch (TeiidRuntimeException e) {
+ if (e.getCause() instanceof QueryPlannerException) {
+ throw (QueryPlannerException)e.getCause();
+ }
+ else if (e.getCause() instanceof QueryMetadataException) {
+ throw (QueryMetadataException)e.getCause();
+ }
+ else if (e.getCause() instanceof TeiidComponentException) {
+ throw (TeiidComponentException)e.getCause();
+ }
+ else {
+ throw e;
+ }
+ }
+ }
+
+ static boolean stagePlannedQuery(MappingSourceNode sourceNode, XMLPlannerEnvironment planEnv)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException, QueryResolverException {
+
+ Option option = planEnv.xmlCommand.getOption();
+
+ // make sure we do not plan staging table for root mapping class.
+ if (sourceNode.isRootSourceNode()) {
+ return false;
+ }
+
+ //TODO: if this source is source for a recursive node, we do not want to stage
+ if (sourceNode.getAliasResultName() != null) {
+ return false;
+ }
+
+ String groupName = sourceNode.getActualResultSetName();
+ ResultSetInfo rsInfo = sourceNode.getResultSetInfo();
+
+ // If this node has been eligible for raising, it will be eligible for staging.
+ if (!rsInfo.isCriteriaRaised()) {
+ return false;
+ }
+
+ // no bindings - no references
+ QueryNode queryNode = QueryUtil.getQueryNode(groupName, planEnv.getGlobalMetadata());
+ if (queryNode.getBindings() != null && !queryNode.getBindings().isEmpty()) {
+ 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);
+
+ Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroupsIgnoreInlineViews(stagableQuery, false);
+
+ //check for already staged queries
+ if (groups.size() == 1) {
+ GroupSymbol group = groups.iterator().next();
+ group = QueryUtil.createResolvedGroup(group.clone(), planEnv.getGlobalMetadata());
+ if (planEnv.isStagingTable(group.getMetadataID()) && stagableQuery.getCriteria() == null) {
+ 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);
+
+ return true;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,314 +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.parser;
-
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.teiid.core.util.Assertion;
-import org.teiid.core.util.StringUtil;
-import org.teiid.language.SQLConstants.Reserved;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.function.FunctionMethods;
-import org.teiid.query.sql.lang.CacheHint;
-import org.teiid.query.sql.lang.FromClause;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.Option;
-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.CriteriaSelector;
-
-public class SQLParserUtil {
-
- String matchesAny(String arg, String ... expected) {
- for (String string : expected) {
- if (string.equalsIgnoreCase(arg)) {
- return arg;
- }
- }
- return null;
- }
-
- String normalizeStringLiteral(String s) {
- int start = 1;
- boolean unescape = false;
- if (s.charAt(0) == 'N') {
- start++;
- } else if (s.charAt(0) == 'E') {
- start++;
- unescape = true;
- }
- char tickChar = s.charAt(start - 1);
- s = s.substring(start, s.length() - 1);
- String result = removeEscapeChars(s, String.valueOf(tickChar));
- if (unescape) {
- result = FunctionMethods.unescape(result);
- }
- return result;
- }
-
- String normalizeId(String s) {
- if (s.indexOf('"') == -1) {
- return s;
- }
- List<String> nameParts = new LinkedList<String>();
- while (s.length() > 0) {
- if (s.charAt(0) == '"') {
- boolean escape = false;
- for (int i = 1; i < s.length(); i++) {
- if (s.charAt(i) != '"') {
- continue;
- }
- escape = !escape;
- boolean end = i == s.length() - 1;
- if (end || (escape && s.charAt(i + 1) == '.')) {
- String part = s.substring(1, i);
- s = s.substring(i + (end?1:2));
- nameParts.add(removeEscapeChars(part, "\"")); //$NON-NLS-1$
- break;
- }
- }
- } else {
- int index = s.indexOf('.');
- if (index == -1) {
- nameParts.add(s);
- break;
- }
- nameParts.add(s.substring(0, index));
- s = s.substring(index + 1);
- }
- }
- StringBuilder sb = new StringBuilder();
- for (Iterator<String> i = nameParts.iterator(); i.hasNext();) {
- sb.append(i.next());
- if (i.hasNext()) {
- sb.append('.');
- }
- }
- return sb.toString();
- }
-
- /**
- * Check if this is a valid string literal
- * @param id Possible string literal
- */
- boolean isStringLiteral(String str, ParseInfo info) {
- if (info.useAnsiQuotedIdentifiers() || str.charAt(0) != '"' || str.charAt(str.length() - 1) != '"') {
- return false;
- }
- int index = 1;
- while (index < str.length() - 1) {
- index = str.indexOf('"', index);
- if (index == -1 || index + 1 == str.length()) {
- return true;
- }
- if (str.charAt(index + 1) != '"') {
- return false;
- }
- index += 2;
- }
- return true;
- }
-
- /**
- * Check that this is a valid alias, remove quotes, and return updated
- * alias string.
- * @param id Metadata alias
- */
- String validateAlias(String id) throws ParseException {
- return validateName(id, false);
- }
-
- private String validateName(String id, boolean element) throws ParseException {
- if(id.indexOf('.') != -1) {
- String key = "SQLParser.Invalid_alias"; //$NON-NLS-1$
- if (element) {
- key = "SQLParser.Invalid_short_name"; //$NON-NLS-1$
- }
- throw new ParseException(QueryPlugin.Util.getString(key, id));
- }
- return id;
- }
-
- /**
- * Check that this is a valid element name, remove quotes
- * @param id Metadata alias
- */
- String validateElementName(String id) throws ParseException {
- return validateName(id, true);
- }
-
- String removeEscapeChars(String str, String tickChar) {
- return StringUtil.replaceAll(str, tickChar + tickChar, tickChar);
- }
-
- void setFromClauseOptions(Token groupID, FromClause fromClause){
- String[] parts = getComment(groupID).split("\\s"); //$NON-NLS-1$
-
- for (int i = 0; i < parts.length; i++) {
- if (parts[i].equalsIgnoreCase(Option.OPTIONAL)) {
- fromClause.setOptional(true);
- }
- }
- }
-
- SubqueryHint getSubqueryHint(Token t) {
- SubqueryHint hint = new SubqueryHint();
- String[] parts = getComment(t).split("\\s"); //$NON-NLS-1$
- for (int i = 0; i < parts.length; i++) {
- if (parts[i].equalsIgnoreCase(SubqueryHint.MJ)) {
- hint.setMergeJoin(true);
- } else if (parts[i].equalsIgnoreCase(SubqueryHint.NOUNNEST)) {
- hint.setNoUnnest(true);
- }
- }
- return hint;
- }
-
- String getComment(Token t) {
- Token optToken = t.specialToken;
- if (optToken == null) {
- return ""; //$NON-NLS-1$
- }
- String hint = optToken.image.substring(2, optToken.image.length() - 2);
- if (hint.startsWith("+")) { //$NON-NLS-1$
- hint = hint.substring(1);
- }
- return hint;
- }
-
- private static Pattern CACHE_HINT = Pattern.compile("/\\*\\+?\\s*cache(\\(\\s*(pref_mem)?\\s*(ttl:\\d{1,19})?\\s*(updatable)?\\s*(scope:(session|vdb|user))?[^\\)]*\\))?[^\\*]*\\*\\/.*", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); //$NON-NLS-1$
-
- static CacheHint getQueryCacheOption(String query) {
- Matcher match = CACHE_HINT.matcher(query);
- if (match.matches()) {
- CacheHint hint = new CacheHint();
- if (match.group(2) !=null) {
- hint.setPrefersMemory(true);
- }
- String ttl = match.group(3);
- if (ttl != null) {
- hint.setTtl(Long.valueOf(ttl.substring(4)));
- }
- if (match.group(4) != null) {
- hint.setUpdatable(true);
- }
- String scope = match.group(5);
- if (scope != null) {
- scope = scope.substring(6);
- hint.setScope(scope);
- }
- return hint;
- }
- return null;
- }
-
- /**
- * Helper for the FROM clause that takes the join type string and adds
- * the join type to the From clause based on that type.
- * @param groupID Left group ID
- * @param rid Right group ID
- * @param joinType Join type word from query
- * @param from From clause to update
- * @throws ParseException if parsing failed
- */
- JoinType getJoinType(Token joinTypeToken) throws ParseException {
- if(joinTypeToken == null) {
- return JoinType.JOIN_INNER;
- }
- String joinType = joinTypeToken.image;
- if(joinType.equalsIgnoreCase(Reserved.INNER)) {
- return JoinType.JOIN_INNER;
- } else if(joinType.equalsIgnoreCase(Reserved.CROSS)) {
- return JoinType.JOIN_CROSS;
- } else if(joinType.equalsIgnoreCase(Reserved.LEFT)) {
- return JoinType.JOIN_LEFT_OUTER;
- } else if(joinType.equalsIgnoreCase(Reserved.RIGHT)) {
- return JoinType.JOIN_RIGHT_OUTER;
- } else if(joinType.equalsIgnoreCase(Reserved.FULL)) {
- return JoinType.JOIN_FULL_OUTER;
- } else if(joinType.equalsIgnoreCase(Reserved.UNION)) {
- return JoinType.JOIN_UNION;
- } else {
- Object[] params = new Object[] { joinType };
- throw new ParseException(QueryPlugin.Util.getString("SQLParser.Unknown_join_type", params)); //$NON-NLS-1$
- }
- }
-
- /**
- * Generate an expression name based on the function type and previous names.
- * @param info Parse info, including counts for each function type
- * @param functionType Null for expression, the function name for aggregates
- * @return New unique function name
- */
- String generateFunctionName(ParseInfo info, String functionType) {
- if (functionType == null) {
- functionType = "expr"; //$NON-NLS-1$
- } else {
- functionType = functionType.toLowerCase();
- }
- Integer num = info.nameCounts.get(functionType);
- if (num == null) {
- num = 0;
- }
- info.nameCounts.put(functionType, num + 1);
- return functionType + (num == 0 ? "" : ""+num); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- int getOperator(String opString) {
- if (opString.equals("=")) { //$NON-NLS-1$
- return CriteriaSelector.COMPARE_EQ;
- } else if (opString.equals("<>") || opString.equals("!=")) { //$NON-NLS-1$ //$NON-NLS-2$
- return CriteriaSelector.COMPARE_NE;
- } else if (opString.equals("<")) { //$NON-NLS-1$
- return CriteriaSelector.COMPARE_LT;
- } else if (opString.equals(">")) { //$NON-NLS-1$
- return CriteriaSelector.COMPARE_GT;
- } else if (opString.equals("<=")) { //$NON-NLS-1$
- return CriteriaSelector.COMPARE_LE;
- } else if (opString.equals(">=")) { //$NON-NLS-1$
- return CriteriaSelector.COMPARE_GE;
- } else if (opString.equalsIgnoreCase("like")) { //$NON-NLS-1$
- return CriteriaSelector.LIKE;
- } else if (opString.equalsIgnoreCase("in")) { //$NON-NLS-1$
- return CriteriaSelector.IN;
- } else if (opString.equalsIgnoreCase("is")) { //$NON-NLS-1$
- return CriteriaSelector.IS_NULL;
- } else if (opString.equalsIgnoreCase("between")) { //$NON-NLS-1$
- return CriteriaSelector.BETWEEN;
- }
-
- Assertion.failed("unknown operator"); //$NON-NLS-1$
- return 0;
- }
-
- SetQuery addQueryToSetOperation(QueryCommand query, QueryCommand rightQuery, SetQuery.Operation type, boolean all) {
- SetQuery setQuery = new SetQuery(type, all, query, rightQuery);
- return setQuery;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,322 @@
+/*
+ * 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 java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.teiid.core.util.Assertion;
+import org.teiid.core.util.StringUtil;
+import org.teiid.language.SQLConstants.Reserved;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.function.FunctionMethods;
+import org.teiid.query.sql.lang.CacheHint;
+import org.teiid.query.sql.lang.FromClause;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.lang.Option;
+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.CriteriaSelector;
+
+public class SQLParserUtil {
+
+ String matchesAny(String arg, String ... expected) {
+ for (String string : expected) {
+ if (string.equalsIgnoreCase(arg)) {
+ return arg;
+ }
+ }
+ return null;
+ }
+
+ String normalizeStringLiteral(String s) {
+ int start = 1;
+ boolean unescape = false;
+ if (s.charAt(0) == 'N') {
+ start++;
+ } else if (s.charAt(0) == 'E') {
+ start++;
+ unescape = true;
+ }
+ char tickChar = s.charAt(start - 1);
+ s = s.substring(start, s.length() - 1);
+ String result = removeEscapeChars(s, String.valueOf(tickChar));
+ if (unescape) {
+ result = FunctionMethods.unescape(result);
+ }
+ return result;
+ }
+
+ String normalizeId(String s) {
+ if (s.indexOf('"') == -1) {
+ return s;
+ }
+ List<String> nameParts = new LinkedList<String>();
+ while (s.length() > 0) {
+ if (s.charAt(0) == '"') {
+ boolean escape = false;
+ for (int i = 1; i < s.length(); i++) {
+ if (s.charAt(i) != '"') {
+ continue;
+ }
+ escape = !escape;
+ boolean end = i == s.length() - 1;
+ if (end || (escape && s.charAt(i + 1) == '.')) {
+ String part = s.substring(1, i);
+ s = s.substring(i + (end?1:2));
+ nameParts.add(removeEscapeChars(part, "\"")); //$NON-NLS-1$
+ break;
+ }
+ }
+ } else {
+ int index = s.indexOf('.');
+ if (index == -1) {
+ nameParts.add(s);
+ break;
+ }
+ nameParts.add(s.substring(0, index));
+ s = s.substring(index + 1);
+ }
+ }
+ StringBuilder sb = new StringBuilder();
+ for (Iterator<String> i = nameParts.iterator(); i.hasNext();) {
+ sb.append(i.next());
+ if (i.hasNext()) {
+ sb.append('.');
+ }
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Check if this is a valid string literal
+ * @param id Possible string literal
+ */
+ boolean isStringLiteral(String str, ParseInfo info) {
+ if (info.useAnsiQuotedIdentifiers() || str.charAt(0) != '"' || str.charAt(str.length() - 1) != '"') {
+ return false;
+ }
+ int index = 1;
+ while (index < str.length() - 1) {
+ index = str.indexOf('"', index);
+ if (index == -1 || index + 1 == str.length()) {
+ return true;
+ }
+ if (str.charAt(index + 1) != '"') {
+ return false;
+ }
+ index += 2;
+ }
+ return true;
+ }
+
+ /**
+ * Check that this is a valid alias, remove quotes, and return updated
+ * alias string.
+ * @param id Metadata alias
+ */
+ String validateAlias(String id) throws ParseException {
+ return validateName(id, false);
+ }
+
+ private String validateName(String id, boolean element) throws ParseException {
+ if(id.indexOf('.') != -1) {
+ String key = "SQLParser.Invalid_alias"; //$NON-NLS-1$
+ if (element) {
+ key = "SQLParser.Invalid_short_name"; //$NON-NLS-1$
+ }
+ throw new ParseException(QueryPlugin.Util.getString(key, id));
+ }
+ return id;
+ }
+
+ /**
+ * Check that this is a valid element name, remove quotes
+ * @param id Metadata alias
+ */
+ String validateElementName(String id) throws ParseException {
+ return validateName(id, true);
+ }
+
+ String removeEscapeChars(String str, String tickChar) {
+ return StringUtil.replaceAll(str, tickChar + tickChar, tickChar);
+ }
+
+ void setFromClauseOptions(Token groupID, FromClause fromClause){
+ String[] parts = getComment(groupID).split("\\s"); //$NON-NLS-1$
+
+ 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);
+ }
+ }
+ }
+
+ SubqueryHint getSubqueryHint(Token t) {
+ SubqueryHint hint = new SubqueryHint();
+ String[] parts = getComment(t).split("\\s"); //$NON-NLS-1$
+ for (int i = 0; i < parts.length; i++) {
+ if (parts[i].equalsIgnoreCase(SubqueryHint.MJ)) {
+ 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;
+ }
+
+ String getComment(Token t) {
+ Token optToken = t.specialToken;
+ if (optToken == null) {
+ return ""; //$NON-NLS-1$
+ }
+ String hint = optToken.image.substring(2, optToken.image.length() - 2);
+ if (hint.startsWith("+")) { //$NON-NLS-1$
+ hint = hint.substring(1);
+ }
+ return hint;
+ }
+
+ private static Pattern CACHE_HINT = Pattern.compile("/\\*\\+?\\s*cache(\\(\\s*(pref_mem)?\\s*(ttl:\\d{1,19})?\\s*(updatable)?\\s*(scope:(session|vdb|user))?[^\\)]*\\))?[^\\*]*\\*\\/.*", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); //$NON-NLS-1$
+
+ static CacheHint getQueryCacheOption(String query) {
+ Matcher match = CACHE_HINT.matcher(query);
+ if (match.matches()) {
+ CacheHint hint = new CacheHint();
+ if (match.group(2) !=null) {
+ hint.setPrefersMemory(true);
+ }
+ String ttl = match.group(3);
+ if (ttl != null) {
+ hint.setTtl(Long.valueOf(ttl.substring(4)));
+ }
+ if (match.group(4) != null) {
+ hint.setUpdatable(true);
+ }
+ String scope = match.group(5);
+ if (scope != null) {
+ scope = scope.substring(6);
+ hint.setScope(scope);
+ }
+ return hint;
+ }
+ return null;
+ }
+
+ /**
+ * Helper for the FROM clause that takes the join type string and adds
+ * the join type to the From clause based on that type.
+ * @param groupID Left group ID
+ * @param rid Right group ID
+ * @param joinType Join type word from query
+ * @param from From clause to update
+ * @throws ParseException if parsing failed
+ */
+ JoinType getJoinType(Token joinTypeToken) throws ParseException {
+ if(joinTypeToken == null) {
+ return JoinType.JOIN_INNER;
+ }
+ String joinType = joinTypeToken.image;
+ if(joinType.equalsIgnoreCase(Reserved.INNER)) {
+ return JoinType.JOIN_INNER;
+ } else if(joinType.equalsIgnoreCase(Reserved.CROSS)) {
+ return JoinType.JOIN_CROSS;
+ } else if(joinType.equalsIgnoreCase(Reserved.LEFT)) {
+ return JoinType.JOIN_LEFT_OUTER;
+ } else if(joinType.equalsIgnoreCase(Reserved.RIGHT)) {
+ return JoinType.JOIN_RIGHT_OUTER;
+ } else if(joinType.equalsIgnoreCase(Reserved.FULL)) {
+ return JoinType.JOIN_FULL_OUTER;
+ } else if(joinType.equalsIgnoreCase(Reserved.UNION)) {
+ return JoinType.JOIN_UNION;
+ } else {
+ Object[] params = new Object[] { joinType };
+ throw new ParseException(QueryPlugin.Util.getString("SQLParser.Unknown_join_type", params)); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Generate an expression name based on the function type and previous names.
+ * @param info Parse info, including counts for each function type
+ * @param functionType Null for expression, the function name for aggregates
+ * @return New unique function name
+ */
+ String generateFunctionName(ParseInfo info, String functionType) {
+ if (functionType == null) {
+ functionType = "expr"; //$NON-NLS-1$
+ } else {
+ functionType = functionType.toLowerCase();
+ }
+ Integer num = info.nameCounts.get(functionType);
+ if (num == null) {
+ num = 0;
+ }
+ info.nameCounts.put(functionType, num + 1);
+ return functionType + (num == 0 ? "" : ""+num); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ int getOperator(String opString) {
+ if (opString.equals("=")) { //$NON-NLS-1$
+ return CriteriaSelector.COMPARE_EQ;
+ } else if (opString.equals("<>") || opString.equals("!=")) { //$NON-NLS-1$ //$NON-NLS-2$
+ return CriteriaSelector.COMPARE_NE;
+ } else if (opString.equals("<")) { //$NON-NLS-1$
+ return CriteriaSelector.COMPARE_LT;
+ } else if (opString.equals(">")) { //$NON-NLS-1$
+ return CriteriaSelector.COMPARE_GT;
+ } else if (opString.equals("<=")) { //$NON-NLS-1$
+ return CriteriaSelector.COMPARE_LE;
+ } else if (opString.equals(">=")) { //$NON-NLS-1$
+ return CriteriaSelector.COMPARE_GE;
+ } else if (opString.equalsIgnoreCase("like")) { //$NON-NLS-1$
+ return CriteriaSelector.LIKE;
+ } else if (opString.equalsIgnoreCase("in")) { //$NON-NLS-1$
+ return CriteriaSelector.IN;
+ } else if (opString.equalsIgnoreCase("is")) { //$NON-NLS-1$
+ return CriteriaSelector.IS_NULL;
+ } else if (opString.equalsIgnoreCase("between")) { //$NON-NLS-1$
+ return CriteriaSelector.BETWEEN;
+ }
+
+ Assertion.failed("unknown operator"); //$NON-NLS-1$
+ return 0;
+ }
+
+ SetQuery addQueryToSetOperation(QueryCommand query, QueryCommand rightQuery, SetQuery.Operation type, boolean all) {
+ SetQuery setQuery = new SetQuery(type, all, query, rightQuery);
+ return setQuery;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/AccessNode.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/relational/AccessNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/AccessNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,318 +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 static org.teiid.query.analysis.AnalysisRecord.*;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.client.plan.PlanNode;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.TupleBatch;
-import org.teiid.common.buffer.TupleSource;
-import org.teiid.common.buffer.BufferManager.BufferReserveMode;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.eval.Evaluator;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.rewriter.QueryRewriter;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.util.CommandContext;
-
-
-public class AccessNode extends SubqueryAwareRelationalNode {
-
- private static final int MAX_CONCURRENT = 10; //TODO: this could be settable via a property
- // Initialization state
- private Command command;
- private String modelName;
- private String connectorBindingId;
- private boolean shouldEvaluate = false;
-
- // Processing state
- private ArrayList<TupleSource> tupleSources = new ArrayList<TupleSource>();
- private boolean isUpdate = false;
- private boolean returnedRows = false;
- protected Command nextCommand;
- private int reserved;
- private int schemaSize;
-
- protected AccessNode() {
- super();
- }
-
- public AccessNode(int nodeID) {
- super(nodeID);
- }
-
- @Override
- public void initialize(CommandContext context, BufferManager bufferManager,
- ProcessorDataManager dataMgr) {
- super.initialize(context, bufferManager, dataMgr);
- this.schemaSize = getBufferManager().getSchemaSize(getOutputElements());
- }
-
- public void reset() {
- super.reset();
- this.tupleSources.clear();
- isUpdate = false;
- returnedRows = false;
- nextCommand = null;
- }
-
- public void setCommand(Command command) {
- this.command = command;
- }
-
- public Command getCommand() {
- return this.command;
- }
-
- public void setModelName(String name) {
- this.modelName = name;
- }
-
- public String getModelName() {
- return this.modelName;
- }
-
- public void setShouldEvaluateExpressions(boolean shouldEvaluate) {
- this.shouldEvaluate = shouldEvaluate;
- }
-
- public void open()
- throws TeiidComponentException, TeiidProcessingException {
-
- // Copy command and resolve references if necessary
- Command atomicCommand = command;
- boolean needProcessing = true;
-
- if (shouldEvaluate) {
- atomicCommand = initialCommand();
- }
- do {
- atomicCommand = nextCommand();
- if(shouldEvaluate) {
- needProcessing = prepareNextCommand(atomicCommand);
- nextCommand = null;
- } else {
- needProcessing = RelationalNodeUtil.shouldExecute(atomicCommand, true);
- }
- // else command will not be changed, so no reason to all this work.
- // Removing this if block and always evaluating has a significant cost that will
- // show up in performance tests for many simple tests that do not require it.
-
- isUpdate = RelationalNodeUtil.isUpdate(atomicCommand);
-
- if(needProcessing) {
- registerRequest(atomicCommand);
- }
- //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()));
- }
-
- static void rewriteAndEvaluate(Command atomicCommand, Evaluator eval, CommandContext context, QueryMetadataInterface metadata)
- throws TeiidProcessingException, TeiidComponentException {
- try {
- // Defect 16059 - Rewrite the command to replace references, etc. with values.
- QueryRewriter.evaluateAndRewrite(atomicCommand, eval, context, metadata);
- } catch (QueryValidatorException e) {
- throw new TeiidProcessingException(e, QueryPlugin.Util.getString("AccessNode.rewrite_failed", atomicCommand)); //$NON-NLS-1$
- }
- }
-
- @SuppressWarnings("unused")
- protected Command initialCommand() throws TeiidProcessingException, TeiidComponentException {
- return nextCommand();
- }
-
- protected Command nextCommand() {
- //it's important to save the next command
- //to ensure that the subquery ids remain stable
- if (nextCommand == null) {
- nextCommand = (Command) command.clone();
- }
- return nextCommand;
- }
-
- protected boolean prepareNextCommand(Command atomicCommand) throws TeiidComponentException, TeiidProcessingException {
- rewriteAndEvaluate(atomicCommand, getEvaluator(Collections.emptyMap()), this.getContext(), this.getContext().getMetadata());
- return RelationalNodeUtil.shouldExecute(atomicCommand, true);
- }
-
- public TupleBatch nextBatchDirect()
- throws BlockedException, TeiidComponentException, TeiidProcessingException {
-
- while (!tupleSources.isEmpty() || hasNextCommand()) {
-
- if (tupleSources.isEmpty() && processCommandsIndividually()) {
- registerNext();
- }
-
- //drain the tuple source(s)
- for (int i = 0; i < this.tupleSources.size(); i++) {
- TupleSource tupleSource = tupleSources.get(i);
- try {
- List<?> tuple = null;
-
- while ((tuple = tupleSource.nextTuple()) != null) {
- returnedRows = true;
- addBatchRow(tuple);
-
- if (isBatchFull()) {
- return pullBatch();
- }
- }
-
- //end of source
- tupleSource.closeSource();
- tupleSources.remove(i--);
- if (reserved > 0) {
- reserved -= schemaSize;
- getBufferManager().releaseBuffers(schemaSize);
- }
- if (!processCommandsIndividually()) {
- registerNext();
- }
- continue;
- } catch (BlockedException e) {
- if (processCommandsIndividually()) {
- throw e;
- }
- continue;
- }
- }
-
- if (processCommandsIndividually()) {
- if (hasPendingRows()) {
- return pullBatch();
- }
- continue;
- }
-
- if (!this.tupleSources.isEmpty()) {
- throw BlockedException.INSTANCE;
- }
- }
-
- if(isUpdate && !returnedRows) {
- List<Integer> tuple = new ArrayList<Integer>(1);
- tuple.add(Integer.valueOf(0));
- // Add tuple to current batch
- addBatchRow(tuple);
- }
- terminateBatches();
- return pullBatch();
- }
-
- private void registerNext() throws TeiidComponentException,
- TeiidProcessingException {
- while (hasNextCommand()) {
- Command atomicCommand = nextCommand();
- if (prepareNextCommand(atomicCommand)) {
- nextCommand = null;
- registerRequest(atomicCommand);
- break;
- }
- nextCommand = null;
- }
- }
-
- private void registerRequest(Command atomicCommand)
- throws TeiidComponentException, TeiidProcessingException {
- int limit = -1;
- if (getParent() instanceof LimitNode) {
- LimitNode parent = (LimitNode)getParent();
- if (parent.getLimit() > 0) {
- limit = parent.getLimit() + parent.getOffset();
- }
- }
- tupleSources.add(getDataManager().registerRequest(getContext(), atomicCommand, modelName, connectorBindingId, getID(), limit));
- if (tupleSources.size() > 1) {
- reserved += getBufferManager().reserveBuffers(schemaSize, BufferReserveMode.FORCE);
- }
- }
-
- protected boolean processCommandsIndividually() {
- return false;
- }
-
- protected boolean hasNextCommand() {
- return false;
- }
-
- public void closeDirect() {
- getBufferManager().releaseBuffers(reserved);
- reserved = 0;
- super.closeDirect();
- closeSources();
- }
-
- private void closeSources() {
- for (TupleSource ts : this.tupleSources) {
- ts.closeSource();
- }
- this.tupleSources.clear();
- }
-
- protected void getNodeString(StringBuffer str) {
- super.getNodeString(str);
- str.append(command);
- }
-
- public Object clone(){
- AccessNode clonedNode = new AccessNode();
- this.copy(this, clonedNode);
- return clonedNode;
- }
-
- protected void copy(AccessNode source, AccessNode target){
- super.copy(source, target);
- target.modelName = source.modelName;
- target.connectorBindingId = source.connectorBindingId;
- target.shouldEvaluate = source.shouldEvaluate;
- target.command = source.command;
- }
-
- public PlanNode getDescriptionProperties() {
- PlanNode props = super.getDescriptionProperties();
- props.addProperty(PROP_SQL, this.command.toString());
- props.addProperty(PROP_MODEL_NAME, this.modelName);
- return props;
- }
-
- public String getConnectorBindingId() {
- return connectorBindingId;
- }
-
- public void setConnectorBindingId(String connectorBindingId) {
- this.connectorBindingId = connectorBindingId;
- }
-
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/AccessNode.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/processor/relational/AccessNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/AccessNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/AccessNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,416 @@
+/*
+ * 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 static org.teiid.query.analysis.AnalysisRecord.*;
+
+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;
+import org.teiid.client.plan.PlanNode;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.TupleBatch;
+import org.teiid.common.buffer.TupleSource;
+import org.teiid.common.buffer.BufferManager.BufferReserveMode;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.eval.Evaluator;
+import org.teiid.query.metadata.QueryMetadataInterface;
+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.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;
+
+
+public class AccessNode extends SubqueryAwareRelationalNode {
+
+ private static final int MAX_CONCURRENT = 10; //TODO: this could be settable via a property
+ // Initialization state
+ private Command command;
+ private String modelName;
+ private String connectorBindingId;
+ private boolean shouldEvaluate = false;
+
+ // Processing state
+ private ArrayList<TupleSource> tupleSources = new ArrayList<TupleSource>();
+ private boolean isUpdate = false;
+ private boolean returnedRows = false;
+ protected Command nextCommand;
+ private int reserved;
+ private int schemaSize;
+
+ private Object[] projection;
+ private List<SelectSymbol> originalSelect;
+ private Object modelId;
+
+ protected AccessNode() {
+ super();
+ }
+
+ public AccessNode(int nodeID) {
+ super(nodeID);
+ }
+
+ @Override
+ public void initialize(CommandContext context, BufferManager bufferManager,
+ ProcessorDataManager dataMgr) {
+ super.initialize(context, bufferManager, dataMgr);
+ this.schemaSize = getBufferManager().getSchemaSize(getOutputElements());
+ }
+
+ public void reset() {
+ super.reset();
+ this.tupleSources.clear();
+ isUpdate = false;
+ returnedRows = false;
+ nextCommand = null;
+ }
+
+ public void setCommand(Command command) {
+ this.command = command;
+ }
+
+ 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;
+ }
+
+ public String getModelName() {
+ return this.modelName;
+ }
+
+ public void setShouldEvaluateExpressions(boolean shouldEvaluate) {
+ this.shouldEvaluate = shouldEvaluate;
+ }
+
+ public void open()
+ throws TeiidComponentException, TeiidProcessingException {
+
+ // Copy command and resolve references if necessary
+ Command atomicCommand = command;
+ boolean needProcessing = true;
+
+ if (shouldEvaluate) {
+ atomicCommand = initialCommand();
+ }
+ do {
+ atomicCommand = nextCommand();
+ if(shouldEvaluate) {
+ needProcessing = prepareNextCommand(atomicCommand);
+ nextCommand = null;
+ } else {
+ needProcessing = RelationalNodeUtil.shouldExecute(atomicCommand, true);
+ }
+ // else command will not be changed, so no reason to all this work.
+ // Removing this if block and always evaluating has a significant cost that will
+ // show up in performance tests for many simple tests that do not require it.
+
+ isUpdate = RelationalNodeUtil.isUpdate(atomicCommand);
+
+ if(needProcessing) {
+ registerRequest(atomicCommand);
+ }
+ //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];
+ }
+ }
+
+ 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 {
+ // Defect 16059 - Rewrite the command to replace references, etc. with values.
+ QueryRewriter.evaluateAndRewrite(atomicCommand, eval, context, metadata);
+ } catch (QueryValidatorException e) {
+ throw new TeiidProcessingException(e, QueryPlugin.Util.getString("AccessNode.rewrite_failed", atomicCommand)); //$NON-NLS-1$
+ }
+ }
+
+ @SuppressWarnings("unused")
+ protected Command initialCommand() throws TeiidProcessingException, TeiidComponentException {
+ return nextCommand();
+ }
+
+ protected Command nextCommand() {
+ //it's important to save the next command
+ //to ensure that the subquery ids remain stable
+ if (nextCommand == null) {
+ nextCommand = (Command) command.clone();
+ }
+ return nextCommand;
+ }
+
+ protected boolean prepareNextCommand(Command atomicCommand) throws TeiidComponentException, TeiidProcessingException {
+ rewriteAndEvaluate(atomicCommand, getEvaluator(Collections.emptyMap()), this.getContext(), this.getContext().getMetadata());
+ return RelationalNodeUtil.shouldExecute(atomicCommand, true);
+ }
+
+ public TupleBatch nextBatchDirect()
+ throws BlockedException, TeiidComponentException, TeiidProcessingException {
+
+ while (!tupleSources.isEmpty() || hasNextCommand()) {
+
+ if (tupleSources.isEmpty() && processCommandsIndividually()) {
+ registerNext();
+ }
+
+ //drain the tuple source(s)
+ for (int i = 0; i < this.tupleSources.size(); i++) {
+ TupleSource tupleSource = tupleSources.get(i);
+ try {
+ List<?> tuple = null;
+
+ 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()) {
+ return pullBatch();
+ }
+ }
+
+ //end of source
+ tupleSource.closeSource();
+ tupleSources.remove(i--);
+ if (reserved > 0) {
+ reserved -= schemaSize;
+ getBufferManager().releaseBuffers(schemaSize);
+ }
+ if (!processCommandsIndividually()) {
+ registerNext();
+ }
+ continue;
+ } catch (BlockedException e) {
+ if (processCommandsIndividually()) {
+ throw e;
+ }
+ continue;
+ }
+ }
+
+ if (processCommandsIndividually()) {
+ if (hasPendingRows()) {
+ return pullBatch();
+ }
+ continue;
+ }
+
+ if (!this.tupleSources.isEmpty()) {
+ throw BlockedException.block(getContext().getRequestId(), "Blocking on source request(s)."); //$NON-NLS-1$
+ }
+ }
+
+ if(isUpdate && !returnedRows) {
+ List<Integer> tuple = new ArrayList<Integer>(1);
+ tuple.add(Integer.valueOf(0));
+ // Add tuple to current batch
+ addBatchRow(tuple);
+ }
+ terminateBatches();
+ return pullBatch();
+ }
+
+ private void registerNext() throws TeiidComponentException,
+ TeiidProcessingException {
+ while (hasNextCommand()) {
+ Command atomicCommand = nextCommand();
+ if (prepareNextCommand(atomicCommand)) {
+ nextCommand = null;
+ registerRequest(atomicCommand);
+ break;
+ }
+ nextCommand = null;
+ }
+ }
+
+ 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();
+ if (parent.getLimit() > 0) {
+ limit = parent.getLimit() + parent.getOffset();
+ }
+ }
+ tupleSources.add(getDataManager().registerRequest(getContext(), atomicCommand, modelName, connectorBindingId, getID(), limit));
+ if (tupleSources.size() > 1) {
+ reserved += getBufferManager().reserveBuffers(schemaSize, BufferReserveMode.FORCE);
+ }
+ }
+
+ protected boolean processCommandsIndividually() {
+ return false;
+ }
+
+ protected boolean hasNextCommand() {
+ return false;
+ }
+
+ public void closeDirect() {
+ getBufferManager().releaseBuffers(reserved);
+ reserved = 0;
+ super.closeDirect();
+ closeSources();
+ }
+
+ private void closeSources() {
+ for (TupleSource ts : this.tupleSources) {
+ ts.closeSource();
+ }
+ this.tupleSources.clear();
+ }
+
+ protected void getNodeString(StringBuffer str) {
+ super.getNodeString(str);
+ str.append(command);
+ }
+
+ public Object clone(){
+ AccessNode clonedNode = new AccessNode();
+ this.copy(this, clonedNode);
+ return clonedNode;
+ }
+
+ 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;
+ }
+
+ public PlanNode getDescriptionProperties() {
+ PlanNode props = super.getDescriptionProperties();
+ props.addProperty(PROP_SQL, this.command.toString());
+ props.addProperty(PROP_MODEL_NAME, this.modelName);
+ return props;
+ }
+
+ public String getConnectorBindingId() {
+ return connectorBindingId;
+ }
+
+ public void setConnectorBindingId(String connectorBindingId) {
+ this.connectorBindingId = connectorBindingId;
+ }
+
+}
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentCriteriaProcessor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/relational/DependentCriteriaProcessor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentCriteriaProcessor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,412 +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 java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.query.optimizer.relational.rules.NewCalculateCostUtil;
-import org.teiid.query.processor.relational.SortUtility.Mode;
-import org.teiid.query.rewriter.QueryRewriter;
-import org.teiid.query.sql.lang.AbstractSetCriteria;
-import org.teiid.query.sql.lang.CollectionValueIterator;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.DependentSetCriteria;
-import org.teiid.query.sql.lang.OrderBy;
-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.util.ValueIterator;
-
-
-public class DependentCriteriaProcessor {
-
- public static class SetState {
-
- Collection<Object> replacement = new LinkedHashSet<Object>();
-
- Expression valueExpression;
-
- ValueIterator valueIterator;
-
- Object nextValue;
-
- boolean isNull;
-
- float maxNdv = NewCalculateCostUtil.UNKNOWN_VALUE;
-
- boolean overMax;
- }
-
- class TupleState {
-
- private SortUtility sortUtility;
- private DependentValueSource dvs;
- private List<SetState> dependentSetStates = new LinkedList<SetState>();
- private String valueSource;
-
- public TupleState(String source) {
- this.valueSource = source;
- }
-
- 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());
- for (SetState setState : dependentSetStates) {
- setState.valueIterator = dvs.getValueIterator(setState.valueExpression);
- if (setState.maxNdv > 0 && setState.maxNdv < dvs.getTupleBuffer().getRowCount()) {
- ValueIterator vi = dvs.getValueIterator(setState.valueExpression);
- Comparable last = null;
- int distinctCount = 0;
- while (vi.hasNext()) {
- Comparable next = (Comparable) vi.next();
- if (last == null || next.compareTo(last) != 0) {
- distinctCount++;
- }
- last = next;
- }
- if (distinctCount > setState.maxNdv) {
- setState.overMax = true;
- }
- }
- }
- }
- }
-
- public void close() {
- if (dvs != null) {
- sortUtility = null;
- dvs.getTupleBuffer().remove();
- dvs = null;
- }
- }
-
- public List<SetState> getDepedentSetStates() {
- return dependentSetStates;
- }
-
- }
-
- private static final int SORT = 2;
- private static final int SET_PROCESSING = 3;
-
- //constructor state
- private int maxSetSize;
- private int maxPredicates;
- private RelationalNode dependentNode;
- private Criteria dependentCrit;
-
- //initialization state
- private List<Criteria> queryCriteria;
- private Map<Integer, SetState> setStates = new HashMap<Integer, SetState>();
- private LinkedHashMap<String, TupleState> dependentState = new LinkedHashMap<String, TupleState>();
- private List<List<SetState>> sources = new ArrayList<List<SetState>>();
-
- // processing state
- private int phase = SORT;
- private LinkedList<Integer> restartIndexes = new LinkedList<Integer>();
- private int currentIndex;
- private boolean hasNextCommand;
- protected SubqueryAwareEvaluator eval;
-
- public DependentCriteriaProcessor(int maxSetSize, int maxPredicates, RelationalNode dependentNode, Criteria dependentCriteria) throws ExpressionEvaluationException, TeiidComponentException {
- this.maxSetSize = maxSetSize;
- this.maxPredicates = maxPredicates;
- this.dependentNode = dependentNode;
- this.dependentCrit = dependentCriteria;
- this.eval = new SubqueryAwareEvaluator(Collections.emptyMap(), dependentNode.getDataManager(), dependentNode.getContext(), dependentNode.getBufferManager());
- queryCriteria = Criteria.separateCriteriaByAnd(dependentCrit);
-
- for (int i = 0; i < queryCriteria.size(); i++) {
- Criteria criteria = queryCriteria.get(i);
- if (!(criteria instanceof AbstractSetCriteria)) {
- continue;
- }
-
- if (criteria instanceof SetCriteria) {
- SetCriteria setCriteria = (SetCriteria)criteria;
- if (setCriteria.isNegated() || setCriteria.getNumberOfValues() <= maxSetSize) {
- continue;
- }
- SetState state = new SetState();
- setStates.put(i, state);
- LinkedHashSet<Object> values = new LinkedHashSet<Object>();
- for (Expression expr : (Collection<Expression>)setCriteria.getValues()) {
- values.add(eval.evaluate(expr, null));
- }
- state.valueIterator = new CollectionValueIterator(values);
- sources.add(Arrays.asList(state));
- } else if (criteria instanceof DependentSetCriteria) {
- DependentSetCriteria dsc = (DependentSetCriteria)criteria;
- String source = dsc.getContextSymbol();
-
- SetState state = new SetState();
- setStates.put(i, state);
- state.valueExpression = dsc.getValueExpression();
- TupleState ts = dependentState.get(source);
- if (ts == null) {
- ts = new TupleState(source);
- dependentState.put(source, ts);
- sources.add(ts.getDepedentSetStates());
- }
- ts.getDepedentSetStates().add(state);
- state.maxNdv = dsc.getMaxNdv();
- }
- }
- }
-
- public void close() {
- if (dependentState != null) {
- for (TupleState state : dependentState.values()) {
- state.close();
- }
- }
- if (this.eval != null) {
- this.eval.close();
- }
- }
-
- public Criteria prepareCriteria() throws TeiidComponentException, TeiidProcessingException {
-
- if (phase == SORT) {
- for (TupleState state : dependentState.values()) {
- state.sort();
- }
-
- phase = SET_PROCESSING;
- }
-
- replaceDependentValueIterators();
-
- LinkedList<Criteria> crits = new LinkedList<Criteria>();
-
- for (int i = 0; i < queryCriteria.size(); i++) {
- SetState state = this.setStates.get(i);
- if (state == null) {
- crits.add((Criteria)queryCriteria.get(i).clone());
- } else {
- Criteria crit = replaceDependentCriteria((AbstractSetCriteria)queryCriteria.get(i), state);
- if (crit == QueryRewriter.FALSE_CRITERIA) {
- return QueryRewriter.FALSE_CRITERIA;
- }
- crits.add(crit);
- }
- }
-
- if (crits.size() == 1) {
- return crits.get(0);
- }
- return new CompoundCriteria(CompoundCriteria.AND, crits);
- }
-
- public void consumedCriteria() {
- // flush only the value iterators starting at the restart index
- // it is only safe to do this after the super call to prepare command
- if (restartIndexes.isEmpty()) {
- return;
- }
-
- int restartIndex = restartIndexes.removeLast().intValue();
-
- for (int i = restartIndex; i < sources.size(); i++) {
-
- List<SetState> source = sources.get(i);
-
- for (SetState setState : source) {
- setState.replacement.clear();
- }
- }
-
- currentIndex = restartIndex;
- }
-
- /**
- * Replace the dependentSet value iterators with the next set of values from the independent tuple source
- *
- * @param dependentSets
- * @param replacementValueIterators
- * @throws TeiidComponentException
- */
- private void replaceDependentValueIterators() throws TeiidComponentException {
- int totalPredicates = sources.size();
- if (this.maxPredicates > 0) {
- //We have a bin packing problem if totalPredicates < sources - We'll address that case later.
- //TODO: better handling for the correlated composite case
- totalPredicates = Math.max(totalPredicates, this.maxPredicates);
- }
- long maxSize = Integer.MAX_VALUE;
- if (this.maxSetSize > 0) {
- maxSize = this.maxSetSize;
- }
- int currentPredicates = 0;
- for (int run = 0; currentPredicates < totalPredicates; run++) {
- currentPredicates = 0;
- if (!restartIndexes.isEmpty()) {
- currentIndex = restartIndexes.removeLast().intValue();
- }
- for (int i = 0; i < sources.size(); i++) {
-
- List<SetState> source = sources.get(i);
-
- if (i == currentIndex++) {
-
- int doneCount = 0;
-
- while (doneCount < source.size()) {
-
- boolean isNull = false;
- boolean lessThanMax = true;
-
- for (SetState state : source) {
- if (state.overMax) {
- doneCount++;
- continue;
- }
- if (state.nextValue == null && !state.isNull) {
- if (state.valueIterator.hasNext()) {
- state.nextValue = state.valueIterator.next();
- state.isNull = state.nextValue == null;
- } else {
- state.valueIterator.reset();
- doneCount++; // should be true for each iterator from this source
- continue;
- }
- }
-
- isNull |= state.isNull;
- lessThanMax &= state.replacement.size() < maxSize * (run + 1);
- }
-
- if (doneCount == source.size()) {
- if (!restartIndexes.isEmpty() && restartIndexes.getLast().intValue() == i) {
- restartIndexes.removeLast();
- }
- break;
- }
-
- if (lessThanMax || isNull) {
- for (SetState state : source) {
- if (!isNull) {
- state.replacement.add(state.nextValue);
- }
- state.nextValue = null;
- state.isNull = false;
- }
- } else {
- restartIndexes.add(i);
- break;
- }
- }
- }
-
- for (SetState setState : source) {
- currentPredicates += setState.replacement.size()/maxSize+(setState.replacement.size()%maxSize!=0?1:0);
- }
- }
-
- if (restartIndexes.isEmpty()) {
- break;
- }
- }
-
- hasNextCommand = !restartIndexes.isEmpty();
- }
-
- protected boolean hasNextCommand() {
- return hasNextCommand;
- }
-
- public Criteria replaceDependentCriteria(AbstractSetCriteria crit, SetState state) {
- if (state.overMax) {
- return QueryRewriter.TRUE_CRITERIA;
- }
- if (state.replacement.isEmpty()) {
- // No values - return criteria that is always false
- return QueryRewriter.FALSE_CRITERIA;
- }
- int numberOfSets = 1;
- int maxSize = Integer.MAX_VALUE;
- if (this.maxSetSize > 0) {
- maxSize = this.maxSetSize;
- numberOfSets = state.replacement.size()/maxSize + (state.replacement.size()%maxSize!=0?1:0);
- }
- Iterator<Object> iter = state.replacement.iterator();
- ArrayList<Criteria> orCrits = new ArrayList<Criteria>(numberOfSets);
-
- for (int i = 0; i < numberOfSets; i++) {
- if (maxSize == 1 || i + 1 == state.replacement.size()) {
- orCrits.add(new CompareCriteria(crit.getExpression(), CompareCriteria.EQ, newConstant(iter.next())));
- } else {
- List<Constant> vals = new ArrayList<Constant>(Math.min(state.replacement.size(), maxSize));
-
- for (int j = 0; j < maxSize && iter.hasNext(); j++) {
- Object val = iter.next();
- vals.add(newConstant(val));
- }
-
- SetCriteria sc = new SetCriteria();
- sc.setExpression(crit.getExpression());
- sc.setValues(vals);
- orCrits.add(sc);
- }
- }
- if (orCrits.size() == 1) {
- return orCrits.get(0);
- }
- return new CompoundCriteria(CompoundCriteria.OR, orCrits);
- }
-
- private Constant newConstant(Object val) {
- Constant c = new Constant(val);
- c.setBindEligible(true);
- return c;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentCriteriaProcessor.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/processor/relational/DependentCriteriaProcessor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentCriteriaProcessor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentCriteriaProcessor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,417 @@
+/*
+ * 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.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.query.optimizer.relational.rules.NewCalculateCostUtil;
+import org.teiid.query.processor.relational.SortUtility.Mode;
+import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.lang.AbstractSetCriteria;
+import org.teiid.query.sql.lang.CollectionValueIterator;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.DependentSetCriteria;
+import org.teiid.query.sql.lang.OrderBy;
+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.util.ValueIterator;
+
+
+public class DependentCriteriaProcessor {
+
+ public static class SetState {
+
+ Collection<Object> replacement = new LinkedHashSet<Object>();
+
+ Expression valueExpression;
+
+ ValueIterator valueIterator;
+
+ Object nextValue;
+
+ boolean isNull;
+
+ float maxNdv = NewCalculateCostUtil.UNKNOWN_VALUE;
+
+ boolean overMax;
+ }
+
+ class TupleState {
+
+ private SortUtility sortUtility;
+ private DependentValueSource dvs;
+ private List<SetState> dependentSetStates = new LinkedList<SetState>();
+ private String valueSource;
+
+ public TupleState(String source) {
+ this.valueSource = source;
+ }
+
+ public void sort() throws BlockedException,
+ TeiidComponentException, TeiidProcessingException {
+ if (dvs == null) {
+ DependentValueSource originalVs = (DependentValueSource)dependentNode.getContext().getVariableContext().getGlobalValue(valueSource);
+ if (!originalVs.isDistinct()) {
+ 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);
+ }
+ 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()) {
+ ValueIterator vi = dvs.getValueIterator(setState.valueExpression);
+ Comparable last = null;
+ int distinctCount = 0;
+ while (vi.hasNext()) {
+ Comparable next = (Comparable) vi.next();
+ if (last == null || next.compareTo(last) != 0) {
+ distinctCount++;
+ }
+ last = next;
+ }
+ if (distinctCount > setState.maxNdv) {
+ setState.overMax = true;
+ }
+ }
+ }
+ }
+ }
+
+ public void close() {
+ if (dvs != null) {
+ sortUtility = null;
+ dvs.getTupleBuffer().remove();
+ dvs = null;
+ }
+ }
+
+ public List<SetState> getDepedentSetStates() {
+ return dependentSetStates;
+ }
+
+ }
+
+ private static final int SORT = 2;
+ private static final int SET_PROCESSING = 3;
+
+ //constructor state
+ private int maxSetSize;
+ private int maxPredicates;
+ private RelationalNode dependentNode;
+ private Criteria dependentCrit;
+
+ //initialization state
+ private List<Criteria> queryCriteria;
+ private Map<Integer, SetState> setStates = new HashMap<Integer, SetState>();
+ private LinkedHashMap<String, TupleState> dependentState = new LinkedHashMap<String, TupleState>();
+ private List<List<SetState>> sources = new ArrayList<List<SetState>>();
+
+ // processing state
+ private int phase = SORT;
+ private LinkedList<Integer> restartIndexes = new LinkedList<Integer>();
+ private int currentIndex;
+ private boolean hasNextCommand;
+ protected SubqueryAwareEvaluator eval;
+
+ public DependentCriteriaProcessor(int maxSetSize, int maxPredicates, RelationalNode dependentNode, Criteria dependentCriteria) throws ExpressionEvaluationException, TeiidComponentException {
+ this.maxSetSize = maxSetSize;
+ this.maxPredicates = maxPredicates;
+ this.dependentNode = dependentNode;
+ this.dependentCrit = dependentCriteria;
+ this.eval = new SubqueryAwareEvaluator(Collections.emptyMap(), dependentNode.getDataManager(), dependentNode.getContext(), dependentNode.getBufferManager());
+ queryCriteria = Criteria.separateCriteriaByAnd(dependentCrit);
+
+ for (int i = 0; i < queryCriteria.size(); i++) {
+ Criteria criteria = queryCriteria.get(i);
+ if (!(criteria instanceof AbstractSetCriteria)) {
+ continue;
+ }
+
+ if (criteria instanceof SetCriteria) {
+ SetCriteria setCriteria = (SetCriteria)criteria;
+ if (setCriteria.isNegated() || setCriteria.getNumberOfValues() <= maxSetSize) {
+ continue;
+ }
+ SetState state = new SetState();
+ setStates.put(i, state);
+ LinkedHashSet<Object> values = new LinkedHashSet<Object>();
+ for (Expression expr : (Collection<Expression>)setCriteria.getValues()) {
+ values.add(eval.evaluate(expr, null));
+ }
+ state.valueIterator = new CollectionValueIterator(values);
+ sources.add(Arrays.asList(state));
+ } else if (criteria instanceof DependentSetCriteria) {
+ DependentSetCriteria dsc = (DependentSetCriteria)criteria;
+ String source = dsc.getContextSymbol();
+
+ SetState state = new SetState();
+ setStates.put(i, state);
+ state.valueExpression = dsc.getValueExpression();
+ TupleState ts = dependentState.get(source);
+ if (ts == null) {
+ ts = new TupleState(source);
+ dependentState.put(source, ts);
+ sources.add(ts.getDepedentSetStates());
+ }
+ ts.getDepedentSetStates().add(state);
+ state.maxNdv = dsc.getMaxNdv();
+ }
+ }
+ }
+
+ public void close() {
+ if (dependentState != null) {
+ for (TupleState state : dependentState.values()) {
+ state.close();
+ }
+ }
+ if (this.eval != null) {
+ this.eval.close();
+ }
+ }
+
+ public Criteria prepareCriteria() throws TeiidComponentException, TeiidProcessingException {
+
+ if (phase == SORT) {
+ for (TupleState state : dependentState.values()) {
+ state.sort();
+ }
+
+ phase = SET_PROCESSING;
+ }
+
+ replaceDependentValueIterators();
+
+ LinkedList<Criteria> crits = new LinkedList<Criteria>();
+
+ for (int i = 0; i < queryCriteria.size(); i++) {
+ SetState state = this.setStates.get(i);
+ if (state == null) {
+ crits.add((Criteria)queryCriteria.get(i).clone());
+ } else {
+ Criteria crit = replaceDependentCriteria((AbstractSetCriteria)queryCriteria.get(i), state);
+ if (crit == QueryRewriter.FALSE_CRITERIA) {
+ return QueryRewriter.FALSE_CRITERIA;
+ }
+ crits.add(crit);
+ }
+ }
+
+ if (crits.size() == 1) {
+ return crits.get(0);
+ }
+ return new CompoundCriteria(CompoundCriteria.AND, crits);
+ }
+
+ public void consumedCriteria() {
+ // flush only the value iterators starting at the restart index
+ // it is only safe to do this after the super call to prepare command
+ if (restartIndexes.isEmpty()) {
+ return;
+ }
+
+ int restartIndex = restartIndexes.removeLast().intValue();
+
+ for (int i = restartIndex; i < sources.size(); i++) {
+
+ List<SetState> source = sources.get(i);
+
+ for (SetState setState : source) {
+ setState.replacement.clear();
+ }
+ }
+
+ currentIndex = restartIndex;
+ }
+
+ /**
+ * Replace the dependentSet value iterators with the next set of values from the independent tuple source
+ *
+ * @param dependentSets
+ * @param replacementValueIterators
+ * @throws TeiidComponentException
+ */
+ private void replaceDependentValueIterators() throws TeiidComponentException {
+ int totalPredicates = sources.size();
+ if (this.maxPredicates > 0) {
+ //We have a bin packing problem if totalPredicates < sources - We'll address that case later.
+ //TODO: better handling for the correlated composite case
+ totalPredicates = Math.max(totalPredicates, this.maxPredicates);
+ }
+ long maxSize = Integer.MAX_VALUE;
+ if (this.maxSetSize > 0) {
+ maxSize = this.maxSetSize;
+ }
+ int currentPredicates = 0;
+ for (int run = 0; currentPredicates < totalPredicates; run++) {
+ currentPredicates = 0;
+ if (!restartIndexes.isEmpty()) {
+ currentIndex = restartIndexes.removeLast().intValue();
+ }
+ for (int i = 0; i < sources.size(); i++) {
+
+ List<SetState> source = sources.get(i);
+
+ if (i == currentIndex++) {
+
+ int doneCount = 0;
+
+ while (doneCount < source.size()) {
+
+ boolean isNull = false;
+ boolean lessThanMax = true;
+
+ for (SetState state : source) {
+ if (state.overMax) {
+ doneCount++;
+ continue;
+ }
+ if (state.nextValue == null && !state.isNull) {
+ if (state.valueIterator.hasNext()) {
+ state.nextValue = state.valueIterator.next();
+ state.isNull = state.nextValue == null;
+ } else {
+ state.valueIterator.reset();
+ doneCount++; // should be true for each iterator from this source
+ continue;
+ }
+ }
+
+ isNull |= state.isNull;
+ lessThanMax &= state.replacement.size() < maxSize * (run + 1);
+ }
+
+ if (doneCount == source.size()) {
+ if (!restartIndexes.isEmpty() && restartIndexes.getLast().intValue() == i) {
+ restartIndexes.removeLast();
+ }
+ break;
+ }
+
+ if (lessThanMax || isNull) {
+ for (SetState state : source) {
+ if (!isNull) {
+ state.replacement.add(state.nextValue);
+ }
+ state.nextValue = null;
+ state.isNull = false;
+ }
+ } else {
+ restartIndexes.add(i);
+ break;
+ }
+ }
+ }
+
+ for (SetState setState : source) {
+ currentPredicates += setState.replacement.size()/maxSize+(setState.replacement.size()%maxSize!=0?1:0);
+ }
+ }
+
+ if (restartIndexes.isEmpty()) {
+ break;
+ }
+ }
+
+ hasNextCommand = !restartIndexes.isEmpty();
+ }
+
+ protected boolean hasNextCommand() {
+ return hasNextCommand;
+ }
+
+ 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()) {
+ // No values - return criteria that is always false
+ return QueryRewriter.FALSE_CRITERIA;
+ }
+ int numberOfSets = 1;
+ int maxSize = Integer.MAX_VALUE;
+ if (this.maxSetSize > 0) {
+ maxSize = this.maxSetSize;
+ numberOfSets = state.replacement.size()/maxSize + (state.replacement.size()%maxSize!=0?1:0);
+ }
+ Iterator<Object> iter = state.replacement.iterator();
+ ArrayList<Criteria> orCrits = new ArrayList<Criteria>(numberOfSets);
+
+ for (int i = 0; i < numberOfSets; i++) {
+ if (maxSize == 1 || i + 1 == state.replacement.size()) {
+ orCrits.add(new CompareCriteria(crit.getExpression(), CompareCriteria.EQ, newConstant(iter.next())));
+ } else {
+ List<Constant> vals = new ArrayList<Constant>(Math.min(state.replacement.size(), maxSize));
+
+ for (int j = 0; j < maxSize && iter.hasNext(); j++) {
+ Object val = iter.next();
+ vals.add(newConstant(val));
+ }
+
+ SetCriteria sc = new SetCriteria();
+ sc.setExpression(crit.getExpression());
+ sc.setValues(vals);
+ orCrits.add(sc);
+ }
+ }
+ if (orCrits.size() == 1) {
+ return orCrits.get(0);
+ }
+ return new CompoundCriteria(CompoundCriteria.OR, orCrits);
+ }
+
+ private Constant newConstant(Object val) {
+ Constant c = new Constant(val);
+ c.setBindEligible(true);
+ return c;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentValueSource.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/relational/DependentValueSource.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentValueSource.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,109 +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 java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.teiid.common.buffer.IndexedTupleSource;
-import org.teiid.common.buffer.TupleBuffer;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.Assertion;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.util.ValueIterator;
-import org.teiid.query.sql.util.ValueIteratorSource;
-
-
-
-/**
- */
-public class DependentValueSource implements
- ValueIteratorSource {
-
- private TupleBuffer buffer;
- private Map<Expression, Set<Object>> cachedSets;
-
- public DependentValueSource(TupleBuffer tupleSourceID) {
- this.buffer = tupleSourceID;
- }
-
- public TupleBuffer getTupleBuffer() {
- return buffer;
- }
-
- /**
- * @throws TeiidComponentException
- * @see org.teiid.query.sql.util.ValueIteratorSource#getValueIterator(org.teiid.query.sql.symbol.Expression)
- */
- public ValueIterator getValueIterator(Expression valueExpression) throws TeiidComponentException {
- IndexedTupleSource its = buffer.createIndexedTupleSource();
- int index = 0;
- if (valueExpression != null) {
- index = buffer.getSchema().indexOf(valueExpression);
- Assertion.assertTrue(index != -1);
- }
- return new TupleSourceValueIterator(its, index);
- }
-
- public Set<Object> getCachedSet(Expression valueExpression) throws TeiidComponentException, TeiidProcessingException {
- Set<Object> result = null;
- if (cachedSets != null) {
- result = cachedSets.get(valueExpression);
- }
- if (result == null) {
- if (buffer.getRowCount() > buffer.getBatchSize()) {
- return null;
- }
- IndexedTupleSource its = buffer.createIndexedTupleSource();
- int index = 0;
- if (valueExpression != null) {
- index = buffer.getSchema().indexOf(valueExpression);
- }
- Assertion.assertTrue(index != -1);
- if (((SingleElementSymbol)buffer.getSchema().get(index)).getType() == DataTypeManager.DefaultDataClasses.BIG_DECIMAL) {
- result = new TreeSet<Object>();
- } else {
- result = new HashSet<Object>();
- }
- while (its.hasNext()) {
- Object value = its.nextTuple().get(index);
- if (value != null) {
- result.add(value);
- }
- }
- its.closeSource();
- if (cachedSets == null) {
- cachedSets = new HashMap<Expression, Set<Object>>();
- }
- cachedSets.put(valueExpression, result);
- }
- return result;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentValueSource.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/processor/relational/DependentValueSource.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentValueSource.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/DependentValueSource.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,129 @@
+/*
+ * 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.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.teiid.common.buffer.IndexedTupleSource;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.Assertion;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.util.ValueIterator;
+import org.teiid.query.sql.util.ValueIteratorSource;
+
+
+
+/**
+ */
+public class DependentValueSource implements
+ ValueIteratorSource {
+
+ 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;
+ }
+
+ public TupleBuffer getTupleBuffer() {
+ return buffer;
+ }
+
+ /**
+ * @throws TeiidComponentException
+ * @see org.teiid.query.sql.util.ValueIteratorSource#getValueIterator(org.teiid.query.sql.symbol.Expression)
+ */
+ public ValueIterator getValueIterator(Expression valueExpression) throws TeiidComponentException {
+ IndexedTupleSource its = buffer.createIndexedTupleSource();
+ int index = 0;
+ if (valueExpression != null) {
+ index = buffer.getSchema().indexOf(valueExpression);
+ Assertion.assertTrue(index != -1);
+ }
+ return new TupleSourceValueIterator(its, index);
+ }
+
+ public Set<Object> getCachedSet(Expression valueExpression) throws TeiidComponentException, TeiidProcessingException {
+ Set<Object> result = null;
+ if (cachedSets != null) {
+ result = cachedSets.get(valueExpression);
+ }
+ if (result == null) {
+ if (buffer.getRowCount() > buffer.getBatchSize()) {
+ return null;
+ }
+ IndexedTupleSource its = buffer.createIndexedTupleSource();
+ int index = 0;
+ if (valueExpression != null) {
+ index = buffer.getSchema().indexOf(valueExpression);
+ }
+ Assertion.assertTrue(index != -1);
+ if (((SingleElementSymbol)buffer.getSchema().get(index)).getType() == DataTypeManager.DefaultDataClasses.BIG_DECIMAL) {
+ result = new TreeSet<Object>();
+ } else {
+ result = new HashSet<Object>();
+ }
+ while (its.hasNext()) {
+ Object value = its.nextTuple().get(index);
+ if (value != null) {
+ result.add(value);
+ }
+ }
+ its.closeSource();
+ if (cachedSets == null) {
+ cachedSets = new HashMap<Expression, Set<Object>>();
+ }
+ cachedSets.put(valueExpression, result);
+ }
+ 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;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/EnhancedSortMergeJoinStrategy.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/relational/EnhancedSortMergeJoinStrategy.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/EnhancedSortMergeJoinStrategy.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,330 +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 java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.teiid.common.buffer.IndexedTupleSource;
-import org.teiid.common.buffer.STree;
-import org.teiid.common.buffer.TupleBrowser;
-import org.teiid.common.buffer.TupleSource;
-import org.teiid.common.buffer.BufferManager.BufferReserveMode;
-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.query.optimizer.relational.rules.NewCalculateCostUtil;
-import org.teiid.query.processor.CollectionTupleSource;
-import org.teiid.query.sql.lang.OrderBy;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-
-
-/**
- * Extends the basic fully sorted merge join to check for conditions necessary
- * to not fully sort one of the sides.
- *
- * Will be used for inner joins and only if both sorts are not required.
- * Degrades to a normal merge join if the tuples are balanced.
- *
- * Refined in 7.4 to use a full index if it is small enough or a repeated merge, rather than a partitioning approach (which was really just a single level index)
- */
-public class EnhancedSortMergeJoinStrategy extends MergeJoinStrategy {
-
- private TupleSource currentSource;
- private SourceState sortedSource;
- private SourceState notSortedSource;
- private List<?> currentTuple;
- private TupleBrowser tb;
- private int reserved;
- private STree index;
- private int[] reverseIndexes;
- private List<?> sortedTuple;
- private boolean repeatedMerge;
-
- /**
- * Number of index batches we'll allow to marked as prefers memory regardless of buffer space
- */
- private int preferMemCutoff = 8;
-
- public EnhancedSortMergeJoinStrategy(SortOption sortLeft, SortOption sortRight) {
- super(sortLeft, sortRight, false);
- }
-
- public void setPreferMemCutoff(int cutoff) {
- this.preferMemCutoff = cutoff;
- }
-
- @Override
- public void close() {
- if (joinNode == null) {
- return;
- }
- super.close();
- if (this.index != null) {
- this.index.remove();
- }
- releaseReserved();
- this.index = null;
- this.tb = null;
- this.currentSource = null;
- this.sortedSource = null;
- this.notSortedSource = null;
- this.sortedTuple = null;
- this.reverseIndexes = null;
- }
-
- /**
- * Create an index of the smaller size
- *
- * TODO: reuse existing temp table indexes
- */
- public void createIndex(SourceState state, boolean sorted) throws TeiidComponentException, TeiidProcessingException {
- int keyLength = state.getExpressionIndexes().length;
- List elements = state.getSource().getOutputElements();
-
- //TODO: minimize reordering, or at least detect when it's not necessary
- int[] reorderedSortIndex = Arrays.copyOf(state.getExpressionIndexes(), elements.size());
- Set<Integer> used = new HashSet<Integer>();
- for (int i : state.getExpressionIndexes()) {
- used.add(i);
- }
- int j = state.getExpressionIndexes().length;
- for (int i = 0; i < elements.size(); i++) {
- if (!used.contains(i)) {
- reorderedSortIndex[j++] = i;
- }
- }
- List<SingleElementSymbol> reordered = RelationalNode.projectTuple(reorderedSortIndex, elements);
- if (!state.isDistinct()) {
- //need to add a rowid, just in case
- reordered = new ArrayList<SingleElementSymbol>(reordered);
- ElementSymbol id = new ElementSymbol("rowId"); //$NON-NLS-1$
- id.setType(DataTypeManager.DefaultDataClasses.INTEGER);
- reordered.add(keyLength, id);
- keyLength++;
- }
- index = this.joinNode.getBufferManager().createSTree(reordered, this.joinNode.getConnectionID(), keyLength);
- index.setPreferMemory(true);
- if (!state.isDistinct()) {
- index.getComparator().setDistinctIndex(keyLength-2);
- }
- IndexedTupleSource its = state.getTupleBuffer().createIndexedTupleSource(!joinNode.isDependent());
- int rowId = 0;
- List<?> lastTuple = null;
- boolean sortedDistinct = sorted && !state.isDistinct();
- int sizeHint = index.getExpectedHeight(state.getTupleBuffer().getRowCount());
- outer: while (its.hasNext()) {
- //detect if sorted and distinct
- List<?> originalTuple = its.nextTuple();
- //remove the tuple if it has null
- for (int i : state.getExpressionIndexes()) {
- if (originalTuple.get(i) == null) {
- continue outer;
- }
- }
- if (sortedDistinct && lastTuple != null && this.compare(lastTuple, originalTuple, state.getExpressionIndexes(), state.getExpressionIndexes()) == 0) {
- sortedDistinct = false;
- }
- lastTuple = originalTuple;
- List<Object> tuple = (List<Object>) RelationalNode.projectTuple(reorderedSortIndex, originalTuple);
- if (!state.isDistinct()) {
- tuple.add(keyLength - 1, rowId++);
- }
- index.insert(tuple, sorted?InsertMode.ORDERED:InsertMode.NEW, sizeHint);
- }
- if (!sorted) {
- index.compact();
- }
- its.closeSource();
- this.reverseIndexes = new int[elements.size()];
- for (int i = 0; i < reverseIndexes.length; i++) {
- int oldIndex = reorderedSortIndex[i];
- this.reverseIndexes[oldIndex] = i + (!state.isDistinct()&&i>=keyLength-1?1:0);
- }
- if (!state.isDistinct()
- && ((!sorted && index.getComparator().isDistinct()) || (sorted && sortedDistinct))) {
- this.index.removeRowIdFromKey();
- state.markDistinct(true);
- }
- }
-
- @Override
- protected void loadLeft() throws TeiidComponentException,
- TeiidProcessingException {
- if (this.joinNode.isDependent()) {
- this.leftSource.getTupleBuffer();
- }
- }
-
- private boolean shouldIndexIfSmall(SourceState source) throws TeiidComponentException, TeiidProcessingException {
- Number cardinality = source.getSource().getEstimateNodeCardinality();
- return (source.hasBuffer() || (cardinality != null && cardinality.floatValue() != NewCalculateCostUtil.UNKNOWN_VALUE && cardinality.floatValue() <= this.joinNode.getBatchSize()))
- && (source.getRowCount() <= this.joinNode.getBatchSize());
- }
-
- @Override
- protected void loadRight() throws TeiidComponentException,
- TeiidProcessingException {
- //the checks are done in a particular order to ensure we don't buffer if possible
- if (processingSortRight == SortOption.SORT && shouldIndexIfSmall(this.leftSource)) {
- this.processingSortRight = SortOption.NOT_SORTED;
- } else if (!this.leftSource.hasBuffer() && processingSortLeft == SortOption.SORT && shouldIndexIfSmall(this.rightSource)) {
- this.processingSortLeft = SortOption.NOT_SORTED;
- } else {
- this.leftSource.getTupleBuffer();
- if (!this.rightSource.hasBuffer() && processingSortRight == SortOption.SORT && shouldIndexIfSmall(this.leftSource)) {
- this.processingSortRight = SortOption.NOT_SORTED;
- } else if (processingSortRight == SortOption.SORT && shouldIndex(this.leftSource, this.rightSource)) {
- this.processingSortRight = SortOption.NOT_SORTED;
- } else if (processingSortLeft == SortOption.SORT && shouldIndex(this.rightSource, this.leftSource)) {
- this.processingSortLeft = SortOption.NOT_SORTED;
- }
- }
- if (this.processingSortLeft != SortOption.NOT_SORTED && this.processingSortRight != SortOption.NOT_SORTED) {
- super.loadRight();
- super.loadLeft();
- return; //degrade to merge join
- }
- if (this.processingSortLeft == SortOption.NOT_SORTED) {
- this.sortedSource = this.rightSource;
- this.notSortedSource = this.leftSource;
-
- if (!repeatedMerge) {
- createIndex(this.rightSource, this.processingSortRight == SortOption.ALREADY_SORTED);
- } else {
- super.loadRight(); //sort if needed
- this.notSortedSource.sort(SortOption.NOT_SORTED); //do a single sort pass
- }
- } else if (this.processingSortRight == SortOption.NOT_SORTED) {
- this.sortedSource = this.leftSource;
- this.notSortedSource = this.rightSource;
-
- if (!repeatedMerge) {
- createIndex(this.leftSource, this.processingSortLeft == SortOption.ALREADY_SORTED);
- } else {
- super.loadLeft(); //sort if needed
- this.notSortedSource.sort(SortOption.NOT_SORTED); //do a single sort pass
- }
- }
- }
-
- private boolean shouldIndex(SourceState possibleIndex, SourceState other) throws TeiidComponentException, TeiidProcessingException {
- if (possibleIndex.getRowCount() * 4 > other.getRowCount()) {
- return false; //index is too large
- }
- int schemaSize = this.joinNode.getBufferManager().getSchemaSize(other.getSource().getOutputElements());
- int toReserve = this.joinNode.getBufferManager().getMaxProcessingKB();
- //check if the other side can be sorted in memory
- if (other.getRowCount() <= this.joinNode.getBatchSize()
- || (possibleIndex.getRowCount() > this.joinNode.getBatchSize() && other.getRowCount()/this.joinNode.getBatchSize() < toReserve/schemaSize)) {
- return false;
- }
- boolean useIndex = false;
- int indexSchemaSize = this.joinNode.getBufferManager().getSchemaSize(possibleIndex.getSource().getOutputElements());
- //approximate that 1/2 of the index will be memory resident
- toReserve = (int)(indexSchemaSize * possibleIndex.getTupleBuffer().getRowCount() / (possibleIndex.getTupleBuffer().getBatchSize() * .5));
- if (toReserve < this.joinNode.getBufferManager().getMaxProcessingKB()) {
- useIndex = true;
- } else if (possibleIndex.getTupleBuffer().getRowCount() / this.joinNode.getBatchSize() < preferMemCutoff) {
- useIndex = true;
- }
- if (useIndex) {
- reserved = this.joinNode.getBufferManager().reserveBuffers(toReserve, BufferReserveMode.FORCE);
- return true;
- }
- this.repeatedMerge = true;
- return true;
- }
-
- private void releaseReserved() {
- this.joinNode.getBufferManager().releaseBuffers(this.reserved);
- this.reserved = 0;
- }
-
- @Override
- protected void process() throws TeiidComponentException,
- TeiidProcessingException {
- if (this.processingSortLeft != SortOption.NOT_SORTED && this.processingSortRight != SortOption.NOT_SORTED) {
- super.process();
- return;
- }
- if (this.sortedSource.getTupleBuffer().getRowCount() == 0) {
- return;
- }
- if (repeatedMerge) {
- while (this.notSortedSource.hasBuffer()) {
- super.process();
- resetMatchState();
- this.sortedSource.resetState();
- this.notSortedSource.nextBuffer();
- }
- return;
- }
- //else this is a single scan against the index
- if (currentSource == null) {
- currentSource = this.notSortedSource.getIterator();
- }
- while (true) {
- if (this.currentTuple == null) {
- currentTuple = this.currentSource.nextTuple();
- if (currentTuple == null) {
- return;
- }
- List<?> key = RelationalNode.projectTuple(this.notSortedSource.getExpressionIndexes(), this.currentTuple);
- tb = new TupleBrowser(this.index, new CollectionTupleSource(Arrays.asList(key).iterator()), OrderBy.ASC);
- }
- if (sortedTuple == null) {
- sortedTuple = tb.nextTuple();
-
- if (sortedTuple == null) {
- currentTuple = null;
- continue;
- }
- }
- List<?> reorderedTuple = RelationalNode.projectTuple(reverseIndexes, sortedTuple);
- List outputTuple = outputTuple(this.processingSortLeft==SortOption.NOT_SORTED?currentTuple:reorderedTuple,
- this.processingSortLeft==SortOption.NOT_SORTED?reorderedTuple:currentTuple);
- boolean matches = this.joinNode.matchesCriteria(outputTuple);
- this.sortedTuple = null;
- if (matches) {
- this.joinNode.addBatchRow(outputTuple);
- }
- }
- }
-
- @Override
- public EnhancedSortMergeJoinStrategy clone() {
- return new EnhancedSortMergeJoinStrategy(this.sortLeft, this.sortRight);
- }
-
- @Override
- public String getName() {
- return "ENHANCED SORT JOIN"; //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/EnhancedSortMergeJoinStrategy.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/processor/relational/EnhancedSortMergeJoinStrategy.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/EnhancedSortMergeJoinStrategy.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/EnhancedSortMergeJoinStrategy.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,356 @@
+/*
+ * 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.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.teiid.common.buffer.IndexedTupleSource;
+import org.teiid.common.buffer.STree;
+import org.teiid.common.buffer.TupleBrowser;
+import org.teiid.common.buffer.TupleSource;
+import org.teiid.common.buffer.BufferManager.BufferReserveMode;
+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.query.optimizer.relational.rules.NewCalculateCostUtil;
+import org.teiid.query.processor.CollectionTupleSource;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+
+
+/**
+ * Extends the basic fully sorted merge join to check for conditions necessary
+ * to not fully sort one of the sides.
+ *
+ * Will be used for inner joins and only if both sorts are not required.
+ * Degrades to a normal merge join if the tuples are balanced.
+ *
+ * Refined in 7.4 to use a full index if it is small enough or a repeated merge, rather than a partitioning approach (which was really just a single level index)
+ */
+public class EnhancedSortMergeJoinStrategy extends MergeJoinStrategy {
+
+ private boolean semiDep;
+
+ private TupleSource currentSource;
+ private SourceState sortedSource;
+ private SourceState notSortedSource;
+ private List<?> currentTuple;
+ private TupleBrowser tb;
+ private int reserved;
+ private STree index;
+ 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
+ */
+ private int preferMemCutoff = 8;
+
+ public EnhancedSortMergeJoinStrategy(SortOption sortLeft, SortOption sortRight) {
+ super(sortLeft, sortRight, false);
+ }
+
+ public void setPreferMemCutoff(int cutoff) {
+ this.preferMemCutoff = cutoff;
+ }
+
+ @Override
+ public void close() {
+ if (joinNode == null) {
+ return;
+ }
+ super.close();
+ if (this.index != null) {
+ this.index.remove();
+ }
+ releaseReserved();
+ this.index = null;
+ this.tb = null;
+ this.currentSource = null;
+ this.sortedSource = null;
+ this.notSortedSource = null;
+ this.sortedTuple = null;
+ this.reverseIndexes = null;
+ }
+
+ /**
+ * Create an index of the smaller size
+ *
+ * TODO: reuse existing temp table indexes
+ */
+ public void createIndex(SourceState state, boolean sorted) throws TeiidComponentException, TeiidProcessingException {
+ int keyLength = state.getExpressionIndexes().length;
+ List elements = state.getSource().getOutputElements();
+
+ //TODO: minimize reordering, or at least detect when it's not necessary
+ int[] reorderedSortIndex = Arrays.copyOf(state.getExpressionIndexes(), elements.size());
+ Set<Integer> used = new HashSet<Integer>();
+ for (int i : state.getExpressionIndexes()) {
+ used.add(i);
+ }
+ int j = state.getExpressionIndexes().length;
+ for (int i = 0; i < elements.size(); i++) {
+ if (!used.contains(i)) {
+ reorderedSortIndex[j++] = i;
+ }
+ }
+ List<SingleElementSymbol> reordered = RelationalNode.projectTuple(reorderedSortIndex, elements);
+ if (!state.isDistinct()) {
+ //need to add a rowid, just in case
+ reordered = new ArrayList<SingleElementSymbol>(reordered);
+ ElementSymbol id = new ElementSymbol("rowId"); //$NON-NLS-1$
+ id.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+ reordered.add(keyLength, id);
+ keyLength++;
+ }
+ index = this.joinNode.getBufferManager().createSTree(reordered, this.joinNode.getConnectionID(), keyLength);
+ index.setPreferMemory(true);
+ if (!state.isDistinct()) {
+ index.getComparator().setDistinctIndex(keyLength-2);
+ }
+ IndexedTupleSource its = state.getTupleBuffer().createIndexedTupleSource(!joinNode.isDependent());
+ int rowId = 0;
+ List<?> lastTuple = null;
+ boolean sortedDistinct = sorted && !state.isDistinct();
+ int sizeHint = index.getExpectedHeight(state.getTupleBuffer().getRowCount());
+ outer: while (its.hasNext()) {
+ //detect if sorted and distinct
+ List<?> originalTuple = its.nextTuple();
+ //remove the tuple if it has null
+ for (int i : state.getExpressionIndexes()) {
+ if (originalTuple.get(i) == null) {
+ continue outer;
+ }
+ }
+ if (sortedDistinct && lastTuple != null && this.compare(lastTuple, originalTuple, state.getExpressionIndexes(), state.getExpressionIndexes()) == 0) {
+ sortedDistinct = false;
+ }
+ lastTuple = originalTuple;
+ List<Object> tuple = (List<Object>) RelationalNode.projectTuple(reorderedSortIndex, originalTuple);
+ if (!state.isDistinct()) {
+ tuple.add(keyLength - 1, rowId++);
+ }
+ index.insert(tuple, sorted?InsertMode.ORDERED:InsertMode.NEW, sizeHint);
+ }
+ if (!sorted) {
+ index.compact();
+ }
+ its.closeSource();
+ this.reverseIndexes = new int[elements.size()];
+ for (int i = 0; i < reverseIndexes.length; i++) {
+ int oldIndex = reorderedSortIndex[i];
+ this.reverseIndexes[oldIndex] = i + (!state.isDistinct()&&i>=keyLength-1?1:0);
+ }
+ if (!state.isDistinct()
+ && ((!sorted && index.getComparator().isDistinct()) || (sorted && sortedDistinct))) {
+ this.index.removeRowIdFromKey();
+ state.markDistinct(true);
+ }
+ }
+
+ @Override
+ protected void loadLeft() throws TeiidComponentException,
+ TeiidProcessingException {
+ if (this.joinNode.isDependent()) {
+ this.leftSource.getTupleBuffer();
+ }
+ }
+
+ private boolean shouldIndexIfSmall(SourceState source) throws TeiidComponentException, TeiidProcessingException {
+ Number cardinality = source.getSource().getEstimateNodeCardinality();
+ return (source.hasBuffer() || (cardinality != null && cardinality.floatValue() != NewCalculateCostUtil.UNKNOWN_VALUE && cardinality.floatValue() <= this.joinNode.getBatchSize()))
+ && (source.getRowCount() <= this.joinNode.getBatchSize());
+ }
+
+ @Override
+ protected void loadRight() throws TeiidComponentException,
+ TeiidProcessingException {
+ //the checks are done in a particular order to ensure we don't buffer if possible
+ if (processingSortRight == SortOption.SORT && shouldIndexIfSmall(this.leftSource)) {
+ this.processingSortRight = SortOption.NOT_SORTED;
+ } else if (!this.leftSource.hasBuffer() && processingSortLeft == SortOption.SORT && shouldIndexIfSmall(this.rightSource)) {
+ this.processingSortLeft = SortOption.NOT_SORTED;
+ } else {
+ this.leftSource.getTupleBuffer();
+ if (!this.rightSource.hasBuffer() && processingSortRight == SortOption.SORT && shouldIndexIfSmall(this.leftSource)) {
+ this.processingSortRight = SortOption.NOT_SORTED;
+ } else if (processingSortRight == SortOption.SORT && shouldIndex(this.leftSource, this.rightSource)) {
+ this.processingSortRight = SortOption.NOT_SORTED;
+ } else if (processingSortLeft == SortOption.SORT && shouldIndex(this.rightSource, this.leftSource)) {
+ this.processingSortLeft = SortOption.NOT_SORTED;
+ }
+ }
+ if (this.processingSortLeft != SortOption.NOT_SORTED && this.processingSortRight != SortOption.NOT_SORTED) {
+ super.loadRight();
+ super.loadLeft();
+ return; //degrade to merge join
+ }
+ if (this.processingSortLeft == SortOption.NOT_SORTED) {
+ this.sortedSource = this.rightSource;
+ this.notSortedSource = this.leftSource;
+
+ if (!repeatedMerge) {
+ createIndex(this.rightSource, this.processingSortRight == SortOption.ALREADY_SORTED);
+ } else {
+ super.loadRight(); //sort if needed
+ this.notSortedSource.sort(SortOption.NOT_SORTED); //do a single sort pass
+ }
+ } else if (this.processingSortRight == SortOption.NOT_SORTED) {
+ 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 {
+ super.loadLeft(); //sort if needed
+ this.notSortedSource.sort(SortOption.NOT_SORTED); //do a single sort pass
+ }
+ }
+ }
+
+ private boolean shouldIndex(SourceState possibleIndex, SourceState other) throws TeiidComponentException, TeiidProcessingException {
+ if (possibleIndex.getRowCount() * 4 > other.getRowCount()) {
+ return false; //index is too large
+ }
+ int schemaSize = this.joinNode.getBufferManager().getSchemaSize(other.getSource().getOutputElements());
+ int toReserve = this.joinNode.getBufferManager().getMaxProcessingKB();
+ //check if the other side can be sorted in memory
+ if (other.getRowCount() <= this.joinNode.getBatchSize()
+ || (possibleIndex.getRowCount() > this.joinNode.getBatchSize() && other.getRowCount()/this.joinNode.getBatchSize() < toReserve/schemaSize)) {
+ return false;
+ }
+ boolean useIndex = false;
+ int indexSchemaSize = this.joinNode.getBufferManager().getSchemaSize(possibleIndex.getSource().getOutputElements());
+ //approximate that 1/2 of the index will be memory resident
+ toReserve = (int)(indexSchemaSize * possibleIndex.getTupleBuffer().getRowCount() / (possibleIndex.getTupleBuffer().getBatchSize() * .5));
+ if (toReserve < this.joinNode.getBufferManager().getMaxProcessingKB()) {
+ useIndex = true;
+ } else if (possibleIndex.getTupleBuffer().getRowCount() / this.joinNode.getBatchSize() < preferMemCutoff) {
+ useIndex = true;
+ }
+ if (useIndex) {
+ reserved = this.joinNode.getBufferManager().reserveBuffers(toReserve, BufferReserveMode.FORCE);
+ return true;
+ }
+ this.repeatedMerge = true;
+ return true;
+ }
+
+ private void releaseReserved() {
+ this.joinNode.getBufferManager().releaseBuffers(this.reserved);
+ this.reserved = 0;
+ }
+
+ @Override
+ protected void process() throws TeiidComponentException,
+ TeiidProcessingException {
+ if (this.processingSortLeft != SortOption.NOT_SORTED && this.processingSortRight != SortOption.NOT_SORTED) {
+ super.process();
+ return;
+ }
+ if (this.sortedSource.getTupleBuffer().getRowCount() == 0) {
+ return;
+ }
+ if (repeatedMerge) {
+ while (this.notSortedSource.hasBuffer()) {
+ super.process();
+ resetMatchState();
+ this.sortedSource.resetState();
+ this.notSortedSource.nextBuffer();
+ }
+ return;
+ }
+ //else this is a single scan against the index
+ if (currentSource == null) {
+ currentSource = this.notSortedSource.getIterator();
+ }
+ while (true) {
+ if (this.currentTuple == null) {
+ currentTuple = this.currentSource.nextTuple();
+ 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);
+ }
+ if (sortedTuple == null) {
+ sortedTuple = tb.nextTuple();
+
+ if (sortedTuple == null) {
+ currentTuple = null;
+ continue;
+ }
+ }
+ List<?> reorderedTuple = RelationalNode.projectTuple(reverseIndexes, sortedTuple);
+ List outputTuple = outputTuple(this.processingSortLeft==SortOption.NOT_SORTED?currentTuple:reorderedTuple,
+ this.processingSortLeft==SortOption.NOT_SORTED?reorderedTuple:currentTuple);
+ boolean matches = this.joinNode.matchesCriteria(outputTuple);
+ this.sortedTuple = null;
+ if (matches) {
+ this.joinNode.addBatchRow(outputTuple);
+ }
+ }
+ }
+
+ @Override
+ public EnhancedSortMergeJoinStrategy clone() {
+ EnhancedSortMergeJoinStrategy clone = new EnhancedSortMergeJoinStrategy(this.sortLeft, this.sortRight);
+ clone.semiDep = this.semiDep;
+ return clone;
+ }
+
+ @Override
+ public String getName() {
+ return "ENHANCED SORT JOIN" + (semiDep?" [SEMI]":""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ public void setSemiDep(boolean semiDep) {
+ this.semiDep = semiDep;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/JoinNode.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/relational/JoinNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/JoinNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,314 +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 static org.teiid.query.analysis.AnalysisRecord.*;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.client.plan.PlanNode;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.TupleBatch;
-import org.teiid.common.buffer.TupleBuffer;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.processor.relational.SourceState.ImplicitBuffer;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.util.CommandContext;
-
-
-/**
- * @since 4.2
- */
-public class JoinNode extends SubqueryAwareRelationalNode {
-
- static class BatchAvailableException extends RuntimeException {}
-
- static BatchAvailableException BATCH_AVILABLE = new BatchAvailableException();
-
- public enum JoinStrategyType {
- MERGE,
- ENHANCED_SORT,
- NESTED_LOOP,
- NESTED_TABLE
- }
-
- private enum State { LOAD_LEFT, LOAD_RIGHT, EXECUTE }
- private State state = State.LOAD_LEFT;
-
- private JoinStrategy joinStrategy;
- private JoinType joinType;
- private String dependentValueSource;
-
- private List leftExpressions;
- private List rightExpressions;
- private boolean leftDistinct;
- private boolean rightDistinct;
- private Criteria joinCriteria;
-
- private Map combinedElementMap;
- private int[] projectionIndexes;
-
- public JoinNode(int nodeID) {
- super(nodeID);
- }
-
- public void setJoinType(JoinType type) {
- this.joinType = type;
- }
-
- public JoinStrategy getJoinStrategy() {
- return this.joinStrategy;
- }
-
- public void setJoinStrategy(JoinStrategy joinStrategy) {
- this.joinStrategy = joinStrategy;
- }
-
- public void setJoinExpressions(List leftExpressions, List rightExpressions) {
- this.leftExpressions = leftExpressions;
- this.rightExpressions = rightExpressions;
- }
-
- public boolean isLeftDistinct() {
- return leftDistinct;
- }
-
- public void setLeftDistinct(boolean leftDistinct) {
- this.leftDistinct = leftDistinct;
- }
-
- public boolean isRightDistinct() {
- return rightDistinct;
- }
-
- public void setRightDistinct(boolean rightDistinct) {
- this.rightDistinct = rightDistinct;
- }
-
- public void setJoinCriteria(Criteria joinCriteria) {
- this.joinCriteria = joinCriteria;
- }
-
- @Override
- public void initialize(CommandContext context, BufferManager bufferManager,
- ProcessorDataManager dataMgr) {
- super.initialize(context, bufferManager, dataMgr);
-
- if (this.combinedElementMap == null) {
- // Create element lookup map for evaluating project expressions
- List combinedElements = new ArrayList(getChildren()[0].getElements());
- combinedElements.addAll(getChildren()[1].getElements());
- this.combinedElementMap = createLookupMap(combinedElements);
- this.projectionIndexes = getProjectionIndexes(combinedElementMap, getElements());
- }
- }
-
- public void open()
- throws TeiidComponentException, TeiidProcessingException {
- // Set Up Join Strategy
- this.joinStrategy.initialize(this);
-
- joinStrategy.openLeft();
-
- if(!isDependent()) {
- joinStrategy.openRight();
- }
-
- this.state = State.LOAD_LEFT;
- }
-
- /**
- * @see org.teiid.query.processor.relational.RelationalNode#clone()
- * @since 4.2
- */
- public Object clone() {
- JoinNode clonedNode = new JoinNode(super.getID());
- super.copy(this, clonedNode);
-
- clonedNode.joinType = this.joinType;
- clonedNode.joinStrategy = this.joinStrategy.clone();
-
- clonedNode.joinCriteria = this.joinCriteria;
-
- clonedNode.leftExpressions = leftExpressions;
-
- clonedNode.rightExpressions = rightExpressions;
- clonedNode.dependentValueSource = this.dependentValueSource;
- clonedNode.rightDistinct = rightDistinct;
- clonedNode.leftDistinct = leftDistinct;
-
- return clonedNode;
- }
-
- /**
- * @see org.teiid.query.processor.relational.RelationalNode#nextBatchDirect()
- * @since 4.2
- */
- protected TupleBatch nextBatchDirect() throws BlockedException,
- TeiidComponentException,
- TeiidProcessingException {
- if (state == State.LOAD_LEFT) {
- if (this.joinType != JoinType.JOIN_FULL_OUTER) {
- this.joinStrategy.leftSource.setImplicitBuffer(ImplicitBuffer.NONE);
- }
- //left child was already opened by the join node
- this.joinStrategy.loadLeft();
- if (isDependent()) {
- TupleBuffer buffer = this.joinStrategy.leftSource.getTupleBuffer();
- this.getContext().getVariableContext().setGlobalValue(this.dependentValueSource, new DependentValueSource(buffer));
- }
- state = State.LOAD_RIGHT;
- }
- if (state == State.LOAD_RIGHT) {
- this.joinStrategy.openRight();
- this.joinStrategy.loadRight();
- state = State.EXECUTE;
- }
- try {
- this.joinStrategy.process();
- this.terminateBatches();
- } catch (BatchAvailableException e) {
- //pull the batch
- }
- return pullBatch();
- }
-
- /**
- * @see org.teiid.query.processor.relational.RelationalNode#getDescriptionProperties()
- * @since 4.2
- */
- public PlanNode getDescriptionProperties() {
- // Default implementation - should be overridden
- PlanNode props = super.getDescriptionProperties();
-
- if(isDependent()) {
- props.addProperty(PROP_DEPENDENT, Boolean.TRUE.toString());
- }
- props.addProperty(PROP_JOIN_STRATEGY, this.joinStrategy.toString());
- props.addProperty(PROP_JOIN_TYPE, this.joinType.toString());
- List<String> critList = getCriteriaList();
- props.addProperty(PROP_JOIN_CRITERIA, critList);
- return props;
- }
-
- private List<String> getCriteriaList() {
- List<String> critList = new ArrayList<String>();
- if (leftExpressions != null) {
- for(int i=0; i < this.leftExpressions.size(); i++) {
- critList.add(this.leftExpressions.get(i).toString() + "=" + this.rightExpressions.get(i).toString()); //$NON-NLS-1$
- }
- }
- if (this.joinCriteria != null) {
- for (Criteria crit : (List<Criteria>)Criteria.separateCriteriaByAnd(joinCriteria)) {
- critList.add(crit.toString());
- }
- }
- return critList;
- }
-
- /**
- * @see org.teiid.query.processor.relational.RelationalNode#getNodeString(java.lang.StringBuffer)
- * @since 4.2
- */
- protected void getNodeString(StringBuffer str) {
- str.append(getClassName());
- str.append("("); //$NON-NLS-1$
- str.append(getID());
- str.append(") [");//$NON-NLS-1$
- if(isDependent()) {
- str.append("Dependent] [");//$NON-NLS-1$
- }
- str.append(this.joinStrategy.toString());
- str.append("] [");//$NON-NLS-1$
- str.append(this.joinType.toString());
- str.append("]"); //$NON-NLS-1$
- if (getJoinType() != JoinType.JOIN_CROSS) {
- str.append(" criteria=").append(getCriteriaList()); //$NON-NLS-1$
- }
- str.append(" output="); //$NON-NLS-1$
- str.append(getElements());
- }
-
- /**
- * @return Returns the isDependent.
- */
- public boolean isDependent() {
- return this.dependentValueSource != null;
- }
-
- /**
- * @param isDependent The isDependent to set.
- */
- public void setDependentValueSource(String dependentValueSource) {
- this.dependentValueSource = dependentValueSource;
- }
-
- public void closeDirect() {
- super.closeDirect();
- joinStrategy.close();
- if (this.getContext() != null && this.dependentValueSource != null) {
- this.getContext().getVariableContext().setGlobalValue(this.dependentValueSource, null);
- }
- }
-
- public JoinType getJoinType() {
- return this.joinType;
- }
-
- Map getCombinedElementMap() {
- return this.combinedElementMap;
- }
-
- public Criteria getJoinCriteria() {
- return this.joinCriteria;
- }
-
- boolean matchesCriteria(List outputTuple) throws BlockedException, TeiidComponentException, ExpressionEvaluationException {
- return (this.joinCriteria == null || getEvaluator(this.combinedElementMap).evaluate(this.joinCriteria, outputTuple));
- }
-
- public List getLeftExpressions() {
- return this.leftExpressions;
- }
-
- public List getRightExpressions() {
- return this.rightExpressions;
- }
-
- @Override
- protected void addBatchRow(List row) {
- List projectTuple = projectTuple(this.projectionIndexes, row);
- super.addBatchRow(projectTuple);
- if (isBatchFull()) {
- throw BATCH_AVILABLE;
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/JoinNode.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/processor/relational/JoinNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/JoinNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/JoinNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,333 @@
+/*
+ * 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 static org.teiid.query.analysis.AnalysisRecord.*;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.client.plan.PlanNode;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.TupleBatch;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.processor.relational.SourceState.ImplicitBuffer;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.util.CommandContext;
+
+
+/**
+ * @since 4.2
+ */
+public class JoinNode extends SubqueryAwareRelationalNode {
+
+ static class BatchAvailableException extends RuntimeException {}
+
+ static BatchAvailableException BATCH_AVILABLE = new BatchAvailableException();
+
+ public enum JoinStrategyType {
+ MERGE,
+ ENHANCED_SORT,
+ NESTED_LOOP,
+ NESTED_TABLE
+ }
+
+ private enum State { LOAD_LEFT, LOAD_RIGHT, EXECUTE }
+ private State state = State.LOAD_LEFT;
+
+ private JoinStrategy joinStrategy;
+ private JoinType joinType;
+ private String dependentValueSource;
+
+ private List leftExpressions;
+ private List rightExpressions;
+ private boolean leftDistinct;
+ private boolean rightDistinct;
+ private Criteria joinCriteria;
+
+ private Map combinedElementMap;
+ private int[] projectionIndexes;
+
+ private DependentValueSource dvs;
+
+ public JoinNode(int nodeID) {
+ super(nodeID);
+ }
+
+ public void setJoinType(JoinType type) {
+ this.joinType = type;
+ }
+
+ public JoinStrategy getJoinStrategy() {
+ return this.joinStrategy;
+ }
+
+ public void setJoinStrategy(JoinStrategy joinStrategy) {
+ this.joinStrategy = joinStrategy;
+ }
+
+ public void setJoinExpressions(List leftExpressions, List rightExpressions) {
+ this.leftExpressions = leftExpressions;
+ this.rightExpressions = rightExpressions;
+ }
+
+ public boolean isLeftDistinct() {
+ return leftDistinct;
+ }
+
+ public void setLeftDistinct(boolean leftDistinct) {
+ this.leftDistinct = leftDistinct;
+ }
+
+ public boolean isRightDistinct() {
+ return rightDistinct;
+ }
+
+ public void setRightDistinct(boolean rightDistinct) {
+ this.rightDistinct = rightDistinct;
+ }
+
+ public void setJoinCriteria(Criteria joinCriteria) {
+ this.joinCriteria = joinCriteria;
+ }
+
+ @Override
+ public void initialize(CommandContext context, BufferManager bufferManager,
+ ProcessorDataManager dataMgr) {
+ super.initialize(context, bufferManager, dataMgr);
+
+ if (this.combinedElementMap == null) {
+ // Create element lookup map for evaluating project expressions
+ List combinedElements = new ArrayList(getChildren()[0].getElements());
+ combinedElements.addAll(getChildren()[1].getElements());
+ this.combinedElementMap = createLookupMap(combinedElements);
+ this.projectionIndexes = getProjectionIndexes(combinedElementMap, getElements());
+ }
+ }
+
+ public void open()
+ throws TeiidComponentException, TeiidProcessingException {
+ // Set Up Join Strategy
+ this.joinStrategy.initialize(this);
+
+ joinStrategy.openLeft();
+
+ if(!isDependent()) {
+ joinStrategy.openRight();
+ }
+
+ this.state = State.LOAD_LEFT;
+ }
+
+ /**
+ * @see org.teiid.query.processor.relational.RelationalNode#clone()
+ * @since 4.2
+ */
+ public Object clone() {
+ JoinNode clonedNode = new JoinNode(super.getID());
+ super.copy(this, clonedNode);
+
+ clonedNode.joinType = this.joinType;
+ clonedNode.joinStrategy = this.joinStrategy.clone();
+
+ clonedNode.joinCriteria = this.joinCriteria;
+
+ clonedNode.leftExpressions = leftExpressions;
+
+ clonedNode.rightExpressions = rightExpressions;
+ clonedNode.dependentValueSource = this.dependentValueSource;
+ clonedNode.rightDistinct = rightDistinct;
+ clonedNode.leftDistinct = leftDistinct;
+
+ return clonedNode;
+ }
+
+ /**
+ * @see org.teiid.query.processor.relational.RelationalNode#nextBatchDirect()
+ * @since 4.2
+ */
+ protected TupleBatch nextBatchDirect() throws BlockedException,
+ TeiidComponentException,
+ TeiidProcessingException {
+ if (state == State.LOAD_LEFT) {
+ if (this.joinType != JoinType.JOIN_FULL_OUTER) {
+ this.joinStrategy.leftSource.setImplicitBuffer(ImplicitBuffer.NONE);
+ }
+ //left child was already opened by the join node
+ this.joinStrategy.loadLeft();
+ if (isDependent()) {
+ TupleBuffer buffer = this.joinStrategy.leftSource.getTupleBuffer();
+ dvs = new DependentValueSource(buffer);
+ dvs.setDistinct(this.joinStrategy.leftSource.isDistinct());
+ this.getContext().getVariableContext().setGlobalValue(this.dependentValueSource, dvs);
+ }
+ state = State.LOAD_RIGHT;
+ }
+ if (state == State.LOAD_RIGHT) {
+ this.joinStrategy.openRight();
+ this.joinStrategy.loadRight();
+ state = State.EXECUTE;
+ }
+ try {
+ this.joinStrategy.process();
+ this.terminateBatches();
+ } catch (BatchAvailableException e) {
+ //pull the batch
+ }
+ return pullBatch();
+ }
+
+ /**
+ * @see org.teiid.query.processor.relational.RelationalNode#getDescriptionProperties()
+ * @since 4.2
+ */
+ public PlanNode getDescriptionProperties() {
+ // Default implementation - should be overridden
+ PlanNode props = super.getDescriptionProperties();
+
+ if(isDependent()) {
+ props.addProperty(PROP_DEPENDENT, Boolean.TRUE.toString());
+ }
+ props.addProperty(PROP_JOIN_STRATEGY, this.joinStrategy.toString());
+ props.addProperty(PROP_JOIN_TYPE, this.joinType.toString());
+ List<String> critList = getCriteriaList();
+ props.addProperty(PROP_JOIN_CRITERIA, critList);
+ return props;
+ }
+
+ private List<String> getCriteriaList() {
+ List<String> critList = new ArrayList<String>();
+ if (leftExpressions != null) {
+ for(int i=0; i < this.leftExpressions.size(); i++) {
+ critList.add(this.leftExpressions.get(i).toString() + "=" + this.rightExpressions.get(i).toString()); //$NON-NLS-1$
+ }
+ }
+ if (this.joinCriteria != null) {
+ for (Criteria crit : (List<Criteria>)Criteria.separateCriteriaByAnd(joinCriteria)) {
+ critList.add(crit.toString());
+ }
+ }
+ return critList;
+ }
+
+ /**
+ * @see org.teiid.query.processor.relational.RelationalNode#getNodeString(java.lang.StringBuffer)
+ * @since 4.2
+ */
+ protected void getNodeString(StringBuffer str) {
+ str.append(getClassName());
+ str.append("("); //$NON-NLS-1$
+ str.append(getID());
+ str.append(") [");//$NON-NLS-1$
+ if(isDependent()) {
+ str.append("Dependent] [");//$NON-NLS-1$
+ }
+ str.append(this.joinStrategy.toString());
+ str.append("] [");//$NON-NLS-1$
+ str.append(this.joinType.toString());
+ str.append("]"); //$NON-NLS-1$
+ if (getJoinType() != JoinType.JOIN_CROSS) {
+ str.append(" criteria=").append(getCriteriaList()); //$NON-NLS-1$
+ }
+ str.append(" output="); //$NON-NLS-1$
+ str.append(getElements());
+ }
+
+ /**
+ * @return Returns the isDependent.
+ */
+ public boolean isDependent() {
+ return this.dependentValueSource != null;
+ }
+
+ /**
+ * @param isDependent The isDependent to set.
+ */
+ public void setDependentValueSource(String dependentValueSource) {
+ 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;
+ }
+
+ Map getCombinedElementMap() {
+ return this.combinedElementMap;
+ }
+
+ public Criteria getJoinCriteria() {
+ return this.joinCriteria;
+ }
+
+ boolean matchesCriteria(List outputTuple) throws BlockedException, TeiidComponentException, ExpressionEvaluationException {
+ return (this.joinCriteria == null || getEvaluator(this.combinedElementMap).evaluate(this.joinCriteria, outputTuple));
+ }
+
+ public List getLeftExpressions() {
+ return this.leftExpressions;
+ }
+
+ public List getRightExpressions() {
+ return this.rightExpressions;
+ }
+
+ @Override
+ protected void addBatchRow(List row) {
+ List projectTuple = projectTuple(this.projectionIndexes, row);
+ super.addBatchRow(projectTuple);
+ if (isBatchFull()) {
+ throw BATCH_AVILABLE;
+ }
+ }
+
+ public DependentValueSource getDependentValueSource() {
+ return dvs;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/ProjectIntoNode.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/relational/ProjectIntoNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/ProjectIntoNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,299 +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 static org.teiid.query.analysis.AnalysisRecord.*;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.teiid.client.plan.PlanNode;
-import org.teiid.common.buffer.BlockedException;
-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.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-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.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.GroupSymbol;
-
-
-public class ProjectIntoNode extends RelationalNode {
-
- public enum Mode {
- BATCH, BULK, ITERATOR, SINGLE
- }
-
- private static int REQUEST_CREATION = 1;
- private static int RESPONSE_PROCESSING = 2;
-
- // Initialization state
- private GroupSymbol intoGroup;
- private List intoElements;
- private String modelName;
- private Mode mode;
-
- // Processing state
- private int batchRow = 1;
- private int insertCount = 0;
- private int phase = REQUEST_CREATION;
- private int requestsRegistered = 0;
- private int tupleSourcesProcessed = 0;
- private boolean sourceDone;
-
- private TupleBuffer buffer;
- private TupleBatch currentBatch;
-
- private TupleSource tupleSource;
-
- protected ProjectIntoNode() {
- super();
- }
-
- public ProjectIntoNode(int nodeID) {
- super(nodeID);
- }
-
- public void reset() {
- super.reset();
- this.phase = REQUEST_CREATION;
- this.batchRow = 1;
- this.insertCount = 0;
- this.tupleSourcesProcessed = 0;
- this.requestsRegistered = 0;
- this.currentBatch=null;
- this.sourceDone=false;
- }
-
- public void setIntoGroup(GroupSymbol group) {
- this.intoGroup = group;
- }
-
- public void setIntoElements(List intoElements) {
- this.intoElements = intoElements;
- }
-
- public void setModelName(String modelName) {
- this.modelName = modelName;
- }
-
- /**
- * Get batch from child node
- * Walk through each row of child batch
- * Bind values to insertCommand
- * Execute insertCommand
- * Update insertCount
- * When no more data is available, output batch with single row containing insertCount
- */
- public TupleBatch nextBatchDirect()
- throws BlockedException, TeiidComponentException, TeiidProcessingException {
-
- while(phase == REQUEST_CREATION) {
-
- checkExitConditions();
-
- /* If we don't have a batch to work, get the next
- */
- if (currentBatch == null) {
- if (sourceDone) {
- phase = RESPONSE_PROCESSING;
- break;
- }
- currentBatch = getChildren()[0].nextBatch(); // can throw BlockedException
- sourceDone = currentBatch.getTerminationFlag();
- this.batchRow = currentBatch.getBeginRow();
-
- //normally we would want to skip a 0 sized batch, but it typically represents the terminal batch
- //and for implicit temp tables we need to issue an empty insert
- if(currentBatch.getRowCount() == 0
- && (!currentBatch.getTerminationFlag() || mode != Mode.ITERATOR)) {
- currentBatch = null;
- continue;
- }
- }
-
- int batchSize = currentBatch.getRowCount();
- int requests = 1;
- switch (mode) {
- case ITERATOR:
- if (buffer == null) {
- buffer = getBufferManager().createTupleBuffer(intoElements, getConnectionID(), TupleSourceType.PROCESSOR);
- }
- buffer.addTupleBatch(currentBatch, true);
- if (currentBatch.getTerminationFlag() && (buffer.getRowCount() != 0 || intoGroup.isImplicitTempGroupSymbol())) {
- Insert insert = new Insert(intoGroup, intoElements, null);
- buffer.close();
- insert.setTupleSource(buffer.createIndexedTupleSource(true));
- // Register insert command against source
- registerRequest(insert);
- } else {
- requests = 0;
- }
- break;
- case BULK:
- //convert to multivalued parameter
- List<Constant> parameters = new ArrayList<Constant>(intoElements.size());
- for (int i = 0; i < intoElements.size(); i++) {
- Constant value = new Constant(null, ((ElementSymbol)intoElements.get(i)).getType());
- value.setMultiValued(new ArrayList<Object>(currentBatch.getTuples().size()));
- parameters.add(value);
- }
- for (List row : currentBatch.getTuples()) {
- for (int i = 0; i < row.size(); i++) {
- ((List<Object>)parameters.get(i).getValue()).add(row.get(i));
- }
- }
- // Create a bulk insert command batching all rows in the current batch.
- Insert insert = new Insert(intoGroup, intoElements, parameters);
- // Register insert command against source
- registerRequest(insert);
- break;
- case BATCH:
- // Register batched update command against source
- int endRow = currentBatch.getEndRow();
- List rows = new ArrayList(endRow-batchRow);
- for(int rowNum = batchRow; rowNum <= endRow; rowNum++) {
-
- insert = new Insert( intoGroup,
- intoElements,
- convertValuesToConstants(currentBatch.getTuple(rowNum), intoElements));
- rows.add( insert );
- }
- registerRequest(new BatchedUpdateCommand( rows ));
- break;
- case SINGLE:
- batchSize = 1;
- // Register insert command against source
- // Defect 16036 - submit a new INSERT command to the DataManager.
- registerRequest(new Insert(intoGroup, intoElements, convertValuesToConstants(currentBatch.getTuple(batchRow), intoElements)));
- }
-
- this.batchRow += batchSize;
- if (batchRow > currentBatch.getEndRow()) {
- currentBatch = null;
- }
- this.requestsRegistered+=requests;
- }
-
- checkExitConditions();
-
- // End this node's work
- List outputRow = new ArrayList(1);
- outputRow.add(new Integer(this.insertCount));
- addBatchRow(outputRow);
- terminateBatches();
- return pullBatch();
- }
-
- private void checkExitConditions() throws TeiidComponentException, BlockedException, TeiidProcessingException {
- if (tupleSource != null) {
- Integer count = (Integer)tupleSource.nextTuple().get(0);
- insertCount += count.intValue();
- closeRequest();
- // Mark as processed
- tupleSourcesProcessed++; // This should set tupleSourcesProcessed to be the same as requestsRegistered
- }
- // RESPONSE_PROCESSING: process tuple sources
- if (tupleSourcesProcessed < requestsRegistered) {
- throw BlockedException.INSTANCE;
- }
-
- }
-
- private void registerRequest(Command command) throws TeiidComponentException, TeiidProcessingException {
- tupleSource = getDataManager().registerRequest(getContext(), command, this.modelName, null, getID(), -1);
- }
-
- private void closeRequest() {
- if (this.buffer != null) {
- this.buffer.remove();
- this.buffer = null;
- }
- if (this.tupleSource != null) {
- tupleSource.closeSource();
- this.tupleSource = null;
- }
- }
-
- protected void getNodeString(StringBuffer str) {
- super.getNodeString(str);
- str.append(intoGroup);
- }
-
- public Object clone(){
- ProjectIntoNode clonedNode = new ProjectIntoNode();
- super.copy(this, clonedNode);
-
- clonedNode.intoGroup = intoGroup;
- clonedNode.intoElements = intoElements;
- clonedNode.modelName = this.modelName;
- clonedNode.mode = this.mode;
-
- return clonedNode;
- }
-
- public PlanNode getDescriptionProperties() {
- PlanNode props = super.getDescriptionProperties();
- props.addProperty(PROP_INTO_GROUP, intoGroup.toString());
- List<String> selectCols = new ArrayList<String>(intoElements.size());
- for(int i=0; i<this.intoElements.size(); i++) {
- selectCols.add(this.intoElements.get(i).toString());
- }
- props.addProperty(PROP_SELECT_COLS, selectCols);
-
- return props;
- }
-
- private List convertValuesToConstants(List values, List elements) {
- ArrayList constants = new ArrayList(values.size());
- for(int i=0; i<elements.size(); i++) {
- ElementSymbol es = (ElementSymbol)elements.get(i);
- Class type = es.getType();
- constants.add(new Constant(values.get(i),type));
- }
- return constants;
- }
-
- public Mode getMode() {
- return mode;
- }
-
- public void setMode(Mode mode) {
- this.mode = mode;
- }
-
- public boolean isTempGroupInsert() {
- return intoGroup.isTempGroupSymbol();
- }
-
- public void closeDirect() {
- closeRequest();
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/ProjectIntoNode.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/processor/relational/ProjectIntoNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/ProjectIntoNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/ProjectIntoNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,299 @@
+/*
+ * 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 static org.teiid.query.analysis.AnalysisRecord.*;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.client.plan.PlanNode;
+import org.teiid.common.buffer.BlockedException;
+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.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+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.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.GroupSymbol;
+
+
+public class ProjectIntoNode extends RelationalNode {
+
+ public enum Mode {
+ BATCH, BULK, ITERATOR, SINGLE
+ }
+
+ private static int REQUEST_CREATION = 1;
+ private static int RESPONSE_PROCESSING = 2;
+
+ // Initialization state
+ private GroupSymbol intoGroup;
+ private List intoElements;
+ private String modelName;
+ private Mode mode;
+
+ // Processing state
+ private int batchRow = 1;
+ private int insertCount = 0;
+ private int phase = REQUEST_CREATION;
+ private int requestsRegistered = 0;
+ private int tupleSourcesProcessed = 0;
+ private boolean sourceDone;
+
+ private TupleBuffer buffer;
+ private TupleBatch currentBatch;
+
+ private TupleSource tupleSource;
+
+ protected ProjectIntoNode() {
+ super();
+ }
+
+ public ProjectIntoNode(int nodeID) {
+ super(nodeID);
+ }
+
+ public void reset() {
+ super.reset();
+ this.phase = REQUEST_CREATION;
+ this.batchRow = 1;
+ this.insertCount = 0;
+ this.tupleSourcesProcessed = 0;
+ this.requestsRegistered = 0;
+ this.currentBatch=null;
+ this.sourceDone=false;
+ }
+
+ public void setIntoGroup(GroupSymbol group) {
+ this.intoGroup = group;
+ }
+
+ public void setIntoElements(List intoElements) {
+ this.intoElements = intoElements;
+ }
+
+ public void setModelName(String modelName) {
+ this.modelName = modelName;
+ }
+
+ /**
+ * Get batch from child node
+ * Walk through each row of child batch
+ * Bind values to insertCommand
+ * Execute insertCommand
+ * Update insertCount
+ * When no more data is available, output batch with single row containing insertCount
+ */
+ public TupleBatch nextBatchDirect()
+ throws BlockedException, TeiidComponentException, TeiidProcessingException {
+
+ while(phase == REQUEST_CREATION) {
+
+ checkExitConditions();
+
+ /* If we don't have a batch to work, get the next
+ */
+ if (currentBatch == null) {
+ if (sourceDone) {
+ phase = RESPONSE_PROCESSING;
+ break;
+ }
+ currentBatch = getChildren()[0].nextBatch(); // can throw BlockedException
+ sourceDone = currentBatch.getTerminationFlag();
+ this.batchRow = currentBatch.getBeginRow();
+
+ //normally we would want to skip a 0 sized batch, but it typically represents the terminal batch
+ //and for implicit temp tables we need to issue an empty insert
+ if(currentBatch.getRowCount() == 0
+ && (!currentBatch.getTerminationFlag() || mode != Mode.ITERATOR)) {
+ currentBatch = null;
+ continue;
+ }
+ }
+
+ int batchSize = currentBatch.getRowCount();
+ int requests = 1;
+ switch (mode) {
+ case ITERATOR:
+ if (buffer == null) {
+ buffer = getBufferManager().createTupleBuffer(intoElements, getConnectionID(), TupleSourceType.PROCESSOR);
+ }
+ buffer.addTupleBatch(currentBatch, true);
+ if (currentBatch.getTerminationFlag() && (buffer.getRowCount() != 0 || intoGroup.isImplicitTempGroupSymbol())) {
+ Insert insert = new Insert(intoGroup, intoElements, null);
+ buffer.close();
+ insert.setTupleSource(buffer.createIndexedTupleSource(true));
+ // Register insert command against source
+ registerRequest(insert);
+ } else {
+ requests = 0;
+ }
+ break;
+ case BULK:
+ //convert to multivalued parameter
+ List<Constant> parameters = new ArrayList<Constant>(intoElements.size());
+ for (int i = 0; i < intoElements.size(); i++) {
+ Constant value = new Constant(null, ((ElementSymbol)intoElements.get(i)).getType());
+ value.setMultiValued(new ArrayList<Object>(currentBatch.getTuples().size()));
+ parameters.add(value);
+ }
+ for (List row : currentBatch.getTuples()) {
+ for (int i = 0; i < row.size(); i++) {
+ ((List<Object>)parameters.get(i).getValue()).add(row.get(i));
+ }
+ }
+ // Create a bulk insert command batching all rows in the current batch.
+ Insert insert = new Insert(intoGroup, intoElements, parameters);
+ // Register insert command against source
+ registerRequest(insert);
+ break;
+ case BATCH:
+ // Register batched update command against source
+ int endRow = currentBatch.getEndRow();
+ List rows = new ArrayList(endRow-batchRow);
+ for(int rowNum = batchRow; rowNum <= endRow; rowNum++) {
+
+ insert = new Insert( intoGroup,
+ intoElements,
+ convertValuesToConstants(currentBatch.getTuple(rowNum), intoElements));
+ rows.add( insert );
+ }
+ registerRequest(new BatchedUpdateCommand( rows ));
+ break;
+ case SINGLE:
+ batchSize = 1;
+ // Register insert command against source
+ // Defect 16036 - submit a new INSERT command to the DataManager.
+ registerRequest(new Insert(intoGroup, intoElements, convertValuesToConstants(currentBatch.getTuple(batchRow), intoElements)));
+ }
+
+ this.batchRow += batchSize;
+ if (batchRow > currentBatch.getEndRow()) {
+ currentBatch = null;
+ }
+ this.requestsRegistered+=requests;
+ }
+
+ checkExitConditions();
+
+ // End this node's work
+ List outputRow = new ArrayList(1);
+ outputRow.add(new Integer(this.insertCount));
+ addBatchRow(outputRow);
+ terminateBatches();
+ return pullBatch();
+ }
+
+ private void checkExitConditions() throws TeiidComponentException, BlockedException, TeiidProcessingException {
+ if (tupleSource != null) {
+ Integer count = (Integer)tupleSource.nextTuple().get(0);
+ insertCount += count.intValue();
+ closeRequest();
+ // Mark as processed
+ tupleSourcesProcessed++; // This should set tupleSourcesProcessed to be the same as requestsRegistered
+ }
+ // RESPONSE_PROCESSING: process tuple sources
+ if (tupleSourcesProcessed < requestsRegistered) {
+ throw BlockedException.block(getContext().getRequestId(), "Blocking on insert update count"); //$NON-NLS-1$
+ }
+
+ }
+
+ private void registerRequest(Command command) throws TeiidComponentException, TeiidProcessingException {
+ tupleSource = getDataManager().registerRequest(getContext(), command, this.modelName, null, getID(), -1);
+ }
+
+ private void closeRequest() {
+ if (this.buffer != null) {
+ this.buffer.remove();
+ this.buffer = null;
+ }
+ if (this.tupleSource != null) {
+ tupleSource.closeSource();
+ this.tupleSource = null;
+ }
+ }
+
+ protected void getNodeString(StringBuffer str) {
+ super.getNodeString(str);
+ str.append(intoGroup);
+ }
+
+ public Object clone(){
+ ProjectIntoNode clonedNode = new ProjectIntoNode();
+ super.copy(this, clonedNode);
+
+ clonedNode.intoGroup = intoGroup;
+ clonedNode.intoElements = intoElements;
+ clonedNode.modelName = this.modelName;
+ clonedNode.mode = this.mode;
+
+ return clonedNode;
+ }
+
+ public PlanNode getDescriptionProperties() {
+ PlanNode props = super.getDescriptionProperties();
+ props.addProperty(PROP_INTO_GROUP, intoGroup.toString());
+ List<String> selectCols = new ArrayList<String>(intoElements.size());
+ for(int i=0; i<this.intoElements.size(); i++) {
+ selectCols.add(this.intoElements.get(i).toString());
+ }
+ props.addProperty(PROP_SELECT_COLS, selectCols);
+
+ return props;
+ }
+
+ private List convertValuesToConstants(List values, List elements) {
+ ArrayList constants = new ArrayList(values.size());
+ for(int i=0; i<elements.size(); i++) {
+ ElementSymbol es = (ElementSymbol)elements.get(i);
+ Class type = es.getType();
+ constants.add(new Constant(values.get(i),type));
+ }
+ return constants;
+ }
+
+ public Mode getMode() {
+ return mode;
+ }
+
+ public void setMode(Mode mode) {
+ this.mode = mode;
+ }
+
+ public boolean isTempGroupInsert() {
+ return intoGroup.isTempGroupSymbol();
+ }
+
+ public void closeDirect() {
+ closeRequest();
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/SortNode.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/relational/SortNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/SortNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,190 +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 static org.teiid.query.analysis.AnalysisRecord.*;
-
-import java.util.List;
-
-import org.teiid.client.plan.PlanNode;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.TupleBatch;
-import org.teiid.common.buffer.TupleBuffer;
-import org.teiid.common.buffer.TupleSource;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.query.processor.BatchIterator;
-import org.teiid.query.processor.relational.SortUtility.Mode;
-import org.teiid.query.sql.lang.OrderByItem;
-
-
-public class SortNode extends RelationalNode {
-
- private List<OrderByItem> items;
- private Mode mode = Mode.SORT;
-
- private SortUtility sortUtility;
- private int phase = SORT;
- private TupleBuffer output;
- private TupleSource outputTs;
- private boolean usingOutput;
-
- private static final int SORT = 2;
- private static final int OUTPUT = 3;
-
- public SortNode(int nodeID) {
- super(nodeID);
- }
-
- public void reset() {
- super.reset();
- sortUtility = null;
- phase = SORT;
- output = null;
- outputTs = null;
- usingOutput = false;
- }
-
- public void setSortElements(List<OrderByItem> items) {
- this.items = items;
- }
-
- public List<OrderByItem> getSortElements() {
- return this.items;
- }
-
- public Mode getMode() {
- return mode;
- }
-
- public void setMode(Mode mode) {
- this.mode = mode;
- }
-
- public TupleBatch nextBatchDirect()
- throws BlockedException, TeiidComponentException, TeiidProcessingException {
- if(this.phase == SORT) {
- sortPhase();
- }
-
- return outputPhase();
- }
-
- private void sortPhase() throws BlockedException, TeiidComponentException, TeiidProcessingException {
- if (this.sortUtility == null) {
- this.sortUtility = new SortUtility(new BatchIterator(getChildren()[0]), items, this.mode, getBufferManager(),
- getConnectionID(), getChildren()[0].getElements());
- }
- this.output = this.sortUtility.sort();
- if (this.outputTs == null) {
- this.outputTs = this.output.createIndexedTupleSource();
- }
- this.phase = OUTPUT;
- }
-
- private TupleBatch outputPhase() throws BlockedException, TeiidComponentException, TeiidProcessingException {
- if (!this.output.isFinal()) {
- this.phase = SORT;
- } else if (!usingOutput) {
- this.output.setForwardOnly(true);
- }
- List<?> tuple = null;
- try {
- while ((tuple = this.outputTs.nextTuple()) != null) {
- //resize to remove unrelated columns
- addBatchRow(tuple.subList(0, this.getElements().size()));
- if (this.isBatchFull()) {
- return pullBatch();
- }
- }
- } catch (BlockedException e) {
- if (this.hasPendingRows()) {
- return this.pullBatch();
- }
- throw e;
- }
- this.terminateBatches();
- return this.pullBatch();
- }
-
- public void closeDirect() {
- if(this.output != null) {
- this.output.remove();
- this.output = null;
- }
- this.outputTs = null;
- }
-
- protected void getNodeString(StringBuffer str) {
- super.getNodeString(str);
- str.append("[").append(mode).append("] "); //$NON-NLS-1$ //$NON-NLS-2$
- if (this.mode != Mode.DUP_REMOVE) {
- str.append(this.items);
- }
- }
-
- protected void copy(SortNode source, SortNode target){
- super.copy(source, target);
- target.items = source.items;
- target.mode = source.mode;
- }
-
- public Object clone(){
- SortNode clonedNode = new SortNode(super.getID());
- this.copy(this, clonedNode);
-
- return clonedNode;
- }
-
- public PlanNode getDescriptionProperties() {
- PlanNode props = super.getDescriptionProperties();
-
- if(this.mode != Mode.DUP_REMOVE && this.items != null) {
- props.addProperty(PROP_SORT_COLS, this.items.toString());
- }
-
- props.addProperty(PROP_SORT_MODE, this.mode.toString());
-
- return props;
- }
-
- @Override
- public TupleBuffer getFinalBuffer() throws BlockedException, TeiidComponentException, TeiidProcessingException {
- if (this.output == null) {
- sortPhase();
- }
- usingOutput = true;
- TupleBuffer result = this.output;
- if (this.output.isFinal()) {
- this.output = null;
- close();
- }
- return result;
- }
-
- @Override
- public boolean hasFinalBuffer() {
- return this.getElements().size() == this.getChildren()[0].getElements().size();
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/SortNode.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/processor/relational/SortNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/SortNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/SortNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,194 @@
+/*
+ * 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 static org.teiid.query.analysis.AnalysisRecord.*;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.client.plan.PlanNode;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.TupleBatch;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.common.buffer.TupleSource;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.query.processor.BatchIterator;
+import org.teiid.query.processor.relational.SortUtility.Mode;
+import org.teiid.query.sql.lang.OrderByItem;
+
+
+public class SortNode extends RelationalNode {
+
+ private List<OrderByItem> items;
+ private Mode mode = Mode.SORT;
+
+ private SortUtility sortUtility;
+ private int phase = SORT;
+ private TupleBuffer output;
+ private TupleSource outputTs;
+ private boolean usingOutput;
+
+ private static final int SORT = 2;
+ private static final int OUTPUT = 3;
+
+ public SortNode(int nodeID) {
+ super(nodeID);
+ }
+
+ public void reset() {
+ super.reset();
+ sortUtility = null;
+ phase = SORT;
+ output = null;
+ outputTs = null;
+ usingOutput = false;
+ }
+
+ public void setSortElements(List<OrderByItem> items) {
+ this.items = items;
+ }
+
+ public List<OrderByItem> getSortElements() {
+ return this.items;
+ }
+
+ public Mode getMode() {
+ return mode;
+ }
+
+ public void setMode(Mode mode) {
+ this.mode = mode;
+ }
+
+ public TupleBatch nextBatchDirect()
+ throws BlockedException, TeiidComponentException, TeiidProcessingException {
+ if(this.phase == SORT) {
+ sortPhase();
+ }
+
+ return outputPhase();
+ }
+
+ private void sortPhase() throws BlockedException, TeiidComponentException, TeiidProcessingException {
+ if (this.sortUtility == null) {
+ this.sortUtility = new SortUtility(new BatchIterator(getChildren()[0]), items, this.mode, getBufferManager(),
+ getConnectionID(), getChildren()[0].getElements());
+ }
+ this.output = this.sortUtility.sort();
+ if (this.outputTs == null) {
+ this.outputTs = this.output.createIndexedTupleSource();
+ }
+ this.phase = OUTPUT;
+ }
+
+ private TupleBatch outputPhase() throws BlockedException, TeiidComponentException, TeiidProcessingException {
+ if (!this.output.isFinal()) {
+ this.phase = SORT;
+ } else if (!usingOutput) {
+ this.output.setForwardOnly(true);
+ }
+ List<?> tuple = null;
+ try {
+ while ((tuple = this.outputTs.nextTuple()) != null) {
+ //resize to remove unrelated columns
+ if (this.getElements().size() < tuple.size()) {
+ tuple = new ArrayList<Object>(tuple.subList(0, this.getElements().size()));
+ }
+ addBatchRow(tuple);
+ if (this.isBatchFull()) {
+ return pullBatch();
+ }
+ }
+ } catch (BlockedException e) {
+ if (this.hasPendingRows()) {
+ return this.pullBatch();
+ }
+ throw e;
+ }
+ this.terminateBatches();
+ return this.pullBatch();
+ }
+
+ public void closeDirect() {
+ if(this.output != null) {
+ this.output.remove();
+ this.output = null;
+ }
+ this.outputTs = null;
+ }
+
+ protected void getNodeString(StringBuffer str) {
+ super.getNodeString(str);
+ str.append("[").append(mode).append("] "); //$NON-NLS-1$ //$NON-NLS-2$
+ if (this.mode != Mode.DUP_REMOVE) {
+ str.append(this.items);
+ }
+ }
+
+ protected void copy(SortNode source, SortNode target){
+ super.copy(source, target);
+ target.items = source.items;
+ target.mode = source.mode;
+ }
+
+ public Object clone(){
+ SortNode clonedNode = new SortNode(super.getID());
+ this.copy(this, clonedNode);
+
+ return clonedNode;
+ }
+
+ public PlanNode getDescriptionProperties() {
+ PlanNode props = super.getDescriptionProperties();
+
+ if(this.mode != Mode.DUP_REMOVE && this.items != null) {
+ props.addProperty(PROP_SORT_COLS, this.items.toString());
+ }
+
+ props.addProperty(PROP_SORT_MODE, this.mode.toString());
+
+ return props;
+ }
+
+ @Override
+ public TupleBuffer getFinalBuffer() throws BlockedException, TeiidComponentException, TeiidProcessingException {
+ if (this.output == null) {
+ sortPhase();
+ }
+ usingOutput = true;
+ TupleBuffer result = this.output;
+ if (this.output.isFinal()) {
+ this.output = null;
+ close();
+ }
+ return result;
+ }
+
+ @Override
+ public boolean hasFinalBuffer() {
+ return this.getElements().size() == this.getChildren()[0].getElements().size();
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/UnionAllNode.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/relational/UnionAllNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/UnionAllNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,154 +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 java.util.Collections;
-
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.TupleBatch;
-import org.teiid.common.buffer.BufferManager.BufferReserveMode;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.util.CommandContext;
-
-
-public class UnionAllNode extends RelationalNode {
-
- private boolean[] sourceDone;
-
- private int outputRow = 1;
- private int reserved;
- private int schemaSize;
-
- public UnionAllNode(int nodeID) {
- super(nodeID);
- }
-
- public void reset() {
- super.reset();
-
- sourceDone = null;
- outputRow = 1;
- }
-
- @Override
- public void initialize(CommandContext context, BufferManager bufferManager,
- ProcessorDataManager dataMgr) {
- super.initialize(context, bufferManager, dataMgr);
- this.schemaSize = getBufferManager().getSchemaSize(getOutputElements());
- }
-
- public void open()
- throws TeiidComponentException, TeiidProcessingException {
-
- // Initialize done flags
- sourceDone = new boolean[getChildren().length];
- if (reserved == 0) {
- reserved = getBufferManager().reserveBuffers((getChildren().length - 1) * schemaSize, BufferReserveMode.FORCE);
- }
- // Open the children
- super.open();
- }
-
- public TupleBatch nextBatchDirect()
- throws BlockedException, TeiidComponentException, TeiidProcessingException {
-
- // Walk through all children and for each one that isn't done, try to retrieve a batch
- // When all sources are done, set the termination flag on that batch
-
- RelationalNode[] children = getChildren();
- int activeSources = 0;
- TupleBatch batch = null;
- for(int i=0; i<children.length; i++) {
- if(children[i] != null && ! sourceDone[i]) {
- activeSources++;
-
- if(batch == null) {
- try {
- batch = children[i].nextBatch();
-
- // Got a batch
- if(batch.getTerminationFlag() == true) {
- // Mark source as being done and decrement the activeSources counter
- sourceDone[i] = true;
- activeSources--;
- if (reserved > 0) {
- getBufferManager().releaseBuffers(schemaSize);
- reserved-=schemaSize;
- }
- }
- } catch(BlockedException e) {
- // no problem - try the next one
- }
- } else {
- // We already have a batch, so we know that
- // 1) we have a batch to return and
- // 2) this isn't the last active source, so we're not returning the last batch
-
- // This is sufficient to break the loop - we won't learn anything new after this
- break;
- }
- }
- }
-
- // Determine what to return
- TupleBatch outputBatch = null;
- if(batch != null) {
- // Rebuild the batch to reset the output row
- outputBatch = new TupleBatch(outputRow, batch.getTuples());
-
- // This is the last unioned batch if:
- // 1) This batch is a termination batch from the child
- // 2) No other active sources exist
- outputBatch.setTerminationFlag(batch.getTerminationFlag() == true && activeSources == 0);
-
- // Update output row for next batch
- outputRow += outputBatch.getRowCount();
-
- } else if(activeSources > 0) {
- // Didn't get a batch but there are active sources so we are blocked
- throw BlockedException.INSTANCE;
- } 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);
- outputBatch.setTerminationFlag(true);
- }
-
- return outputBatch;
- }
-
- @Override
- public void closeDirect() {
- getBufferManager().releaseBuffers(reserved);
- reserved = 0;
- }
-
- public Object clone(){
- UnionAllNode clonedNode = new UnionAllNode(super.getID());
- super.copy(this, clonedNode);
- return clonedNode;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/UnionAllNode.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/processor/relational/UnionAllNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/UnionAllNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/relational/UnionAllNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,154 @@
+/*
+ * 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.Collections;
+
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.TupleBatch;
+import org.teiid.common.buffer.BufferManager.BufferReserveMode;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.util.CommandContext;
+
+
+public class UnionAllNode extends RelationalNode {
+
+ private boolean[] sourceDone;
+
+ private int outputRow = 1;
+ private int reserved;
+ private int schemaSize;
+
+ public UnionAllNode(int nodeID) {
+ super(nodeID);
+ }
+
+ public void reset() {
+ super.reset();
+
+ sourceDone = null;
+ outputRow = 1;
+ }
+
+ @Override
+ public void initialize(CommandContext context, BufferManager bufferManager,
+ ProcessorDataManager dataMgr) {
+ super.initialize(context, bufferManager, dataMgr);
+ this.schemaSize = getBufferManager().getSchemaSize(getOutputElements());
+ }
+
+ public void open()
+ throws TeiidComponentException, TeiidProcessingException {
+
+ // Initialize done flags
+ sourceDone = new boolean[getChildren().length];
+ if (reserved == 0) {
+ reserved = getBufferManager().reserveBuffers((getChildren().length - 1) * schemaSize, BufferReserveMode.FORCE);
+ }
+ // Open the children
+ super.open();
+ }
+
+ public TupleBatch nextBatchDirect()
+ throws BlockedException, TeiidComponentException, TeiidProcessingException {
+
+ // Walk through all children and for each one that isn't done, try to retrieve a batch
+ // When all sources are done, set the termination flag on that batch
+
+ RelationalNode[] children = getChildren();
+ int activeSources = 0;
+ TupleBatch batch = null;
+ for(int i=0; i<children.length; i++) {
+ if(children[i] != null && ! sourceDone[i]) {
+ activeSources++;
+
+ if(batch == null) {
+ try {
+ batch = children[i].nextBatch();
+
+ // Got a batch
+ if(batch.getTerminationFlag() == true) {
+ // Mark source as being done and decrement the activeSources counter
+ sourceDone[i] = true;
+ activeSources--;
+ if (reserved > 0) {
+ getBufferManager().releaseBuffers(schemaSize);
+ reserved-=schemaSize;
+ }
+ }
+ } catch(BlockedException e) {
+ // no problem - try the next one
+ }
+ } else {
+ // We already have a batch, so we know that
+ // 1) we have a batch to return and
+ // 2) this isn't the last active source, so we're not returning the last batch
+
+ // This is sufficient to break the loop - we won't learn anything new after this
+ break;
+ }
+ }
+ }
+
+ // Determine what to return
+ TupleBatch outputBatch = null;
+ if(batch != null) {
+ // Rebuild the batch to reset the output row
+ outputBatch = new TupleBatch(outputRow, batch.getTuples());
+
+ // This is the last unioned batch if:
+ // 1) This batch is a termination batch from the child
+ // 2) No other active sources exist
+ outputBatch.setTerminationFlag(batch.getTerminationFlag() == true && activeSources == 0);
+
+ // Update output row for next batch
+ outputRow += outputBatch.getRowCount();
+
+ } else if(activeSources > 0) {
+ // Didn't get a batch but there are active sources so we are blocked
+ 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);
+ outputBatch.setTerminationFlag(true);
+ }
+
+ return outputBatch;
+ }
+
+ @Override
+ public void closeDirect() {
+ getBufferManager().releaseBuffers(reserved);
+ reserved = 0;
+ }
+
+ public Object clone(){
+ UnionAllNode clonedNode = new UnionAllNode(super.getID());
+ super.copy(this, clonedNode);
+ return clonedNode;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/xml/JoinedWhileInstruction.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/xml/JoinedWhileInstruction.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/xml/JoinedWhileInstruction.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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$
- }
-}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/xml/XMLContext.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/xml/XMLContext.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/xml/XMLContext.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,197 +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.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.util.VariableContext;
-
-
-
-/**
- * A XML context is an object which is passed between all the xml processing instructions.
- * context will have all the information possible for the block instructions to execute. It will
- * also have access to the parent context, however it will not have information on the sibiling
- * blocks.
- */
-class XMLContext {
-
- // map between variables and their values
- Map resultsMap = new HashMap();
-
- // reference to the parent variable context
- XMLContext parentContext;
-
- Map executorMap = new HashMap();
-
- VariableContext variableContext = new VariableContext();
-
- /**
- * 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);
- }
-
- public XMLContext getParentContext() {
- return this.parentContext;
- }
-
- /**
- * Get the current row of the given result set
- * @param aliasResultName
- * @return
- */
- public List getCurrentRow(String aliasResultName) throws TeiidComponentException, TeiidProcessingException {
- PlanExecutor executor = (PlanExecutor)this.resultsMap.get(aliasResultName);
- if (executor == null) {
- if (this.parentContext != null) {
- return this.parentContext.getCurrentRow(aliasResultName);
- }
- throw new TeiidComponentException(QueryPlugin.Util.getString("results_not_found", aliasResultName)); //$NON-NLS-1$
- }
- return executor.currentRow();
- }
-
- /**
- * Get the next row from the result set given.
- * @param aliasResultName
- * @return
- * @throws TeiidComponentException
- */
- public List getNextRow(String aliasResultName) throws TeiidComponentException, TeiidProcessingException {
- PlanExecutor executor = (PlanExecutor)this.resultsMap.get(aliasResultName);
- if (executor == null) {
- if (this.parentContext != null) {
- return this.parentContext.getNextRow(aliasResultName);
- }
- throw new TeiidComponentException(QueryPlugin.Util.getString("results_not_found", aliasResultName)); //$NON-NLS-1$
- }
- return executor.nextRow();
- }
-
- /**
- * Register the Result Set with the current context
- * @param resultName
- * @param id
- */
- public void setResultSet(String resultName, PlanExecutor executor) {
- this.resultsMap.put(resultName, executor);
- }
-
- /**
- * Be sure that when removing the results, we do not walk into the parent context
- * 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);
- if (executor != null) {
- executor.close();
- }
- }
-
- /**
- * Get the schema elements for the resultset. (note that the alias names only apply to results
- * not any thing else)
- * @param resultName
- * @return
- * @throws TeiidComponentException
- */
- public List getOutputElements(String resultName) throws TeiidComponentException {
- PlanExecutor executor = (PlanExecutor)this.resultsMap.get(resultName);
- if (executor == null) {
- if (this.parentContext != null) {
- return this.parentContext.getOutputElements(resultName);
- }
- throw new TeiidComponentException(QueryPlugin.Util.getString("results_not_found", resultName)); //$NON-NLS-1$
- }
- return executor.getOutputElements();
- }
-
-
- /**
- * This will return element map containing the current row of all the parent resultset objects.
- * @return
- */
- public Map getReferenceValues() {
- HashMap map = new HashMap();
- variableContext.getFlattenedContextMap(map);
- return map;
- }
-
- /**
- * Get a registered plan executor object for the result
- * @param resultName
- * @return
- */
- public PlanExecutor getResultExecutor(String resultName) {
- return (PlanExecutor)this.executorMap.get(resultName);
- }
-
- /**
- * Set a registered plan executor object for the result
- * @param resultName
- * @param executor
- */
- public void setResultExecutor(String resultName, PlanExecutor executor) {
- this.executorMap.put(resultName, executor);
- }
-
- /**
- * Remove registered plan executor object for the result
- * @param resultName
- */
- public void removeResultExecutor(String resultName) {
- this.executorMap.remove(resultName);
- }
-
- public VariableContext getVariableContext() {
- return variableContext;
- }
-
-
- void setVariableValues(String resultSetName,
- List row) throws TeiidComponentException {
- List elements = getOutputElements(resultSetName);
-
- for (int index = 0; index < elements.size(); index++) {
- ElementSymbol symbol = (ElementSymbol)elements.get(index);
- variableContext.setValue(new ElementSymbol(resultSetName + ElementSymbol.SEPARATOR + symbol.getShortName()), row.get(index));
- }
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/xml/XMLContext.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/processor/xml/XMLContext.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/xml/XMLContext.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/processor/xml/XMLContext.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,198 @@
+/*
+ * 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.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.util.VariableContext;
+
+
+
+/**
+ * A XML context is an object which is passed between all the xml processing instructions.
+ * context will have all the information possible for the block instructions to execute. It will
+ * also have access to the parent context, however it will not have information on the sibiling
+ * blocks.
+ */
+class XMLContext {
+
+ // map between variables and their values
+ Map<String, PlanExecutor> resultsMap = new HashMap<String, PlanExecutor>();
+
+ // reference to the parent variable context
+ XMLContext parentContext;
+
+ Map<String, PlanExecutor> executorMap = new HashMap<String, PlanExecutor>();
+
+ VariableContext variableContext = new VariableContext();
+
+ /**
+ * Constructor for VariableContext.
+ */
+ public XMLContext() {
+ }
+
+ /**
+ * Constructor for VariableContext.
+ */
+ public XMLContext(XMLContext parent) {
+ this.parentContext = parent;
+ this.variableContext.setParentContext(parent.variableContext);
+ }
+
+ public XMLContext getParentContext() {
+ return this.parentContext;
+ }
+
+ /**
+ * Get the current row of the given result set
+ * @param aliasResultName
+ * @return
+ */
+ 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);
+ }
+ throw new TeiidComponentException(QueryPlugin.Util.getString("results_not_found", aliasResultName)); //$NON-NLS-1$
+ }
+ return executor.currentRow();
+ }
+
+ /**
+ * Get the next row from the result set given.
+ * @param aliasResultName
+ * @return
+ * @throws TeiidComponentException
+ */
+ 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);
+ }
+ throw new TeiidComponentException(QueryPlugin.Util.getString("results_not_found", aliasResultName)); //$NON-NLS-1$
+ }
+ return executor.nextRow();
+ }
+
+ /**
+ * Register the Result Set with the current context
+ * @param resultName
+ * @param id
+ */
+ public void setResultSet(String resultName, PlanExecutor executor) {
+ this.resultsMap.put(resultName, executor);
+ }
+
+ /**
+ * Be sure that when removing the results, we do not walk into the parent context
+ * as there may be another resultset with same name. (recursive condition)
+ */
+ public void removeResultSet(String resultName) throws TeiidComponentException {
+ PlanExecutor executor = this.resultsMap.remove(resultName);
+ if (executor != null) {
+ executor.close();
+ }
+ }
+
+ /**
+ * Get the schema elements for the resultset. (note that the alias names only apply to results
+ * not any thing else)
+ * @param resultName
+ * @return
+ * @throws TeiidComponentException
+ */
+ 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);
+ }
+ throw new TeiidComponentException(QueryPlugin.Util.getString("results_not_found", resultName)); //$NON-NLS-1$
+ }
+ return executor.getOutputElements();
+ }
+
+
+ /**
+ * This will return element map containing the current row of all the parent resultset objects.
+ * @return
+ */
+ public Map getReferenceValues() {
+ HashMap map = new HashMap();
+ variableContext.getFlattenedContextMap(map);
+ return map;
+ }
+
+ /**
+ * Get a registered plan executor object for the result
+ * @param resultName
+ * @return
+ */
+ public PlanExecutor getResultExecutor(String resultName) {
+ return this.executorMap.get(resultName);
+ }
+
+ /**
+ * Set a registered plan executor object for the result
+ * @param resultName
+ * @param executor
+ */
+ public void setResultExecutor(String resultName, PlanExecutor executor) {
+ this.executorMap.put(resultName, executor);
+ }
+
+ /**
+ * Remove registered plan executor object for the result
+ * @param resultName
+ */
+ public void removeResultExecutor(String resultName) {
+ this.executorMap.remove(resultName);
+ }
+
+ public VariableContext getVariableContext() {
+ return variableContext;
+ }
+
+
+ void setVariableValues(String resultSetName,
+ 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));
+ }
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/InsertResolver.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/resolver/command/InsertResolver.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/InsertResolver.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,292 +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.resolver.command;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-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.QueryResolverException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.Assertion;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.resolver.ProcedureContainerResolver;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.resolver.VariableResolver;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.resolver.util.ResolverVisitor;
-import org.teiid.query.sql.ProcedureReservedWords;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.GroupContext;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.ProcedureContainer;
-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.GroupSymbol;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-
-
-/**
- * This class knows how to expand and resolve INSERT commands.
- */
-public class InsertResolver extends ProcedureContainerResolver implements VariableResolver {
-
- /**
- * Resolve an INSERT. Need to resolve elements, constants, types, etc.
- * @see org.teiid.query.resolver.ProcedureContainerResolver#resolveProceduralCommand(org.teiid.query.sql.lang.Command, org.teiid.query.metadata.TempMetadataAdapter)
- */
- public void resolveProceduralCommand(Command command, TempMetadataAdapter metadata)
- throws QueryMetadataException, QueryResolverException, TeiidComponentException {
-
- // Cast to known type
- Insert insert = (Insert) command;
-
- if (insert.getValues() != null) {
- QueryResolver.resolveSubqueries(command, metadata, null);
- //variables and values must be resolved separately to account for implicitly defined temp groups
- resolveList(insert.getValues(), metadata, insert.getExternalGroupContexts(), null);
- }
- //resolve subquery if there
- if(insert.getQueryExpression() != null) {
- QueryResolver.setChildMetadata(insert.getQueryExpression(), command);
-
- QueryResolver.resolveCommand(insert.getQueryExpression(), metadata.getMetadata(), false);
- }
-
- Set<GroupSymbol> groups = new HashSet<GroupSymbol>();
- groups.add(insert.getGroup());
-
- // resolve any functions in the values
- List values = insert.getValues();
- boolean usingQuery = insert.getQueryExpression() != null;
-
- if (usingQuery) {
- values = insert.getQueryExpression().getProjectedSymbols();
- }
-
- 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());
- }
- } else {
- for (int i = 0; i < values.size(); i++) {
- if (usingQuery) {
- SingleElementSymbol ses = (SingleElementSymbol)values.get(i);
- ElementSymbol es = new ElementSymbol(ses.getShortName());
- es.setType(ses.getType());
- insert.addVariable(es);
- } else {
- insert.addVariable(new ElementSymbol("expr" + i)); //$NON-NLS-1$
- }
- }
- }
- } else if (insert.getGroup().isResolved()) {
- resolveVariables(metadata, insert, groups);
- }
-
- resolveTypes(insert, metadata, values, usingQuery);
-
- if (!insert.getGroup().isResolved()) { //define the implicit temp group
- if(insert.getQueryExpression() != null) {
- ResolverUtil.resolveImplicitTempGroup(metadata, insert.getGroup(), insert.getQueryExpression().getProjectedSymbols());
- }else {
- ResolverUtil.resolveImplicitTempGroup(metadata, insert.getGroup(), insert.getVariables());
- }
- resolveVariables(metadata, insert, groups);
-
- //ensure that the types match
- resolveTypes(insert, metadata, values, usingQuery);
- }
-
- if (insert.getQueryExpression() != null && metadata.isVirtualGroup(insert.getGroup().getMetadataID())) {
- 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());
- references.add(ref);
- }
- insert.setValues(references);
- }
- }
-
- private void resolveVariables(TempMetadataAdapter metadata,
- Insert insert,
- Set<GroupSymbol> groups) throws TeiidComponentException,
- QueryResolverException {
- try {
- resolveList(insert.getVariables(), metadata, null, groups);
- } catch (QueryResolverException e) {
- throw new QueryResolverException(e, QueryPlugin.Util.getString("ERR.015.012.0054", insert.getGroup(), e.getUnresolvedSymbols())); //$NON-NLS-1$
- }
- }
-
- private void resolveList(Collection elements, TempMetadataAdapter metadata,
- GroupContext externalGroups, Set<GroupSymbol> groups) throws TeiidComponentException,
- QueryResolverException {
- for (Iterator i = elements.iterator(); i.hasNext();) {
- Expression expr = (Expression)i.next();
- ResolverVisitor.resolveLanguageObject(expr, groups, externalGroups, metadata);
- }
- }
-
- /**
- * @param insert
- * @param values
- * @param usingQuery
- * @throws QueryResolverException
- */
- public void resolveTypes(Insert insert, TempMetadataAdapter metadata, List values, boolean usingQuery) throws QueryResolverException {
-
- List newValues = new ArrayList(values.size());
-
- // check that # of variables == # of values
- if(values.size() != insert.getVariables().size()) {
- throw new QueryResolverException("ERR.015.008.0010", QueryPlugin.Util.getString("ERR.015.008.0010", insert.getVariables().size(), values.size())); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- Iterator valueIter = values.iterator();
- Iterator 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();
-
- if (!usingQuery) {
- ResolverUtil.setDesiredType(expression, element.getType(), insert);
- }
-
- if(element.getType() != null && expression.getType() != null) {
- String elementTypeName = DataTypeManager.getDataTypeName(element.getType());
- if (!usingQuery) {
- newValues.add(ResolverUtil.convertExpression(expression, elementTypeName, metadata));
- } else if (element.getType() != expression.getType()
- && !DataTypeManager.isImplicitConversion(DataTypeManager.getDataTypeName(expression.getType()),
- DataTypeManager.getDataTypeName(element.getType()))) {
- //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) {
- element.setType(expression.getType());
- newValues.add(expression);
- } else {
- Assertion.failed("Cannot determine element or expression type"); //$NON-NLS-1$
- }
- }
-
- if (!usingQuery) {
- insert.setValues(newValues);
- }
- }
-
- /**
- * @param metadata
- * @param group
- * @return
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- */
- protected String getPlan(QueryMetadataInterface metadata,
- GroupSymbol group) throws TeiidComponentException,
- QueryMetadataException {
- return metadata.getInsertPlan(group.getMetadataID());
- }
-
- /**
- * @see org.teiid.query.resolver.ProcedureContainerResolver#resolveGroup(org.teiid.query.metadata.TempMetadataAdapter, org.teiid.query.sql.lang.ProcedureContainer)
- */
- protected void resolveGroup(TempMetadataAdapter metadata,
- ProcedureContainer procCommand) throws TeiidComponentException,
- QueryResolverException {
- if (!procCommand.getGroup().isImplicitTempGroupSymbol() || metadata.getMetadataStore().getTempGroupID(procCommand.getGroup().getName()) != null) {
- super.resolveGroup(metadata, procCommand);
- }
- }
-
- /**
- * @throws TeiidComponentException
- * @throws QueryResolverException
- * @throws QueryMetadataException
- * @see org.teiid.query.resolver.CommandResolver#getVariableValues(org.teiid.query.sql.lang.Command, org.teiid.query.metadata.QueryMetadataInterface)
- */
- public Map<ElementSymbol, Expression> getVariableValues(Command command, boolean changingOnly,
- QueryMetadataInterface metadata) throws QueryMetadataException, QueryResolverException, TeiidComponentException {
-
- Insert insert = (Insert) command;
-
- Map<ElementSymbol, Expression> result = new HashMap<ElementSymbol, Expression>();
-
- // iterate over the variables and values they should be the same number
- Iterator<ElementSymbol> varIter = insert.getVariables().iterator();
- Iterator valIter = null;
- if (insert.getQueryExpression() != null) {
- valIter = insert.getQueryExpression().getProjectedSymbols().iterator();
- } else {
- valIter = insert.getValues().iterator();
- }
- while (varIter.hasNext()) {
- ElementSymbol varSymbol = varIter.next().clone();
-
- varSymbol.getGroupSymbol().setName(ProcedureReservedWords.CHANGING);
- result.put(varSymbol, new Constant(Boolean.TRUE));
- if (!changingOnly) {
- varSymbol = varSymbol.clone();
- varSymbol.getGroupSymbol().setName(ProcedureReservedWords.INPUTS);
- result.put(varSymbol, (Expression)valIter.next());
- }
- }
-
- Collection<ElementSymbol> insertElmnts = ResolverUtil.resolveElementsInGroup(insert.getGroup(), metadata);
-
- insertElmnts.removeAll(insert.getVariables());
-
- Iterator<ElementSymbol> defaultIter = insertElmnts.iterator();
- while(defaultIter.hasNext()) {
- ElementSymbol varSymbol = defaultIter.next().clone();
- varSymbol.getGroupSymbol().setName(ProcedureReservedWords.CHANGING);
- result.put(varSymbol, new Constant(Boolean.FALSE));
-
- if (!changingOnly) {
- Expression value = ResolverUtil.getDefault(varSymbol, metadata);
- varSymbol = varSymbol.clone();
- varSymbol.getGroupSymbol().setName(ProcedureReservedWords.INPUTS);
- result.put(varSymbol, value);
- }
- }
-
- return result;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/InsertResolver.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/resolver/command/InsertResolver.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/InsertResolver.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/InsertResolver.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,292 @@
+/*
+ * 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.resolver.command;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+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.QueryResolverException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.Assertion;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.resolver.ProcedureContainerResolver;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.resolver.VariableResolver;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.resolver.util.ResolverVisitor;
+import org.teiid.query.sql.ProcedureReservedWords;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.GroupContext;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.ProcedureContainer;
+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.GroupSymbol;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+
+
+/**
+ * This class knows how to expand and resolve INSERT commands.
+ */
+public class InsertResolver extends ProcedureContainerResolver implements VariableResolver {
+
+ /**
+ * Resolve an INSERT. Need to resolve elements, constants, types, etc.
+ * @see org.teiid.query.resolver.ProcedureContainerResolver#resolveProceduralCommand(org.teiid.query.sql.lang.Command, org.teiid.query.metadata.TempMetadataAdapter)
+ */
+ public void resolveProceduralCommand(Command command, TempMetadataAdapter metadata)
+ throws QueryMetadataException, QueryResolverException, TeiidComponentException {
+
+ // Cast to known type
+ Insert insert = (Insert) command;
+
+ if (insert.getValues() != null) {
+ QueryResolver.resolveSubqueries(command, metadata, null);
+ //variables and values must be resolved separately to account for implicitly defined temp groups
+ resolveList(insert.getValues(), metadata, insert.getExternalGroupContexts(), null);
+ }
+ //resolve subquery if there
+ if(insert.getQueryExpression() != null) {
+ QueryResolver.setChildMetadata(insert.getQueryExpression(), command);
+
+ QueryResolver.resolveCommand(insert.getQueryExpression(), metadata.getMetadata(), false);
+ }
+
+ Set<GroupSymbol> groups = new HashSet<GroupSymbol>();
+ groups.add(insert.getGroup());
+
+ // resolve any functions in the values
+ List values = insert.getValues();
+ boolean usingQuery = insert.getQueryExpression() != null;
+
+ if (usingQuery) {
+ values = insert.getQueryExpression().getProjectedSymbols();
+ }
+
+ 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());
+ }
+ } else {
+ for (int i = 0; i < values.size(); i++) {
+ if (usingQuery) {
+ SingleElementSymbol ses = (SingleElementSymbol)values.get(i);
+ ElementSymbol es = new ElementSymbol(ses.getShortName());
+ es.setType(ses.getType());
+ insert.addVariable(es);
+ } else {
+ insert.addVariable(new ElementSymbol("expr" + i)); //$NON-NLS-1$
+ }
+ }
+ }
+ } else if (insert.getGroup().isResolved()) {
+ resolveVariables(metadata, insert, groups);
+ }
+
+ resolveTypes(insert, metadata, values, usingQuery);
+
+ if (!insert.getGroup().isResolved()) { //define the implicit temp group
+ if(insert.getQueryExpression() != null) {
+ ResolverUtil.resolveImplicitTempGroup(metadata, insert.getGroup(), insert.getQueryExpression().getProjectedSymbols());
+ }else {
+ ResolverUtil.resolveImplicitTempGroup(metadata, insert.getGroup(), insert.getVariables());
+ }
+ resolveVariables(metadata, insert, groups);
+
+ //ensure that the types match
+ resolveTypes(insert, metadata, values, usingQuery);
+ }
+
+ if (insert.getQueryExpression() != null && metadata.isVirtualGroup(insert.getGroup().getMetadataID())) {
+ 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(insert.getVariables().get(i).getType());
+ references.add(ref);
+ }
+ insert.setValues(references);
+ }
+ }
+
+ private void resolveVariables(TempMetadataAdapter metadata,
+ Insert insert,
+ Set<GroupSymbol> groups) throws TeiidComponentException,
+ QueryResolverException {
+ try {
+ resolveList(insert.getVariables(), metadata, null, groups);
+ } catch (QueryResolverException e) {
+ throw new QueryResolverException(e, QueryPlugin.Util.getString("ERR.015.012.0054", insert.getGroup(), e.getUnresolvedSymbols())); //$NON-NLS-1$
+ }
+ }
+
+ private void resolveList(Collection elements, TempMetadataAdapter metadata,
+ GroupContext externalGroups, Set<GroupSymbol> groups) throws TeiidComponentException,
+ QueryResolverException {
+ for (Iterator i = elements.iterator(); i.hasNext();) {
+ Expression expr = (Expression)i.next();
+ ResolverVisitor.resolveLanguageObject(expr, groups, externalGroups, metadata);
+ }
+ }
+
+ /**
+ * @param insert
+ * @param values
+ * @param usingQuery
+ * @throws QueryResolverException
+ */
+ public void resolveTypes(Insert insert, TempMetadataAdapter metadata, List values, boolean usingQuery) throws QueryResolverException {
+
+ List newValues = new ArrayList(values.size());
+
+ // check that # of variables == # of values
+ if(values.size() != insert.getVariables().size()) {
+ throw new QueryResolverException("ERR.015.008.0010", QueryPlugin.Util.getString("ERR.015.008.0010", insert.getVariables().size(), values.size())); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ Iterator valueIter = values.iterator();
+ Iterator 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();
+
+ if (!usingQuery) {
+ ResolverUtil.setDesiredType(expression, element.getType(), insert);
+ }
+
+ if(element.getType() != null && expression.getType() != null) {
+ String elementTypeName = DataTypeManager.getDataTypeName(element.getType());
+ if (!usingQuery) {
+ newValues.add(ResolverUtil.convertExpression(expression, elementTypeName, metadata));
+ } else if (element.getType() != expression.getType()
+ && !DataTypeManager.isImplicitConversion(DataTypeManager.getDataTypeName(expression.getType()),
+ DataTypeManager.getDataTypeName(element.getType()))) {
+ //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) {
+ element.setType(expression.getType());
+ newValues.add(expression);
+ } else {
+ Assertion.failed("Cannot determine element or expression type"); //$NON-NLS-1$
+ }
+ }
+
+ if (!usingQuery) {
+ insert.setValues(newValues);
+ }
+ }
+
+ /**
+ * @param metadata
+ * @param group
+ * @return
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ */
+ protected String getPlan(QueryMetadataInterface metadata,
+ GroupSymbol group) throws TeiidComponentException,
+ QueryMetadataException {
+ return metadata.getInsertPlan(group.getMetadataID());
+ }
+
+ /**
+ * @see org.teiid.query.resolver.ProcedureContainerResolver#resolveGroup(org.teiid.query.metadata.TempMetadataAdapter, org.teiid.query.sql.lang.ProcedureContainer)
+ */
+ protected void resolveGroup(TempMetadataAdapter metadata,
+ ProcedureContainer procCommand) throws TeiidComponentException,
+ QueryResolverException {
+ if (!procCommand.getGroup().isImplicitTempGroupSymbol() || metadata.getMetadataStore().getTempGroupID(procCommand.getGroup().getName()) != null) {
+ super.resolveGroup(metadata, procCommand);
+ }
+ }
+
+ /**
+ * @throws TeiidComponentException
+ * @throws QueryResolverException
+ * @throws QueryMetadataException
+ * @see org.teiid.query.resolver.CommandResolver#getVariableValues(org.teiid.query.sql.lang.Command, org.teiid.query.metadata.QueryMetadataInterface)
+ */
+ public Map<ElementSymbol, Expression> getVariableValues(Command command, boolean changingOnly,
+ QueryMetadataInterface metadata) throws QueryMetadataException, QueryResolverException, TeiidComponentException {
+
+ Insert insert = (Insert) command;
+
+ Map<ElementSymbol, Expression> result = new HashMap<ElementSymbol, Expression>();
+
+ // iterate over the variables and values they should be the same number
+ Iterator<ElementSymbol> varIter = insert.getVariables().iterator();
+ Iterator valIter = null;
+ if (insert.getQueryExpression() != null) {
+ valIter = insert.getQueryExpression().getProjectedSymbols().iterator();
+ } else {
+ valIter = insert.getValues().iterator();
+ }
+ while (varIter.hasNext()) {
+ ElementSymbol varSymbol = varIter.next().clone();
+
+ varSymbol.getGroupSymbol().setName(ProcedureReservedWords.CHANGING);
+ result.put(varSymbol, new Constant(Boolean.TRUE));
+ if (!changingOnly) {
+ varSymbol = varSymbol.clone();
+ varSymbol.getGroupSymbol().setName(ProcedureReservedWords.INPUTS);
+ result.put(varSymbol, (Expression)valIter.next());
+ }
+ }
+
+ Collection<ElementSymbol> insertElmnts = ResolverUtil.resolveElementsInGroup(insert.getGroup(), metadata);
+
+ insertElmnts.removeAll(insert.getVariables());
+
+ Iterator<ElementSymbol> defaultIter = insertElmnts.iterator();
+ while(defaultIter.hasNext()) {
+ ElementSymbol varSymbol = defaultIter.next().clone();
+ varSymbol.getGroupSymbol().setName(ProcedureReservedWords.CHANGING);
+ result.put(varSymbol, new Constant(Boolean.FALSE));
+
+ if (!changingOnly) {
+ Expression value = ResolverUtil.getDefault(varSymbol, metadata);
+ varSymbol = varSymbol.clone();
+ varSymbol.getGroupSymbol().setName(ProcedureReservedWords.INPUTS);
+ result.put(varSymbol, value);
+ }
+ }
+
+ return result;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/SimpleQueryResolver.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/resolver/command/SimpleQueryResolver.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/SimpleQueryResolver.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,595 +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.resolver.command;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-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.QueryResolverException;
-import org.teiid.api.exception.query.UnresolvedSymbolDescription;
-import org.teiid.client.metadata.ParameterInfo;
-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.QueryPlugin;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.StoredProcedureInfo;
-import org.teiid.query.metadata.SupportConstants;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.metadata.TempMetadataID;
-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.ArrayTable;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.From;
-import org.teiid.query.sql.lang.FromClause;
-import org.teiid.query.sql.lang.Into;
-import org.teiid.query.sql.lang.JoinPredicate;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.SubqueryCompareCriteria;
-import org.teiid.query.sql.lang.SubqueryContainer;
-import org.teiid.query.sql.lang.SubqueryFromClause;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.lang.TableFunctionReference;
-import org.teiid.query.sql.lang.TextTable;
-import org.teiid.query.sql.lang.UnaryFromClause;
-import org.teiid.query.sql.lang.WithQueryCommand;
-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.Reference;
-import org.teiid.query.sql.symbol.ScalarSubquery;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-
-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)
- */
- public void resolveCommand(Command command, TempMetadataAdapter metadata, boolean resolveNullLiterals)
- throws QueryMetadataException, QueryResolverException, TeiidComponentException {
-
- Query query = (Query) command;
-
- resolveWith(metadata, query);
-
- try {
- QueryResolverVisitor qrv = new QueryResolverVisitor(query, metadata);
- qrv.visit(query);
- ResolverVisitor visitor = (ResolverVisitor)qrv.getVisitor();
- visitor.throwException(true);
- } catch (TeiidRuntimeException e) {
- if (e.getChild() instanceof QueryMetadataException) {
- throw (QueryMetadataException)e.getChild();
- }
- if (e.getChild() instanceof QueryResolverException) {
- throw (QueryResolverException)e.getChild();
- }
- if (e.getChild() instanceof TeiidComponentException) {
- throw (TeiidComponentException)e.getChild();
- }
- throw e;
- }
-
- if (query.getLimit() != null) {
- ResolverUtil.resolveLimit(query.getLimit());
- }
-
- if (query.getOrderBy() != null) {
- ResolverUtil.resolveOrderBy(query.getOrderBy(), query, metadata);
- }
-
- List symbols = query.getSelect().getProjectedSymbols();
-
- if (query.getInto() != null) {
- GroupSymbol symbol = query.getInto().getGroup();
- ResolverUtil.resolveImplicitTempGroup(metadata, symbol, symbols);
- } else if (resolveNullLiterals) {
- ResolverUtil.resolveNullLiterals(symbols);
- }
- }
-
- static void resolveWith(TempMetadataAdapter metadata,
- QueryCommand query) throws QueryResolverException, TeiidComponentException {
- if (query.getWith() == null) {
- return;
- }
- LinkedHashSet<GroupSymbol> discoveredGroups = new LinkedHashSet<GroupSymbol>();
- for (WithQueryCommand obj : query.getWith()) {
- QueryCommand queryExpression = obj.getCommand();
-
- QueryResolver.setChildMetadata(queryExpression, query);
-
- QueryResolver.resolveCommand(queryExpression, metadata.getMetadata(), false);
-
- if (!discoveredGroups.add(obj.getGroupSymbol())) {
- throw new QueryResolverException(QueryPlugin.Util.getString("SimpleQueryResolver.duplicate_with", obj.getGroupSymbol())); //$NON-NLS-1$
- }
- List<? extends SingleElementSymbol> projectedSymbols = obj.getCommand().getProjectedSymbols();
- if (obj.getColumns() != null && !obj.getColumns().isEmpty()) {
- if (obj.getColumns().size() != projectedSymbols.size()) {
- throw new QueryResolverException(QueryPlugin.Util.getString("SimpleQueryResolver.mismatched_with_columns", obj.getGroupSymbol())); //$NON-NLS-1$
- }
- Iterator<ElementSymbol> iter = obj.getColumns().iterator();
- for (SingleElementSymbol singleElementSymbol : projectedSymbols) {
- ElementSymbol es = iter.next();
- es.setType(singleElementSymbol.getType());
- }
- projectedSymbols = obj.getColumns();
- }
- TempMetadataID id = ResolverUtil.addTempGroup(metadata, obj.getGroupSymbol(), projectedSymbols, true);
- obj.getGroupSymbol().setMetadataID(metadata.getMetadataStore().getTempGroupID(obj.getGroupSymbol().getName()));
- obj.getGroupSymbol().setIsTempTable(true);
- List<GroupSymbol> groups = Collections.singletonList(obj.getGroupSymbol());
- if (obj.getColumns() != null && !obj.getColumns().isEmpty()) {
- for (SingleElementSymbol singleElementSymbol : projectedSymbols) {
- ResolverVisitor.resolveLanguageObject(singleElementSymbol, groups, metadata);
- }
- }
- if (obj.getColumns() != null && !obj.getColumns().isEmpty()) {
- Iterator<ElementSymbol> iter = obj.getColumns().iterator();
- for (TempMetadataID colid : id.getElements()) {
- ElementSymbol es = iter.next();
- es.setMetadataID(colid);
- es.setGroupSymbol(obj.getGroupSymbol());
- }
- }
- }
- }
-
- 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);
- 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;
- }
-
- return groupSymbols.get(0);
- }
-
- public static class QueryResolverVisitor extends PostOrderNavigator {
-
- private LinkedHashSet<GroupSymbol> currentGroups = new LinkedHashSet<GroupSymbol>();
- private LinkedList<GroupSymbol> discoveredGroups = new LinkedList<GroupSymbol>();
- private List<GroupSymbol> implicitGroups = new LinkedList<GroupSymbol>();
- private TempMetadataAdapter metadata;
- private Query query;
- private boolean allowImplicit = true;
-
- public QueryResolverVisitor(Query query, TempMetadataAdapter metadata) {
- super(new ResolverVisitor(metadata, null, query.getExternalGroupContexts()));
- ResolverVisitor visitor = (ResolverVisitor)getVisitor();
- visitor.setGroups(currentGroups);
- this.query = query;
- this.metadata = metadata;
- }
-
- protected void postVisitVisitor(LanguageObject obj) {
- super.postVisitVisitor(obj);
- ResolverVisitor visitor = (ResolverVisitor)getVisitor();
- try {
- visitor.throwException(false);
- } catch (TeiidException e) {
- throw new TeiidRuntimeException(e);
- }
- }
-
- /**
- * Resolving a Query requires a special ordering
- */
- public void visit(Query obj) {
- visitNode(obj.getInto());
- visitNode(obj.getFrom());
- visitNode(obj.getCriteria());
- visitNode(obj.getGroupBy());
- visitNode(obj.getHaving());
- visitNode(obj.getSelect());
- }
-
- public void visit(GroupSymbol obj) {
- try {
- ResolverUtil.resolveGroup(obj, metadata);
- } catch (TeiidException err) {
- throw new TeiidRuntimeException(err);
- }
- }
-
- private void resolveSubQuery(SubqueryContainer<?> obj, Collection<GroupSymbol> externalGroups) {
- Command command = obj.getCommand();
-
- QueryResolver.setChildMetadata(command, query);
- command.pushNewResolvingContext(externalGroups);
-
- try {
- QueryResolver.resolveCommand(command, metadata.getMetadata(), false);
- } catch (TeiidException err) {
- throw new TeiidRuntimeException(err);
- }
- }
-
- public void visit(AllSymbol obj) {
- try {
- List<ElementSymbol> elementSymbols = new ArrayList<ElementSymbol>();
- for (GroupSymbol group : currentGroups) {
- elementSymbols.addAll(resolveSelectableElements(group));
- }
- obj.setElementSymbols(elementSymbols);
- } catch (TeiidComponentException err) {
- throw new TeiidRuntimeException(err);
- }
- }
-
- private List<ElementSymbol> resolveSelectableElements(GroupSymbol group) throws QueryMetadataException,
- TeiidComponentException {
- List<ElementSymbol> elements = ResolverUtil.resolveElementsInGroup(group, metadata);
-
- List<ElementSymbol> result = new ArrayList<ElementSymbol>(elements.size());
-
- // 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.setGroupSymbol(group);
- result.add(element);
- }
- }
- 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);
- }
-
- public void visit(ExistsCriteria obj) {
- resolveSubQuery(obj, this.currentGroups);
- }
-
- public void visit(SubqueryCompareCriteria obj) {
- visitNode(obj.getLeftExpression());
- resolveSubQuery(obj, this.currentGroups);
- postVisitVisitor(obj);
- }
-
- public void visit(SubquerySetCriteria obj) {
- visitNode(obj.getExpression());
- resolveSubQuery(obj, this.currentGroups);
- postVisitVisitor(obj);
- }
-
- @Override
- public void visit(TextTable obj) {
- LinkedHashSet<GroupSymbol> saved = preTableFunctionReference(obj);
- this.visitNode(obj.getFile());
- try {
- obj.setFile(ResolverUtil.convertExpression(obj.getFile(), DataTypeManager.DefaultDataTypes.CLOB, metadata));
- } catch (QueryResolverException e) {
- throw new TeiidRuntimeException(e);
- }
- postTableFunctionReference(obj, saved);
- //set to fixed width if any column has width specified
- for (TextTable.TextColumn col : obj.getColumns()) {
- if (col.getWidth() != null) {
- obj.setFixedWidth(true);
- break;
- }
- }
- }
-
- @Override
- public void visit(ArrayTable obj) {
- LinkedHashSet<GroupSymbol> saved = preTableFunctionReference(obj);
- visitNode(obj.getArrayValue());
- postTableFunctionReference(obj, saved);
- }
-
- @Override
- public void visit(XMLTable obj) {
- LinkedHashSet<GroupSymbol> saved = preTableFunctionReference(obj);
- visitNodes(obj.getPassing());
- postTableFunctionReference(obj, saved);
- try {
- obj.compileXqueryExpression();
- for (XMLTable.XMLColumn column : obj.getColumns()) {
- if (column.getDefaultExpression() == null) {
- continue;
- }
- ResolverVisitor.resolveLanguageObject(column.getDefaultExpression(), metadata);
- Expression ex = ResolverUtil.convertExpression(column.getDefaultExpression(), DataTypeManager.getDataTypeName(column.getSymbol().getType()), metadata);
- column.setDefaultExpression(ex);
- }
- } catch (TeiidException e) {
- throw new TeiidRuntimeException(e);
- }
- }
-
- public LinkedHashSet<GroupSymbol> preTableFunctionReference(TableFunctionReference tfr) {
- LinkedHashSet<GroupSymbol> saved = new LinkedHashSet<GroupSymbol>(this.currentGroups);
- if (allowImplicit) {
- currentGroups.addAll(this.implicitGroups);
- }
- return saved;
- }
-
- public void postTableFunctionReference(TableFunctionReference obj, LinkedHashSet<GroupSymbol> saved) {
- //we didn't create a true external context, so we manually mark external
- for (ElementSymbol symbol : ElementCollectorVisitor.getElements(obj, false)) {
- if (symbol.isExternalReference()) {
- continue;
- }
- if (implicitGroups.contains(symbol.getGroupSymbol())) {
- symbol.setIsExternalReference(true);
- }
- }
- if (allowImplicit) {
- this.currentGroups.clear();
- this.currentGroups.addAll(saved);
- }
- discoveredGroup(obj.getGroupSymbol());
- try {
- ResolverUtil.addTempGroup(metadata, obj.getGroupSymbol(), obj.getProjectedSymbols(), false);
- } catch (QueryResolverException err) {
- throw new TeiidRuntimeException(err);
- }
- obj.getGroupSymbol().setMetadataID(metadata.getMetadataStore().getTempGroupID(obj.getGroupSymbol().getName()));
- //now resolve the projected symbols
- Set<GroupSymbol> groups = new HashSet<GroupSymbol>();
- groups.add(obj.getGroupSymbol());
- for (ElementSymbol symbol : obj.getProjectedSymbols()) {
- try {
- ResolverVisitor.resolveLanguageObject(symbol, groups, null, metadata);
- } catch (TeiidException e) {
- throw new TeiidRuntimeException(e);
- }
- }
- }
-
- public void visit(SubqueryFromClause obj) {
- Collection<GroupSymbol> externalGroups = this.currentGroups;
- if (obj.isTable() && allowImplicit) {
- externalGroups = new ArrayList<GroupSymbol>(externalGroups);
- externalGroups.addAll(this.implicitGroups);
- }
- resolveSubQuery(obj, externalGroups);
- discoveredGroup(obj.getGroupSymbol());
- try {
- ResolverUtil.addTempGroup(metadata, obj.getGroupSymbol(), obj.getCommand().getProjectedSymbols(), false);
- } catch (QueryResolverException err) {
- throw new TeiidRuntimeException(err);
- }
- obj.getGroupSymbol().setMetadataID(metadata.getMetadataStore().getTempGroupID(obj.getGroupSymbol().getName()));
- }
-
- public void visit(UnaryFromClause obj) {
- GroupSymbol group = obj.getGroup();
- visitNode(group);
- try {
- if (!group.isProcedure() && metadata.isXMLGroup(group.getMetadataID())) {
- throw new QueryResolverException("ERR.015.008.0003", QueryPlugin.Util.getString("ERR.015.008.0003")); //$NON-NLS-1$ //$NON-NLS-2$
- }
- discoveredGroup(group);
- if (group.isProcedure()) {
- createProcRelational(obj);
- }
- } catch(TeiidException e) {
- throw new TeiidRuntimeException(e);
- }
- }
-
- private void discoveredGroup(GroupSymbol group) {
- discoveredGroups.add(group);
- if (allowImplicit) {
- implicitGroups.add(group);
- }
- }
-
- private void createProcRelational(UnaryFromClause obj)
- throws TeiidComponentException, QueryMetadataException,
- QueryResolverException {
- GroupSymbol group = obj.getGroup();
- String fullName = metadata.getFullName(group.getMetadataID());
- String queryName = group.getName();
-
- StoredProcedureInfo storedProcedureInfo = metadata.getStoredProcedureInfoForProcedure(fullName);
-
- StoredProcedure storedProcedureCommand = new StoredProcedure();
- storedProcedureCommand.setProcedureRelational(true);
- storedProcedureCommand.setProcedureName(fullName);
-
- List<SPParameter> metadataParams = storedProcedureInfo.getParameters();
-
- Query procQuery = new Query();
- From from = new From();
- from.addClause(new SubqueryFromClause("X", storedProcedureCommand)); //$NON-NLS-1$
- procQuery.setFrom(from);
- Select select = new Select();
- select.addSymbol(new AllInGroupSymbol("X.*")); //$NON-NLS-1$
- procQuery.setSelect(select);
-
- List<String> accessPatternElementNames = new LinkedList<String>();
-
- int paramIndex = 1;
-
- for (SPParameter metadataParameter : metadataParams) {
- SPParameter clonedParam = (SPParameter)metadataParameter.clone();
- if (clonedParam.getParameterType()==ParameterInfo.IN || metadataParameter.getParameterType()==ParameterInfo.INOUT) {
- ElementSymbol paramSymbol = clonedParam.getParameterSymbol();
- Reference ref = new Reference(paramSymbol);
- clonedParam.setExpression(ref);
- clonedParam.setIndex(paramIndex++);
- storedProcedureCommand.setParameter(clonedParam);
-
- String aliasName = paramSymbol.getShortName();
-
- if (metadataParameter.getParameterType()==ParameterInfo.INOUT) {
- aliasName += "_IN"; //$NON-NLS-1$
- }
-
- SingleElementSymbol newSymbol = new AliasSymbol(aliasName, new ExpressionSymbol(paramSymbol.getShortName(), ref));
-
- select.addSymbol(newSymbol);
- accessPatternElementNames.add(queryName + ElementSymbol.SEPARATOR + aliasName);
- }
- }
-
- QueryResolver.resolveCommand(procQuery, metadata.getMetadata());
-
- List<SingleElementSymbol> projectedSymbols = procQuery.getProjectedSymbols();
-
- HashSet<String> foundNames = new HashSet<String>();
-
- for (SingleElementSymbol ses : projectedSymbols) {
- if (!foundNames.add(ses.getShortCanonicalName())) {
- throw new QueryResolverException(QueryPlugin.Util.getString("SimpleQueryResolver.Proc_Relational_Name_conflict", fullName)); //$NON-NLS-1$
- }
- }
-
- TempMetadataID id = metadata.getMetadataStore().getTempGroupID(queryName);
-
- if (id == null) {
- metadata.getMetadataStore().addTempGroup(queryName, projectedSymbols, true);
-
- id = metadata.getMetadataStore().getTempGroupID(queryName);
- id.setOriginalMetadataID(storedProcedureCommand.getProcedureID());
- if (!accessPatternElementNames.isEmpty()) {
- List<TempMetadataID> accessPatternIds = new LinkedList<TempMetadataID>();
-
- for (String name : accessPatternElementNames) {
- accessPatternIds.add(metadata.getMetadataStore().getTempElementID(name));
- }
-
- id.setAccessPatterns(Arrays.asList(new TempMetadataID("procedure access pattern", accessPatternIds))); //$NON-NLS-1$
- }
- }
-
- group.setMetadataID(id);
-
- obj.setExpandedCommand(procQuery);
- }
-
- /**
- * @see org.teiid.query.sql.navigator.PreOrPostOrderNavigator#visit(org.teiid.query.sql.lang.Into)
- */
- public void visit(Into obj) {
- if (!obj.getGroup().isImplicitTempGroupSymbol()) {
- super.visit(obj);
- }
- }
-
- public void visit(JoinPredicate obj) {
- assert currentGroups.isEmpty();
- List<GroupSymbol> tempImplicitGroups = new ArrayList<GroupSymbol>(discoveredGroups);
- discoveredGroups.clear();
- visitNode(obj.getLeftClause());
- List<GroupSymbol> leftGroups = new ArrayList<GroupSymbol>(discoveredGroups);
- discoveredGroups.clear();
- visitNode(obj.getRightClause());
- discoveredGroups.addAll(leftGroups);
- addDiscoveredGroups();
- visitNodes(obj.getJoinCriteria());
- discoveredGroups.addAll(currentGroups);
- currentGroups.clear();
- discoveredGroups.addAll(tempImplicitGroups);
- }
-
- private void addDiscoveredGroups() {
- for (GroupSymbol group : discoveredGroups) {
- if (!this.currentGroups.add(group)) {
- String msg = QueryPlugin.Util.getString("ERR.015.008.0046", group.getName()); //$NON-NLS-1$
- QueryResolverException qre = new QueryResolverException("ERR.015.008.0046", msg); //$NON-NLS-1$
- qre.addUnresolvedSymbol(new UnresolvedSymbolDescription(group.toString(), msg));
- throw new TeiidRuntimeException(qre);
- }
- }
- discoveredGroups.clear();
- }
-
- public void visit(From obj) {
- assert currentGroups.isEmpty();
- for (FromClause clause : (List<FromClause>)obj.getClauses()) {
- checkImplicit(clause);
- }
- super.visit(obj);
- addDiscoveredGroups();
- }
-
- private void checkImplicit(FromClause clause) {
- if (clause instanceof JoinPredicate) {
- JoinPredicate jp = (JoinPredicate)clause;
- if (jp.getJoinType() == JoinType.JOIN_FULL_OUTER || jp.getJoinType() == JoinType.JOIN_RIGHT_OUTER) {
- allowImplicit = false;
- return;
- }
- checkImplicit(jp.getLeftClause());
- if (allowImplicit) {
- checkImplicit(jp.getRightClause());
- }
- }
- }
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/SimpleQueryResolver.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/resolver/command/SimpleQueryResolver.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/SimpleQueryResolver.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/SimpleQueryResolver.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,598 @@
+/*
+ * 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.resolver.command;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+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.QueryResolverException;
+import org.teiid.api.exception.query.UnresolvedSymbolDescription;
+import org.teiid.client.metadata.ParameterInfo;
+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.QueryPlugin;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.StoredProcedureInfo;
+import org.teiid.query.metadata.SupportConstants;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.metadata.TempMetadataID;
+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.ArrayTable;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.From;
+import org.teiid.query.sql.lang.FromClause;
+import org.teiid.query.sql.lang.Into;
+import org.teiid.query.sql.lang.JoinPredicate;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.SubqueryCompareCriteria;
+import org.teiid.query.sql.lang.SubqueryContainer;
+import org.teiid.query.sql.lang.SubqueryFromClause;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.lang.TableFunctionReference;
+import org.teiid.query.sql.lang.TextTable;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.lang.WithQueryCommand;
+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.Reference;
+import org.teiid.query.sql.symbol.ScalarSubquery;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+
+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)
+ */
+ public void resolveCommand(Command command, TempMetadataAdapter metadata, boolean resolveNullLiterals)
+ throws QueryMetadataException, QueryResolverException, TeiidComponentException {
+
+ Query query = (Query) command;
+
+ resolveWith(metadata, query);
+
+ try {
+ QueryResolverVisitor qrv = new QueryResolverVisitor(query, metadata);
+ qrv.visit(query);
+ ResolverVisitor visitor = (ResolverVisitor)qrv.getVisitor();
+ visitor.throwException(true);
+ } catch (TeiidRuntimeException e) {
+ if (e.getChild() instanceof QueryMetadataException) {
+ throw (QueryMetadataException)e.getChild();
+ }
+ if (e.getChild() instanceof QueryResolverException) {
+ throw (QueryResolverException)e.getChild();
+ }
+ if (e.getChild() instanceof TeiidComponentException) {
+ throw (TeiidComponentException)e.getChild();
+ }
+ throw e;
+ }
+
+ if (query.getLimit() != null) {
+ ResolverUtil.resolveLimit(query.getLimit());
+ }
+
+ if (query.getOrderBy() != null) {
+ ResolverUtil.resolveOrderBy(query.getOrderBy(), query, metadata);
+ }
+
+ List<SingleElementSymbol> symbols = query.getSelect().getProjectedSymbols();
+
+ if (query.getInto() != null) {
+ GroupSymbol symbol = query.getInto().getGroup();
+ ResolverUtil.resolveImplicitTempGroup(metadata, symbol, symbols);
+ } else if (resolveNullLiterals) {
+ ResolverUtil.resolveNullLiterals(symbols);
+ }
+ }
+
+ static void resolveWith(TempMetadataAdapter metadata,
+ QueryCommand query) throws QueryResolverException, TeiidComponentException {
+ if (query.getWith() == null) {
+ return;
+ }
+ LinkedHashSet<GroupSymbol> discoveredGroups = new LinkedHashSet<GroupSymbol>();
+ for (WithQueryCommand obj : query.getWith()) {
+ QueryCommand queryExpression = obj.getCommand();
+
+ QueryResolver.setChildMetadata(queryExpression, query);
+
+ QueryResolver.resolveCommand(queryExpression, metadata.getMetadata(), false);
+
+ if (!discoveredGroups.add(obj.getGroupSymbol())) {
+ throw new QueryResolverException(QueryPlugin.Util.getString("SimpleQueryResolver.duplicate_with", obj.getGroupSymbol())); //$NON-NLS-1$
+ }
+ List<? extends SingleElementSymbol> projectedSymbols = obj.getCommand().getProjectedSymbols();
+ if (obj.getColumns() != null && !obj.getColumns().isEmpty()) {
+ if (obj.getColumns().size() != projectedSymbols.size()) {
+ throw new QueryResolverException(QueryPlugin.Util.getString("SimpleQueryResolver.mismatched_with_columns", obj.getGroupSymbol())); //$NON-NLS-1$
+ }
+ Iterator<ElementSymbol> iter = obj.getColumns().iterator();
+ for (SingleElementSymbol singleElementSymbol : projectedSymbols) {
+ ElementSymbol es = iter.next();
+ es.setType(singleElementSymbol.getType());
+ }
+ projectedSymbols = obj.getColumns();
+ }
+ TempMetadataID id = ResolverUtil.addTempGroup(metadata, obj.getGroupSymbol(), projectedSymbols, true);
+ obj.getGroupSymbol().setMetadataID(metadata.getMetadataStore().getTempGroupID(obj.getGroupSymbol().getName()));
+ obj.getGroupSymbol().setIsTempTable(true);
+ List<GroupSymbol> groups = Collections.singletonList(obj.getGroupSymbol());
+ if (obj.getColumns() != null && !obj.getColumns().isEmpty()) {
+ for (SingleElementSymbol singleElementSymbol : projectedSymbols) {
+ ResolverVisitor.resolveLanguageObject(singleElementSymbol, groups, metadata);
+ }
+ }
+ if (obj.getColumns() != null && !obj.getColumns().isEmpty()) {
+ Iterator<ElementSymbol> iter = obj.getColumns().iterator();
+ for (TempMetadataID colid : id.getElements()) {
+ ElementSymbol es = iter.next();
+ es.setMetadataID(colid);
+ es.setGroupSymbol(obj.getGroupSymbol());
+ }
+ }
+ }
+ }
+
+ 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);
+ 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;
+ }
+
+ return groupSymbols.get(0);
+ }
+
+ public static class QueryResolverVisitor extends PostOrderNavigator {
+
+ private LinkedHashSet<GroupSymbol> currentGroups = new LinkedHashSet<GroupSymbol>();
+ private LinkedList<GroupSymbol> discoveredGroups = new LinkedList<GroupSymbol>();
+ private List<GroupSymbol> implicitGroups = new LinkedList<GroupSymbol>();
+ private TempMetadataAdapter metadata;
+ private Query query;
+ private boolean allowImplicit = true;
+
+ public QueryResolverVisitor(Query query, TempMetadataAdapter metadata) {
+ super(new ResolverVisitor(metadata, null, query.getExternalGroupContexts()));
+ ResolverVisitor visitor = (ResolverVisitor)getVisitor();
+ visitor.setGroups(currentGroups);
+ this.query = query;
+ this.metadata = metadata;
+ }
+
+ protected void postVisitVisitor(LanguageObject obj) {
+ super.postVisitVisitor(obj);
+ ResolverVisitor visitor = (ResolverVisitor)getVisitor();
+ try {
+ visitor.throwException(false);
+ } catch (TeiidException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+
+ /**
+ * Resolving a Query requires a special ordering
+ */
+ public void visit(Query obj) {
+ visitNode(obj.getInto());
+ visitNode(obj.getFrom());
+ visitNode(obj.getCriteria());
+ visitNode(obj.getGroupBy());
+ visitNode(obj.getHaving());
+ visitNode(obj.getSelect());
+ }
+
+ public void visit(GroupSymbol obj) {
+ try {
+ ResolverUtil.resolveGroup(obj, metadata);
+ } catch (TeiidException err) {
+ throw new TeiidRuntimeException(err);
+ }
+ }
+
+ private void resolveSubQuery(SubqueryContainer<?> obj, Collection<GroupSymbol> externalGroups) {
+ Command command = obj.getCommand();
+
+ QueryResolver.setChildMetadata(command, query);
+ command.pushNewResolvingContext(externalGroups);
+
+ try {
+ QueryResolver.resolveCommand(command, metadata.getMetadata(), false);
+ } catch (TeiidException err) {
+ throw new TeiidRuntimeException(err);
+ }
+ }
+
+ public void visit(AllSymbol obj) {
+ try {
+ List<ElementSymbol> elementSymbols = new ArrayList<ElementSymbol>();
+ for (GroupSymbol group : currentGroups) {
+ elementSymbols.addAll(resolveSelectableElements(group));
+ }
+ obj.setElementSymbols(elementSymbols);
+ } catch (TeiidComponentException err) {
+ throw new TeiidRuntimeException(err);
+ }
+ }
+
+ private List<ElementSymbol> resolveSelectableElements(GroupSymbol group) throws QueryMetadataException,
+ TeiidComponentException {
+ List<ElementSymbol> elements = ResolverUtil.resolveElementsInGroup(group, metadata);
+
+ List<ElementSymbol> result = new ArrayList<ElementSymbol>(elements.size());
+
+ // Look for elements that are not selectable and remove them
+ for (ElementSymbol element : elements) {
+ if(metadata.elementSupports(element.getMetadataID(), SupportConstants.Element.SELECT)) {
+ element = element.clone();
+ element.setGroupSymbol(group);
+ result.add(element);
+ }
+ }
+ 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);
+ }
+
+ public void visit(ExistsCriteria obj) {
+ resolveSubQuery(obj, this.currentGroups);
+ }
+
+ public void visit(SubqueryCompareCriteria obj) {
+ visitNode(obj.getLeftExpression());
+ resolveSubQuery(obj, this.currentGroups);
+ postVisitVisitor(obj);
+ }
+
+ public void visit(SubquerySetCriteria obj) {
+ visitNode(obj.getExpression());
+ resolveSubQuery(obj, this.currentGroups);
+ postVisitVisitor(obj);
+ }
+
+ @Override
+ public void visit(TextTable obj) {
+ LinkedHashSet<GroupSymbol> saved = preTableFunctionReference(obj);
+ this.visitNode(obj.getFile());
+ try {
+ obj.setFile(ResolverUtil.convertExpression(obj.getFile(), DataTypeManager.DefaultDataTypes.CLOB, metadata));
+ } catch (QueryResolverException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ postTableFunctionReference(obj, saved);
+ //set to fixed width if any column has width specified
+ for (TextTable.TextColumn col : obj.getColumns()) {
+ if (col.getWidth() != null) {
+ obj.setFixedWidth(true);
+ break;
+ }
+ }
+ }
+
+ @Override
+ public void visit(ArrayTable obj) {
+ LinkedHashSet<GroupSymbol> saved = preTableFunctionReference(obj);
+ visitNode(obj.getArrayValue());
+ postTableFunctionReference(obj, saved);
+ }
+
+ @Override
+ public void visit(XMLTable obj) {
+ LinkedHashSet<GroupSymbol> saved = preTableFunctionReference(obj);
+ visitNodes(obj.getPassing());
+ postTableFunctionReference(obj, saved);
+ try {
+ obj.compileXqueryExpression();
+ for (XMLTable.XMLColumn column : obj.getColumns()) {
+ if (column.getDefaultExpression() == null) {
+ continue;
+ }
+ ResolverVisitor.resolveLanguageObject(column.getDefaultExpression(), metadata);
+ Expression ex = ResolverUtil.convertExpression(column.getDefaultExpression(), DataTypeManager.getDataTypeName(column.getSymbol().getType()), metadata);
+ column.setDefaultExpression(ex);
+ }
+ } catch (TeiidException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+
+ /**
+ * @param tfr
+ */
+ public LinkedHashSet<GroupSymbol> preTableFunctionReference(TableFunctionReference tfr) {
+ LinkedHashSet<GroupSymbol> saved = new LinkedHashSet<GroupSymbol>(this.currentGroups);
+ if (allowImplicit) {
+ currentGroups.addAll(this.implicitGroups);
+ }
+ return saved;
+ }
+
+ public void postTableFunctionReference(TableFunctionReference obj, LinkedHashSet<GroupSymbol> saved) {
+ //we didn't create a true external context, so we manually mark external
+ for (ElementSymbol symbol : ElementCollectorVisitor.getElements(obj, false)) {
+ if (symbol.isExternalReference()) {
+ continue;
+ }
+ if (implicitGroups.contains(symbol.getGroupSymbol())) {
+ symbol.setIsExternalReference(true);
+ }
+ }
+ if (allowImplicit) {
+ this.currentGroups.clear();
+ this.currentGroups.addAll(saved);
+ }
+ discoveredGroup(obj.getGroupSymbol());
+ try {
+ ResolverUtil.addTempGroup(metadata, obj.getGroupSymbol(), obj.getProjectedSymbols(), false);
+ } catch (QueryResolverException err) {
+ throw new TeiidRuntimeException(err);
+ }
+ obj.getGroupSymbol().setMetadataID(metadata.getMetadataStore().getTempGroupID(obj.getGroupSymbol().getName()));
+ //now resolve the projected symbols
+ Set<GroupSymbol> groups = new HashSet<GroupSymbol>();
+ groups.add(obj.getGroupSymbol());
+ for (ElementSymbol symbol : obj.getProjectedSymbols()) {
+ try {
+ ResolverVisitor.resolveLanguageObject(symbol, groups, null, metadata);
+ } catch (TeiidException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+ }
+
+ public void visit(SubqueryFromClause obj) {
+ Collection<GroupSymbol> externalGroups = this.currentGroups;
+ if (obj.isTable() && allowImplicit) {
+ externalGroups = new ArrayList<GroupSymbol>(externalGroups);
+ externalGroups.addAll(this.implicitGroups);
+ }
+ resolveSubQuery(obj, externalGroups);
+ discoveredGroup(obj.getGroupSymbol());
+ try {
+ ResolverUtil.addTempGroup(metadata, obj.getGroupSymbol(), obj.getCommand().getProjectedSymbols(), false);
+ } catch (QueryResolverException err) {
+ throw new TeiidRuntimeException(err);
+ }
+ obj.getGroupSymbol().setMetadataID(metadata.getMetadataStore().getTempGroupID(obj.getGroupSymbol().getName()));
+ }
+
+ public void visit(UnaryFromClause obj) {
+ GroupSymbol group = obj.getGroup();
+ visitNode(group);
+ try {
+ if (!group.isProcedure() && metadata.isXMLGroup(group.getMetadataID())) {
+ throw new QueryResolverException("ERR.015.008.0003", QueryPlugin.Util.getString("ERR.015.008.0003")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ discoveredGroup(group);
+ if (group.isProcedure()) {
+ createProcRelational(obj);
+ }
+ } catch(TeiidException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+
+ private void discoveredGroup(GroupSymbol group) {
+ discoveredGroups.add(group);
+ if (allowImplicit) {
+ implicitGroups.add(group);
+ }
+ }
+
+ private void createProcRelational(UnaryFromClause obj)
+ throws TeiidComponentException, QueryMetadataException,
+ QueryResolverException {
+ GroupSymbol group = obj.getGroup();
+ String fullName = metadata.getFullName(group.getMetadataID());
+ String queryName = group.getName();
+
+ StoredProcedureInfo storedProcedureInfo = metadata.getStoredProcedureInfoForProcedure(fullName);
+
+ StoredProcedure storedProcedureCommand = new StoredProcedure();
+ storedProcedureCommand.setProcedureRelational(true);
+ storedProcedureCommand.setProcedureName(fullName);
+
+ List<SPParameter> metadataParams = storedProcedureInfo.getParameters();
+
+ Query procQuery = new Query();
+ From from = new From();
+ from.addClause(new SubqueryFromClause("X", storedProcedureCommand)); //$NON-NLS-1$
+ procQuery.setFrom(from);
+ Select select = new Select();
+ select.addSymbol(new AllInGroupSymbol("X.*")); //$NON-NLS-1$
+ procQuery.setSelect(select);
+
+ List<String> accessPatternElementNames = new LinkedList<String>();
+
+ int paramIndex = 1;
+
+ for (SPParameter metadataParameter : metadataParams) {
+ SPParameter clonedParam = (SPParameter)metadataParameter.clone();
+ if (clonedParam.getParameterType()==ParameterInfo.IN || metadataParameter.getParameterType()==ParameterInfo.INOUT) {
+ ElementSymbol paramSymbol = clonedParam.getParameterSymbol();
+ Reference ref = new Reference(paramSymbol);
+ clonedParam.setExpression(ref);
+ clonedParam.setIndex(paramIndex++);
+ storedProcedureCommand.setParameter(clonedParam);
+
+ String aliasName = paramSymbol.getShortName();
+
+ if (metadataParameter.getParameterType()==ParameterInfo.INOUT) {
+ aliasName += "_IN"; //$NON-NLS-1$
+ }
+
+ SingleElementSymbol newSymbol = new AliasSymbol(aliasName, new ExpressionSymbol(paramSymbol.getShortName(), ref));
+
+ select.addSymbol(newSymbol);
+ accessPatternElementNames.add(queryName + ElementSymbol.SEPARATOR + aliasName);
+ }
+ }
+
+ QueryResolver.resolveCommand(procQuery, metadata.getMetadata());
+
+ List<SingleElementSymbol> projectedSymbols = procQuery.getProjectedSymbols();
+
+ HashSet<String> foundNames = new HashSet<String>();
+
+ for (SingleElementSymbol ses : projectedSymbols) {
+ if (!foundNames.add(ses.getShortCanonicalName())) {
+ throw new QueryResolverException(QueryPlugin.Util.getString("SimpleQueryResolver.Proc_Relational_Name_conflict", fullName)); //$NON-NLS-1$
+ }
+ }
+
+ TempMetadataID id = metadata.getMetadataStore().getTempGroupID(queryName);
+
+ if (id == null) {
+ metadata.getMetadataStore().addTempGroup(queryName, projectedSymbols, true);
+
+ id = metadata.getMetadataStore().getTempGroupID(queryName);
+ id.setOriginalMetadataID(storedProcedureCommand.getProcedureID());
+ if (!accessPatternElementNames.isEmpty()) {
+ List<TempMetadataID> accessPatternIds = new LinkedList<TempMetadataID>();
+
+ for (String name : accessPatternElementNames) {
+ accessPatternIds.add(metadata.getMetadataStore().getTempElementID(name));
+ }
+
+ id.setAccessPatterns(Arrays.asList(new TempMetadataID("procedure access pattern", accessPatternIds))); //$NON-NLS-1$
+ }
+ }
+
+ group.setMetadataID(id);
+
+ obj.setExpandedCommand(procQuery);
+ }
+
+ /**
+ * @see org.teiid.query.sql.navigator.PreOrPostOrderNavigator#visit(org.teiid.query.sql.lang.Into)
+ */
+ public void visit(Into obj) {
+ if (!obj.getGroup().isImplicitTempGroupSymbol()) {
+ super.visit(obj);
+ }
+ }
+
+ public void visit(JoinPredicate obj) {
+ assert currentGroups.isEmpty();
+ List<GroupSymbol> tempImplicitGroups = new ArrayList<GroupSymbol>(discoveredGroups);
+ discoveredGroups.clear();
+ visitNode(obj.getLeftClause());
+ List<GroupSymbol> leftGroups = new ArrayList<GroupSymbol>(discoveredGroups);
+ discoveredGroups.clear();
+ visitNode(obj.getRightClause());
+ discoveredGroups.addAll(leftGroups);
+ addDiscoveredGroups();
+ visitNodes(obj.getJoinCriteria());
+ discoveredGroups.addAll(currentGroups);
+ currentGroups.clear();
+ discoveredGroups.addAll(tempImplicitGroups);
+ }
+
+ private void addDiscoveredGroups() {
+ for (GroupSymbol group : discoveredGroups) {
+ if (!this.currentGroups.add(group)) {
+ String msg = QueryPlugin.Util.getString("ERR.015.008.0046", group.getName()); //$NON-NLS-1$
+ QueryResolverException qre = new QueryResolverException("ERR.015.008.0046", msg); //$NON-NLS-1$
+ qre.addUnresolvedSymbol(new UnresolvedSymbolDescription(group.toString(), msg));
+ throw new TeiidRuntimeException(qre);
+ }
+ }
+ discoveredGroups.clear();
+ }
+
+ public void visit(From obj) {
+ assert currentGroups.isEmpty();
+ for (FromClause clause : obj.getClauses()) {
+ checkImplicit(clause);
+ }
+ super.visit(obj);
+ addDiscoveredGroups();
+ }
+
+ private void checkImplicit(FromClause clause) {
+ if (clause instanceof JoinPredicate) {
+ JoinPredicate jp = (JoinPredicate)clause;
+ if (jp.getJoinType() == JoinType.JOIN_FULL_OUTER || jp.getJoinType() == JoinType.JOIN_RIGHT_OUTER) {
+ allowImplicit = false;
+ return;
+ }
+ checkImplicit(jp.getLeftClause());
+ if (allowImplicit) {
+ checkImplicit(jp.getRightClause());
+ }
+ }
+ }
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/XMLQueryResolver.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/resolver/command/XMLQueryResolver.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/XMLQueryResolver.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,408 +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.resolver.command;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.util.StringUtil;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataAdapter;
-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.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.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.SelectSymbol;
-import org.teiid.query.sql.visitor.CommandCollectorVisitor;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-
-
-/**
- */
-public class XMLQueryResolver implements CommandResolver {
-
- /**
- * @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 {
-
- Query query = (Query) command;
-
- // set isXML flag
- query.setIsXML(true);
-
- // get the group on this query
- Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(query, true);
- GroupSymbol group = groups.iterator().next();
-
- //external groups
- GroupContext externalGroups = query.getExternalGroupContexts();
-
- // valid elements for select
- List<ElementSymbol> validSelectElems = getElementsInDocument(group, metadata);
- resolveXMLSelect(query, group, validSelectElems, metadata);
-
- // valid elements for criteria and order by
- Collection<ElementSymbol> validCriteriaElements = collectValidCriteriaElements(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);
- // Resolve functions in current query
- ResolverVisitor.resolveLanguageObject(crit, metadata);
- }
-
- // resolve any orderby specified on the query
- if(orderBy != null) {
- resolveXMLOrderBy(orderBy, externalGroups, validCriteriaElements, metadata);
- }
-
- //we throw exceptions in these cases, since the clauses will not be resolved
- if (query.getGroupBy() != null) {
- throw new QueryResolverException(QueryPlugin.Util.getString("ERR.015.012.0031")); //$NON-NLS-1$
- }
-
- if (query.getHaving() != null) {
- throw new QueryResolverException(QueryPlugin.Util.getString("ERR.015.012.0032")); //$NON-NLS-1$
- }
- }
-
- /**
- * Method resolveXMLSelect.
- * @param select Select clause in user command
- * @param group GroupSymbol
- * @param externalGroups Collection of external groups
- * @param validElements Collection of valid elements
- * @param metadata QueryMetadataInterface the metadata(for resolving criteria on temp groups)
- * @throws QueryResolverException if resolving order by fails
- * @throws QueryMetadataException if resolving fails
- * @throws TeiidComponentException if resolving fails
- */
- void resolveXMLSelect(Query query, GroupSymbol group, List<ElementSymbol> validElements, QueryMetadataInterface metadata)
- throws QueryMetadataException, TeiidComponentException, QueryResolverException {
-
- GroupContext externalGroups = null;
-
- Select select = query.getSelect();
- // Allow SELECT DISTINCT, which is ignored. It is meaningless except for
- // self-entity relation using relate() functionality
-
- List elements = select.getSymbols();
- for (int i = 0; i < elements.size(); i++) {
- SelectSymbol ss = (SelectSymbol) elements.get(i);
-
- if (ss instanceof ElementSymbol) {
- // Here we make an assumption that: all elements named with "xml" must use qualified name
- // rather than a simple "xml" in order to distinguish it from "SELECT xml" and
- // "SELECT model.document.xml" case, both of whom stand for selecting the whole document.
-
- // Then "SELECT xml" or "SELECT model.document.xml" can only stand for one meaning with two cases:
- // 1) whole document
- // 2) whole document, root name = "xml", too
-
- // 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$
- 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);
- select.addSymbol(all);
- query.setSelect(select);
- return;
- }
- // normal elements
- resolveElement((ElementSymbol)ss, validElements, externalGroups, metadata);
- } else if (ss instanceof AllInGroupSymbol) {
- // 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);
-
- // 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);
-
- // 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;
- } else if (ss instanceof ExpressionSymbol) {
- throw new QueryResolverException(QueryPlugin.Util.getString("XMLQueryResolver.no_expressions_in_select")); //$NON-NLS-1$
- } else if (ss instanceof AliasSymbol) {
- throw new QueryResolverException("ERR.015.008.0070", QueryPlugin.Util.getString("ERR.015.008.0070")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- }
- }
-
- /**
- * 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);
-
- // 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();
- String name = metadata.getFullName(tempGroupID);
- GroupSymbol tempGroup = new GroupSymbol(name);
- tempGroup.setMetadataID(tempGroupID);
-
- validElements.addAll(ResolverUtil.resolveElementsInGroup(tempGroup, metadata));
- }
- 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
- * temporary table at the root of the document model (if a temp table exists there).</p>
- * <p>A QueryResolverException will be thrown under the following circumstances:
- * <ol>
- * <li>the elements of the XML criteria cannot be resolved</li>
- * <li>the "@" attribute prefix is used to specify that the node is an attribute, but
- * a document node is found that is an element</li>
- * <li>an element is supplied in the criteria and is ambiguous (multiple
- * document nodes and/or root temp table elements exist which have that name)</li>
- * </ol></p>
- * <p>If an element is supplied in the criteria and is ambiguous (multiple document nodes and/or
- * root temp table elements of that name exist)
- * @param criteria The criteria object that should be resolved
- * @param group The group on the query.
- * @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)
- throws QueryMetadataException, TeiidComponentException, QueryResolverException {
-
- // Walk through each element in criteria and check against valid elements
- Collection<ElementSymbol> critElems = ElementCollectorVisitor.getElements(criteria, false);
- for (ElementSymbol critElem : critElems) {
- if(! critElem.isExternalReference()) {
- resolveElement(critElem, validElements, externalGroups, metadata);
- }
- }
- }
-
- /**
- * Resolve OrderBy clause specified on the XML Query.
- * @param orderBy Order By clause in user command
- * @param group GroupSymbol
- * @param externalGroups Collection of external groups
- * @param validElements Collection of valid elements
- * @param metadata QueryMetadataInterface the metadata(for resolving criteria on temp groups)
- * @throws QueryResolverException if resolving order by fails
- * @throws QueryMetadataException if resolving fails
- * @throws TeiidComponentException if resolving fails
- */
- static void resolveXMLOrderBy(OrderBy orderBy, GroupContext externalGroups, Collection<ElementSymbol> validElements, QueryMetadataInterface metadata)
- throws QueryMetadataException, TeiidComponentException, QueryResolverException {
-
- // Walk through each element in OrderBy clause and check against valid elements
- Collection<ElementSymbol> orderElems = ElementCollectorVisitor.getElements(orderBy, false);
- for (ElementSymbol orderElem : orderElems) {
- resolveElement(orderElem, validElements, externalGroups, metadata);
- }
- }
-
- /**
- * Resolve Element method.
- * @param elem
- * @param validElements
- * @param externalGroups
- * @param metadata
- * @throws QueryResolverException
- * @throws QueryMetadataException
- * @throws TeiidComponentException
- */
- static void resolveElement(ElementSymbol elem, Collection<ElementSymbol> validElements, GroupContext externalGroups, QueryMetadataInterface metadata)
- throws QueryResolverException, QueryMetadataException, TeiidComponentException {
-
- // Get exact matching name
- String critElemName = elem.getName();
- String critElemNameSuffix = "." + elem.getCanonicalName(); //$NON-NLS-1$
-
- // Prepare results
- ElementSymbol exactMatch = null;
- List<ElementSymbol> partialMatches = new ArrayList<ElementSymbol>(2); // anything over 1 is an error and should be rare
-
- //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);
-
- // look up name based on ID match - will work for uuid version
- try {
-
- 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$
- }
- }
-
- 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)
- throws TeiidComponentException, QueryMetadataException {
-
- List<ElementSymbol> elements = new ArrayList<ElementSymbol>();
- String nodeName = metadata.getFullName(node.getMetadataID());
- for (ElementSymbol validElement : validElements) {
- String qualifiedName = validElement.getName();
- if (qualifiedName.equals(nodeName) || qualifiedName.startsWith(nodeName+ElementSymbol.SEPARATOR)) {
- elements.add(validElement);
- }
- }
- return elements;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/XMLQueryResolver.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/resolver/command/XMLQueryResolver.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/XMLQueryResolver.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/command/XMLQueryResolver.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,536 @@
+/*
+ * 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.resolver.command;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+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.SelectSymbol;
+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);
+ }
+
+ public void resolveCommand(Query query, GroupSymbol docGroup, TempMetadataAdapter metadata)
+ throws QueryMetadataException, QueryResolverException, TeiidComponentException {
+ // set isXML flag
+ 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> 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
+ root.addAll(collectTempElements(group, metadata));
+
+ Criteria crit = query.getCriteria();
+ OrderBy orderBy = query.getOrderBy();
+
+ if(crit != null) {
+ 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, root, metadata);
+ }
+
+ //we throw exceptions in these cases, since the clauses will not be resolved
+ if (query.getGroupBy() != null) {
+ throw new QueryResolverException(QueryPlugin.Util.getString("ERR.015.012.0031")); //$NON-NLS-1$
+ }
+
+ if (query.getHaving() != null) {
+ throw new QueryResolverException(QueryPlugin.Util.getString("ERR.015.012.0032")); //$NON-NLS-1$
+ }
+ }
+
+ 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
+ * @param group GroupSymbol
+ * @param externalGroups Collection of external groups
+ * @param validElements Collection of valid elements
+ * @param metadata QueryMetadataInterface the metadata(for resolving criteria on temp groups)
+ * @throws QueryResolverException if resolving order by fails
+ * @throws QueryMetadataException if resolving fails
+ * @throws TeiidComponentException if resolving fails
+ */
+ void resolveXMLSelect(boolean subquery, Query query, GroupSymbol group, ResolvingNode validElements, QueryMetadataInterface metadata)
+ throws QueryMetadataException, TeiidComponentException, QueryResolverException {
+
+ GroupContext externalGroups = null;
+
+ Select select = query.getSelect();
+ // Allow SELECT DISTINCT, which is ignored. It is meaningless except for
+ // self-entity relation using relate() functionality
+
+ List elements = select.getSymbols();
+ for (int i = 0; i < elements.size(); i++) {
+ SelectSymbol ss = (SelectSymbol) elements.get(i);
+
+ if (ss instanceof ElementSymbol) {
+ // Here we make an assumption that: all elements named with "xml" must use qualified name
+ // rather than a simple "xml" in order to distinguish it from "SELECT xml" and
+ // "SELECT model.document.xml" case, both of whom stand for selecting the whole document.
+
+ // Then "SELECT xml" or "SELECT model.document.xml" can only stand for one meaning with two cases:
+ // 1) whole document
+ // 2) whole document, root name = "xml", too
+
+ // 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(!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.values());
+ select.addSymbol(all);
+ query.setSelect(select);
+ return;
+ }
+ // normal elements
+ resolveElement((ElementSymbol)ss, validElements, externalGroups, metadata);
+ } else if (ss instanceof AllInGroupSymbol) {
+ // 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);
+
+ // Check for case where we have model.doc.*
+ if(elementPart.equalsIgnoreCase(group.getName())) {
+ select.clearSymbols();
+ AllSymbol all = new AllSymbol();
+ all.setElementSymbols(validElements.values());
+ select.addSymbol(all);
+ query.setSelect(select);
+ } else {
+ // resovlve the node which is specified
+ ElementSymbol elementSymbol = new ElementSymbol(elementPart);
+ resolveElement(elementSymbol, validElements, externalGroups, metadata);
+
+ // now find all the elements under this node and set as elements.
+ List<ElementSymbol> elementsInNode = getElementsUnderNode(elementSymbol.getMetadataID(), validElements.values(), metadata);
+ ((AllInGroupSymbol)ss).setElementSymbols(elementsInNode);
+ }
+ } else if (ss instanceof AllSymbol) {
+ AllSymbol all = (AllSymbol)ss;
+ all.setElementSymbols(validElements.values());
+ return;
+ } else if (ss instanceof ExpressionSymbol) {
+ throw new QueryResolverException(QueryPlugin.Util.getString("XMLQueryResolver.no_expressions_in_select")); //$NON-NLS-1$
+ } else if (ss instanceof AliasSymbol) {
+ throw new QueryResolverException("ERR.015.008.0070", QueryPlugin.Util.getString("ERR.015.008.0070")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ }
+ }
+
+ 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());
+ for (Object tempGroupID : tempGroups) {
+ String name = metadata.getFullName(tempGroupID);
+ GroupSymbol tempGroup = new GroupSymbol(name);
+ tempGroup.setMetadataID(tempGroupID);
+
+ validElements.addAll(ResolverUtil.resolveElementsInGroup(tempGroup, metadata));
+ }
+ 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
+ * temporary table at the root of the document model (if a temp table exists there).</p>
+ * <p>A QueryResolverException will be thrown under the following circumstances:
+ * <ol>
+ * <li>the elements of the XML criteria cannot be resolved</li>
+ * <li>the "@" attribute prefix is used to specify that the node is an attribute, but
+ * a document node is found that is an element</li>
+ * <li>an element is supplied in the criteria and is ambiguous (multiple
+ * document nodes and/or root temp table elements exist which have that name)</li>
+ * </ol></p>
+ * <p>If an element is supplied in the criteria and is ambiguous (multiple document nodes and/or
+ * root temp table elements of that name exist)
+ * @param criteria The criteria object that should be resolved
+ * @param group The group on the query.
+ * @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(LanguageObject criteria,GroupContext externalGroups, ResolvingNode validElements, QueryMetadataInterface metadata)
+ throws QueryMetadataException, TeiidComponentException, QueryResolverException {
+
+ // Walk through each element in criteria and check against valid elements
+ Collection<ElementSymbol> critElems = ElementCollectorVisitor.getElements(criteria, false);
+ for (ElementSymbol critElem : critElems) {
+ if(! critElem.isExternalReference()) {
+ resolveElement(critElem, validElements, externalGroups, metadata);
+ }
+ }
+ }
+
+ /**
+ * Resolve OrderBy clause specified on the XML Query.
+ * @param orderBy Order By clause in user command
+ * @param group GroupSymbol
+ * @param externalGroups Collection of external groups
+ * @param validElements Collection of valid elements
+ * @param metadata QueryMetadataInterface the metadata(for resolving criteria on temp groups)
+ * @throws QueryResolverException if resolving order by fails
+ * @throws QueryMetadataException if resolving fails
+ * @throws TeiidComponentException if resolving fails
+ */
+ 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
+ Collection<ElementSymbol> orderElems = ElementCollectorVisitor.getElements(orderBy, false);
+ for (ElementSymbol orderElem : orderElems) {
+ resolveElement(orderElem, validElements, externalGroups, metadata);
+ }
+ }
+
+ /**
+ * Resolve Element method.
+ * @param elem
+ * @param validElements
+ * @param externalGroups
+ * @param metadata
+ * @throws QueryResolverException
+ * @throws QueryMetadataException
+ * @throws TeiidComponentException
+ */
+ static void resolveElement(ElementSymbol elem, ResolvingNode validElements, GroupContext externalGroups, QueryMetadataInterface metadata)
+ throws QueryResolverException, QueryMetadataException, TeiidComponentException {
+
+ // Get exact matching name
+ String partialName = elem.getName();
+ String fullName = partialName;
+
+ 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<ElementSymbol> partialMatches = current.values();
+
+ 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$
+ }
+
+ 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> getElementsUnderNode(Object mid, Collection<ElementSymbol> validElements, QueryMetadataInterface metadata)
+ throws TeiidComponentException, QueryMetadataException {
+
+ List<ElementSymbol> elements = new ArrayList<ElementSymbol>();
+ String nodeName = metadata.getFullName(mid);
+ for (ElementSymbol validElement : validElements) {
+ String qualifiedName = validElement.getName();
+ if (StringUtil.startsWithIgnoreCase(qualifiedName, nodeName) && (qualifiedName.length() == nodeName.length() || qualifiedName.charAt(nodeName.length()) == '.')) {
+ elements.add(validElement);
+ }
+ }
+ return elements;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1098 +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.resolver.util;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-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;
-import java.util.Map;
-import java.util.Set;
-
-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.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.types.TransformationException;
-import org.teiid.core.types.DataTypeManager.DefaultDataTypes;
-import org.teiid.core.util.StringUtil;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.function.FunctionDescriptor;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.metadata.GroupInfo;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.StoredProcedureInfo;
-import org.teiid.query.metadata.SupportConstants;
-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.RuleChooseJoinStrategy;
-import org.teiid.query.optimizer.relational.rules.RuleRaiseAccess;
-import org.teiid.query.sql.LanguageObject;
-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.FromClause;
-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.OrderBy;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.SubqueryContainer;
-import org.teiid.query.sql.lang.UnaryFromClause;
-import org.teiid.query.sql.symbol.AbstractCaseExpression;
-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.Function;
-import org.teiid.query.sql.symbol.GroupSymbol;
-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.util.SymbolMap;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-
-
-/**
- * Utilities used during resolution
- */
-public class ResolverUtil {
-
- public static class ResolvedLookup {
- private GroupSymbol group;
- private ElementSymbol keyElement;
- private ElementSymbol returnElement;
-
- void setGroup(GroupSymbol group) {
- this.group = group;
- }
- public GroupSymbol getGroup() {
- return group;
- }
- void setKeyElement(ElementSymbol keyElement) {
- this.keyElement = keyElement;
- }
- public ElementSymbol getKeyElement() {
- return keyElement;
- }
- void setReturnElement(ElementSymbol returnElement) {
- this.returnElement = returnElement;
- }
- public ElementSymbol getReturnElement() {
- return returnElement;
- }
- }
-
- // Can't construct
- private ResolverUtil() {}
-
- /*
- * Type Conversion Utilities
- */
-
- /**
- * Gets the most specific type to which all the given types have an implicit
- * conversion. The method decides a common type as follows:
- * <ul>
- * <li>If one or more of the given types is a candidate, then this method
- * will return the candidate that occurs first in the given array.
- * This is why the order of the names in the array is important. </li>
- * <li>Otherwise, if none of them is a candidate, this method will attempt
- * to find a common type to which all of them can be implicitly
- * converted.</li>
- * <li>Otherwise this method is unable to find a common type to which all
- * the given types can be implicitly converted, and therefore returns
- * a null.</li>
- * </ul>
- * @param typeNames an ordered array of unique type names.
- * @return a type name to which all the given types can be converted
- */
- public static String getCommonType(String[] typeNames) {
- if (typeNames == null || typeNames.length == 0) {
- return null;
- }
- // If there is only one type, then simply return it
- if (typeNames.length == 1) {
- return typeNames[0];
- }
- // A type can be implicitly converted to itself, so we put the implicit
- // conversions as well as the original type in the working list of
- // conversions.
- HashSet<String> commonConversions = new LinkedHashSet<String>();
- commonConversions.add(typeNames[0]);
- commonConversions.addAll(DataTypeManager.getImplicitConversions(typeNames[0]));
- for (int i = 1; i < typeNames.length; i++ ) {
- HashSet<String> conversions = new LinkedHashSet<String>(DataTypeManager.getImplicitConversions(typeNames[i]));
- conversions.add(typeNames[i]);
- // Equivalent to set intersection
- commonConversions.retainAll(conversions);
- }
- if (commonConversions.isEmpty()) {
- return null;
- }
- for (int i = 0; i < typeNames.length; i++) {
- if (commonConversions.contains(typeNames[i])) {
- return typeNames[i];
- }
- }
- commonConversions.remove(DefaultDataTypes.STRING);
- commonConversions.remove(DefaultDataTypes.OBJECT);
- if (!commonConversions.isEmpty()) {
- return commonConversions.iterator().next();
- }
- return null;
- }
-
- /**
- * Gets whether there exists an implicit conversion from the source type to
- * the target type
- * @param fromType
- * @param toType
- * @return true if there exists an implicit conversion from the
- * <code>fromType</code> to the <code>toType</code>.
- */
- public static boolean canImplicitlyConvert(String fromType, String toType) {
- if (fromType.equals(toType)) return true;
- return DataTypeManager.isImplicitConversion(fromType, toType);
- }
-
- /**
- * Replaces a sourceExpression with a conversion of the source expression
- * to the target type. If the source type and target type are the same,
- * this method does nothing.
- * @param sourceExpression
- * @param targetTypeName
- * @return
- * @throws QueryResolverException
- */
- public static Expression convertExpression(Expression sourceExpression, String targetTypeName, QueryMetadataInterface metadata) throws QueryResolverException {
- return convertExpression(sourceExpression,
- DataTypeManager.getDataTypeName(sourceExpression.getType()),
- targetTypeName, metadata);
- }
-
- /**
- * Replaces a sourceExpression with a conversion of the source expression
- * to the target type. If the source type and target type are the same,
- * this method does nothing.
- * @param sourceExpression
- * @param sourceTypeName
- * @param targetTypeName
- * @return
- * @throws QueryResolverException
- */
- public static Expression convertExpression(Expression sourceExpression, String sourceTypeName, String targetTypeName, QueryMetadataInterface metadata) throws QueryResolverException {
- if (sourceTypeName.equals(targetTypeName)) {
- return sourceExpression;
- }
-
- if(canImplicitlyConvert(sourceTypeName, targetTypeName)
- || (sourceExpression instanceof Constant && convertConstant(sourceTypeName, targetTypeName, (Constant)sourceExpression) != null)) {
- return getConversion(sourceExpression, sourceTypeName, targetTypeName, true, metadata.getFunctionLibrary());
- }
-
- //Expression is wrong type and can't convert
- throw new QueryResolverException("ERR.015.008.0041", QueryPlugin.Util.getString("ERR.015.008.0041", new Object[] {targetTypeName, sourceExpression, sourceTypeName})); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public static Constant convertConstant(String sourceTypeName,
- String targetTypeName,
- Constant constant) {
- if (!DataTypeManager.isTransformable(sourceTypeName, targetTypeName)) {
- return null;
- }
-
- try {
- //try to get the converted constant, if this fails then it is not in a valid format
- Constant result = getProperlyTypedConstant(constant.getValue(), DataTypeManager.getDataTypeClass(targetTypeName));
-
- if (DataTypeManager.DefaultDataTypes.STRING.equals(sourceTypeName)) {
- if (DataTypeManager.DefaultDataTypes.CHAR.equals(targetTypeName)) {
- String value = (String)constant.getValue();
- if (value != null && value.length() != 1) {
- return null;
- }
- }
- return result;
- }
-
- //for non-strings, ensure that the conversion is consistent
- if (!DataTypeManager.isTransformable(targetTypeName, sourceTypeName)) {
- return null;
- }
-
- if (!(constant.getValue() instanceof Comparable)) {
- return null; //this is the case for xml constants
- }
-
- Constant reverse = getProperlyTypedConstant(result.getValue(), constant.getType());
-
- if (((Comparable)constant.getValue()).compareTo(reverse.getValue()) == 0) {
- return result;
- }
- } catch (QueryResolverException e) {
-
- }
-
- return null;
- }
-
- public static Function getConversion(Expression sourceExpression,
- String sourceTypeName,
- String targetTypeName,
- boolean implicit, FunctionLibrary library) {
- Class<?> srcType = DataTypeManager.getDataTypeClass(sourceTypeName);
-
- FunctionDescriptor fd = library.findTypedConversionFunction(srcType, DataTypeManager.getDataTypeClass(targetTypeName));
-
- Function conversion = new Function(fd.getName(), new Expression[] { sourceExpression, new Constant(targetTypeName) });
- conversion.setType(DataTypeManager.getDataTypeClass(targetTypeName));
- conversion.setFunctionDescriptor(fd);
- if (implicit) {
- conversion.makeImplicit();
- }
-
- return conversion;
- }
-
- /**
- * Utility to set the type of an expression if it is a Reference and has a null type.
- * @param expression the expression to test
- * @param targetType the target type, if the expression's type is null.
- * @throws QueryResolverException if unable to set the reference type to the target type.
- */
- public static void setDesiredType(Expression expression, Class<?> targetType, LanguageObject surroundingExpression) throws QueryResolverException {
- if (expression instanceof Reference) {
- Reference ref = (Reference)expression;
- if (ref.isPositional() && ref.getType() == null) {
- if (targetType == null) {
- throw new QueryResolverException("ERR.015.008.0026", QueryPlugin.Util.getString("ERR.015.008.0026", surroundingExpression)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- ref.setType(targetType);
- }
- } else if (expression instanceof Function) {
- Function f = (Function)expression;
- if (f.getType() == null) {
- f.setType(targetType);
- }
- }
- }
-
- /**
- * Attempt to resolve the order by throws QueryResolverException if the
- * symbol is not of SingleElementSymbol type
- *
- * @param orderBy
- * @param fromClauseGroups
- * groups of the FROM clause of the query (for resolving
- * ambiguous unqualified element names), or empty List if a Set
- * Query Order By is being resolved
- * @param knownElements
- * resolved elements from SELECT clause, which are only ones
- * allowed to be in ORDER BY
- * @param metadata
- * QueryMetadataInterface
- */
- public static void resolveOrderBy(OrderBy orderBy, QueryCommand command, QueryMetadataInterface metadata)
- throws QueryResolverException, QueryMetadataException, TeiidComponentException {
-
- List<SingleElementSymbol> knownElements = command.getProjectedQuery().getSelect().getProjectedSymbols();
-
- boolean isSimpleQuery = false;
- List fromClauseGroups = Collections.emptyList();
-
- if (command instanceof Query) {
- Query query = (Query)command;
- isSimpleQuery = !query.getSelect().isDistinct() && !query.hasAggregates();
- if (query.getFrom() != null) {
- fromClauseGroups = query.getFrom().getGroups();
- }
- }
-
- // Cached state, if needed
- String[] knownShortNames = new String[knownElements.size()];
- List<Expression> expressions = new ArrayList<Expression>(knownElements.size());
-
- for(int i=0; i<knownElements.size(); i++) {
- SingleElementSymbol knownSymbol = knownElements.get(i);
- expressions.add(SymbolMap.getExpression(knownSymbol));
- if (knownSymbol instanceof ExpressionSymbol) {
- continue;
- }
-
- String name = knownSymbol.getShortName();
-
- knownShortNames[i] = name;
- }
-
- for (int i = 0; i < orderBy.getVariableCount(); i++) {
- SingleElementSymbol sortKey = orderBy.getVariable(i);
- if (sortKey instanceof ElementSymbol) {
- ElementSymbol symbol = (ElementSymbol)sortKey;
- String groupPart = null;
- if (symbol.getGroupSymbol() != null) {
- groupPart = symbol.getGroupSymbol().getName();
- }
- String symbolName = symbol.getName();
- String shortName = symbol.getShortName();
- if (groupPart == null) {
- int position = -1;
- SingleElementSymbol matchedSymbol = null;
- // walk the SELECT col short names, looking for a match on the current ORDER BY 'short name'
- for(int j=0; j<knownShortNames.length; j++) {
- if( !shortName.equalsIgnoreCase( knownShortNames[j] )) {
- continue;
- }
- // if we already have a matched symbol, matching again here means it is duplicate/ambiguous
- if(matchedSymbol != null) {
- if (!matchedSymbol.equals(knownElements.get(j))) {
- throw new QueryResolverException("ERR.015.008.0042", QueryPlugin.Util.getString("ERR.015.008.0042", symbolName)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- continue;
- }
- matchedSymbol = knownElements.get(j);
- position = j;
- }
- if (matchedSymbol != null) {
- TempMetadataID tempMetadataID = new TempMetadataID(symbol.getName(), matchedSymbol.getType());
- symbol.setMetadataID(tempMetadataID);
- symbol.setType(matchedSymbol.getType());
- }
- if (position != -1) {
- orderBy.setExpressionPosition(i, position);
- continue;
- }
- }
- } else if (sortKey instanceof ExpressionSymbol) {
- // check for legacy positional
- ExpressionSymbol es = (ExpressionSymbol)sortKey;
- if (es.getExpression() instanceof Constant) {
- Constant c = (Constant)es.getExpression();
- int elementOrder = Integer.valueOf(c.getValue().toString()).intValue();
- // adjust for the 1 based index.
- if (elementOrder > knownElements.size() || elementOrder < 1) {
- throw new QueryResolverException(QueryPlugin.Util.getString("SQLParser.non_position_constant", c)); //$NON-NLS-1$
- }
- orderBy.setExpressionPosition(i, elementOrder - 1);
- continue;
- }
- }
- //handle order by expressions
- if (command instanceof SetQuery) {
- throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.setquery_order_expression", sortKey)); //$NON-NLS-1$
- }
- for (ElementSymbol symbol : ElementCollectorVisitor.getElements(sortKey, false)) {
- try {
- ResolverVisitor.resolveLanguageObject(symbol, fromClauseGroups, command.getExternalGroupContexts(), metadata);
- } catch(QueryResolverException e) {
- throw new QueryResolverException(e, "ERR.015.008.0043", QueryPlugin.Util.getString("ERR.015.008.0043", symbol.getName()) );//$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- ResolverVisitor.resolveLanguageObject(sortKey, metadata);
-
- int index = expressions.indexOf(SymbolMap.getExpression(sortKey));
- if (index == -1 && !isSimpleQuery) {
- throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.invalid_unrelated", sortKey)); //$NON-NLS-1$
- }
- orderBy.setExpressionPosition(i, index);
- }
- }
-
- /**
- * Get the default value for the parameter, which could be null
- * if the parameter is set to NULLABLE. If no default is available,
- * a QueryResolverException will be thrown.
- *
- * @param symbol ElementSymbol retrieved from metadata, fully-resolved
- * @param metadata QueryMetadataInterface
- * @return expr param (if it is non-null) or default value (if there is one)
- * or null Constant (if parameter is optional and therefore allows this)
- * @throws QueryResolverException if expr is null, parameter is required and no
- * default value is defined
- * @throws QueryMetadataException for error retrieving metadata
- * @throws TeiidComponentException
- * @since 4.3
- */
- public static Expression getDefault(ElementSymbol symbol, QueryMetadataInterface metadata) throws TeiidComponentException, QueryMetadataException, QueryResolverException {
- //Check if there is a default value, if so use it
- Object mid = symbol.getMetadataID();
- Class<?> type = symbol.getType();
-
- Object defaultValue = metadata.getDefaultValue(mid);
-
- if (defaultValue == null && !metadata.elementSupports(mid, SupportConstants.Element.NULL)) {
- throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.required_param", symbol.getOutputName())); //$NON-NLS-1$
- }
-
- return getProperlyTypedConstant(defaultValue, type);
- }
-
- /**
- * Construct a Constant with proper type, given the String default
- * value for the parameter and the parameter type. Throw a
- * QueryResolverException if the String can't be transformed.
- * @param defaultValue, either null or a String
- * @param parameterType modeled type of parameter (MetaMatrix runtime type)
- * @return Constant with proper type and default value Object of proper Class. Will
- * be null Constant if defaultValue is null.
- * @throws QueryResolverException if TransformationException is encountered
- * @since 4.3
- */
- private static Constant getProperlyTypedConstant(Object defaultValue,
- Class parameterType)
- throws QueryResolverException{
- try {
- Object newValue = DataTypeManager.transformValue(defaultValue, parameterType);
- return new Constant(newValue, parameterType);
- } catch (TransformationException e) {
- throw new QueryResolverException(e, QueryPlugin.Util.getString("ResolverUtil.error_converting_value_type", defaultValue, defaultValue.getClass(), parameterType)); //$NON-NLS-1$
- }
- }
-
- /**
- * Returns the resolved elements in the given group. This method has the side effect of caching the resolved elements on the group object.
- * The resolved elements may not contain non-selectable columns depending on the metadata first used for resolving.
- *
- */
- public static List<ElementSymbol> resolveElementsInGroup(GroupSymbol group, QueryMetadataInterface metadata)
- throws QueryMetadataException, TeiidComponentException {
- return new ArrayList<ElementSymbol>(getGroupInfo(group, metadata).getSymbolList());
- }
-
- static GroupInfo getGroupInfo(GroupSymbol group,
- QueryMetadataInterface metadata)
- throws TeiidComponentException, QueryMetadataException {
- String key = GroupInfo.CACHE_PREFIX + group.getCanonicalName();
- GroupInfo groupInfo = (GroupInfo)metadata.getFromMetadataCache(group.getMetadataID(), key);
-
- if (groupInfo == null) {
- group = group.clone();
- // get all elements from the metadata
- List elementIDs = metadata.getElementIDsInGroupID(group.getMetadataID());
-
- LinkedHashMap<Object, ElementSymbol> symbols = new LinkedHashMap<Object, ElementSymbol>(elementIDs.size());
-
- for (Object elementID : elementIDs) {
- String elementName = metadata.getName(elementID);
- // Form an element symbol from the ID
- ElementSymbol element = new ElementSymbol(elementName, DataTypeManager.getCanonicalString(StringUtil.toUpperCase(elementName)), group);
- element.setMetadataID(elementID);
- element.setType( DataTypeManager.getDataTypeClass(metadata.getElementType(element.getMetadataID())) );
-
- symbols.put(elementID, element);
- }
- groupInfo = new GroupInfo(symbols);
- metadata.addToMetadataCache(group.getMetadataID(), key, groupInfo);
- }
- return groupInfo;
- }
-
- /**
- * When access patterns are flattened, they are an approximation the user
- * may need to enter as criteria.
- *
- * @param metadata
- * @param groups
- * @param flatten
- * @return
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- */
- public static List getAccessPatternElementsInGroups(final QueryMetadataInterface metadata, Collection groups, boolean flatten) throws TeiidComponentException, QueryMetadataException {
- List accessPatterns = null;
- Iterator i = groups.iterator();
- while (i.hasNext()){
-
- GroupSymbol group = (GroupSymbol)i.next();
-
- //Check this group for access pattern(s).
- Collection accessPatternIDs = metadata.getAccessPatternsInGroup(group.getMetadataID());
- if (accessPatternIDs != null && accessPatternIDs.size() > 0){
- Iterator j = accessPatternIDs.iterator();
- if (accessPatterns == null){
- accessPatterns = new ArrayList();
- }
- while (j.hasNext()) {
- List elements = metadata.getElementIDsInAccessPattern(j.next());
- GroupInfo groupInfo = getGroupInfo(group, metadata);
- List result = new ArrayList(elements.size());
- for (Iterator iterator = elements.iterator(); iterator.hasNext();) {
- Object id = iterator.next();
- ElementSymbol symbol = groupInfo.getSymbol(id);
- assert symbol != null;
- result.add(symbol);
- }
- if (flatten) {
- accessPatterns.addAll(result);
- } else {
- accessPatterns.add(new AccessPattern(result));
- }
- }
- }
- }
-
- return accessPatterns;
- }
-
- public static void resolveLimit(Limit limit) throws QueryResolverException {
- if (limit.getOffset() != null) {
- setDesiredType(limit.getOffset(), DataTypeManager.DefaultDataClasses.INTEGER, limit);
- }
- setDesiredType(limit.getRowLimit(), DataTypeManager.DefaultDataClasses.INTEGER, limit);
- }
-
- public static void resolveImplicitTempGroup(TempMetadataAdapter metadata, GroupSymbol symbol, List symbols)
- throws TeiidComponentException, QueryResolverException {
-
- if (symbol.isImplicitTempGroupSymbol()) {
- if (metadata.getMetadataStore().getTempElementElementIDs(symbol.getCanonicalName())==null) {
- addTempGroup(metadata, symbol, symbols, true);
- }
- ResolverUtil.resolveGroup(symbol, metadata);
- }
- }
-
- public static TempMetadataID addTempGroup(TempMetadataAdapter metadata,
- GroupSymbol symbol,
- List<? extends SingleElementSymbol> symbols, boolean tempTable) throws QueryResolverException {
- HashSet<String> names = new HashSet<String>();
- for (SingleElementSymbol ses : symbols) {
- if (!names.add(ses.getShortCanonicalName())) {
- throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.duplicateName", symbol, ses.getShortName())); //$NON-NLS-1$
- }
- }
-
- if (tempTable) {
- resolveNullLiterals(symbols);
- }
- TempMetadataStore store = metadata.getMetadataStore();
- return store.addTempGroup(symbol.getName(), symbols, !tempTable, tempTable);
- }
-
- public static TempMetadataID addTempTable(TempMetadataAdapter metadata,
- GroupSymbol symbol,
- List<? extends SingleElementSymbol> symbols) throws QueryResolverException {
- return addTempGroup(metadata, symbol, symbols, true);
- }
-
- /**
- * Look for a null literal in the SELECT clause and set it's type to STRING. This ensures that
- * the result set metadata retrieved for this query will be properly set to something other than
- * the internal NullType. Added for defect 15437.
- *
- * @param select The select clause
- * @since 4.2
- */
- public static void resolveNullLiterals(List symbols) {
- for (int i = 0; i < symbols.size(); i++) {
- SelectSymbol selectSymbol = (SelectSymbol) symbols.get(i);
-
- if (!(selectSymbol instanceof SingleElementSymbol)) {
- continue;
- }
-
- SingleElementSymbol symbol = (SingleElementSymbol)selectSymbol;
-
- setTypeIfNull(symbol, DataTypeManager.DefaultDataClasses.STRING);
- }
- }
-
- public static void setTypeIfNull(SingleElementSymbol symbol,
- Class<?> replacement) {
- if(!DataTypeManager.DefaultDataClasses.NULL.equals(symbol.getType()) && symbol.getType() != null) {
- return;
- }
- if(symbol instanceof AliasSymbol) {
- symbol = ((AliasSymbol)symbol).getSymbol();
- }
- if(symbol instanceof ExpressionSymbol && !(symbol instanceof AggregateSymbol)) {
- ExpressionSymbol exprSymbol = (ExpressionSymbol) symbol;
- Expression expr = exprSymbol.getExpression();
-
- if(expr instanceof Constant) {
- exprSymbol.setExpression(new Constant(null, replacement));
- } else if (expr instanceof AbstractCaseExpression) {
- ((AbstractCaseExpression)expr).setType(replacement);
- } else if (expr instanceof ScalarSubquery) {
- ((ScalarSubquery)expr).setType(replacement);
- } else {
- try {
- ResolverUtil.setDesiredType(expr, replacement, symbol);
- } catch (QueryResolverException e) {
- //cannot happen
- }
- }
- } else if(symbol instanceof ElementSymbol) {
- ElementSymbol elementSymbol = (ElementSymbol)symbol;
- elementSymbol.setType(replacement);
- }
- }
-
- /**
- *
- * @param groupContext
- * @param groups
- * @param metadata
- * @return the List of groups that match the given groupContext out of the supplied collection
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- */
- public static List<GroupSymbol> findMatchingGroups(String groupContext,
- Collection<GroupSymbol> groups,
- QueryMetadataInterface metadata) throws TeiidComponentException,
- QueryMetadataException {
-
- if (groups == null) {
- return null;
- }
-
- LinkedList<GroupSymbol> matchedGroups = new LinkedList<GroupSymbol>();
-
- if (groupContext == null) {
- matchedGroups.addAll(groups);
- } else {
- for (GroupSymbol group : groups) {
- String fullName = group.getCanonicalName();
- if (nameMatchesGroup(groupContext, matchedGroups, group, fullName)) {
- if (groupContext.length() == fullName.length()) {
- return matchedGroups;
- }
- continue;
- }
-
- // don't try to vdb qualify temp metadata
- if (group.getMetadataID() instanceof TempMetadataID) {
- continue;
- }
-
- String actualVdbName = metadata.getVirtualDatabaseName();
-
- if (actualVdbName != null) {
- fullName = actualVdbName.toUpperCase() + ElementSymbol.SEPARATOR + fullName;
- if (nameMatchesGroup(groupContext, matchedGroups, group, fullName)
- && groupContext.length() == fullName.length()) {
- return matchedGroups;
- }
- }
- }
- }
-
- return matchedGroups;
- }
-
-
- public static boolean nameMatchesGroup(String groupContext,
- String fullName) {
- //if there is a name match, make sure that it is the full name or a proper qualifier
- if (fullName.endsWith(groupContext)) {
- int matchIndex = fullName.length() - groupContext.length();
- if (matchIndex == 0 || fullName.charAt(matchIndex - 1) == '.') {
- return true;
- }
- }
- return false;
- }
-
- private static boolean nameMatchesGroup(String groupContext,
- LinkedList<GroupSymbol> matchedGroups,
- GroupSymbol group,
- String fullName) {
- if (nameMatchesGroup(groupContext, fullName)) {
- matchedGroups.add(group);
- return true;
- }
- return false;
- }
-
- /**
- * Check the type of the (left) expression and the type of the single
- * projected symbol of the subquery. If they are not the same, try to find
- * an implicit conversion from the former type to the latter type, and wrap
- * the left expression in that conversion function; otherwise throw an
- * Exception.
- * @param expression the Expression on one side of the predicate criteria
- * @param crit the SubqueryContainer containing the subquery Command of the other
- * side of the predicate criteria
- * @return implicit conversion Function, or null if none is necessary
- * @throws QueryResolverException if a conversion is necessary but none can
- * be found
- */
- static Expression resolveSubqueryPredicateCriteria(Expression expression, SubqueryContainer crit, QueryMetadataInterface metadata)
- throws QueryResolverException {
-
- // Check that type of the expression is same as the type of the
- // single projected symbol of the subquery
- Class exprType = expression.getType();
- if(exprType == null) {
- throw new QueryResolverException("ERR.015.008.0030", QueryPlugin.Util.getString("ERR.015.008.0030", expression)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- String exprTypeName = DataTypeManager.getDataTypeName(exprType);
-
- Collection<SingleElementSymbol> projectedSymbols = crit.getCommand().getProjectedSymbols();
- if (projectedSymbols.size() != 1){
- throw new QueryResolverException("ERR.015.008.0032", QueryPlugin.Util.getString("ERR.015.008.0032", crit.getCommand())); //$NON-NLS-1$ //$NON-NLS-2$
- }
- Class<?> subqueryType = projectedSymbols.iterator().next().getType();
- String subqueryTypeName = DataTypeManager.getDataTypeName(subqueryType);
- Expression result = null;
- try {
- result = convertExpression(expression, exprTypeName, subqueryTypeName, metadata);
- } catch (QueryResolverException qre) {
- throw new QueryResolverException(qre, "ERR.015.008.0033", QueryPlugin.Util.getString("ERR.015.008.0033", crit)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return result;
- }
-
- public static ResolvedLookup resolveLookup(Function lookup, QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
- Expression[] args = lookup.getArgs();
- ResolvedLookup result = new ResolvedLookup();
- // Special code to handle setting return type of the lookup function to match the type of the return element
- if( !(args[0] instanceof Constant) || !(args[1] instanceof Constant) || !(args[2] instanceof Constant)) {
- throw new QueryResolverException("ERR.015.008.0063", QueryPlugin.Util.getString("ERR.015.008.0063")); //$NON-NLS-1$ //$NON-NLS-2$
- }
- // If code table name in lookup function refers to temp group throw exception
- GroupSymbol groupSym = new GroupSymbol((String) ((Constant)args[0]).getValue());
- try {
- groupSym.setMetadataID(metadata.getGroupID((String) ((Constant)args[0]).getValue()));
- if (groupSym.getMetadataID() instanceof TempMetadataID) {
- throw new QueryResolverException("ERR.015.008.0065", QueryPlugin.Util.getString("ERR.015.008.0065", ((Constant)args[0]).getValue())); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } catch(QueryMetadataException e) {
- throw new QueryResolverException("ERR.015.008.0062", QueryPlugin.Util.getString("ERR.015.008.0062", ((Constant)args[0]).getValue())); //$NON-NLS-1$ //$NON-NLS-2$
- }
- result.setGroup(groupSym);
-
- List<GroupSymbol> groups = Arrays.asList(groupSym);
-
- String returnElementName = (String) ((Constant)args[0]).getValue() + "." + (String) ((Constant)args[1]).getValue(); //$NON-NLS-1$
- ElementSymbol returnElement = new ElementSymbol(returnElementName);
- try {
- ResolverVisitor.resolveLanguageObject(returnElement, groups, metadata);
- } catch(QueryMetadataException e) {
- throw new QueryResolverException("ERR.015.008.0062", QueryPlugin.Util.getString("ERR.015.008.0062", returnElementName)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- result.setReturnElement(returnElement);
-
- String keyElementName = (String) ((Constant)args[0]).getValue() + "." + (String) ((Constant)args[2]).getValue(); //$NON-NLS-1$
- ElementSymbol keyElement = new ElementSymbol(keyElementName);
- try {
- ResolverVisitor.resolveLanguageObject(keyElement, groups, metadata);
- } catch(QueryMetadataException e) {
- throw new QueryResolverException("ERR.015.008.0062", QueryPlugin.Util.getString("ERR.015.008.0062", keyElementName)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- result.setKeyElement(keyElement);
- args[3] = convertExpression(args[3], DataTypeManager.getDataTypeName(keyElement.getType()), metadata);
- return result;
- }
-
- private static QueryResolverException handleUnresolvedGroup(GroupSymbol symbol, String description) {
- UnresolvedSymbolDescription usd = new UnresolvedSymbolDescription(symbol.toString(), description);
- QueryResolverException e = new QueryResolverException(usd.getDescription()+": "+usd.getSymbol()); //$NON-NLS-1$
- e.setUnresolvedSymbols(Arrays.asList(usd));
- return e;
- }
-
- public static void resolveGroup(GroupSymbol symbol, QueryMetadataInterface metadata)
- throws TeiidComponentException, QueryResolverException {
-
- if (symbol.getMetadataID() != null){
- return;
- }
-
- // determine the "metadataID" part of the symbol to look up
- String potentialID = symbol.getNonCorrelationName();
-
- String name = symbol.getName();
- String definition = symbol.getDefinition();
-
- Object groupID = null;
- try {
- // get valid GroupID for possibleID - this may throw exceptions if group is invalid
- groupID = metadata.getGroupID(potentialID);
- } catch(QueryMetadataException e) {
- // didn't find this group ID
- }
-
- // If that didn't work, try to strip a vdb name from potentialID
- String vdbName = null;
- if(groupID == null) {
- String[] parts = potentialID.split("\\.", 2); //$NON-NLS-1$
- if (parts.length > 1 && parts[0].equalsIgnoreCase(metadata.getVirtualDatabaseName())) {
- try {
- groupID = metadata.getGroupID(parts[1]);
- } catch(QueryMetadataException e) {
- // ignore - just didn't find it
- }
- if(groupID != null) {
- potentialID = parts[1];
- vdbName = parts[0];
- }
- }
- }
-
- // the group could be partially qualified, verify that this group exists
- // and there is only one group that matches the given partial name
- if(groupID == null) {
- Collection groupNames = null;
- try {
- groupNames = metadata.getGroupsForPartialName(potentialID);
- } catch(QueryMetadataException e) {
- // ignore - just didn't find it
- }
-
- if(groupNames != null) {
- int matches = groupNames.size();
- if(matches == 1) {
- potentialID = (String) groupNames.iterator().next();
- try {
- // get valid GroupID for possibleID - this may throw exceptions if group is invalid
- groupID = metadata.getGroupID(potentialID);
- //set group full name
- if(symbol.getDefinition() != null){
- symbol.setDefinition(potentialID);
- }else{
- symbol.setName(potentialID);
- }
- } catch(QueryMetadataException e) {
- // didn't find this group ID
- }
- } else if(matches > 1) {
- throw handleUnresolvedGroup(symbol, QueryPlugin.Util.getString("ERR.015.008.0055")); //$NON-NLS-1$
- }
- }
- }
-
- if (groupID == null || metadata.isProcedure(groupID)) {
- //try procedure relational resolving
- try {
- StoredProcedureInfo storedProcedureInfo = metadata.getStoredProcedureInfoForProcedure(potentialID);
- symbol.setProcedure(true);
- groupID = storedProcedureInfo.getProcedureID();
- } catch(QueryMetadataException e) {
- // just ignore
- }
- }
-
- if(groupID == null) {
- throw handleUnresolvedGroup(symbol, QueryPlugin.Util.getString("ERR.015.008.0056")); //$NON-NLS-1$
- }
- // set real metadata ID in the symbol
- symbol.setMetadataID(groupID);
- if(vdbName != null) {
- // reset name or definition to strip vdb name
- if(symbol.getDefinition() == null) {
- symbol.setName(potentialID);
- } else {
- symbol.setDefinition(potentialID);
- }
- }
- try {
- if (!symbol.isProcedure()) {
- symbol.setIsTempTable(metadata.isTemporaryTable(groupID));
- }
- } catch(QueryMetadataException e) {
- // should not come here
- }
-
- symbol.setOutputDefinition(definition);
- symbol.setOutputName(name);
- }
-
- public static void findKeyPreserved(Query query, Set<GroupSymbol> keyPreservingGroups, QueryMetadataInterface metadata)
- throws TeiidComponentException, QueryMetadataException {
- if (query.getFrom() == null) {
- return;
- }
- if (query.getFrom().getClauses().size() == 1) {
- findKeyPreserved((FromClause)query.getFrom().getClauses().get(0), keyPreservingGroups, metadata);
- return;
- }
- //non-ansi join
- Set<GroupSymbol> groups = new HashSet<GroupSymbol>(query.getFrom().getGroups());
- for (GroupSymbol groupSymbol : groups) {
- if (metadata.getUniqueKeysInGroup(groupSymbol.getMetadataID()).isEmpty()) {
- return;
- }
- }
- LinkedList<Expression> leftExpressions = new LinkedList<Expression>();
- LinkedList<Expression> rightExpressions = new LinkedList<Expression>();
- for (Criteria crit : Criteria.separateCriteriaByAnd(query.getCriteria())) {
- if (!(crit instanceof CompareCriteria)) {
- continue;
- }
- CompareCriteria cc = (CompareCriteria)crit;
- if (cc.getOperator() != CompareCriteria.EQ) {
- continue;
- }
- if (cc.getLeftExpression() instanceof ElementSymbol && cc.getRightExpression() instanceof ElementSymbol) {
- ElementSymbol left = (ElementSymbol)cc.getLeftExpression();
- ElementSymbol right = (ElementSymbol)cc.getRightExpression();
- int compare = left.getGroupSymbol().compareTo(right.getGroupSymbol());
- if (compare > 0) {
- leftExpressions.add(left);
- rightExpressions.add(right);
- } else if (compare != 0) {
- leftExpressions.add(right);
- rightExpressions.add(left);
- }
- }
- }
- HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits = createGroupMap(leftExpressions, rightExpressions);
- HashSet<GroupSymbol> tempSet = new HashSet<GroupSymbol>();
- HashSet<GroupSymbol> nonKeyPreserved = new HashSet<GroupSymbol>();
- for (GroupSymbol group : groups) {
- LinkedHashSet<GroupSymbol> visited = new LinkedHashSet<GroupSymbol>();
- LinkedList<GroupSymbol> toVisit = new LinkedList<GroupSymbol>();
- toVisit.add(group);
- while (!toVisit.isEmpty()) {
- GroupSymbol visiting = toVisit.removeLast();
- if (!visited.add(visiting) || nonKeyPreserved.contains(visiting)) {
- continue;
- }
- if (keyPreservingGroups.contains(visiting)) {
- visited.addAll(groups);
- break;
- }
- toVisit.addAll(findKeyPreserved(tempSet, Collections.singleton(visiting), crits, true, metadata, groups));
- toVisit.addAll(findKeyPreserved(tempSet, Collections.singleton(visiting), crits, false, metadata, groups));
- }
- if (visited.containsAll(groups)) {
- keyPreservingGroups.add(group);
- } else {
- nonKeyPreserved.add(group);
- }
- }
- }
-
- public static void findKeyPreserved(FromClause clause, Set<GroupSymbol> keyPreservingGroups, QueryMetadataInterface metadata)
- throws TeiidComponentException, QueryMetadataException {
- if (clause instanceof UnaryFromClause) {
- UnaryFromClause ufc = (UnaryFromClause)clause;
-
- if (!metadata.getUniqueKeysInGroup(ufc.getGroup().getMetadataID()).isEmpty()) {
- keyPreservingGroups.add(ufc.getGroup());
- }
- }
- if (clause instanceof JoinPredicate) {
- JoinPredicate jp = (JoinPredicate)clause;
- if (jp.getJoinType() == JoinType.JOIN_CROSS || jp.getJoinType() == JoinType.JOIN_FULL_OUTER) {
- return;
- }
- HashSet<GroupSymbol> leftPk = new HashSet<GroupSymbol>();
- findKeyPreserved(jp.getLeftClause(), leftPk, metadata);
- HashSet<GroupSymbol> rightPk = new HashSet<GroupSymbol>();
- findKeyPreserved(jp.getRightClause(), rightPk, metadata);
-
- if (leftPk.isEmpty() && rightPk.isEmpty()) {
- return;
- }
-
- HashSet<GroupSymbol> leftGroups = new HashSet<GroupSymbol>();
- HashSet<GroupSymbol> rightGroups = new HashSet<GroupSymbol>();
- jp.getLeftClause().collectGroups(leftGroups);
- jp.getRightClause().collectGroups(rightGroups);
-
- LinkedList<Expression> leftExpressions = new LinkedList<Expression>();
- LinkedList<Expression> rightExpressions = new LinkedList<Expression>();
- RuleChooseJoinStrategy.separateCriteria(leftGroups, rightGroups, leftExpressions, rightExpressions, jp.getJoinCriteria(), new LinkedList<Criteria>());
-
- HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits = createGroupMap(leftExpressions, rightExpressions);
- if (!leftPk.isEmpty() && (jp.getJoinType() == JoinType.JOIN_INNER || jp.getJoinType() == JoinType.JOIN_LEFT_OUTER)) {
- findKeyPreserved(keyPreservingGroups, leftPk, crits, true, metadata, rightPk);
- }
- if (!rightPk.isEmpty() && (jp.getJoinType() == JoinType.JOIN_INNER || jp.getJoinType() == JoinType.JOIN_RIGHT_OUTER)) {
- findKeyPreserved(keyPreservingGroups, rightPk, crits, false, metadata, leftPk);
- }
- }
- }
-
- private static HashMap<List<GroupSymbol>, List<HashSet<Object>>> createGroupMap(
- LinkedList<Expression> leftExpressions,
- LinkedList<Expression> rightExpressions) {
- HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits = new HashMap<List<GroupSymbol>, List<HashSet<Object>>>();
-
- for (int i = 0; i < leftExpressions.size(); i++) {
- Expression lexpr = leftExpressions.get(i);
- Expression rexpr = rightExpressions.get(i);
- if (!(lexpr instanceof ElementSymbol) || !(rexpr instanceof ElementSymbol)) {
- continue;
- }
- ElementSymbol les = (ElementSymbol)lexpr;
- ElementSymbol res = (ElementSymbol)rexpr;
- List<GroupSymbol> tbls = Arrays.asList(les.getGroupSymbol(), res.getGroupSymbol());
- List<HashSet<Object>> ids = crits.get(tbls);
- if (ids == null) {
- ids = Arrays.asList(new HashSet<Object>(), new HashSet<Object>());
- crits.put(tbls, ids);
- }
- ids.get(0).add(les.getMetadataID());
- ids.get(1).add(res.getMetadataID());
- }
- return crits;
- }
-
- static private HashSet<GroupSymbol> findKeyPreserved(Set<GroupSymbol> keyPreservingGroups,
- Set<GroupSymbol> pk,
- HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits, boolean left, QueryMetadataInterface metadata, Set<GroupSymbol> otherGroups)
- throws TeiidComponentException, QueryMetadataException {
- HashSet<GroupSymbol> result = new HashSet<GroupSymbol>();
- for (GroupSymbol gs : pk) {
- for (Map.Entry<List<GroupSymbol>, List<HashSet<Object>>> entry : crits.entrySet()) {
- if (!entry.getKey().get(left?0:1).equals(gs) || !otherGroups.contains(entry.getKey().get(left?1:0))) {
- continue;
- }
- if (RuleRaiseAccess.matchesForeignKey(metadata, entry.getValue().get(left?0:1), entry.getValue().get(left?1:0), gs, false)) {
- keyPreservingGroups.add(gs);
- result.add(entry.getKey().get(left?1:0));
- }
- }
- }
- return result;
- }
-
- /**
- * This method will convert all elements in a command to their fully qualified name.
- * @param command Command to convert
- */
- public static void fullyQualifyElements(Command command) {
- Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(command, false, true);
- for (ElementSymbol element : elements) {
- element.setDisplayFullyQualified(true);
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1098 @@
+/*
+ * 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.resolver.util;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+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;
+import java.util.Map;
+import java.util.Set;
+
+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.TeiidComponentException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.TransformationException;
+import org.teiid.core.types.DataTypeManager.DefaultDataTypes;
+import org.teiid.core.util.StringUtil;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.function.FunctionDescriptor;
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.metadata.GroupInfo;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.StoredProcedureInfo;
+import org.teiid.query.metadata.SupportConstants;
+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.RuleChooseJoinStrategy;
+import org.teiid.query.optimizer.relational.rules.RuleRaiseAccess;
+import org.teiid.query.sql.LanguageObject;
+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.FromClause;
+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.OrderBy;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.SubqueryContainer;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.symbol.AbstractCaseExpression;
+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.Function;
+import org.teiid.query.sql.symbol.GroupSymbol;
+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.util.SymbolMap;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+
+
+/**
+ * Utilities used during resolution
+ */
+public class ResolverUtil {
+
+ public static class ResolvedLookup {
+ private GroupSymbol group;
+ private ElementSymbol keyElement;
+ private ElementSymbol returnElement;
+
+ void setGroup(GroupSymbol group) {
+ this.group = group;
+ }
+ public GroupSymbol getGroup() {
+ return group;
+ }
+ void setKeyElement(ElementSymbol keyElement) {
+ this.keyElement = keyElement;
+ }
+ public ElementSymbol getKeyElement() {
+ return keyElement;
+ }
+ void setReturnElement(ElementSymbol returnElement) {
+ this.returnElement = returnElement;
+ }
+ public ElementSymbol getReturnElement() {
+ return returnElement;
+ }
+ }
+
+ // Can't construct
+ private ResolverUtil() {}
+
+ /*
+ * Type Conversion Utilities
+ */
+
+ /**
+ * Gets the most specific type to which all the given types have an implicit
+ * conversion. The method decides a common type as follows:
+ * <ul>
+ * <li>If one or more of the given types is a candidate, then this method
+ * will return the candidate that occurs first in the given array.
+ * This is why the order of the names in the array is important. </li>
+ * <li>Otherwise, if none of them is a candidate, this method will attempt
+ * to find a common type to which all of them can be implicitly
+ * converted.</li>
+ * <li>Otherwise this method is unable to find a common type to which all
+ * the given types can be implicitly converted, and therefore returns
+ * a null.</li>
+ * </ul>
+ * @param typeNames an ordered array of unique type names.
+ * @return a type name to which all the given types can be converted
+ */
+ public static String getCommonType(String[] typeNames) {
+ if (typeNames == null || typeNames.length == 0) {
+ return null;
+ }
+ // If there is only one type, then simply return it
+ if (typeNames.length == 1) {
+ return typeNames[0];
+ }
+ // A type can be implicitly converted to itself, so we put the implicit
+ // conversions as well as the original type in the working list of
+ // conversions.
+ HashSet<String> commonConversions = new LinkedHashSet<String>();
+ commonConversions.add(typeNames[0]);
+ commonConversions.addAll(DataTypeManager.getImplicitConversions(typeNames[0]));
+ for (int i = 1; i < typeNames.length; i++ ) {
+ HashSet<String> conversions = new LinkedHashSet<String>(DataTypeManager.getImplicitConversions(typeNames[i]));
+ conversions.add(typeNames[i]);
+ // Equivalent to set intersection
+ commonConversions.retainAll(conversions);
+ }
+ if (commonConversions.isEmpty()) {
+ return null;
+ }
+ for (int i = 0; i < typeNames.length; i++) {
+ if (commonConversions.contains(typeNames[i])) {
+ return typeNames[i];
+ }
+ }
+ commonConversions.remove(DefaultDataTypes.STRING);
+ commonConversions.remove(DefaultDataTypes.OBJECT);
+ if (!commonConversions.isEmpty()) {
+ return commonConversions.iterator().next();
+ }
+ return null;
+ }
+
+ /**
+ * Gets whether there exists an implicit conversion from the source type to
+ * the target type
+ * @param fromType
+ * @param toType
+ * @return true if there exists an implicit conversion from the
+ * <code>fromType</code> to the <code>toType</code>.
+ */
+ public static boolean canImplicitlyConvert(String fromType, String toType) {
+ if (fromType.equals(toType)) return true;
+ return DataTypeManager.isImplicitConversion(fromType, toType);
+ }
+
+ /**
+ * Replaces a sourceExpression with a conversion of the source expression
+ * to the target type. If the source type and target type are the same,
+ * this method does nothing.
+ * @param sourceExpression
+ * @param targetTypeName
+ * @return
+ * @throws QueryResolverException
+ */
+ public static Expression convertExpression(Expression sourceExpression, String targetTypeName, QueryMetadataInterface metadata) throws QueryResolverException {
+ return convertExpression(sourceExpression,
+ DataTypeManager.getDataTypeName(sourceExpression.getType()),
+ targetTypeName, metadata);
+ }
+
+ /**
+ * Replaces a sourceExpression with a conversion of the source expression
+ * to the target type. If the source type and target type are the same,
+ * this method does nothing.
+ * @param sourceExpression
+ * @param sourceTypeName
+ * @param targetTypeName
+ * @return
+ * @throws QueryResolverException
+ */
+ public static Expression convertExpression(Expression sourceExpression, String sourceTypeName, String targetTypeName, QueryMetadataInterface metadata) throws QueryResolverException {
+ if (sourceTypeName.equals(targetTypeName)) {
+ return sourceExpression;
+ }
+
+ if(canImplicitlyConvert(sourceTypeName, targetTypeName)
+ || (sourceExpression instanceof Constant && convertConstant(sourceTypeName, targetTypeName, (Constant)sourceExpression) != null)) {
+ return getConversion(sourceExpression, sourceTypeName, targetTypeName, true, metadata.getFunctionLibrary());
+ }
+
+ //Expression is wrong type and can't convert
+ throw new QueryResolverException("ERR.015.008.0041", QueryPlugin.Util.getString("ERR.015.008.0041", new Object[] {targetTypeName, sourceExpression, sourceTypeName})); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ public static Constant convertConstant(String sourceTypeName,
+ String targetTypeName,
+ Constant constant) {
+ if (!DataTypeManager.isTransformable(sourceTypeName, targetTypeName)) {
+ return null;
+ }
+
+ try {
+ //try to get the converted constant, if this fails then it is not in a valid format
+ Constant result = getProperlyTypedConstant(constant.getValue(), DataTypeManager.getDataTypeClass(targetTypeName));
+
+ if (DataTypeManager.DefaultDataTypes.STRING.equals(sourceTypeName)) {
+ if (DataTypeManager.DefaultDataTypes.CHAR.equals(targetTypeName)) {
+ String value = (String)constant.getValue();
+ if (value != null && value.length() != 1) {
+ return null;
+ }
+ }
+ return result;
+ }
+
+ //for non-strings, ensure that the conversion is consistent
+ if (!DataTypeManager.isTransformable(targetTypeName, sourceTypeName)) {
+ return null;
+ }
+
+ if (!(constant.getValue() instanceof Comparable)) {
+ return null; //this is the case for xml constants
+ }
+
+ Constant reverse = getProperlyTypedConstant(result.getValue(), constant.getType());
+
+ if (((Comparable)constant.getValue()).compareTo(reverse.getValue()) == 0) {
+ return result;
+ }
+ } catch (QueryResolverException e) {
+
+ }
+
+ return null;
+ }
+
+ public static Function getConversion(Expression sourceExpression,
+ String sourceTypeName,
+ String targetTypeName,
+ boolean implicit, FunctionLibrary library) {
+ Class<?> srcType = DataTypeManager.getDataTypeClass(sourceTypeName);
+
+ FunctionDescriptor fd = library.findTypedConversionFunction(srcType, DataTypeManager.getDataTypeClass(targetTypeName));
+
+ Function conversion = new Function(fd.getName(), new Expression[] { sourceExpression, new Constant(targetTypeName) });
+ conversion.setType(DataTypeManager.getDataTypeClass(targetTypeName));
+ conversion.setFunctionDescriptor(fd);
+ if (implicit) {
+ conversion.makeImplicit();
+ }
+
+ return conversion;
+ }
+
+ /**
+ * Utility to set the type of an expression if it is a Reference and has a null type.
+ * @param expression the expression to test
+ * @param targetType the target type, if the expression's type is null.
+ * @throws QueryResolverException if unable to set the reference type to the target type.
+ */
+ public static void setDesiredType(Expression expression, Class<?> targetType, LanguageObject surroundingExpression) throws QueryResolverException {
+ if (expression instanceof Reference) {
+ Reference ref = (Reference)expression;
+ if (ref.isPositional() && ref.getType() == null) {
+ if (targetType == null) {
+ throw new QueryResolverException("ERR.015.008.0026", QueryPlugin.Util.getString("ERR.015.008.0026", surroundingExpression)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ ref.setType(targetType);
+ }
+ } else if (expression instanceof Function) {
+ Function f = (Function)expression;
+ if (f.getType() == null) {
+ f.setType(targetType);
+ }
+ }
+ }
+
+ /**
+ * Attempt to resolve the order by throws QueryResolverException if the
+ * symbol is not of SingleElementSymbol type
+ *
+ * @param orderBy
+ * @param fromClauseGroups
+ * groups of the FROM clause of the query (for resolving
+ * ambiguous unqualified element names), or empty List if a Set
+ * Query Order By is being resolved
+ * @param knownElements
+ * resolved elements from SELECT clause, which are only ones
+ * allowed to be in ORDER BY
+ * @param metadata
+ * QueryMetadataInterface
+ */
+ public static void resolveOrderBy(OrderBy orderBy, QueryCommand command, QueryMetadataInterface metadata)
+ throws QueryResolverException, QueryMetadataException, TeiidComponentException {
+
+ List<SingleElementSymbol> knownElements = command.getProjectedQuery().getSelect().getProjectedSymbols();
+
+ boolean isSimpleQuery = false;
+ List fromClauseGroups = Collections.emptyList();
+
+ if (command instanceof Query) {
+ Query query = (Query)command;
+ isSimpleQuery = !query.getSelect().isDistinct() && !query.hasAggregates();
+ if (query.getFrom() != null) {
+ fromClauseGroups = query.getFrom().getGroups();
+ }
+ }
+
+ // Cached state, if needed
+ String[] knownShortNames = new String[knownElements.size()];
+ List<Expression> expressions = new ArrayList<Expression>(knownElements.size());
+
+ for(int i=0; i<knownElements.size(); i++) {
+ SingleElementSymbol knownSymbol = knownElements.get(i);
+ expressions.add(SymbolMap.getExpression(knownSymbol));
+ if (knownSymbol instanceof ExpressionSymbol) {
+ continue;
+ }
+
+ String name = knownSymbol.getShortName();
+
+ knownShortNames[i] = name;
+ }
+
+ for (int i = 0; i < orderBy.getVariableCount(); i++) {
+ SingleElementSymbol sortKey = orderBy.getVariable(i);
+ if (sortKey instanceof ElementSymbol) {
+ ElementSymbol symbol = (ElementSymbol)sortKey;
+ String groupPart = null;
+ if (symbol.getGroupSymbol() != null) {
+ groupPart = symbol.getGroupSymbol().getName();
+ }
+ String symbolName = symbol.getName();
+ String shortName = symbol.getShortName();
+ if (groupPart == null) {
+ int position = -1;
+ SingleElementSymbol matchedSymbol = null;
+ // walk the SELECT col short names, looking for a match on the current ORDER BY 'short name'
+ for(int j=0; j<knownShortNames.length; j++) {
+ if( !shortName.equalsIgnoreCase( knownShortNames[j] )) {
+ continue;
+ }
+ // if we already have a matched symbol, matching again here means it is duplicate/ambiguous
+ if(matchedSymbol != null) {
+ if (!matchedSymbol.equals(knownElements.get(j))) {
+ throw new QueryResolverException("ERR.015.008.0042", QueryPlugin.Util.getString("ERR.015.008.0042", symbolName)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ continue;
+ }
+ matchedSymbol = knownElements.get(j);
+ position = j;
+ }
+ if (matchedSymbol != null) {
+ TempMetadataID tempMetadataID = new TempMetadataID(symbol.getName(), matchedSymbol.getType());
+ symbol.setMetadataID(tempMetadataID);
+ symbol.setType(matchedSymbol.getType());
+ }
+ if (position != -1) {
+ orderBy.setExpressionPosition(i, position);
+ continue;
+ }
+ }
+ } else if (sortKey instanceof ExpressionSymbol) {
+ // check for legacy positional
+ ExpressionSymbol es = (ExpressionSymbol)sortKey;
+ if (es.getExpression() instanceof Constant) {
+ Constant c = (Constant)es.getExpression();
+ int elementOrder = Integer.valueOf(c.getValue().toString()).intValue();
+ // adjust for the 1 based index.
+ if (elementOrder > knownElements.size() || elementOrder < 1) {
+ throw new QueryResolverException(QueryPlugin.Util.getString("SQLParser.non_position_constant", c)); //$NON-NLS-1$
+ }
+ orderBy.setExpressionPosition(i, elementOrder - 1);
+ continue;
+ }
+ }
+ //handle order by expressions
+ if (command instanceof SetQuery) {
+ throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.setquery_order_expression", sortKey)); //$NON-NLS-1$
+ }
+ for (ElementSymbol symbol : ElementCollectorVisitor.getElements(sortKey, false)) {
+ try {
+ ResolverVisitor.resolveLanguageObject(symbol, fromClauseGroups, command.getExternalGroupContexts(), metadata);
+ } catch(QueryResolverException e) {
+ throw new QueryResolverException(e, "ERR.015.008.0043", QueryPlugin.Util.getString("ERR.015.008.0043", symbol.getName()) );//$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+ ResolverVisitor.resolveLanguageObject(sortKey, metadata);
+
+ int index = expressions.indexOf(SymbolMap.getExpression(sortKey));
+ if (index == -1 && !isSimpleQuery) {
+ throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.invalid_unrelated", sortKey)); //$NON-NLS-1$
+ }
+ orderBy.setExpressionPosition(i, index);
+ }
+ }
+
+ /**
+ * Get the default value for the parameter, which could be null
+ * if the parameter is set to NULLABLE. If no default is available,
+ * a QueryResolverException will be thrown.
+ *
+ * @param symbol ElementSymbol retrieved from metadata, fully-resolved
+ * @param metadata QueryMetadataInterface
+ * @return expr param (if it is non-null) or default value (if there is one)
+ * or null Constant (if parameter is optional and therefore allows this)
+ * @throws QueryResolverException if expr is null, parameter is required and no
+ * default value is defined
+ * @throws QueryMetadataException for error retrieving metadata
+ * @throws TeiidComponentException
+ * @since 4.3
+ */
+ public static Expression getDefault(ElementSymbol symbol, QueryMetadataInterface metadata) throws TeiidComponentException, QueryMetadataException, QueryResolverException {
+ //Check if there is a default value, if so use it
+ Object mid = symbol.getMetadataID();
+ Class<?> type = symbol.getType();
+
+ Object defaultValue = metadata.getDefaultValue(mid);
+
+ if (defaultValue == null && !metadata.elementSupports(mid, SupportConstants.Element.NULL)) {
+ throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.required_param", symbol.getOutputName())); //$NON-NLS-1$
+ }
+
+ return getProperlyTypedConstant(defaultValue, type);
+ }
+
+ /**
+ * Construct a Constant with proper type, given the String default
+ * value for the parameter and the parameter type. Throw a
+ * QueryResolverException if the String can't be transformed.
+ * @param defaultValue, either null or a String
+ * @param parameterType modeled type of parameter (MetaMatrix runtime type)
+ * @return Constant with proper type and default value Object of proper Class. Will
+ * be null Constant if defaultValue is null.
+ * @throws QueryResolverException if TransformationException is encountered
+ * @since 4.3
+ */
+ private static Constant getProperlyTypedConstant(Object defaultValue,
+ Class parameterType)
+ throws QueryResolverException{
+ try {
+ Object newValue = DataTypeManager.transformValue(defaultValue, parameterType);
+ return new Constant(newValue, parameterType);
+ } catch (TransformationException e) {
+ throw new QueryResolverException(e, QueryPlugin.Util.getString("ResolverUtil.error_converting_value_type", defaultValue, defaultValue.getClass(), parameterType)); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Returns the resolved elements in the given group. This method has the side effect of caching the resolved elements on the group object.
+ * The resolved elements may not contain non-selectable columns depending on the metadata first used for resolving.
+ *
+ */
+ public static List<ElementSymbol> resolveElementsInGroup(GroupSymbol group, QueryMetadataInterface metadata)
+ throws QueryMetadataException, TeiidComponentException {
+ return new ArrayList<ElementSymbol>(getGroupInfo(group, metadata).getSymbolList());
+ }
+
+ static GroupInfo getGroupInfo(GroupSymbol group,
+ QueryMetadataInterface metadata)
+ throws TeiidComponentException, QueryMetadataException {
+ String key = GroupInfo.CACHE_PREFIX + group.getCanonicalName();
+ GroupInfo groupInfo = (GroupInfo)metadata.getFromMetadataCache(group.getMetadataID(), key);
+
+ if (groupInfo == null) {
+ group = group.clone();
+ // get all elements from the metadata
+ List elementIDs = metadata.getElementIDsInGroupID(group.getMetadataID());
+
+ LinkedHashMap<Object, ElementSymbol> symbols = new LinkedHashMap<Object, ElementSymbol>(elementIDs.size());
+
+ for (Object elementID : elementIDs) {
+ String elementName = metadata.getName(elementID);
+ // Form an element symbol from the ID
+ ElementSymbol element = new ElementSymbol(elementName, DataTypeManager.getCanonicalString(StringUtil.toUpperCase(elementName)), group);
+ element.setMetadataID(elementID);
+ element.setType( DataTypeManager.getDataTypeClass(metadata.getElementType(element.getMetadataID())) );
+
+ symbols.put(elementID, element);
+ }
+ groupInfo = new GroupInfo(symbols);
+ metadata.addToMetadataCache(group.getMetadataID(), key, groupInfo);
+ }
+ return groupInfo;
+ }
+
+ /**
+ * When access patterns are flattened, they are an approximation the user
+ * may need to enter as criteria.
+ *
+ * @param metadata
+ * @param groups
+ * @param flatten
+ * @return
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ */
+ public static List getAccessPatternElementsInGroups(final QueryMetadataInterface metadata, Collection groups, boolean flatten) throws TeiidComponentException, QueryMetadataException {
+ List accessPatterns = null;
+ Iterator i = groups.iterator();
+ while (i.hasNext()){
+
+ GroupSymbol group = (GroupSymbol)i.next();
+
+ //Check this group for access pattern(s).
+ Collection accessPatternIDs = metadata.getAccessPatternsInGroup(group.getMetadataID());
+ if (accessPatternIDs != null && accessPatternIDs.size() > 0){
+ Iterator j = accessPatternIDs.iterator();
+ if (accessPatterns == null){
+ accessPatterns = new ArrayList();
+ }
+ while (j.hasNext()) {
+ List elements = metadata.getElementIDsInAccessPattern(j.next());
+ GroupInfo groupInfo = getGroupInfo(group, metadata);
+ List result = new ArrayList(elements.size());
+ for (Iterator iterator = elements.iterator(); iterator.hasNext();) {
+ Object id = iterator.next();
+ ElementSymbol symbol = groupInfo.getSymbol(id);
+ assert symbol != null;
+ result.add(symbol);
+ }
+ if (flatten) {
+ accessPatterns.addAll(result);
+ } else {
+ accessPatterns.add(new AccessPattern(result));
+ }
+ }
+ }
+ }
+
+ return accessPatterns;
+ }
+
+ public static void resolveLimit(Limit limit) throws QueryResolverException {
+ if (limit.getOffset() != null) {
+ setDesiredType(limit.getOffset(), DataTypeManager.DefaultDataClasses.INTEGER, limit);
+ }
+ setDesiredType(limit.getRowLimit(), DataTypeManager.DefaultDataClasses.INTEGER, limit);
+ }
+
+ public static void resolveImplicitTempGroup(TempMetadataAdapter metadata, GroupSymbol symbol, List symbols)
+ throws TeiidComponentException, QueryResolverException {
+
+ if (symbol.isImplicitTempGroupSymbol()) {
+ if (metadata.getMetadataStore().getTempElementElementIDs(symbol.getCanonicalName())==null) {
+ addTempGroup(metadata, symbol, symbols, true);
+ }
+ ResolverUtil.resolveGroup(symbol, metadata);
+ }
+ }
+
+ public static TempMetadataID addTempGroup(TempMetadataAdapter metadata,
+ GroupSymbol symbol,
+ List<? extends SingleElementSymbol> symbols, boolean tempTable) throws QueryResolverException {
+ HashSet<String> names = new HashSet<String>();
+ for (SingleElementSymbol ses : symbols) {
+ if (!names.add(ses.getShortCanonicalName())) {
+ throw new QueryResolverException(QueryPlugin.Util.getString("ResolverUtil.duplicateName", symbol, ses.getShortName())); //$NON-NLS-1$
+ }
+ }
+
+ if (tempTable) {
+ resolveNullLiterals(symbols);
+ }
+ TempMetadataStore store = metadata.getMetadataStore();
+ return store.addTempGroup(symbol.getName(), symbols, !tempTable, tempTable);
+ }
+
+ public static TempMetadataID addTempTable(TempMetadataAdapter metadata,
+ GroupSymbol symbol,
+ List<? extends SingleElementSymbol> symbols) throws QueryResolverException {
+ return addTempGroup(metadata, symbol, symbols, true);
+ }
+
+ /**
+ * Look for a null literal in the SELECT clause and set it's type to STRING. This ensures that
+ * the result set metadata retrieved for this query will be properly set to something other than
+ * the internal NullType. Added for defect 15437.
+ *
+ * @param select The select clause
+ * @since 4.2
+ */
+ public static void resolveNullLiterals(List symbols) {
+ for (int i = 0; i < symbols.size(); i++) {
+ SelectSymbol selectSymbol = (SelectSymbol) symbols.get(i);
+
+ if (!(selectSymbol instanceof SingleElementSymbol)) {
+ continue;
+ }
+
+ SingleElementSymbol symbol = (SingleElementSymbol)selectSymbol;
+
+ setTypeIfNull(symbol, DataTypeManager.DefaultDataClasses.STRING);
+ }
+ }
+
+ public static void setTypeIfNull(SingleElementSymbol symbol,
+ Class<?> replacement) {
+ if(!DataTypeManager.DefaultDataClasses.NULL.equals(symbol.getType()) && symbol.getType() != null) {
+ return;
+ }
+ if(symbol instanceof AliasSymbol) {
+ symbol = ((AliasSymbol)symbol).getSymbol();
+ }
+ if(symbol instanceof ExpressionSymbol && !(symbol instanceof AggregateSymbol)) {
+ ExpressionSymbol exprSymbol = (ExpressionSymbol) symbol;
+ Expression expr = exprSymbol.getExpression();
+
+ if(expr instanceof Constant) {
+ exprSymbol.setExpression(new Constant(null, replacement));
+ } else if (expr instanceof AbstractCaseExpression) {
+ ((AbstractCaseExpression)expr).setType(replacement);
+ } else if (expr instanceof ScalarSubquery) {
+ ((ScalarSubquery)expr).setType(replacement);
+ } else {
+ try {
+ ResolverUtil.setDesiredType(expr, replacement, symbol);
+ } catch (QueryResolverException e) {
+ //cannot happen
+ }
+ }
+ } else if(symbol instanceof ElementSymbol) {
+ ElementSymbol elementSymbol = (ElementSymbol)symbol;
+ elementSymbol.setType(replacement);
+ }
+ }
+
+ /**
+ *
+ * @param groupContext
+ * @param groups
+ * @param metadata
+ * @return the List of groups that match the given groupContext out of the supplied collection
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ */
+ public static List<GroupSymbol> findMatchingGroups(String groupContext,
+ Collection<GroupSymbol> groups,
+ QueryMetadataInterface metadata) throws TeiidComponentException,
+ QueryMetadataException {
+
+ if (groups == null) {
+ return null;
+ }
+
+ LinkedList<GroupSymbol> matchedGroups = new LinkedList<GroupSymbol>();
+
+ if (groupContext == null) {
+ matchedGroups.addAll(groups);
+ } else {
+ for (GroupSymbol group : groups) {
+ String fullName = group.getCanonicalName();
+ if (nameMatchesGroup(groupContext, matchedGroups, group, fullName)) {
+ if (groupContext.length() == fullName.length()) {
+ return matchedGroups;
+ }
+ continue;
+ }
+
+ // don't try to vdb qualify temp metadata
+ if (group.getMetadataID() instanceof TempMetadataID) {
+ continue;
+ }
+
+ String actualVdbName = metadata.getVirtualDatabaseName();
+
+ if (actualVdbName != null) {
+ fullName = actualVdbName.toUpperCase() + ElementSymbol.SEPARATOR + fullName;
+ if (nameMatchesGroup(groupContext, matchedGroups, group, fullName)
+ && groupContext.length() == fullName.length()) {
+ return matchedGroups;
+ }
+ }
+ }
+ }
+
+ return matchedGroups;
+ }
+
+
+ public static boolean nameMatchesGroup(String groupContext,
+ String fullName) {
+ //if there is a name match, make sure that it is the full name or a proper qualifier
+ if (fullName.endsWith(groupContext)) {
+ int matchIndex = fullName.length() - groupContext.length();
+ if (matchIndex == 0 || fullName.charAt(matchIndex - 1) == '.') {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean nameMatchesGroup(String groupContext,
+ LinkedList<GroupSymbol> matchedGroups,
+ GroupSymbol group,
+ String fullName) {
+ if (nameMatchesGroup(groupContext, fullName)) {
+ matchedGroups.add(group);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Check the type of the (left) expression and the type of the single
+ * projected symbol of the subquery. If they are not the same, try to find
+ * an implicit conversion from the former type to the latter type, and wrap
+ * the left expression in that conversion function; otherwise throw an
+ * Exception.
+ * @param expression the Expression on one side of the predicate criteria
+ * @param crit the SubqueryContainer containing the subquery Command of the other
+ * side of the predicate criteria
+ * @return implicit conversion Function, or null if none is necessary
+ * @throws QueryResolverException if a conversion is necessary but none can
+ * be found
+ */
+ static Expression resolveSubqueryPredicateCriteria(Expression expression, SubqueryContainer crit, QueryMetadataInterface metadata)
+ throws QueryResolverException {
+
+ // Check that type of the expression is same as the type of the
+ // single projected symbol of the subquery
+ Class exprType = expression.getType();
+ if(exprType == null) {
+ throw new QueryResolverException("ERR.015.008.0030", QueryPlugin.Util.getString("ERR.015.008.0030", expression)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ String exprTypeName = DataTypeManager.getDataTypeName(exprType);
+
+ Collection<SingleElementSymbol> projectedSymbols = crit.getCommand().getProjectedSymbols();
+ if (projectedSymbols.size() != 1){
+ throw new QueryResolverException("ERR.015.008.0032", QueryPlugin.Util.getString("ERR.015.008.0032", crit.getCommand())); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ Class<?> subqueryType = projectedSymbols.iterator().next().getType();
+ String subqueryTypeName = DataTypeManager.getDataTypeName(subqueryType);
+ Expression result = null;
+ try {
+ result = convertExpression(expression, exprTypeName, subqueryTypeName, metadata);
+ } catch (QueryResolverException qre) {
+ throw new QueryResolverException(qre, "ERR.015.008.0033", QueryPlugin.Util.getString("ERR.015.008.0033", crit)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return result;
+ }
+
+ public static ResolvedLookup resolveLookup(Function lookup, QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
+ Expression[] args = lookup.getArgs();
+ ResolvedLookup result = new ResolvedLookup();
+ // Special code to handle setting return type of the lookup function to match the type of the return element
+ if( !(args[0] instanceof Constant) || !(args[1] instanceof Constant) || !(args[2] instanceof Constant)) {
+ throw new QueryResolverException("ERR.015.008.0063", QueryPlugin.Util.getString("ERR.015.008.0063")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ // If code table name in lookup function refers to temp group throw exception
+ GroupSymbol groupSym = new GroupSymbol((String) ((Constant)args[0]).getValue());
+ try {
+ groupSym.setMetadataID(metadata.getGroupID((String) ((Constant)args[0]).getValue()));
+ if (groupSym.getMetadataID() instanceof TempMetadataID) {
+ throw new QueryResolverException("ERR.015.008.0065", QueryPlugin.Util.getString("ERR.015.008.0065", ((Constant)args[0]).getValue())); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ } catch(QueryMetadataException e) {
+ throw new QueryResolverException("ERR.015.008.0062", QueryPlugin.Util.getString("ERR.015.008.0062", ((Constant)args[0]).getValue())); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ result.setGroup(groupSym);
+
+ List<GroupSymbol> groups = Arrays.asList(groupSym);
+
+ String returnElementName = (String) ((Constant)args[0]).getValue() + "." + (String) ((Constant)args[1]).getValue(); //$NON-NLS-1$
+ ElementSymbol returnElement = new ElementSymbol(returnElementName);
+ try {
+ ResolverVisitor.resolveLanguageObject(returnElement, groups, metadata);
+ } catch(QueryMetadataException e) {
+ throw new QueryResolverException("ERR.015.008.0062", QueryPlugin.Util.getString("ERR.015.008.0062", returnElementName)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ result.setReturnElement(returnElement);
+
+ String keyElementName = (String) ((Constant)args[0]).getValue() + "." + (String) ((Constant)args[2]).getValue(); //$NON-NLS-1$
+ ElementSymbol keyElement = new ElementSymbol(keyElementName);
+ try {
+ ResolverVisitor.resolveLanguageObject(keyElement, groups, metadata);
+ } catch(QueryMetadataException e) {
+ throw new QueryResolverException("ERR.015.008.0062", QueryPlugin.Util.getString("ERR.015.008.0062", keyElementName)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ result.setKeyElement(keyElement);
+ args[3] = convertExpression(args[3], DataTypeManager.getDataTypeName(keyElement.getType()), metadata);
+ return result;
+ }
+
+ private static QueryResolverException handleUnresolvedGroup(GroupSymbol symbol, String description) {
+ UnresolvedSymbolDescription usd = new UnresolvedSymbolDescription(symbol.toString(), description);
+ QueryResolverException e = new QueryResolverException(usd.getDescription()+": "+usd.getSymbol()); //$NON-NLS-1$
+ e.setUnresolvedSymbols(Arrays.asList(usd));
+ return e;
+ }
+
+ public static void resolveGroup(GroupSymbol symbol, QueryMetadataInterface metadata)
+ throws TeiidComponentException, QueryResolverException {
+
+ if (symbol.getMetadataID() != null){
+ return;
+ }
+
+ // determine the "metadataID" part of the symbol to look up
+ String potentialID = symbol.getNonCorrelationName();
+
+ String name = symbol.getName();
+ String definition = symbol.getDefinition();
+
+ Object groupID = null;
+ try {
+ // get valid GroupID for possibleID - this may throw exceptions if group is invalid
+ groupID = metadata.getGroupID(potentialID);
+ } catch(QueryMetadataException e) {
+ // didn't find this group ID
+ }
+
+ // If that didn't work, try to strip a vdb name from potentialID
+ String vdbName = null;
+ if(groupID == null) {
+ String[] parts = potentialID.split("\\.", 2); //$NON-NLS-1$
+ if (parts.length > 1 && parts[0].equalsIgnoreCase(metadata.getVirtualDatabaseName())) {
+ try {
+ groupID = metadata.getGroupID(parts[1]);
+ } catch(QueryMetadataException e) {
+ // ignore - just didn't find it
+ }
+ if(groupID != null) {
+ potentialID = parts[1];
+ vdbName = parts[0];
+ }
+ }
+ }
+
+ // the group could be partially qualified, verify that this group exists
+ // and there is only one group that matches the given partial name
+ if(groupID == null) {
+ Collection groupNames = null;
+ try {
+ groupNames = metadata.getGroupsForPartialName(potentialID);
+ } catch(QueryMetadataException e) {
+ // ignore - just didn't find it
+ }
+
+ if(groupNames != null) {
+ int matches = groupNames.size();
+ if(matches == 1) {
+ potentialID = (String) groupNames.iterator().next();
+ try {
+ // get valid GroupID for possibleID - this may throw exceptions if group is invalid
+ groupID = metadata.getGroupID(potentialID);
+ //set group full name
+ if(symbol.getDefinition() != null){
+ symbol.setDefinition(potentialID);
+ }else{
+ symbol.setName(potentialID);
+ }
+ } catch(QueryMetadataException e) {
+ // didn't find this group ID
+ }
+ } else if(matches > 1) {
+ throw handleUnresolvedGroup(symbol, QueryPlugin.Util.getString("ERR.015.008.0055")); //$NON-NLS-1$
+ }
+ }
+ }
+
+ if (groupID == null || metadata.isProcedure(groupID)) {
+ //try procedure relational resolving
+ try {
+ StoredProcedureInfo storedProcedureInfo = metadata.getStoredProcedureInfoForProcedure(potentialID);
+ symbol.setProcedure(true);
+ groupID = storedProcedureInfo.getProcedureID();
+ } catch(QueryMetadataException e) {
+ // just ignore
+ }
+ }
+
+ if(groupID == null) {
+ throw handleUnresolvedGroup(symbol, QueryPlugin.Util.getString("ERR.015.008.0056")); //$NON-NLS-1$
+ }
+ // set real metadata ID in the symbol
+ symbol.setMetadataID(groupID);
+ if(vdbName != null) {
+ // reset name or definition to strip vdb name
+ if(symbol.getDefinition() == null) {
+ symbol.setName(potentialID);
+ } else {
+ symbol.setDefinition(potentialID);
+ }
+ }
+ try {
+ if (!symbol.isProcedure()) {
+ symbol.setIsTempTable(metadata.isTemporaryTable(groupID));
+ }
+ } catch(QueryMetadataException e) {
+ // should not come here
+ }
+
+ symbol.setOutputDefinition(definition);
+ symbol.setOutputName(name);
+ }
+
+ public static void findKeyPreserved(Query query, Set<GroupSymbol> keyPreservingGroups, QueryMetadataInterface metadata)
+ throws TeiidComponentException, QueryMetadataException {
+ if (query.getFrom() == null) {
+ return;
+ }
+ if (query.getFrom().getClauses().size() == 1) {
+ findKeyPreserved(query.getFrom().getClauses().get(0), keyPreservingGroups, metadata);
+ return;
+ }
+ //non-ansi join
+ Set<GroupSymbol> groups = new HashSet<GroupSymbol>(query.getFrom().getGroups());
+ for (GroupSymbol groupSymbol : groups) {
+ if (metadata.getUniqueKeysInGroup(groupSymbol.getMetadataID()).isEmpty()) {
+ return;
+ }
+ }
+ LinkedList<Expression> leftExpressions = new LinkedList<Expression>();
+ LinkedList<Expression> rightExpressions = new LinkedList<Expression>();
+ for (Criteria crit : Criteria.separateCriteriaByAnd(query.getCriteria())) {
+ if (!(crit instanceof CompareCriteria)) {
+ continue;
+ }
+ CompareCriteria cc = (CompareCriteria)crit;
+ if (cc.getOperator() != CompareCriteria.EQ) {
+ continue;
+ }
+ if (cc.getLeftExpression() instanceof ElementSymbol && cc.getRightExpression() instanceof ElementSymbol) {
+ ElementSymbol left = (ElementSymbol)cc.getLeftExpression();
+ ElementSymbol right = (ElementSymbol)cc.getRightExpression();
+ int compare = left.getGroupSymbol().compareTo(right.getGroupSymbol());
+ if (compare > 0) {
+ leftExpressions.add(left);
+ rightExpressions.add(right);
+ } else if (compare != 0) {
+ leftExpressions.add(right);
+ rightExpressions.add(left);
+ }
+ }
+ }
+ HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits = createGroupMap(leftExpressions, rightExpressions);
+ HashSet<GroupSymbol> tempSet = new HashSet<GroupSymbol>();
+ HashSet<GroupSymbol> nonKeyPreserved = new HashSet<GroupSymbol>();
+ for (GroupSymbol group : groups) {
+ LinkedHashSet<GroupSymbol> visited = new LinkedHashSet<GroupSymbol>();
+ LinkedList<GroupSymbol> toVisit = new LinkedList<GroupSymbol>();
+ toVisit.add(group);
+ while (!toVisit.isEmpty()) {
+ GroupSymbol visiting = toVisit.removeLast();
+ if (!visited.add(visiting) || nonKeyPreserved.contains(visiting)) {
+ continue;
+ }
+ if (keyPreservingGroups.contains(visiting)) {
+ visited.addAll(groups);
+ break;
+ }
+ toVisit.addAll(findKeyPreserved(tempSet, Collections.singleton(visiting), crits, true, metadata, groups));
+ toVisit.addAll(findKeyPreserved(tempSet, Collections.singleton(visiting), crits, false, metadata, groups));
+ }
+ if (visited.containsAll(groups)) {
+ keyPreservingGroups.add(group);
+ } else {
+ nonKeyPreserved.add(group);
+ }
+ }
+ }
+
+ public static void findKeyPreserved(FromClause clause, Set<GroupSymbol> keyPreservingGroups, QueryMetadataInterface metadata)
+ throws TeiidComponentException, QueryMetadataException {
+ if (clause instanceof UnaryFromClause) {
+ UnaryFromClause ufc = (UnaryFromClause)clause;
+
+ if (!metadata.getUniqueKeysInGroup(ufc.getGroup().getMetadataID()).isEmpty()) {
+ keyPreservingGroups.add(ufc.getGroup());
+ }
+ }
+ if (clause instanceof JoinPredicate) {
+ JoinPredicate jp = (JoinPredicate)clause;
+ if (jp.getJoinType() == JoinType.JOIN_CROSS || jp.getJoinType() == JoinType.JOIN_FULL_OUTER) {
+ return;
+ }
+ HashSet<GroupSymbol> leftPk = new HashSet<GroupSymbol>();
+ findKeyPreserved(jp.getLeftClause(), leftPk, metadata);
+ HashSet<GroupSymbol> rightPk = new HashSet<GroupSymbol>();
+ findKeyPreserved(jp.getRightClause(), rightPk, metadata);
+
+ if (leftPk.isEmpty() && rightPk.isEmpty()) {
+ return;
+ }
+
+ HashSet<GroupSymbol> leftGroups = new HashSet<GroupSymbol>();
+ HashSet<GroupSymbol> rightGroups = new HashSet<GroupSymbol>();
+ jp.getLeftClause().collectGroups(leftGroups);
+ jp.getRightClause().collectGroups(rightGroups);
+
+ LinkedList<Expression> leftExpressions = new LinkedList<Expression>();
+ LinkedList<Expression> rightExpressions = new LinkedList<Expression>();
+ RuleChooseJoinStrategy.separateCriteria(leftGroups, rightGroups, leftExpressions, rightExpressions, jp.getJoinCriteria(), new LinkedList<Criteria>());
+
+ HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits = createGroupMap(leftExpressions, rightExpressions);
+ if (!leftPk.isEmpty() && (jp.getJoinType() == JoinType.JOIN_INNER || jp.getJoinType() == JoinType.JOIN_LEFT_OUTER)) {
+ findKeyPreserved(keyPreservingGroups, leftPk, crits, true, metadata, rightPk);
+ }
+ if (!rightPk.isEmpty() && (jp.getJoinType() == JoinType.JOIN_INNER || jp.getJoinType() == JoinType.JOIN_RIGHT_OUTER)) {
+ findKeyPreserved(keyPreservingGroups, rightPk, crits, false, metadata, leftPk);
+ }
+ }
+ }
+
+ private static HashMap<List<GroupSymbol>, List<HashSet<Object>>> createGroupMap(
+ LinkedList<Expression> leftExpressions,
+ LinkedList<Expression> rightExpressions) {
+ HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits = new HashMap<List<GroupSymbol>, List<HashSet<Object>>>();
+
+ for (int i = 0; i < leftExpressions.size(); i++) {
+ Expression lexpr = leftExpressions.get(i);
+ Expression rexpr = rightExpressions.get(i);
+ if (!(lexpr instanceof ElementSymbol) || !(rexpr instanceof ElementSymbol)) {
+ continue;
+ }
+ ElementSymbol les = (ElementSymbol)lexpr;
+ ElementSymbol res = (ElementSymbol)rexpr;
+ List<GroupSymbol> tbls = Arrays.asList(les.getGroupSymbol(), res.getGroupSymbol());
+ List<HashSet<Object>> ids = crits.get(tbls);
+ if (ids == null) {
+ ids = Arrays.asList(new HashSet<Object>(), new HashSet<Object>());
+ crits.put(tbls, ids);
+ }
+ ids.get(0).add(les.getMetadataID());
+ ids.get(1).add(res.getMetadataID());
+ }
+ return crits;
+ }
+
+ static private HashSet<GroupSymbol> findKeyPreserved(Set<GroupSymbol> keyPreservingGroups,
+ Set<GroupSymbol> pk,
+ HashMap<List<GroupSymbol>, List<HashSet<Object>>> crits, boolean left, QueryMetadataInterface metadata, Set<GroupSymbol> otherGroups)
+ throws TeiidComponentException, QueryMetadataException {
+ HashSet<GroupSymbol> result = new HashSet<GroupSymbol>();
+ for (GroupSymbol gs : pk) {
+ for (Map.Entry<List<GroupSymbol>, List<HashSet<Object>>> entry : crits.entrySet()) {
+ if (!entry.getKey().get(left?0:1).equals(gs) || !otherGroups.contains(entry.getKey().get(left?1:0))) {
+ continue;
+ }
+ if (RuleRaiseAccess.matchesForeignKey(metadata, entry.getValue().get(left?0:1), entry.getValue().get(left?1:0), gs, false)) {
+ keyPreservingGroups.add(gs);
+ result.add(entry.getKey().get(left?1:0));
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * This method will convert all elements in a command to their fully qualified name.
+ * @param command Command to convert
+ */
+ public static void fullyQualifyElements(Command command) {
+ Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(command, false, true);
+ for (ElementSymbol element : elements) {
+ element.setDisplayFullyQualified(true);
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,3139 +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.rewriter;
-
-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.Collection;
-import java.util.Collections;
-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;
-import java.util.StringTokenizer;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.FunctionExecutionException;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.common.buffer.BlockedException;
-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.util.Assertion;
-import org.teiid.core.util.TimestampWithTimezone;
-import org.teiid.language.SQLConstants.NonReserved;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.eval.Evaluator;
-import org.teiid.query.function.FunctionDescriptor;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.function.FunctionMethods;
-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.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;
-import org.teiid.query.processor.relational.RelationalNodeUtil;
-import org.teiid.query.resolver.ProcedureContainerResolver;
-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.ProcedureReservedWords;
-import org.teiid.query.sql.LanguageObject.Util;
-import org.teiid.query.sql.lang.AbstractSetCriteria;
-import org.teiid.query.sql.lang.ArrayTable;
-import org.teiid.query.sql.lang.BatchedUpdateCommand;
-import org.teiid.query.sql.lang.BetweenCriteria;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.DependentSetCriteria;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.ExpressionCriteria;
-import org.teiid.query.sql.lang.From;
-import org.teiid.query.sql.lang.FromClause;
-import org.teiid.query.sql.lang.GroupBy;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.Into;
-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;
-import org.teiid.query.sql.lang.OrderByItem;
-import org.teiid.query.sql.lang.ProcedureContainer;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.lang.SetClause;
-import org.teiid.query.sql.lang.SetClauseList;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.SubqueryCompareCriteria;
-import org.teiid.query.sql.lang.SubqueryContainer;
-import org.teiid.query.sql.lang.SubqueryFromClause;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.lang.TextTable;
-import org.teiid.query.sql.lang.TranslatableProcedureContainer;
-import org.teiid.query.sql.lang.UnaryFromClause;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.lang.WithQueryCommand;
-import org.teiid.query.sql.lang.XMLTable;
-import org.teiid.query.sql.lang.PredicateCriteria.Negatable;
-import org.teiid.query.sql.navigator.DeepPostOrderNavigator;
-import org.teiid.query.sql.navigator.PostOrderNavigator;
-import org.teiid.query.sql.proc.AssignmentStatement;
-import org.teiid.query.sql.proc.Block;
-import org.teiid.query.sql.proc.CommandStatement;
-import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
-import org.teiid.query.sql.proc.CriteriaSelector;
-import org.teiid.query.sql.proc.ExpressionStatement;
-import org.teiid.query.sql.proc.HasCriteria;
-import org.teiid.query.sql.proc.IfStatement;
-import org.teiid.query.sql.proc.LoopStatement;
-import org.teiid.query.sql.proc.Statement;
-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.symbol.AggregateSymbol;
-import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.CaseExpression;
-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.Reference;
-import org.teiid.query.sql.symbol.ScalarSubquery;
-import org.teiid.query.sql.symbol.SearchedCaseExpression;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-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.CorrelatedReferenceCollectorVisitor;
-import org.teiid.query.sql.visitor.CriteriaTranslatorVisitor;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.sql.visitor.EvaluatableVisitor;
-import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
-import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
-import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
-import org.teiid.query.sql.visitor.EvaluatableVisitor.EvaluationLevel;
-import org.teiid.query.util.CommandContext;
-import org.teiid.query.validator.UpdateValidator.UpdateInfo;
-import org.teiid.query.validator.UpdateValidator.UpdateMapping;
-import org.teiid.translator.SourceSystemFunctions;
-
-
-/**
- * Rewrites commands and command fragments to a form that is better for planning and execution. There is a current limitation that
- * command objects themselves cannot change type, since the same object is always used.
- */
-public class QueryRewriter {
-
- public static final CompareCriteria TRUE_CRITERIA = new CompareCriteria(new Constant(1, DataTypeManager.DefaultDataClasses.INTEGER), CompareCriteria.EQ, new Constant(1, DataTypeManager.DefaultDataClasses.INTEGER));
- public static final CompareCriteria FALSE_CRITERIA = new CompareCriteria(new Constant(1, DataTypeManager.DefaultDataClasses.INTEGER), CompareCriteria.EQ, new Constant(0, DataTypeManager.DefaultDataClasses.INTEGER));
- public static final CompareCriteria UNKNOWN_CRITERIA = new CompareCriteria(new Constant(null, DataTypeManager.DefaultDataClasses.STRING), CompareCriteria.NE, new Constant(null, DataTypeManager.DefaultDataClasses.STRING));
-
- private static final Map<String, String> ALIASED_FUNCTIONS = new HashMap<String, String>();
-
- static {
- ALIASED_FUNCTIONS.put("lower", SourceSystemFunctions.LCASE); //$NON-NLS-1$
- ALIASED_FUNCTIONS.put("upper", SourceSystemFunctions.UCASE); //$NON-NLS-1$
- ALIASED_FUNCTIONS.put("cast", SourceSystemFunctions.CONVERT); //$NON-NLS-1$
- ALIASED_FUNCTIONS.put("nvl", SourceSystemFunctions.IFNULL); //$NON-NLS-1$
- ALIASED_FUNCTIONS.put("||", SourceSystemFunctions.CONCAT); //$NON-NLS-1$
- ALIASED_FUNCTIONS.put("chr", SourceSystemFunctions.CHAR); //$NON-NLS-1$
- }
-
- private static final Set<String> PARSE_FORMAT_TYPES = new HashSet<String>(Arrays.asList(DataTypeManager.DefaultDataTypes.TIME,
- DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.DefaultDataTypes.BIG_DECIMAL,
- DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.LONG,
- DataTypeManager.DefaultDataTypes.FLOAT, DataTypeManager.DefaultDataTypes.DOUBLE));
-
- private QueryMetadataInterface metadata;
- private CommandContext context;
- private CreateUpdateProcedureCommand procCommand;
-
- private boolean rewriteSubcommands;
- private boolean processing;
- private Evaluator evaluator;
- private Map<ElementSymbol, Expression> variables; //constant propagation
- private int commandType;
-
- private QueryRewriter(QueryMetadataInterface metadata,
- CommandContext context, CreateUpdateProcedureCommand procCommand) {
- this.metadata = metadata;
- this.context = context;
- this.procCommand = procCommand;
- this.evaluator = new Evaluator(Collections.emptyMap(), null, context);
- }
-
- public static Command evaluateAndRewrite(Command command, Evaluator eval, CommandContext context, QueryMetadataInterface metadata) throws TeiidProcessingException, TeiidComponentException {
- QueryRewriter queryRewriter = new QueryRewriter(metadata, context, null);
- queryRewriter.evaluator = eval;
- queryRewriter.rewriteSubcommands = true;
- queryRewriter.processing = true;
- return queryRewriter.rewriteCommand(command, false);
- }
-
- public static Command rewrite(Command command, CreateUpdateProcedureCommand procCommand, QueryMetadataInterface metadata, CommandContext context, Map<ElementSymbol, Expression> variableValues, int commandType) throws TeiidComponentException, TeiidProcessingException{
- QueryRewriter rewriter = new QueryRewriter(metadata, context, procCommand);
- rewriter.rewriteSubcommands = true;
- rewriter.variables = variableValues;
- rewriter.commandType = commandType;
- return rewriter.rewriteCommand(command, false);
- }
-
- public static Command rewrite(Command command, QueryMetadataInterface metadata, CommandContext context) throws TeiidComponentException, TeiidProcessingException{
- return rewrite(command, null, metadata, context, null, Command.TYPE_UNKNOWN);
- }
-
- /**
- * Rewrites the command and all of its subcommands (both embedded and non-embedded)
- *
- * @param command
- * @param removeOrderBy
- * @return
- * @throws QueryValidatorException
- */
- private Command rewriteCommand(Command command, boolean removeOrderBy) throws TeiidComponentException, TeiidProcessingException{
- QueryMetadataInterface oldMetadata = metadata;
- CreateUpdateProcedureCommand oldProcCommand = procCommand;
-
- Map tempMetadata = command.getTemporaryMetadata();
- if(tempMetadata != null) {
- metadata = new TempMetadataAdapter(metadata, new TempMetadataStore(tempMetadata));
- }
-
- switch(command.getType()) {
- case Command.TYPE_QUERY:
- QueryCommand queryCommand = (QueryCommand)command;
- if (removeOrderBy && queryCommand.getLimit() == null) {
- queryCommand.setOrderBy(null);
- }
- if (queryCommand.getWith() != null) {
- for (WithQueryCommand withQueryCommand : queryCommand.getWith()) {
- if (withQueryCommand.getColumns() == null) {
- List<ElementSymbol> columns = ResolverUtil.resolveElementsInGroup(withQueryCommand.getGroupSymbol(), metadata);
- withQueryCommand.setColumns(LanguageObject.Util.deepClone(columns, ElementSymbol.class));
- }
- rewriteSubqueryContainer(withQueryCommand, true);
- }
- }
- if(command instanceof Query) {
- command = rewriteQuery((Query) command);
- }else {
- command = rewriteSetQuery((SetQuery) command);
- }
- break;
- case Command.TYPE_STORED_PROCEDURE:
- command = rewriteExec((StoredProcedure) command);
- break;
- case Command.TYPE_INSERT:
- command = rewriteInsert((Insert) command);
- break;
- case Command.TYPE_UPDATE:
- command = rewriteUpdate((Update) command);
- break;
- case Command.TYPE_DELETE:
- command = rewriteDelete((Delete) command);
- break;
- case Command.TYPE_UPDATE_PROCEDURE:
- procCommand = (CreateUpdateProcedureCommand) command;
- command = rewriteUpdateProcedure((CreateUpdateProcedureCommand) command);
- break;
- case Command.TYPE_BATCHED_UPDATE:
- List subCommands = ((BatchedUpdateCommand)command).getUpdateCommands();
- for (int i = 0; i < subCommands.size(); i++) {
- Command subCommand = (Command)subCommands.get(i);
- subCommand = rewriteCommand(subCommand, false);
- subCommands.set(i, subCommand);
- }
- break;
- case Command.TYPE_TRIGGER_ACTION:
- TriggerAction ta = (TriggerAction)command;
- ta.setBlock(rewriteBlock(ta.getBlock()));
- break;
- }
-
- this.metadata = oldMetadata;
- this.procCommand = oldProcCommand;
- return command;
- }
-
- private Command rewriteUpdateProcedure(CreateUpdateProcedureCommand command)
- throws TeiidComponentException, TeiidProcessingException{
- Map<ElementSymbol, Expression> oldVariables = variables;
- if (command.getUserCommand() != null) {
- variables = QueryResolver.getVariableValues(command.getUserCommand(), false, metadata);
- commandType = command.getUserCommand().getType();
- }
-
- Block block = rewriteBlock(command.getBlock());
- command.setBlock(block);
-
- variables = oldVariables;
-
- return command;
- }
-
- private Block rewriteBlock(Block block)
- throws TeiidComponentException, TeiidProcessingException{
- List statements = block.getStatements();
- Iterator stmtIter = statements.iterator();
-
- List newStmts = new ArrayList(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);
- }
- }
-
- block.setStatements(newStmts);
-
- return block;
- }
-
- private Object rewriteStatement(Statement statement)
- throws TeiidComponentException, TeiidProcessingException{
-
- // evaluate the HAS Criteria on the procedure and rewrite
- int stmtType = statement.getType();
- switch(stmtType) {
- case Statement.TYPE_IF:
- IfStatement ifStmt = (IfStatement) statement;
- Criteria ifCrit = ifStmt.getCondition();
- Criteria evalCrit = rewriteCriteria(ifCrit);
-
- ifStmt.setCondition(evalCrit);
- if(evalCrit.equals(TRUE_CRITERIA)) {
- Block ifblock = rewriteBlock(ifStmt.getIfBlock());
- return ifblock.getStatements();
- } else if(evalCrit.equals(FALSE_CRITERIA) || evalCrit.equals(UNKNOWN_CRITERIA)) {
- if(ifStmt.hasElseBlock()) {
- Block elseBlock = rewriteBlock(ifStmt.getElseBlock());
- return elseBlock.getStatements();
- }
- return null;
- } else {
- Block ifblock = rewriteBlock(ifStmt.getIfBlock());
- ifStmt.setIfBlock(ifblock);
- if(ifStmt.hasElseBlock()) {
- Block elseBlock = rewriteBlock(ifStmt.getElseBlock());
- ifStmt.setElseBlock(elseBlock);
- }
- }
- return ifStmt;
- case Statement.TYPE_ERROR:
- case Statement.TYPE_DECLARE:
- case Statement.TYPE_ASSIGNMENT:
- ExpressionStatement exprStmt = (ExpressionStatement) statement;
- // replace variables to references, these references are later
- // replaced in the processor with variable values
- Expression expr = exprStmt.getExpression();
- if (expr != null) {
- expr = rewriteExpressionDirect(expr);
- exprStmt.setExpression(expr);
- }
- return exprStmt;
- case Statement.TYPE_COMMAND:
- CommandStatement cmdStmt = (CommandStatement) statement;
- rewriteSubqueryContainer(cmdStmt, false);
-
- if(cmdStmt.getCommand().getType() == Command.TYPE_UPDATE) {
- Update update = (Update)cmdStmt.getCommand();
- if (update.getChangeList().isEmpty()) {
- return null;
- }
- }
- return statement;
- case Statement.TYPE_LOOP:
- LoopStatement loop = (LoopStatement)statement;
-
- rewriteSubqueryContainer(loop, false);
-
- rewriteBlock(loop.getBlock());
-
- if (loop.getBlock().getStatements().isEmpty()) {
- return null;
- }
-
- return loop;
- case Statement.TYPE_WHILE:
- WhileStatement whileStatement = (WhileStatement) statement;
- Criteria crit = whileStatement.getCondition();
- crit = rewriteCriteria(crit);
-
- whileStatement.setCondition(crit);
- 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;
- }
- whileStatement.setBlock(rewriteBlock(whileStatement.getBlock()));
-
- if (whileStatement.getBlock().getStatements().isEmpty()) {
- return null;
- }
-
- return whileStatement;
- default:
- return statement;
- }
- }
-
- /**
- * @param removeOrderBy
- * @param assStmt
- * @throws QueryValidatorException
- */
- private void rewriteSubqueryContainer(SubqueryContainer container, boolean removeOrderBy) throws TeiidComponentException, TeiidProcessingException{
- if (rewriteSubcommands && container.getCommand() != null && (container.getCommand().getProcessorPlan() == null || processing)) {
- container.setCommand(rewriteCommand(container.getCommand(), removeOrderBy));
- }
- }
-
- /**
- * <p>The HasCriteria evaluates to a TRUE_CRITERIA or a FALSE_CRITERIA, it checks to see
- * if type of criteria on the elements specified by the CriteriaSelector is specified on
- * the user's command.</p>
- */
- private Criteria rewriteCriteria(HasCriteria hasCrit) {
- Criteria userCrit = null;
- Command userCommand = procCommand.getUserCommand();
- int cmdType = userCommand.getType();
- switch(cmdType) {
- case Command.TYPE_DELETE:
- userCrit = ((Delete)userCommand).getCriteria();
- break;
- case Command.TYPE_UPDATE:
- userCrit = ((Update)userCommand).getCriteria();
- break;
- default:
- return FALSE_CRITERIA;
- }
-
- if(userCrit == null) {
- return FALSE_CRITERIA;
- }
-
- // get the CriteriaSelector, elements on the selector and the selector type
- CriteriaSelector selector = hasCrit.getSelector();
-
- Collection hasCritElmts = null;
- if(selector.hasElements()) {
- hasCritElmts = selector.getElements();
- // collect elements present on the user's criteria and check if
- // all of the hasCriteria elements are among them
- Collection<ElementSymbol> userElmnts = ElementCollectorVisitor.getElements(userCrit, true);
- if(!userElmnts.containsAll(hasCritElmts)) {
- return FALSE_CRITERIA;
- }
- }
-
- int selectorType = selector.getSelectorType();
- // if no selector type specified return true
- // already checked all HAS elements present on user criteria
- if(selectorType == CriteriaSelector.NO_TYPE) {
- return TRUE_CRITERIA;
- }
-
- // collect all predicate criteria present on the user's criteria
- for (Criteria predicateCriteria : Criteria.separateCriteriaByAnd(userCrit)) {
- // atleast one of the hasElemnets should be on this predicate else
- // proceed to the next predicate
- Collection<ElementSymbol> predElmnts = ElementCollectorVisitor.getElements(predicateCriteria, true);
- if(selector.hasElements()) {
- Iterator hasIter = hasCritElmts.iterator();
- boolean containsElmnt = false;
- while(hasIter.hasNext()) {
- ElementSymbol hasElmnt = (ElementSymbol) hasIter.next();
- if(predElmnts.contains(hasElmnt)) {
- containsElmnt = true;
- }
- }
-
- if(!containsElmnt) {
- continue;
- }
- }
-
- // check if the predicate criteria type maches the type specified
- // by the criteria selector
- switch(selectorType) {
- case CriteriaSelector.IN:
- if(predicateCriteria instanceof SetCriteria) {
- return TRUE_CRITERIA;
- }
- break;
- case CriteriaSelector.LIKE:
- if(predicateCriteria instanceof MatchCriteria) {
- return TRUE_CRITERIA;
- }
- break;
- case CriteriaSelector.IS_NULL:
- if(predicateCriteria instanceof IsNullCriteria) {
- return TRUE_CRITERIA;
- }
- break;
- case CriteriaSelector.BETWEEN:
- if(predicateCriteria instanceof BetweenCriteria) {
- return TRUE_CRITERIA;
- }
- break;
- default: // EQ, GT, LT, GE, LE criteria
- if(predicateCriteria instanceof CompareCriteria) {
- CompareCriteria compCrit = (CompareCriteria) predicateCriteria;
- if(compCrit.getOperator() == selectorType) {
- return TRUE_CRITERIA;
- }
- }
- break;
- }
- }
-
- return FALSE_CRITERIA;
- }
-
- /**
- * <p>TranslateCriteria is evaluated by translating elements on parts(restricted by the type
- * of criteria and elements specified on the CriteriaSelector) the user's criteria
- * using the translations provided on the TranslateCriteria and symbol mapping between
- * virtual group elements and the expressions on the query transformation defining the
- * virtual group.</p>
- */
- private Criteria rewriteCriteria(TranslateCriteria transCrit)
- throws TeiidComponentException, TeiidProcessingException{
-
- // criteria translated
- Criteria translatedCriteria = null;
-
- // get the user's command from the procedure
- Command userCmd = procCommand.getUserCommand();
-
- if (!(userCmd instanceof TranslatableProcedureContainer)) {
- return FALSE_CRITERIA;
- }
-
- Criteria userCriteria = ((TranslatableProcedureContainer)userCmd).getCriteria();
-
- if (userCriteria == null) {
- return TRUE_CRITERIA;
- }
-
- // get the symbolmap between virtual elements and theie counterpart expressions
- // from the virtual group's query transform
- CriteriaTranslatorVisitor translateVisitor = new CriteriaTranslatorVisitor(procCommand.getSymbolMap());
-
- translateVisitor.setCriteriaSelector(transCrit.getSelector());
- if(transCrit.hasTranslations()) {
- translateVisitor.setTranslations(transCrit.getTranslations());
- }
-
- // create a clone of user's criteria that is then translated
- Criteria userClone = (Criteria) userCriteria.clone();
-
- userClone = translateVisitor.translate(userClone);
-
- // translated criteria
- ((TranslatableProcedureContainer)userCmd).addImplicitParameters(translateVisitor.getImplicitParams());
-
- translatedCriteria = rewriteCriteria(userClone);
-
- // apply any implicit conversions
- try {
- ResolverVisitor.resolveLanguageObject(translatedCriteria, metadata);
- } catch(TeiidException ex) {
- throw new QueryValidatorException(ex, "ERR.015.009.0002", QueryPlugin.Util.getString("ERR.015.009.0002", translatedCriteria)); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return translatedCriteria;
- }
-
- private Command rewriteQuery(Query query)
- throws TeiidComponentException, TeiidProcessingException{
-
- // Rewrite from clause
- From from = query.getFrom();
- if(from != null){
- List<FromClause> clauses = new ArrayList<FromClause>(from.getClauses().size());
- Iterator clauseIter = from.getClauses().iterator();
- while(clauseIter.hasNext()) {
- clauses.add( rewriteFromClause(query, (FromClause) clauseIter.next()) );
- }
- from.setClauses(clauses);
- } else {
- query.setOrderBy(null);
- }
-
- // Rewrite criteria
- Criteria crit = query.getCriteria();
- if(crit != null) {
- if (query.getIsXML()) {
- //only rewrite expressions, removing whole predicates could change the nature of the query,
- //because we aren't considering the xml pseudo-functions context, row limit, etc.
- rewriteExpressions(crit);
- } else {
- crit = rewriteCriteria(crit);
- }
- if(crit == TRUE_CRITERIA) {
- query.setCriteria(null);
- } else if (crit == UNKNOWN_CRITERIA) {
- query.setCriteria(FALSE_CRITERIA);
- } else {
- query.setCriteria(crit);
- }
- }
-
- if (from != null && !query.getIsXML()) {
- writeSubqueriesAsJoins(query);
- }
-
- query = rewriteGroupBy(query);
-
- // Rewrite having
- Criteria having = query.getHaving();
- if(having != null) {
- crit = rewriteCriteria(having);
- if(crit == TRUE_CRITERIA) {
- query.setHaving(null);
- } else {
- query.setHaving(crit);
- }
- }
-
- rewriteExpressions(query.getSelect());
-
- if (!query.getIsXML()) {
- query = (Query)rewriteOrderBy(query);
- }
-
- if (query.getLimit() != null) {
- query.setLimit(rewriteLimitClause(query.getLimit()));
- }
-
- if (query.getInto() != null) {
- return rewriteSelectInto(query);
- }
-
- return query;
- }
-
- private void writeSubqueriesAsJoins(Query query)
- throws TeiidComponentException, QueryMetadataException,
- QueryResolverException {
- if (query.getCriteria() == null) {
- return;
- }
- RuleMergeCriteria rmc = new RuleMergeCriteria(null, null, null, this.context, this.metadata);
- List<Criteria> current = Criteria.separateCriteriaByAnd(query.getCriteria());
- query.setCriteria(null);
- List<GroupSymbol> groups = query.getFrom().getGroups();
- HashSet<String> names = new HashSet<String>();
- for (GroupSymbol gs : groups) {
- names.add(gs.getCanonicalName());
- }
- for (Iterator<Criteria> crits = current.iterator(); crits.hasNext();) {
- PlannedResult plannedResult = rmc.findSubquery(crits.next());
- if (plannedResult.not || plannedResult.query == null || plannedResult.query.getProcessorPlan() != null
- || plannedResult.query.getWith() != null) {
- continue;
- }
- if (plannedResult.query.getCorrelatedReferences() == null) {
- //create the correlated refs if they exist
- //there is a little bit of a design problem here that null usually means no refs.
- ArrayList<Reference> correlatedReferences = new ArrayList<Reference>();
- CorrelatedReferenceCollectorVisitor.collectReferences(plannedResult.query, groups, correlatedReferences);
- if (!correlatedReferences.isEmpty()) {
- SymbolMap map = new SymbolMap();
- for (Reference reference : correlatedReferences) {
- map.addMapping(reference.getExpression(), reference.getExpression());
- }
- plannedResult.query.setCorrelatedReferences(map);
- }
- }
- boolean requiresDistinct = requiresDistinctRows(query);
- 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$
- viewName.setName(viewName.getCanonicalName());
- viewName.setDefinition(null);
- 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>();
- for (SingleElementSymbol symbol : plannedResult.query.getSelect().getProjectedSymbols()) {
- expressionMap.put(SymbolMap.getExpression(symbol), 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)));
- }
- 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));
- query.getTemporaryMetadata().putAll(q.getTemporaryMetadata());
- //transform the query into an inner join
- }
- query.setCriteria(Criteria.combineCriteria(query.getCriteria(), Criteria.combineCriteria(current)));
- }
-
- private boolean requiresDistinctRows(Query query) {
- Set<AggregateSymbol> aggs = new HashSet<AggregateSymbol>();
- aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(query.getSelect(), false));
- aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(query.getHaving(), false));
- if (!aggs.isEmpty() || query.getGroupBy() != null) {
- if (!AggregateSymbol.areAggregatesCardinalityDependent(aggs)) {
- return false;
- }
- } else if (query.getSelect().isDistinct()) {
- for (SingleElementSymbol projectSymbol : query.getSelect().getProjectedSymbols()) {
- Expression ex = SymbolMap.getExpression(projectSymbol);
- if (FunctionCollectorVisitor.isNonDeterministic(ex)) {
- return true;
- }
- if (!ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(ex).isEmpty()) {
- return true;
- }
- }
- return false;
- }
- return true;
- }
-
- /**
- * Converts a group by with expressions into a group by with only element symbols and an inline view
- * @param query
- * @return
- * @throws QueryValidatorException
- */
- private Query rewriteGroupBy(Query query) throws TeiidComponentException, TeiidProcessingException{
- if (query.getGroupBy() == null) {
- 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);
- return query;
- }
-
- public static boolean isDistinctWithGroupBy(Query query) {
- GroupBy groupBy = query.getGroupBy();
- if (groupBy == null) {
- return false;
- }
- HashSet<Expression> selectExpressions = new HashSet<Expression>();
- for (SingleElementSymbol selectExpr : query.getSelect().getProjectedSymbols()) {
- selectExpressions.add(SymbolMap.getExpression(selectExpr));
- }
- for (SingleElementSymbol groupByExpr : (List<SingleElementSymbol>)groupBy.getSymbols()) {
- if (!selectExpressions.contains(groupByExpr)) {
- return false;
- }
- }
- return true;
- }
-
- private void rewriteExpressions(LanguageObject obj) throws TeiidComponentException, TeiidProcessingException{
- if (obj == null) {
- return;
- }
- ExpressionMappingVisitor visitor = new ExpressionMappingVisitor(null) {
- /**
- * @see org.teiid.query.sql.visitor.ExpressionMappingVisitor#replaceExpression(org.teiid.query.sql.symbol.Expression)
- */
- @Override
- public Expression replaceExpression(Expression element) {
- try {
- return rewriteExpressionDirect(element);
- } catch (TeiidException err) {
- throw new TeiidRuntimeException(err);
- }
- }
- };
- try {
- PostOrderNavigator.doVisit(obj, visitor);
- } catch (TeiidRuntimeException err) {
- if (err.getChild() instanceof TeiidComponentException) {
- throw (TeiidComponentException)err.getChild();
- }
- if (err.getChild() instanceof TeiidProcessingException) {
- throw (TeiidProcessingException)err.getChild();
- }
- throw err;
- }
- }
-
- /**
- * Rewrite the order by clause.
- * Unrelated order by expressions will cause the creation of nested inline views.
- *
- * @param query
- * @throws TeiidComponentException, MetaMatrixProcessingException
- */
- public QueryCommand rewriteOrderBy(QueryCommand queryCommand) throws TeiidComponentException {
- final OrderBy orderBy = queryCommand.getOrderBy();
- if (orderBy == null) {
- return queryCommand;
- }
- Select select = queryCommand.getProjectedQuery().getSelect();
- final List<SingleElementSymbol> projectedSymbols = select.getProjectedSymbols();
-
- LinkedList<OrderByItem> unrelatedItems = new LinkedList<OrderByItem>();
-
- boolean hasUnrelatedExpression = 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;
- }
-
- public static boolean 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);
- int index = orderBy.getExpressionPosition(i);
- boolean isUnrelated = false;
- if (index == -1) {
- unrelatedItems.add(orderBy.getOrderByItems().get(i));
- isUnrelated = (querySymbol instanceof ExpressionSymbol);
- } else {
- querySymbol = (SingleElementSymbol)projectedSymbols.get(index);
- }
- Expression expr = SymbolMap.getExpression(querySymbol);
- if (!previousExpressions.add(expr) || (queryCommand instanceof Query && EvaluatableVisitor.willBecomeConstant(expr))) {
- 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;
- }
-
- /**
- * This method will alias each of the select into elements to the corresponding column name in the
- * target table. This ensures that they will all be uniquely named.
- *
- * @param query
- * @throws QueryValidatorException
- */
- private Insert rewriteSelectInto(Query query) throws TeiidProcessingException{
- Into into = query.getInto();
- try {
- List<ElementSymbol> allIntoElements = Util.deepClone(ResolverUtil.resolveElementsInGroup(into.getGroup(), metadata), ElementSymbol.class);
- Insert insert = new Insert(into.getGroup(), allIntoElements, Collections.emptyList());
- query.setInto(null);
- insert.setQueryExpression(query);
- return rewriteInsert(correctDatatypes(insert));
- } catch (QueryMetadataException err) {
- throw new QueryValidatorException(err, err.getMessage());
- } catch (TeiidComponentException err) {
- throw new QueryValidatorException(err, err.getMessage());
- }
- }
-
- private Insert correctDatatypes(Insert insert) {
- boolean needsView = false;
- for (int i = 0; !needsView && i < insert.getVariables().size(); i++) {
- SingleElementSymbol ses = insert.getVariables().get(i);
- if (ses.getType() != insert.getQueryExpression().getProjectedSymbols().get(i).getType()) {
- needsView = true;
- }
- }
- if (needsView) {
- try {
- insert.setQueryExpression(createInlineViewQuery(new GroupSymbol("X"), insert.getQueryExpression(), metadata, insert.getVariables())); //$NON-NLS-1$
- } catch (TeiidException err) {
- throw new TeiidRuntimeException(err);
- }
- }
- return insert;
- }
-
- private void correctProjectedTypes(List actualSymbolTypes, Query query) {
-
- List symbols = query.getSelect().getProjectedSymbols();
-
- List newSymbols = SetQuery.getTypedProjectedSymbols(symbols, actualSymbolTypes, this.metadata);
-
- query.getSelect().setSymbols(newSymbols);
- }
-
- private SetQuery rewriteSetQuery(SetQuery setQuery)
- throws TeiidComponentException, TeiidProcessingException{
-
- if (setQuery.getProjectedTypes() != null) {
- for (QueryCommand command : setQuery.getQueryCommands()) {
- if (!(command instanceof Query)) {
- continue;
- }
- correctProjectedTypes(setQuery.getProjectedTypes(), (Query)command);
- }
- setQuery.setProjectedTypes(null, null);
- }
-
- setQuery.setLeftQuery((QueryCommand)rewriteCommand(setQuery.getLeftQuery(), true));
- setQuery.setRightQuery((QueryCommand)rewriteCommand(setQuery.getRightQuery(), true));
-
- rewriteOrderBy(setQuery);
-
- if (setQuery.getLimit() != null) {
- setQuery.setLimit(rewriteLimitClause(setQuery.getLimit()));
- }
-
- return setQuery;
- }
-
- private FromClause rewriteFromClause(Query parent, FromClause clause)
- throws TeiidComponentException, TeiidProcessingException{
- if(clause instanceof JoinPredicate) {
- return rewriteJoinPredicate(parent, (JoinPredicate) clause);
- } else if (clause instanceof SubqueryFromClause) {
- rewriteSubqueryContainer((SubqueryFromClause)clause, true);
- } else if (clause instanceof TextTable) {
- TextTable tt = (TextTable)clause;
- tt.setFile(rewriteExpressionDirect(tt.getFile()));
- } else if (clause instanceof XMLTable) {
- XMLTable xt = (XMLTable)clause;
- xt.rewriteDefaultColumn();
- rewriteExpressions(clause);
- } else if (clause instanceof ArrayTable) {
- ArrayTable at = (ArrayTable)clause;
- at.setArrayValue(rewriteExpressionDirect(at.getArrayValue()));
- }
- return clause;
- }
-
- private JoinPredicate rewriteJoinPredicate(Query parent, JoinPredicate predicate)
- throws TeiidComponentException, TeiidProcessingException{
- List joinCrits = predicate.getJoinCriteria();
- if(joinCrits != null && joinCrits.size() > 0) {
- //rewrite join crits by rewriting a compound criteria
- Criteria criteria = new CompoundCriteria(new ArrayList(joinCrits));
- joinCrits.clear();
- criteria = rewriteCriteria(criteria);
- if (criteria instanceof CompoundCriteria && ((CompoundCriteria)criteria).getOperator() == CompoundCriteria.AND) {
- joinCrits.addAll(((CompoundCriteria)criteria).getCriteria());
- } else {
- joinCrits.add(criteria);
- }
- predicate.setJoinCriteria(joinCrits);
- }
-
- if (predicate.getJoinType() == JoinType.JOIN_UNION) {
- predicate.setJoinType(JoinType.JOIN_FULL_OUTER);
- predicate.setJoinCriteria(new ArrayList<Criteria>(Arrays.asList(FALSE_CRITERIA)));
- } else if (predicate.getJoinType() == JoinType.JOIN_RIGHT_OUTER) {
- predicate.setJoinType(JoinType.JOIN_LEFT_OUTER);
- FromClause leftClause = predicate.getLeftClause();
- predicate.setLeftClause(predicate.getRightClause());
- predicate.setRightClause(leftClause);
- }
-
- predicate.setLeftClause( rewriteFromClause(parent, predicate.getLeftClause() ));
- predicate.setRightClause( rewriteFromClause(parent, predicate.getRightClause() ));
-
- return predicate;
- }
-
- /**
- * Rewrite the criteria by evaluating some trivial cases.
- * @param criteria The criteria to rewrite
- * @param metadata
- * @param userCriteria The criteria on user's command, used in rewriting HasCriteria
- * in the procedural language.
- * @return The re-written criteria
- */
- public static Criteria rewriteCriteria(Criteria criteria, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException{
- return new QueryRewriter(metadata, context, procCommand).rewriteCriteria(criteria);
- }
-
- /**
- * Rewrite the criteria by evaluating some trivial cases.
- * @param criteria The criteria to rewrite
- * @param userCriteria The criteria on user's command, used in rewriting HasCriteria
- * in the procedural language.
- * @return The re-written criteria
- */
- private Criteria rewriteCriteria(Criteria criteria) throws TeiidComponentException, TeiidProcessingException{
- if(criteria instanceof CompoundCriteria) {
- return rewriteCriteria((CompoundCriteria)criteria, true);
- } else if(criteria instanceof NotCriteria) {
- criteria = rewriteCriteria((NotCriteria)criteria);
- } else if(criteria instanceof CompareCriteria) {
- criteria = rewriteCriteria((CompareCriteria)criteria);
- } else if(criteria instanceof SubqueryCompareCriteria) {
- criteria = rewriteCriteria((SubqueryCompareCriteria)criteria);
- } else if(criteria instanceof MatchCriteria) {
- criteria = rewriteCriteria((MatchCriteria)criteria);
- } else if(criteria instanceof SetCriteria) {
- criteria = rewriteCriteria((SetCriteria)criteria);
- } else if(criteria instanceof IsNullCriteria) {
- criteria = rewriteCriteria((IsNullCriteria)criteria);
- } else if(criteria instanceof BetweenCriteria) {
- criteria = rewriteCriteria((BetweenCriteria)criteria);
- } else if(criteria instanceof HasCriteria) {
- criteria = rewriteCriteria((HasCriteria)criteria);
- } else if(criteria instanceof TranslateCriteria) {
- criteria = rewriteCriteria((TranslateCriteria)criteria);
- } else if (criteria instanceof ExistsCriteria) {
- ExistsCriteria exists = (ExistsCriteria)criteria;
- if (exists.shouldEvaluate() && processing) {
- return getCriteria(evaluator.evaluate(exists, null));
- }
- rewriteSubqueryContainer((SubqueryContainer)criteria, true);
- if (!RelationalNodeUtil.shouldExecute(exists.getCommand(), false, true)) {
- return exists.isNegated()?TRUE_CRITERIA:FALSE_CRITERIA;
- }
- if (exists.getCommand().getProcessorPlan() == null) {
- if (exists.getCommand() instanceof Query) {
- Query query = (Query)exists.getCommand();
- if ((query.getLimit() == null || query.getOrderBy() == null) && query.getSelect().getProjectedSymbols().size() > 1) {
- query.getSelect().clearSymbols();
- query.getSelect().addSymbol(new ExpressionSymbol("x", new Constant(1))); //$NON-NLS-1$
- }
- }
- addImplicitLimit(exists, 1);
- }
- } else if (criteria instanceof SubquerySetCriteria) {
- SubquerySetCriteria sub = (SubquerySetCriteria)criteria;
- if (rewriteLeftExpression(sub)) {
- return UNKNOWN_CRITERIA;
- }
- rewriteSubqueryContainer(sub, true);
- if (!RelationalNodeUtil.shouldExecute(sub.getCommand(), false, true)) {
- return getSimpliedCriteria(criteria, sub.getExpression(), !sub.isNegated(), true);
- }
- } else if (criteria instanceof DependentSetCriteria) {
- criteria = rewriteDependentSetCriteria((DependentSetCriteria)criteria);
- } else if (criteria instanceof ExpressionCriteria) {
- return new CompareCriteria(((ExpressionCriteria) criteria).getExpression(), CompareCriteria.EQ, new Constant(Boolean.TRUE));
- }
-
- return evaluateCriteria(criteria);
- }
-
- private void addImplicitLimit(SubqueryContainer<QueryCommand> container, int rowLimit) {
- if (container.getCommand().getLimit() != null) {
- Limit lim = container.getCommand().getLimit();
- if (lim.getRowLimit() instanceof Constant) {
- Constant c = (Constant)lim.getRowLimit();
- if (!c.isMultiValued() && Integer.valueOf(rowLimit).compareTo((Integer) c.getValue()) <= 0) {
- lim.setRowLimit(new Constant(rowLimit));
- if (lim.getRowLimit() == null) {
- lim.setImplicit(true);
- container.getCommand().setOrderBy(null);
- }
- }
- }
- return;
- }
- boolean addLimit = true;
- if (container.getCommand() instanceof Query) {
- Query query = (Query)container.getCommand();
- addLimit = !(query.hasAggregates() && query.getGroupBy() == null);
- }
- if (addLimit) {
- Limit lim = new Limit(null, new Constant(rowLimit));
- lim.setImplicit(true);
- container.getCommand().setLimit(lim);
- }
- }
-
- private Criteria rewriteDependentSetCriteria(DependentSetCriteria dsc)
- throws TeiidComponentException, TeiidProcessingException{
- if (!processing) {
- if (rewriteLeftExpression(dsc)) {
- return UNKNOWN_CRITERIA;
- }
- }
- return dsc;
- }
-
- /**
- * Performs simple expression flattening
- *
- * @param criteria
- * @return
- */
- public static Criteria optimizeCriteria(CompoundCriteria criteria, QueryMetadataInterface metadata) {
- try {
- return new QueryRewriter(metadata, null, null).rewriteCriteria(criteria, false);
- } catch (TeiidException err) {
- //shouldn't happen
- return criteria;
- }
- }
-
- /** May be simplified if this is an AND and a sub criteria is always
- * false or if this is an OR and a sub criteria is always true
- */
- private Criteria rewriteCriteria(CompoundCriteria criteria, boolean rewrite) throws TeiidComponentException, TeiidProcessingException{
- List<Criteria> crits = criteria.getCriteria();
- int operator = criteria.getOperator();
-
- // Walk through crits and collect converted ones
- LinkedHashSet<Criteria> newCrits = new LinkedHashSet<Criteria>(crits.size());
- HashMap<Expression, Criteria> exprMap = new HashMap<Expression, Criteria>();
- for (Criteria converted : crits) {
- if (rewrite) {
- converted = rewriteCriteria(converted);
- } else if (converted instanceof CompoundCriteria) {
- converted = rewriteCriteria((CompoundCriteria)converted, false);
- }
- List<Criteria> critList = null;
- if (converted instanceof CompoundCriteria) {
- CompoundCriteria other = (CompoundCriteria)converted;
- if (other.getOperator() == criteria.getOperator()) {
- critList = other.getCriteria();
- }
- }
- if (critList == null) {
- critList = Arrays.asList(converted);
- }
- for (Criteria criteria2 : critList) {
- converted = criteria2;
- //begin boolean optimizations
- if(TRUE_CRITERIA.equals(converted)) {
- if(operator == CompoundCriteria.OR) {
- // this OR must be true as at least one branch is always true
- return converted;
- }
- } else if(FALSE_CRITERIA.equals(converted)) {
- if(operator == CompoundCriteria.AND) {
- // this AND must be false as at least one branch is always false
- return converted;
- }
- } else if (UNKNOWN_CRITERIA.equals(converted)) {
- if (operator == CompoundCriteria.AND) {
- return FALSE_CRITERIA;
- }
- } else {
- if (operator == CompoundCriteria.AND) {
- converted = rewriteAndConjunct(converted, exprMap, newCrits);
- if (converted != null) {
- return converted;
- }
- } else {
- //or
- if (converted instanceof SetCriteria) {
- SetCriteria sc = (SetCriteria)converted;
- if (!sc.isNegated() && sc.isAllConstants()) {
- Criteria crit = exprMap.get(sc.getExpression());
- if (crit == null) {
- exprMap.put(sc.getExpression(), sc);
- } else if (crit instanceof SetCriteria) {
- SetCriteria other = (SetCriteria)crit;
- other.getValues().addAll(sc.getValues());
- continue;
- } else {
- newCrits.remove(crit);
- CompareCriteria cc = (CompareCriteria)crit;
- sc.getValues().add(cc.getRightExpression());
- }
- }
- } else if (converted instanceof CompareCriteria) {
- CompareCriteria cc = (CompareCriteria)converted;
- if (cc.getOperator() == CompareCriteria.EQ && cc.getRightExpression() instanceof Constant) {
- Criteria crit = exprMap.get(cc.getLeftExpression());
- if (crit == null) {
- exprMap.put(cc.getLeftExpression(), cc);
- } else if (crit instanceof SetCriteria) {
- SetCriteria other = (SetCriteria)crit;
- other.getValues().add(cc.getRightExpression());
- continue;
- } else {
- newCrits.remove(crit);
- CompareCriteria other = (CompareCriteria)crit;
- SetCriteria sc = new SetCriteria(cc.getLeftExpression(), new LinkedHashSet<Expression>());
- sc.setAllConstants(true);
- sc.getValues().add(cc.getRightExpression());
- sc.getValues().add(other.getRightExpression());
- exprMap.put(sc.getExpression(), sc);
- converted = sc;
- }
- }
- }
- newCrits.add(converted);
- }
- }
- }
- }
-
- if(newCrits.size() == 0) {
- if(operator == CompoundCriteria.AND) {
- return TRUE_CRITERIA;
- }
- return FALSE_CRITERIA;
- } else if(newCrits.size() == 1) {
- // Only one sub crit now, so just return it
- return newCrits.iterator().next();
- } else {
- criteria.getCriteria().clear();
- criteria.getCriteria().addAll(newCrits);
- return criteria;
- }
- }
-
- /**
- * Rewrite the given conjunct
- * @return null if the conjunct was internally handled
- */
- private Criteria rewriteAndConjunct(Criteria converted, Map<Expression, Criteria> exprMap, LinkedHashSet<Criteria> newCrits) throws ExpressionEvaluationException {
- if (converted instanceof IsNullCriteria) {
- IsNullCriteria inc = (IsNullCriteria)converted;
- if (!inc.isNegated()) {
- Criteria crit = exprMap.get(inc.getExpression());
- if (crit == null) {
- exprMap.put(inc.getExpression(), converted);
- } else if (!(crit instanceof IsNullCriteria)) {
- return FALSE_CRITERIA;
- }
- }
- } else if (converted instanceof SetCriteria) {
- SetCriteria sc = (SetCriteria)converted;
- Criteria crit = exprMap.get(sc.getExpression());
- if (crit instanceof IsNullCriteria) {
- return FALSE_CRITERIA;
- }
- if (!sc.isNegated() && sc.isAllConstants()) {
- if (crit == null) {
- exprMap.put(sc.getExpression(), converted);
- } else if (crit instanceof SetCriteria) {
- SetCriteria sc1 = (SetCriteria)crit;
- newCrits.remove(sc1);
- sc1.getValues().retainAll(sc.getValues());
- if (sc1.getValues().isEmpty()) {
- return FALSE_CRITERIA;
- }
- //TODO: single value as compare criteria
- newCrits.add(sc1);
- exprMap.put(sc1.getExpression(), sc1);
- return null;
- } else {
- CompareCriteria cc = (CompareCriteria)crit;
- for (Iterator<Constant> exprIter = sc.getValues().iterator(); exprIter.hasNext();) {
- if (!Evaluator.compare(cc, exprIter.next().getValue(), ((Constant)cc.getRightExpression()).getValue())) {
- exprIter.remove();
- }
- }
- if (sc.getValues().isEmpty()) {
- return FALSE_CRITERIA;
- }
- if (cc.getOperator() != CompareCriteria.EQ) {
- newCrits.remove(cc);
- //TODO: single value as compare criteria
- exprMap.put(sc.getExpression(), sc);
- } else {
- return null;
- }
- }
- }
- } else if (converted instanceof CompareCriteria) {
- CompareCriteria cc = (CompareCriteria)converted;
- Criteria crit = exprMap.get(cc.getLeftExpression());
- if (crit instanceof IsNullCriteria) {
- return FALSE_CRITERIA;
- }
- if (cc.getRightExpression() instanceof Constant) {
- if (crit == null) {
- exprMap.put(cc.getLeftExpression(), cc);
- } else if (crit instanceof SetCriteria) {
- SetCriteria sc = (SetCriteria)crit;
- boolean modified = false;
- for (Iterator<Constant> exprIter = sc.getValues().iterator(); exprIter.hasNext();) {
- if (!Evaluator.compare(cc, exprIter.next().getValue(), ((Constant)cc.getRightExpression()).getValue())) {
- if (!modified) {
- modified = true;
- newCrits.remove(sc);
- }
- exprIter.remove();
- }
- }
- //TODO: single value as compare criteria
- if (sc.getValues().isEmpty()) {
- return FALSE_CRITERIA;
- }
- if (cc.getOperator() == CompareCriteria.EQ) {
- exprMap.put(cc.getLeftExpression(), cc);
- } else if (modified) {
- newCrits.add(sc);
- exprMap.put(sc.getExpression(), sc);
- return null;
- }
- } else {
- CompareCriteria cc1 = (CompareCriteria)crit;
- if (cc1.getOperator() == CompareCriteria.NE) {
- exprMap.put(cc.getLeftExpression(), cc);
- } else if (cc1.getOperator() == CompareCriteria.EQ) {
- if (!Evaluator.compare(cc1, ((Constant)cc1.getRightExpression()).getValue(), ((Constant)cc.getRightExpression()).getValue())) {
- return FALSE_CRITERIA;
- }
- return null;
- }
- if (cc.getOperator() == CompareCriteria.EQ) {
- if (!Evaluator.compare(cc1, ((Constant)cc.getRightExpression()).getValue(), ((Constant)cc1.getRightExpression()).getValue())) {
- return FALSE_CRITERIA;
- }
- exprMap.put(cc.getLeftExpression(), cc);
- newCrits.remove(cc1);
- }
- }
- }
- }
- newCrits.add(converted);
- return null;
- }
-
- private Criteria evaluateCriteria(Criteria crit) throws TeiidComponentException, TeiidProcessingException{
- if(EvaluatableVisitor.isFullyEvaluatable(crit, !processing)) {
- try {
- Boolean eval = evaluator.evaluateTVL(crit, Collections.emptyList());
-
- return getCriteria(eval);
-
- } catch(ExpressionEvaluationException e) {
- throw new QueryValidatorException(e, "ERR.015.009.0001", QueryPlugin.Util.getString("ERR.015.009.0001", crit)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- return crit;
- }
-
- private Criteria getCriteria(Boolean eval) {
- if (eval == null) {
- return UNKNOWN_CRITERIA;
- }
-
- if(Boolean.TRUE.equals(eval)) {
- return TRUE_CRITERIA;
- }
-
- return FALSE_CRITERIA;
- }
-
- private Criteria rewriteCriteria(NotCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
- Criteria innerCrit = criteria.getCriteria();
- if (innerCrit instanceof CompoundCriteria) {
- //reduce to only negation of predicates, so that the null/unknown handling criteria is applied appropriately
- return rewriteCriteria(Criteria.applyDemorgan(innerCrit));
- }
- if (innerCrit instanceof Negatable) {
- ((Negatable) innerCrit).negate();
- return rewriteCriteria(innerCrit);
- }
- if (innerCrit instanceof NotCriteria) {
- return rewriteCriteria(((NotCriteria)innerCrit).getCriteria());
- }
- innerCrit = rewriteCriteria(innerCrit);
- if(innerCrit == TRUE_CRITERIA) {
- return FALSE_CRITERIA;
- } else if(innerCrit == FALSE_CRITERIA) {
- return TRUE_CRITERIA;
- } else if (innerCrit == UNKNOWN_CRITERIA) {
- return UNKNOWN_CRITERIA;
- }
- criteria.setCriteria(innerCrit);
- return criteria;
- }
-
- /**
- * Rewrites "a [NOT] BETWEEN b AND c" as "a >= b AND a <= c", or as "a <= b OR a>= c"
- * @param criteria
- * @return
- * @throws QueryValidatorException
- */
- private Criteria rewriteCriteria(BetweenCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
- CompareCriteria lowerCriteria = new CompareCriteria(criteria.getExpression(),
- criteria.isNegated() ? CompareCriteria.LT: CompareCriteria.GE,
- criteria.getLowerExpression());
- CompareCriteria upperCriteria = new CompareCriteria(criteria.getExpression(),
- criteria.isNegated() ? CompareCriteria.GT: CompareCriteria.LE,
- criteria.getUpperExpression());
- CompoundCriteria newCriteria = new CompoundCriteria(criteria.isNegated() ? CompoundCriteria.OR : CompoundCriteria.AND,
- lowerCriteria,
- upperCriteria);
-
- return rewriteCriteria(newCriteria);
- }
-
- private Criteria rewriteCriteria(CompareCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
- Expression leftExpr = rewriteExpressionDirect(criteria.getLeftExpression());
- Expression rightExpr = rewriteExpressionDirect(criteria.getRightExpression());
- criteria.setLeftExpression(leftExpr);
- criteria.setRightExpression(rightExpr);
-
- if (isNull(leftExpr) || isNull(rightExpr)) {
- return UNKNOWN_CRITERIA;
- }
-
- boolean rightConstant = false;
- if(EvaluatableVisitor.willBecomeConstant(rightExpr)) {
- rightConstant = true;
- } else if (EvaluatableVisitor.willBecomeConstant(leftExpr)) {
- // Swap in this particular case for connectors
- criteria.setLeftExpression(rightExpr);
- criteria.setRightExpression(leftExpr);
-
- // Check for < or > operator as we have to switch it
- switch(criteria.getOperator()) {
- case CompareCriteria.LT: criteria.setOperator(CompareCriteria.GT); break;
- case CompareCriteria.LE: criteria.setOperator(CompareCriteria.GE); break;
- case CompareCriteria.GT: criteria.setOperator(CompareCriteria.LT); break;
- case CompareCriteria.GE: criteria.setOperator(CompareCriteria.LE); break;
- }
- rightConstant = true;
- }
-
- Function f = null;
- while (rightConstant && f != criteria.getLeftExpression() && criteria.getLeftExpression() instanceof Function) {
- f = (Function)criteria.getLeftExpression();
- Criteria result = simplifyWithInverse(criteria);
- if (!(result instanceof CompareCriteria)) {
- return result;
- }
- criteria = (CompareCriteria)result;
- }
-
- Criteria modCriteria = simplifyTimestampMerge(criteria);
- if(modCriteria instanceof CompareCriteria) {
- modCriteria = simplifyTimestampMerge2((CompareCriteria)modCriteria);
- }
- return modCriteria;
- }
-
- public static boolean isNull(Expression expr) {
- return expr instanceof Constant && ((Constant)expr).isNull();
- }
-
- /*
- * The thing of primary importance here is that the use of the 'ANY' predicate
- * quantifier is replaced with the canonical and equivalent 'SOME'
- */
- 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) {
- 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;
- }
- 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());
-
- if (isNull(leftExpr)) {
- return UNKNOWN_CRITERIA;
- }
-
- criteria.setLeftExpression(leftExpr);
-
- if (criteria.getPredicateQuantifier() == SubqueryCompareCriteria.ANY){
- criteria.setPredicateQuantifier(SubqueryCompareCriteria.SOME);
- }
-
- rewriteSubqueryContainer(criteria, true);
-
- if (!RelationalNodeUtil.shouldExecute(criteria.getCommand(), false, true)) {
- return getSimpliedCriteria(criteria, criteria.getLeftExpression(), criteria.getPredicateQuantifier()==SubqueryCompareCriteria.ALL, true);
- }
-
- return criteria;
- }
-
- private Criteria simplifyWithInverse(CompareCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
- Expression leftExpr = criteria.getLeftExpression();
-
- Function leftFunction = (Function) leftExpr;
- if(isSimpleMathematicalFunction(leftFunction)) {
- return simplifyMathematicalCriteria(criteria);
- }
- if (FunctionLibrary.isConvert(leftFunction)) {
- return simplifyConvertFunction(criteria);
- }
- return simplifyParseFormatFunction(criteria);
- }
-
- private boolean isSimpleMathematicalFunction(Function function) {
- String funcName = function.getName();
- if(funcName.equals("+") || funcName.equals("-") || funcName.equals("*") || funcName.equals("/")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Expression[] args = function.getArgs();
- if(args[0] instanceof Constant || args[1] instanceof Constant) {
- return true;
- }
- }
-
- // fall through - not simple mathematical
- return false;
- }
-
- // Constants used in simplifying mathematical criteria
- private Integer INTEGER_ZERO = new Integer(0);
- private Double DOUBLE_ZERO = new Double(0);
- private Float FLOAT_ZERO = new Float(0);
- private Long LONG_ZERO = new Long(0);
- private BigInteger BIG_INTEGER_ZERO = new BigInteger("0"); //$NON-NLS-1$
- private BigDecimal BIG_DECIMAL_ZERO = new BigDecimal("0"); //$NON-NLS-1$
- private Short SHORT_ZERO = new Short((short)0);
- private Byte BYTE_ZERO = new Byte((byte)0);
-
- /**
- * @param criteria
- * @return CompareCriteria
- */
- private CompareCriteria simplifyMathematicalCriteria(CompareCriteria criteria)
- throws TeiidComponentException, TeiidProcessingException{
-
- Expression leftExpr = criteria.getLeftExpression();
- Expression rightExpr = criteria.getRightExpression();
-
- // Identify all the pieces of this criteria
- Function function = (Function) leftExpr;
- String funcName = function.getName();
- Expression[] args = function.getArgs();
- Constant const1 = null;
- Expression expr = null;
- if(args[1] instanceof Constant) {
- const1 = (Constant) args[1];
- expr = args[0];
- } else {
- if(funcName.equals("+") || funcName.equals("*")) { //$NON-NLS-1$ //$NON-NLS-2$
- const1 = (Constant) args[0];
- expr = args[1];
- } else {
- // If we have "5 - x = 10" or "5 / x = 10", abort!
- return criteria;
- }
- }
- int operator = criteria.getOperator();
-
- // Determine opposite function
- String oppFunc = null;
- switch(funcName.charAt(0)) {
- case '+': oppFunc = "-"; break; //$NON-NLS-1$
- case '-': oppFunc = "+"; break; //$NON-NLS-1$
- case '*': oppFunc = "/"; break; //$NON-NLS-1$
- case '/': oppFunc = "*"; break; //$NON-NLS-1$
- }
-
- // Create a function of the two constants and evaluate it
- Expression combinedConst = null;
- FunctionLibrary funcLib = this.metadata.getFunctionLibrary();
- FunctionDescriptor descriptor = funcLib.findFunction(oppFunc, new Class[] { rightExpr.getType(), const1.getType() });
- if (descriptor == null){
- //See defect 9380 - this can be caused by const2 being a null Constant, for example (? + 1) < null
- return criteria;
- }
-
-
- if (rightExpr instanceof Constant) {
- Constant const2 = (Constant)rightExpr;
- try {
- Object result = descriptor.invokeFunction(new Object[] { const2.getValue(), const1.getValue() } );
- combinedConst = new Constant(result, descriptor.getReturnType());
- } catch(FunctionExecutionException e) {
- throw new QueryValidatorException(e, "ERR.015.009.0003", QueryPlugin.Util.getString("ERR.015.009.0003", e.getMessage())); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } else {
- Function conversion = new Function(descriptor.getName(), new Expression[] { rightExpr, const1 });
- conversion.setType(leftExpr.getType());
- conversion.setFunctionDescriptor(descriptor);
- combinedConst = conversion;
-
- }
-
- // Flip operator if necessary
- if(! (operator == CompareCriteria.EQ || operator == CompareCriteria.NE) &&
- (oppFunc.equals("*") || oppFunc.equals("/")) ) { //$NON-NLS-1$ //$NON-NLS-2$
-
- Object value = const1.getValue();
- if(value != null) {
- Class type = const1.getType();
- Comparable comparisonObject = null;
- if(type.equals(DataTypeManager.DefaultDataClasses.INTEGER)) {
- comparisonObject = INTEGER_ZERO;
- } else if(type.equals(DataTypeManager.DefaultDataClasses.DOUBLE)) {
- comparisonObject = DOUBLE_ZERO;
- } else if(type.equals(DataTypeManager.DefaultDataClasses.FLOAT)) {
- comparisonObject = FLOAT_ZERO;
- } else if(type.equals(DataTypeManager.DefaultDataClasses.LONG)) {
- comparisonObject = LONG_ZERO;
- } else if(type.equals(DataTypeManager.DefaultDataClasses.BIG_INTEGER)) {
- comparisonObject = BIG_INTEGER_ZERO;
- } else if(type.equals(DataTypeManager.DefaultDataClasses.BIG_DECIMAL)) {
- comparisonObject = BIG_DECIMAL_ZERO;
- } else if(type.equals(DataTypeManager.DefaultDataClasses.SHORT)) {
- comparisonObject = SHORT_ZERO;
- } else if(type.equals(DataTypeManager.DefaultDataClasses.BYTE)) {
- comparisonObject = BYTE_ZERO;
- } else {
- // Unknown type
- return criteria;
- }
-
- // If value is less than comparison object (which is zero),
- // then need to switch operator.
- if(comparisonObject.compareTo(value) > 0) {
- switch(operator) {
- case CompareCriteria.LE: operator = CompareCriteria.GE; break;
- case CompareCriteria.LT: operator = CompareCriteria.GT; break;
- case CompareCriteria.GE: operator = CompareCriteria.LE; break;
- case CompareCriteria.GT: operator = CompareCriteria.LT; break;
- }
- }
- }
- }
-
- criteria.setLeftExpression(expr);
- criteria.setRightExpression(combinedConst);
- criteria.setOperator(operator);
-
- // Return new simplified criteria
- return criteria;
- }
-
- /**
- * This method attempts to rewrite compare criteria of the form
- *
- * <code>convert(typedColumn, string) = '5'</code>
- *
- * into
- *
- * <code>typedColumn = convert('5', typeOfColumn)</code>
- * where 'typeOfColumn' is the type of 'typedColumn'
- *
- * if, for example, the type of the column is integer, than the above
- * can be pre-evaluated to
- *
- * <code>typedColumn = 5 </code>
- *
- * Right expression has already been checked to be a Constant, left expression to be
- * a function. Function is known to be "convert" or "cast".
- *
- * @param crit CompareCriteria
- * @return same Criteria instance (possibly optimized)
- * @throws QueryValidatorException
- * @since 4.2
- */
- private Criteria simplifyConvertFunction(CompareCriteria crit) {
- Function leftFunction = (Function) crit.getLeftExpression();
- Expression leftExpr = leftFunction.getArgs()[0];
-
- if(!(crit.getRightExpression() instanceof Constant)
- //TODO: this can be relaxed for order preserving operations
- || !(crit.getOperator() == CompareCriteria.EQ || crit.getOperator() == CompareCriteria.NE)) {
- return crit;
- }
-
- Constant rightConstant = (Constant) crit.getRightExpression();
-
- String leftExprTypeName = DataTypeManager.getDataTypeName(leftExpr.getType());
-
- Constant result = ResolverUtil.convertConstant(DataTypeManager.getDataTypeName(rightConstant.getType()), leftExprTypeName, rightConstant);
- if (result == null) {
- return getSimpliedCriteria(crit, leftExpr, crit.getOperator() != CompareCriteria.EQ, true);
- }
- Constant other = ResolverUtil.convertConstant(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()), result);
- if (other == null || ((Comparable)rightConstant.getValue()).compareTo(other.getValue()) != 0) {
- return getSimpliedCriteria(crit, leftExpr, crit.getOperator() != CompareCriteria.EQ, true);
- }
-
- if (!DataTypeManager.isImplicitConversion(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()))) {
- return crit;
- }
-
- crit.setRightExpression(result);
- crit.setLeftExpression(leftExpr);
-
- return crit;
- }
-
-
- /**
- * This method attempts to rewrite set criteria of the form
- *
- * <code>convert(typedColumn, string) in ('5', '6')</code>
- *
- * into
- *
- * <code>typedColumn in (convert('5', typeOfColumn), convert('6', typeOfColumn)) </code>
- * where 'typeOfColumn' is the type of 'typedColumn'
- *
- * if, for example, the type of the column is integer, than the above
- * can be pre-evaluated to
- *
- * <code>typedColumn in (5,6) </code>
- *
- * Right expression has already been checked to be a Constant, left expression to be
- * a function. Function is known to be "convert" or "cast". The scope of this change
- * will be limited to the case where the left expression is attempting to convert to
- * 'string'.
- *
- * @param crit CompareCriteria
- * @return same Criteria instance (possibly optimized)
- * @throws QueryValidatorException
- * @since 4.2
- */
- private Criteria simplifyConvertFunction(SetCriteria crit) throws TeiidComponentException, TeiidProcessingException{
- Function leftFunction = (Function) crit.getExpression();
- Expression leftExpr = leftFunction.getArgs()[0];
- String leftExprTypeName = DataTypeManager.getDataTypeName(leftExpr.getType());
-
- Iterator i = crit.getValues().iterator();
- Collection newValues = new ArrayList(crit.getNumberOfValues());
-
- boolean convertedAll = true;
- boolean removedSome = false;
- while (i.hasNext()) {
- Object next = i.next();
- if (!(next instanceof Constant)) {
- convertedAll = false;
- continue;
- }
-
- Constant rightConstant = (Constant) next;
-
- Constant result = ResolverUtil.convertConstant(DataTypeManager.getDataTypeName(rightConstant.getType()), leftExprTypeName, rightConstant);
- if (result != null) {
- Constant other = ResolverUtil.convertConstant(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()), result);
- if (other == null || ((Comparable)rightConstant.getValue()).compareTo(other.getValue()) != 0) {
- result = null;
- }
- }
-
- if (result == null) {
- removedSome = true;
- i.remove();
- } else if (DataTypeManager.isImplicitConversion(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()))) {
- newValues.add(result);
- } else {
- convertedAll = false;
- }
- }
-
- if (!convertedAll) {
- if (!removedSome) {
- return crit; //just return as is
- }
- } else {
- if (newValues.isEmpty()) {
- return getSimpliedCriteria(crit, leftExpr, !crit.isNegated(), true);
- }
- crit.setExpression(leftExpr);
- crit.setValues(newValues);
- }
- return rewriteCriteria(crit);
- }
-
- private Criteria simplifyParseFormatFunction(CompareCriteria crit) {
- //TODO: this can be relaxed for order preserving operations
- if(!(crit.getOperator() == CompareCriteria.EQ || crit.getOperator() == CompareCriteria.NE)) {
- return crit;
- }
- boolean isFormat = false;
- Function leftFunction = (Function) crit.getLeftExpression();
- String funcName = leftFunction.getName().toLowerCase();
- String inverseFunction = null;
- if(funcName.startsWith("parse")) { //$NON-NLS-1$
- String type = funcName.substring(5);
- if (!PARSE_FORMAT_TYPES.contains(type)) {
- return crit;
- }
- inverseFunction = "format" + type; //$NON-NLS-1$
- } else if(funcName.startsWith("format")) { //$NON-NLS-1$
- String type = funcName.substring(6);
- if (!PARSE_FORMAT_TYPES.contains(type)) {
- return crit;
- }
- inverseFunction = "parse" + type; //$NON-NLS-1$
- isFormat = true;
- } else {
- return crit;
- }
- Expression rightExpr = crit.getRightExpression();
- if (!(rightExpr instanceof Constant)) {
- return crit;
- }
- Expression leftExpr = leftFunction.getArgs()[0];
- Expression formatExpr = leftFunction.getArgs()[1];
- if(!(formatExpr instanceof Constant)) {
- return crit;
- }
- String format = (String)((Constant)formatExpr).getValue();
- FunctionLibrary funcLib = this.metadata.getFunctionLibrary();
- FunctionDescriptor descriptor = funcLib.findFunction(inverseFunction, new Class[] { rightExpr.getType(), formatExpr.getType() });
- if(descriptor == null){
- return crit;
- }
- Object value = ((Constant)rightExpr).getValue();
- try {
- Object result = descriptor.invokeFunction(new Object[] {((Constant)rightExpr).getValue(), format});
- result = leftFunction.getFunctionDescriptor().invokeFunction(new Object[] { result, format } );
- if (((Comparable)value).compareTo(result) != 0) {
- return getSimpliedCriteria(crit, leftExpr, crit.getOperator() != CompareCriteria.EQ, true);
- }
- } catch(FunctionExecutionException e) {
- //Not all numeric formats are invertable, so just return the criteria as it may still be valid
- return crit;
- }
- //parseFunctions are all potentially narrowing
- if (!isFormat) {
- return crit;
- }
- //TODO: if format is not lossy, then invert the function
- return crit;
- }
-
- /**
- * This method applies a similar simplification as the previous method for Case 1829. This is conceptually
- * the same thing but done using the timestampCreate system function.
- *
- * TIMESTAMPCREATE(rpcolli_physical.RPCOLLI.Table_B.date_field, rpcolli_physical.RPCOLLI.Table_B.time_field)
- * = {ts'1969-09-20 18:30:45.0'}
- *
- * -------------
- *
- * rpcolli_physical.RPCOLLI.Table_B.date_field = {d'1969-09-20'}
- * AND
- * rpcolli_physical.RPCOLLI.Table_B.time_field = {t'18:30:45'}
- *
- *
- * @param criteria Compare criteria
- * @return Simplified criteria, if possible
- */
- private Criteria simplifyTimestampMerge2(CompareCriteria criteria) {
- if(criteria.getOperator() != CompareCriteria.EQ) {
- return criteria;
- }
-
- Expression leftExpr = criteria.getLeftExpression();
- Expression rightExpr = criteria.getRightExpression();
-
- // Allow for concat and string literal to be on either side
- Function tsCreateFunction = null;
- Constant timestampConstant = null;
- if(leftExpr instanceof Function && rightExpr instanceof Constant) {
- tsCreateFunction = (Function) leftExpr;
- timestampConstant = (Constant) rightExpr;
- } else {
- return criteria;
- }
-
- // Verify data type of constant and that constant has a value
- if(! timestampConstant.getType().equals(DataTypeManager.DefaultDataClasses.TIMESTAMP)) {
- return criteria;
- }
-
- // Verify function is timestampCreate function
- if(! (tsCreateFunction.getName().equalsIgnoreCase("timestampCreate"))) { //$NON-NLS-1$
- return criteria;
- }
-
- // Get timestamp literal and break into pieces
- Timestamp ts = (Timestamp) timestampConstant.getValue();
- String tsStr = ts.toString();
- Date date = Date.valueOf(tsStr.substring(0, 10));
- Time time = Time.valueOf(tsStr.substring(11, 19));
-
- // Get timestampCreate args
- Expression[] args = tsCreateFunction.getArgs();
-
- // Rebuild the function
- CompareCriteria dateCrit = new CompareCriteria(args[0], CompareCriteria.EQ, new Constant(date, DataTypeManager.DefaultDataClasses.DATE));
- CompareCriteria timeCrit = new CompareCriteria(args[1], CompareCriteria.EQ, new Constant(time, DataTypeManager.DefaultDataClasses.TIME));
- CompoundCriteria compCrit = new CompoundCriteria(CompoundCriteria.AND, dateCrit, timeCrit);
- return compCrit;
- }
-
- /**
- * This method also applies the same simplification for Case 1829. This is conceptually
- * the same thing but done using the timestampCreate system function.
- *
- * formatDate(rpcolli_physical.RPCOLLI.Table_B.date_field, 'yyyy-MM-dd')
- * || formatTime(rpcolli_physical.RPCOLLI.Table_B.time_field, ' HH:mm:ss') = '1969-09-20 18:30:45'
- *
- * -------------
- *
- * rpcolli_physical.RPCOLLI.Table_B.date_field = {d'1969-09-20'}
- * AND
- * rpcolli_physical.RPCOLLI.Table_B.time_field = {t'18:30:45'}
- *
- *
- * @param criteria Compare criteria
- * @return Simplified criteria, if possible
- */
-
- private Criteria simplifyTimestampMerge(CompareCriteria criteria) {
- if(criteria.getOperator() != CompareCriteria.EQ) {
- return criteria;
- }
-
- Expression leftExpr = criteria.getLeftExpression();
- Expression rightExpr = criteria.getRightExpression();
-
- // Allow for concat and string literal to be on either side
- Function concatFunction = null;
- Constant timestampConstant = null;
- if(leftExpr instanceof Function && rightExpr instanceof Constant) {
- concatFunction = (Function) leftExpr;
- timestampConstant = (Constant) rightExpr;
- } else {
- return criteria;
- }
-
- // Verify data type of string constant and that constant has a value
- if(! timestampConstant.getType().equals(DataTypeManager.DefaultDataClasses.STRING)) {
- return criteria;
- }
-
- // Verify function is concat function
- if(! (concatFunction.getName().equalsIgnoreCase("concat") || concatFunction.getName().equals("||"))) { //$NON-NLS-1$ //$NON-NLS-2$
- return criteria;
- }
-
- // Verify concat has formatdate and formattime functions
- Expression[] args = concatFunction.getArgs();
- if(! (args[0] instanceof Function && args[1] instanceof Function)) {
- return criteria;
- }
- Function formatDateFunction = (Function) args[0];
- Function formatTimeFunction = (Function) args[1];
- if(! (formatDateFunction.getName().equalsIgnoreCase("formatdate") && formatTimeFunction.getName().equalsIgnoreCase("formattime"))) { //$NON-NLS-1$ //$NON-NLS-2$
- return criteria;
- }
-
- // Verify format functions have constants
- if(! (formatDateFunction.getArgs()[1] instanceof Constant && formatTimeFunction.getArgs()[1] instanceof Constant)) {
- return criteria;
- }
-
- // Verify length of combined date/time constants == timestamp constant
- String dateFormat = (String) ((Constant)formatDateFunction.getArgs()[1]).getValue();
- String timeFormat = (String) ((Constant)formatTimeFunction.getArgs()[1]).getValue();
- String timestampValue = (String) timestampConstant.getValue();
-
- // Passed all the checks, so build the optimized version
- try {
- Timestamp ts = FunctionMethods.parseTimestamp(timestampValue, dateFormat + timeFormat);
- Constant dateConstant = new Constant(TimestampWithTimezone.createDate(ts));
- CompareCriteria dateCompare = new CompareCriteria(formatDateFunction.getArgs()[0], CompareCriteria.EQ, dateConstant);
-
- Constant timeConstant = new Constant(TimestampWithTimezone.createTime(ts));
- CompareCriteria timeCompare = new CompareCriteria(formatTimeFunction.getArgs()[0], CompareCriteria.EQ, timeConstant);
-
- CompoundCriteria compCrit = new CompoundCriteria(CompoundCriteria.AND, dateCompare, timeCompare);
- return compCrit;
-
- } catch(FunctionExecutionException e) {
- return criteria;
- }
- }
-
- private Criteria rewriteCriteria(MatchCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
- criteria.setLeftExpression( rewriteExpressionDirect(criteria.getLeftExpression()));
- criteria.setRightExpression( rewriteExpressionDirect(criteria.getRightExpression()));
-
- if (isNull(criteria.getLeftExpression()) || isNull(criteria.getRightExpression())) {
- return UNKNOWN_CRITERIA;
- }
-
- Expression rightExpr = criteria.getRightExpression();
- if(rightExpr instanceof Constant && rightExpr.getType().equals(DataTypeManager.DefaultDataClasses.STRING)) {
- 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 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;
- }
-
- private Criteria getSimpliedCriteria(Criteria crit, Expression a, boolean outcome, boolean nullPossible) {
- if (nullPossible) {
- if (outcome) {
- if (processing) {
- return crit;
- }
- IsNullCriteria inc = new IsNullCriteria(a);
- inc.setNegated(true);
- return inc;
- }
- } else if (outcome) {
- return TRUE_CRITERIA;
- }
- return FALSE_CRITERIA;
- }
-
- private boolean rewriteLeftExpression(AbstractSetCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
- criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
-
- if (isNull(criteria.getExpression())) {
- return true;
- }
-
- return false;
- }
-
- private Criteria rewriteCriteria(SetCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
- if (criteria.isAllConstants() && criteria.getValues().size() > 1) {
- return criteria;
- }
-
- criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
-
- if (rewriteLeftExpression(criteria)) {
- return UNKNOWN_CRITERIA;
- }
-
- Collection vals = criteria.getValues();
-
- LinkedHashSet newVals = new LinkedHashSet(vals.size());
- Iterator valIter = vals.iterator();
- boolean allConstants = true;
- boolean hasNull = false;
- while(valIter.hasNext()) {
- Expression value = rewriteExpressionDirect( (Expression) valIter.next());
- if (isNull(value)) {
- hasNull = true;
- continue;
- }
- allConstants &= value instanceof Constant;
- newVals.add(value);
- }
-
- int size = newVals.size();
- if (size == 1) {
- Expression value = (Expression)newVals.iterator().next();
- return rewriteCriteria(new CompareCriteria(criteria.getExpression(), criteria.isNegated()?CompareCriteria.NE:CompareCriteria.EQ, value));
- }
-
- criteria.setValues(newVals);
- if (allConstants) {
- criteria.setAllConstants(true);
- }
-
- if (size == 0) {
- if (hasNull) {
- return UNKNOWN_CRITERIA;
- }
- return getSimpliedCriteria(criteria, criteria.getExpression(), !criteria.isNegated(), true);
- }
-
- if(criteria.getExpression() instanceof Function ) {
- Function leftFunction = (Function)criteria.getExpression();
- if(FunctionLibrary.isConvert(leftFunction)) {
- return simplifyConvertFunction(criteria);
- }
- }
-
- return criteria;
- }
-
- private Criteria rewriteCriteria(IsNullCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
- criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
- return criteria;
- }
-
- public static Expression rewriteExpression(Expression expression, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException{
- return new QueryRewriter(metadata, context, procCommand).rewriteExpressionDirect(expression);
- }
-
- private Expression rewriteExpressionDirect(Expression expression) throws TeiidComponentException, TeiidProcessingException{
- if (expression instanceof Constant) {
- return expression;
- }
- if (expression instanceof ElementSymbol) {
- ElementSymbol es = (ElementSymbol)expression;
- Class<?> type = es.getType();
- if (!processing && es.isExternalReference()) {
- if (variables == null) {
- return new Reference(es);
- }
- Expression value = variables.get(es);
-
- if (value == null) {
- if (es.getGroupSymbol().getSchema() == null) {
- String grpName = es.getGroupSymbol().getShortCanonicalName();
- if (grpName.equals(ProcedureReservedWords.INPUTS)) {
- return new Constant(null, es.getType());
- }
- if (grpName.equals(ProcedureReservedWords.CHANGING)) {
- Assertion.failed("Changing value should not be null"); //$NON-NLS-1$
- }
- }
- } else if (value instanceof Constant) {
- if (value.getType() == type) {
- return value;
- }
- try {
- return new Constant(FunctionMethods.convert(((Constant)value).getValue(), DataTypeManager.getDataTypeName(type)), es.getType());
- } catch (FunctionExecutionException e) {
- throw new QueryValidatorException(e, e.getMessage());
- }
- }
- return new Reference(es);
- }
- return expression;
- }
- boolean isBindEligible = true;
- if(expression instanceof Function) {
- isBindEligible = !isConstantConvert(expression);
- expression = rewriteFunction((Function) expression);
- } else if (expression instanceof CaseExpression) {
- expression = rewriteCaseExpression((CaseExpression)expression);
- } else if (expression instanceof SearchedCaseExpression) {
- expression = rewriteCaseExpression((SearchedCaseExpression)expression);
- } else if (expression instanceof ScalarSubquery) {
- ScalarSubquery subquery = (ScalarSubquery)expression;
- if (subquery.shouldEvaluate() && processing) {
- return new Constant(evaluator.evaluate(subquery, null), subquery.getType());
- }
- rewriteSubqueryContainer(subquery, true);
- if (!RelationalNodeUtil.shouldExecute(subquery.getCommand(), false, true)) {
- return new Constant(null, subquery.getType());
- }
- if (subquery.getCommand().getProcessorPlan() == null) {
- addImplicitLimit(subquery, 2);
- }
- return expression;
- } else if (expression instanceof ExpressionSymbol) {
- if (expression instanceof AggregateSymbol) {
- expression = rewriteExpression((AggregateSymbol)expression);
- } else {
- expression = rewriteExpressionDirect(((ExpressionSymbol)expression).getExpression());
- }
- } else if (expression instanceof Criteria) {
- expression = rewriteCriteria((Criteria)expression);
- } else {
- rewriteExpressions(expression);
- }
-
- if(!processing) {
- if (!EvaluatableVisitor.isFullyEvaluatable(expression, true)) {
- return expression;
- }
- } else if (!(expression instanceof Reference) && !EvaluatableVisitor.isEvaluatable(expression, EvaluationLevel.PROCESSING)) {
- return expression;
- }
-
- return evaluate(expression, isBindEligible);
- }
-
- private Constant evaluate(Expression expression, boolean isBindEligible)
- throws ExpressionEvaluationException, BlockedException,
- TeiidComponentException {
- Object value = evaluator.evaluate(expression, Collections.emptyList());
- if (value instanceof Constant) {
- return (Constant)value; //multi valued substitution
- }
- Constant result = new Constant(value, expression.getType());
- result.setBindEligible(isBindEligible);
- return result;
- }
-
- private boolean isConstantConvert(Expression ex) {
- if (ex instanceof Constant) {
- return true;
- }
- if (!(ex instanceof Function)) {
- return false;
- }
- Function f = (Function)ex;
- if (!FunctionLibrary.isConvert(f)) {
- return false;
- }
- return isConstantConvert(f.getArg(0));
- }
-
- private Expression rewriteExpression(AggregateSymbol expression) {
- if (expression.isBoolean()) {
- if (expression.getAggregateFunction() == Type.EVERY) {
- expression.setAggregateFunction(Type.MIN);
- } else {
- 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);
- }
- }
- return expression;
- }
-
- private static Map<String, Integer> FUNCTION_MAP = new HashMap<String, Integer>();
-
- static {
- FUNCTION_MAP.put(FunctionLibrary.SPACE.toLowerCase(), 0);
- FUNCTION_MAP.put(FunctionLibrary.FROM_UNIXTIME.toLowerCase(), 1);
- FUNCTION_MAP.put(FunctionLibrary.NULLIF.toLowerCase(), 2);
- FUNCTION_MAP.put(FunctionLibrary.COALESCE.toLowerCase(), 3);
- FUNCTION_MAP.put(FunctionLibrary.CONCAT2.toLowerCase(), 4);
- FUNCTION_MAP.put(FunctionLibrary.TIMESTAMPADD.toLowerCase(), 5);
- FUNCTION_MAP.put(FunctionLibrary.PARSEDATE.toLowerCase(), 6);
- FUNCTION_MAP.put(FunctionLibrary.PARSETIME.toLowerCase(), 7);
- FUNCTION_MAP.put(FunctionLibrary.FORMATDATE.toLowerCase(), 8);
- FUNCTION_MAP.put(FunctionLibrary.FORMATTIME.toLowerCase(), 9);
- }
-
- private Expression rewriteFunction(Function function) throws TeiidComponentException, TeiidProcessingException{
- //rewrite alias functions
- String functionLowerName = function.getName().toLowerCase();
- String actualName =ALIASED_FUNCTIONS.get(functionLowerName);
- FunctionLibrary funcLibrary = this.metadata.getFunctionLibrary();
-
- if (actualName != null) {
- function.setName(actualName);
- Expression[] args = function.getArgs();
- Class<?>[] types = new Class[args.length];
- for(int i=0; i<args.length; i++) {
- types[i] = args[i].getType();
- }
- FunctionDescriptor descriptor = funcLibrary.findFunction(actualName, types);
- function.setFunctionDescriptor(descriptor);
- }
-
- Integer code = FUNCTION_MAP.get(functionLowerName);
- if (code != null) {
- switch (code) {
- case 0: { //space(x) => repeat(' ', x)
- Function result = new Function(SourceSystemFunctions.REPEAT,
- new Expression[] {new Constant(" "), function.getArg(0)}); //$NON-NLS-1$
- //resolve the function
- FunctionDescriptor descriptor =
- funcLibrary.findFunction(SourceSystemFunctions.REPEAT, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER});
- result.setFunctionDescriptor(descriptor);
- result.setType(DataTypeManager.DefaultDataClasses.STRING);
- function = result;
- break;
- }
- case 1: {//from_unixtime(a) => timestampadd(SQL_TSI_SECOND, a, new Timestamp(0))
- Function result = new Function(FunctionLibrary.TIMESTAMPADD,
- new Expression[] {new Constant(NonReserved.SQL_TSI_SECOND), function.getArg(0), new Constant(new Timestamp(0)) });
- //resolve the function
- FunctionDescriptor descriptor =
- funcLibrary.findFunction(FunctionLibrary.TIMESTAMPADD, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER, DataTypeManager.DefaultDataClasses.TIMESTAMP });
- result.setFunctionDescriptor(descriptor);
- result.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
- function = result;
- break;
- }
- case 2: { //rewrite nullif(a, b) => case when (a = b) then null else a
- List when = Arrays.asList(new Criteria[] {new CompareCriteria(function.getArg(0), CompareCriteria.EQ, function.getArg(1))});
- Constant nullConstant = new Constant(null, function.getType());
- List then = Arrays.asList(new Expression[] {nullConstant});
- SearchedCaseExpression caseExpr = new SearchedCaseExpression(when, then);
- caseExpr.setElseExpression(function.getArg(0));
- caseExpr.setType(function.getType());
- return rewriteExpressionDirect(caseExpr);
- }
- case 3: {
- Expression[] args = function.getArgs();
- if (args.length == 2) {
- Function result = new Function(SourceSystemFunctions.IFNULL,
- new Expression[] {function.getArg(0), function.getArg(1) });
- //resolve the function
- FunctionDescriptor descriptor =
- funcLibrary.findFunction(SourceSystemFunctions.IFNULL, new Class[] { function.getType(), function.getType() });
- result.setFunctionDescriptor(descriptor);
- result.setType(function.getType());
- function = result;
- }
- break;
- }
- case 4: { //rewrite concat2 - CONCAT2(a, b) ==> CASE WHEN (a is NULL AND b is NULL) THEN NULL ELSE CONCAT( NVL(a, ''), NVL(b, '') )
- Expression[] args = function.getArgs();
- Function[] newArgs = new Function[args.length];
-
- for(int i=0; i<args.length; i++) {
- newArgs[i] = new Function(SourceSystemFunctions.IFNULL, new Expression[] {args[i], new Constant("")}); //$NON-NLS-1$
- newArgs[i].setType(args[i].getType());
- Assertion.assertTrue(args[i].getType() == DataTypeManager.DefaultDataClasses.STRING);
- FunctionDescriptor descriptor =
- funcLibrary.findFunction(SourceSystemFunctions.IFNULL, new Class[] { args[i].getType(), DataTypeManager.DefaultDataClasses.STRING });
- newArgs[i].setFunctionDescriptor(descriptor);
- }
-
- Function concat = new Function(SourceSystemFunctions.CONCAT, newArgs);
- concat.setType(DataTypeManager.DefaultDataClasses.STRING);
- FunctionDescriptor descriptor =
- funcLibrary.findFunction(SourceSystemFunctions.CONCAT, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING });
- concat.setFunctionDescriptor(descriptor);
-
- List when = Arrays.asList(new Criteria[] {new CompoundCriteria(CompoundCriteria.AND, new IsNullCriteria(args[0]), new IsNullCriteria(args[1]))});
- Constant nullConstant = new Constant(null, DataTypeManager.DefaultDataClasses.STRING);
- List then = Arrays.asList(new Expression[] {nullConstant});
- SearchedCaseExpression caseExpr = new SearchedCaseExpression(when, then);
- caseExpr.setElseExpression(concat);
- caseExpr.setType(DataTypeManager.DefaultDataClasses.STRING);
- return rewriteExpressionDirect(caseExpr);
- }
- case 5: {
- if (function.getType() != DataTypeManager.DefaultDataClasses.TIMESTAMP) {
- FunctionDescriptor descriptor =
- funcLibrary.findFunction(SourceSystemFunctions.TIMESTAMPADD, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER, DataTypeManager.DefaultDataClasses.TIMESTAMP });
- function.setFunctionDescriptor(descriptor);
- Class<?> type = function.getType();
- function.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
- function.getArgs()[2] = ResolverUtil.getConversion(function.getArg(2), DataTypeManager.getDataTypeName(type), DataTypeManager.DefaultDataTypes.TIMESTAMP, false, funcLibrary);
- function = ResolverUtil.getConversion(function, DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.getDataTypeName(type), false, funcLibrary);
- }
- break;
- }
- case 6:
- case 7: {
- FunctionDescriptor descriptor =
- funcLibrary.findFunction(SourceSystemFunctions.PARSETIMESTAMP, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING });
- function.setName(SourceSystemFunctions.PARSETIMESTAMP);
- function.setFunctionDescriptor(descriptor);
- Class<?> type = function.getType();
- function.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
- function = ResolverUtil.getConversion(function, DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.getDataTypeName(type), false, funcLibrary);
- break;
- }
- case 8:
- case 9: {
- FunctionDescriptor descriptor =
- funcLibrary.findFunction(SourceSystemFunctions.FORMATTIMESTAMP, new Class[] { DataTypeManager.DefaultDataClasses.TIMESTAMP, DataTypeManager.DefaultDataClasses.STRING });
- function.setName(SourceSystemFunctions.FORMATTIMESTAMP);
- function.setFunctionDescriptor(descriptor);
- function.getArgs()[0] = ResolverUtil.getConversion(function.getArg(0), DataTypeManager.getDataTypeName(function.getArg(0).getType()), DataTypeManager.DefaultDataTypes.TIMESTAMP, false, funcLibrary);
- break;
- }
- }
- }
-
- Expression[] args = function.getArgs();
- Expression[] newArgs = new Expression[args.length];
-
- // Rewrite args
- for(int i=0; i<args.length; i++) {
- newArgs[i] = rewriteExpressionDirect(args[i]);
- if (isNull(newArgs[i]) && !function.getFunctionDescriptor().isNullDependent()) {
- return new Constant(null, function.getType());
- }
- }
- 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(srcType != null && tgtType != null && srcType.equals(tgtType)) {
- return newArgs[0];
- }
-
- }
-
- //convert DECODESTRING function to CASE expression
- if( function.getName().equalsIgnoreCase(FunctionLibrary.DECODESTRING)
- || function.getName().equalsIgnoreCase(FunctionLibrary.DECODEINTEGER)) {
- return convertDecodeFunction(function);
- }
-
- return function;
- }
-
- private Expression convertDecodeFunction(Function function){
- Expression exprs[] = function.getArgs();
- String decodeString = (String)((Constant)exprs[1]).getValue();
- String decodeDelimiter = ","; //$NON-NLS-1$
- if(exprs.length == 3){
- decodeDelimiter = (String)((Constant)exprs[2]).getValue();
- }
- List<Criteria> newWhens = new ArrayList<Criteria>();
- List<Constant> newThens = new ArrayList<Constant>();
- Constant elseConst = null;
- StringTokenizer tokenizer = new StringTokenizer(decodeString, decodeDelimiter);
- while (tokenizer.hasMoreTokens()) {
- String resultString;
- String compareString =
- convertString(tokenizer.nextToken().trim());
- if (tokenizer.hasMoreTokens()) {
- resultString = convertString(tokenizer.nextToken().trim());
- Criteria crit;
- if (compareString == null) {
- crit = new IsNullCriteria((Expression) exprs[0].clone());
- } else {
- crit = new CompareCriteria((Expression) exprs[0].clone(), CompareCriteria.EQ, new Constant(compareString));
- }
- newWhens.add(crit);
- newThens.add(new Constant(resultString));
- }else {
- elseConst = new Constant(compareString);
- }
- }
- SearchedCaseExpression newCaseExpr = new SearchedCaseExpression(newWhens, newThens);
- if(elseConst != null) {
- newCaseExpr.setElseExpression(elseConst);
- }else {
- newCaseExpr.setElseExpression(exprs[0]);
- }
-
- newCaseExpr.setType(function.getType());
- return newCaseExpr;
- }
-
- private static String convertString(String string) {
- /*
- * if there are no characters in the compare string we designate that as
- * an indication of null. ie if the decode string looks like this:
- *
- * "'this', 1,,'null'"
- *
- * Then if the value in the first argument is null then the String 'null' is
- * returned from the function.
- */
- if (string.equals("")) { //$NON-NLS-1$
- return null;
- }
-
- /*
- * we also allow the use of the keyword null in the decode string. if it
- * wished to match on the string 'null' then the string must be qualified by
- * ' designators.
- */
- if(string.equalsIgnoreCase("null")){ //$NON-NLS-1$
- return null;
- }
-
- /*
- * Here we check to see if the String in the decode String submitted
- * was surrounded by String literal characters. In this case we strip
- * these literal characters from the String.
- */
- if ((string.startsWith("\"") && string.endsWith("\"")) //$NON-NLS-1$ //$NON-NLS-2$
- || (string.startsWith("'") && string.endsWith("'"))) { //$NON-NLS-1$ //$NON-NLS-2$
- if (string.length() == 2) {
- /*
- * This is an indication that the desired string to be compared is
- * the "" empty string, so we return it as such.
- */
- string = ""; //$NON-NLS-1$
- } else if (!string.equalsIgnoreCase("'") && !string.equalsIgnoreCase("\"")){ //$NON-NLS-1$ //$NON-NLS-2$
- string = string.substring(1);
- string = string.substring(0, string.length()-1);
- }
- }
-
- return string;
- }
-
- private Expression rewriteCaseExpression(CaseExpression expr)
- throws TeiidComponentException, TeiidProcessingException{
- List<CompareCriteria> whens = new ArrayList<CompareCriteria>(expr.getWhenCount());
- for (Expression expression: (List<Expression>)expr.getWhen()) {
- whens.add(new CompareCriteria((Expression)expr.getExpression().clone(), CompareCriteria.EQ, expression));
- }
- SearchedCaseExpression sce = new SearchedCaseExpression(whens, expr.getThen());
- sce.setElseExpression(expr.getElseExpression());
- sce.setType(expr.getType());
- return rewriteCaseExpression(sce);
- }
-
- private Expression rewriteCaseExpression(SearchedCaseExpression expr)
- throws TeiidComponentException, TeiidProcessingException{
- int whenCount = expr.getWhenCount();
- ArrayList<Criteria> whens = new ArrayList<Criteria>(whenCount);
- ArrayList<Expression> thens = new ArrayList<Expression>(whenCount);
-
- for (int i = 0; i < whenCount; i++) {
-
- // Check the when to see if this CASE can be rewritten due to an always true/false when
- Criteria rewrittenWhen = rewriteCriteria(expr.getWhenCriteria(i));
- if(rewrittenWhen == TRUE_CRITERIA) {
- // WHEN is always true, so just return the THEN
- return rewriteExpressionDirect(expr.getThenExpression(i));
- }
- if (rewrittenWhen == FALSE_CRITERIA || rewrittenWhen == UNKNOWN_CRITERIA) {
- continue;
- }
-
- whens.add(rewrittenWhen);
- thens.add(rewriteExpressionDirect(expr.getThenExpression(i)));
- }
-
- if (expr.getElseExpression() != null) {
- expr.setElseExpression(rewriteExpressionDirect(expr.getElseExpression()));
- }
-
- Expression elseExpr = expr.getElseExpression();
- if(whens.size() == 0) {
- // No WHENs left, so just return the ELSE
- if(elseExpr == null) {
- // No else, no valid whens, just return null constant typed same as CASE
- return new Constant(null, expr.getType());
- }
-
- // Rewrite the else and return
- return elseExpr;
- }
-
- expr.setWhen(whens, thens);
-
- /* optimization for case 5413:
- * If all of the remaining 'thens' and the 'else' evaluate to the same value,
- * just return the 'else' expression.
- */
-
- if ( elseExpr != null ) {
- boolean bAllMatch = true;
-
- for (int i = 0; i < whenCount; i++) {
- if ( !thens.get( i ).equals(elseExpr) ) {
- bAllMatch = false;
- break;
- }
- }
-
- if ( bAllMatch ) {
- return elseExpr;
- }
- }
-
- return expr;
- }
-
- private Command rewriteExec(StoredProcedure storedProcedure) throws TeiidComponentException, TeiidProcessingException{
- //After this method, no longer need to display named parameters
- storedProcedure.setDisplayNamedParameters(false);
-
- for (SPParameter param : storedProcedure.getInputParameters()) {
- if (!processing) {
- param.setExpression(rewriteExpressionDirect(param.getExpression()));
- } else if (!(param.getExpression() instanceof Constant)) {
- boolean isBindEligible = !isConstantConvert(param.getExpression());
- param.setExpression(evaluate(param.getExpression(), isBindEligible));
- }
- }
- return storedProcedure;
- }
-
- private Insert rewriteInsert(Insert insert) throws TeiidComponentException, TeiidProcessingException{
- UpdateInfo info = insert.getUpdateInfo();
- if (info != null && info.isInherentInsert()) {
- //TODO: update error messages
- UpdateMapping mapping = info.findInsertUpdateMapping(insert, true);
- if (mapping == null) {
- throw new QueryValidatorException(QueryPlugin.Util.getString("ValidationVisitor.nonUpdatable", insert.getVariables())); //$NON-NLS-1$
- }
- Map<ElementSymbol, ElementSymbol> symbolMap = mapping.getUpdatableViewSymbols();
- List<ElementSymbol> mappedSymbols = new ArrayList<ElementSymbol>(insert.getVariables().size());
- for (ElementSymbol symbol : insert.getVariables()) {
- mappedSymbols.add(symbolMap.get(symbol));
- }
- insert.setVariables(mappedSymbols);
- insert.setGroup(mapping.getGroup().clone());
- insert.setUpdateInfo(ProcedureContainerResolver.getUpdateInfo(insert.getGroup(), metadata, Command.TYPE_INSERT));
- return rewriteInsert(insert);
- }
-
- if ( insert.getQueryExpression() != null ) {
- insert.setQueryExpression((QueryCommand)rewriteCommand(insert.getQueryExpression(), true));
- return correctDatatypes(insert);
- }
- // Evaluate any function / constant trees in the insert values
- List expressions = insert.getValues();
- List evalExpressions = new ArrayList(expressions.size());
- Iterator expIter = expressions.iterator();
- while(expIter.hasNext()) {
- Expression exp = (Expression) expIter.next();
- evalExpressions.add( rewriteExpressionDirect( exp ));
- }
-
- insert.setValues(evalExpressions);
- return insert;
- }
-
- public static Query createInlineViewQuery(GroupSymbol inlineGroup,
- Command nested,
- QueryMetadataInterface metadata,
- List<? extends SingleElementSymbol> actualSymbols) throws QueryMetadataException,
- QueryResolverException,
- TeiidComponentException {
- Query query = new Query();
- Select select = new Select();
- query.setSelect(select);
- From from = new From();
- from.addClause(new UnaryFromClause(inlineGroup));
- TempMetadataStore store = new TempMetadataStore();
- TempMetadataAdapter tma = new TempMetadataAdapter(metadata, store);
- if (nested instanceof QueryCommand) {
- Query firstProject = ((QueryCommand)nested).getProjectedQuery();
- makeSelectUnique(firstProject.getSelect(), false);
- }
- TempMetadataID gid = store.addTempGroup(inlineGroup.getName(), nested.getProjectedSymbols());
- inlineGroup.setMetadataID(gid);
-
- List<Class<?>> actualTypes = new ArrayList<Class<?>>(nested.getProjectedSymbols().size());
- for (SingleElementSymbol ses : actualSymbols) {
- actualTypes.add(ses.getType());
- }
- List<SingleElementSymbol> selectSymbols = SetQuery.getTypedProjectedSymbols(ResolverUtil.resolveElementsInGroup(inlineGroup, tma), actualTypes, tma);
- Iterator<? extends SingleElementSymbol> iter = actualSymbols.iterator();
- for (SingleElementSymbol ses : selectSymbols) {
- ses = (SingleElementSymbol)ses.clone();
- SingleElementSymbol actual = iter.next();
- if (!ses.getShortCanonicalName().equals(actual.getShortCanonicalName())) {
- if (ses instanceof AliasSymbol) {
- ((AliasSymbol)ses).setShortName(actual.getShortName());
- } else {
- ses = new AliasSymbol(actual.getShortName(), ses);
- }
- }
- select.addSymbol(ses);
- }
- query.setFrom(from);
- QueryResolver.resolveCommand(query, tma);
- query.setOption(nested.getOption());
- from.getClauses().clear();
- SubqueryFromClause sqfc = new SubqueryFromClause(inlineGroup.getName());
- sqfc.setCommand(nested);
- sqfc.getGroupSymbol().setMetadataID(inlineGroup.getMetadataID());
- from.addClause(sqfc);
- //copy the metadata onto the new query so that temp metadata adapters will be used in later calls
- query.getTemporaryMetadata().putAll(store.getData());
- return query;
- }
-
- public static void makeSelectUnique(Select select, boolean expressionSymbolsOnly) {
-
- select.setSymbols(select.getProjectedSymbols());
-
- List symbols = select.getSymbols();
-
- HashSet<String> uniqueNames = new HashSet<String>();
-
- for(int i = 0; i < symbols.size(); i++) {
-
- SingleElementSymbol symbol = (SingleElementSymbol)symbols.get(i);
-
- String baseName = symbol.getShortCanonicalName();
- String name = baseName;
-
- int exprID = 0;
- while (true) {
- if (uniqueNames.add(name)) {
- break;
- }
- name = baseName + '_' + (exprID++);
- }
-
- if (expressionSymbolsOnly && !(symbol instanceof ExpressionSymbol)) {
- continue;
- }
-
- boolean hasAlias = false;
- // Strip alias if it exists
- if(symbol instanceof AliasSymbol) {
- symbol = ((AliasSymbol)symbol).getSymbol();
- hasAlias = true;
- }
-
- if (((symbol instanceof ExpressionSymbol) && !hasAlias) || !name.equalsIgnoreCase(baseName)) {
- symbols.set(i, new AliasSymbol(name, symbol));
- }
- }
- }
-
- private Command rewriteUpdate(Update update) throws TeiidComponentException, TeiidProcessingException{
- UpdateInfo info = update.getUpdateInfo();
- if (info != null && info.isInherentUpdate()) {
- if (!info.getUnionBranches().isEmpty()) {
- List<Command> batchedUpdates = new ArrayList<Command>(info.getUnionBranches().size() + 1);
- for (UpdateInfo branchInfo : info.getUnionBranches()) {
- batchedUpdates.add(rewriteInherentUpdate((Update)update.clone(), branchInfo));
- }
- batchedUpdates.add(0, rewriteInherentUpdate(update, info));
- return new BatchedUpdateCommand(batchedUpdates);
- }
- return rewriteInherentUpdate(update, info);
- }
-
- if (commandType == Command.TYPE_UPDATE && variables != null) {
- SetClauseList newChangeList = new SetClauseList();
- for (SetClause entry : update.getChangeList().getClauses()) {
- Expression rightExpr = entry.getValue();
- boolean retainChange = checkInputVariables(rightExpr);
- if (retainChange) {
- newChangeList.addClause(entry.getSymbol(), entry.getValue());
- }
- }
- update.setChangeList(newChangeList);
- }
-
- // Evaluate any function on the right side of set clauses
- for (SetClause entry : update.getChangeList().getClauses()) {
- entry.setValue(rewriteExpressionDirect(entry.getValue()));
- }
-
- // Rewrite criteria
- Criteria crit = update.getCriteria();
- if(crit != null) {
- update.setCriteria(rewriteCriteria(crit));
- }
-
- return update;
- }
-
- private Command rewriteInherentUpdate(Update update, UpdateInfo info)
- throws QueryValidatorException, QueryMetadataException,
- TeiidComponentException, QueryResolverException,
- TeiidProcessingException {
- UpdateMapping mapping = info.findUpdateMapping(update.getChangeList().getClauseMap().keySet(), false);
- if (mapping == null) {
- throw new QueryValidatorException(QueryPlugin.Util.getString("ValidationVisitor.nonUpdatable", update.getChangeList().getClauseMap().keySet())); //$NON-NLS-1$
- }
- Map<ElementSymbol, ElementSymbol> symbolMap = mapping.getUpdatableViewSymbols();
- if (info.isSimple()) {
- update.setGroup(mapping.getGroup().clone());
- for (SetClause clause : update.getChangeList().getClauses()) {
- clause.setSymbol(symbolMap.get(clause.getSymbol()));
- }
- //TODO: properly handle correlated references
- DeepPostOrderNavigator.doVisit(update, new ExpressionMappingVisitor(symbolMap, true));
- if (info.getViewDefinition().getCriteria() != null) {
- update.setCriteria(Criteria.combineCriteria(update.getCriteria(), (Criteria)info.getViewDefinition().getCriteria().clone()));
- }
- //resolve
- update.setUpdateInfo(ProcedureContainerResolver.getUpdateInfo(update.getGroup(), metadata, Command.TYPE_UPDATE));
- return rewriteUpdate(update);
- }
- Query query = (Query)info.getViewDefinition().clone();
- query.setOrderBy(null);
- SymbolMap expressionMapping = SymbolMap.createSymbolMap(update.getGroup(), query.getProjectedSymbols(), metadata);
-
- ArrayList<SingleElementSymbol> selectSymbols = mapChangeList(update, symbolMap);
- query.setSelect(new Select(selectSymbols));
- ExpressionMappingVisitor emv = new ExpressionMappingVisitor(expressionMapping.asMap(), true);
- PostOrderNavigator.doVisit(query.getSelect(), emv);
-
- Criteria crit = update.getCriteria();
- if (crit != null) {
- PostOrderNavigator.doVisit(crit, emv);
- query.setCriteria(Criteria.combineCriteria(query.getCriteria(), crit));
- }
- GroupSymbol group = mapping.getGroup();
- String correlationName = mapping.getCorrelatedName().getName();
-
- return createUpdateProcedure(update, query, group, correlationName);
- }
-
- private ArrayList<SingleElementSymbol> mapChangeList(Update update,
- Map<ElementSymbol, ElementSymbol> symbolMap) {
- ArrayList<SingleElementSymbol> selectSymbols = new ArrayList<SingleElementSymbol>(update.getChangeList().getClauses().size());
- int i = 0;
- for (SetClause clause : update.getChangeList().getClauses()) {
- Expression ex = clause.getValue();
- SingleElementSymbol selectSymbol = null;
- if (!EvaluatableVisitor.willBecomeConstant(ex)) {
- if (!(ex instanceof SingleElementSymbol)) {
- selectSymbol = new ExpressionSymbol("expr", ex); //$NON-NLS-1$
- } else {
- selectSymbol = (SingleElementSymbol)ex;
- }
- selectSymbols.add(new AliasSymbol("s_" +i, selectSymbol)); //$NON-NLS-1$
- ex = new ElementSymbol("s_" +i); //$NON-NLS-1$
- }
- if (symbolMap != null) {
- clause.setSymbol(symbolMap.get(clause.getSymbol()));
- }
- i++;
- }
- return selectSymbols;
- }
-
- private Command createUpdateProcedure(Update update, Query query,
- GroupSymbol group, String correlationName)
- throws TeiidComponentException, QueryMetadataException,
- QueryResolverException, TeiidProcessingException {
- Update newUpdate = new Update();
- newUpdate.setChangeList(update.getChangeList());
- newUpdate.setGroup(group.clone());
- List<Criteria> pkCriteria = createPkCriteria(group, correlationName, query);
- newUpdate.setCriteria(new CompoundCriteria(pkCriteria));
- return asLoopProcedure(update.getGroup(), query, newUpdate);
- }
-
- /**
- * rewrite as loop on (query) as X begin newupdate; rows_updated = rows_updated + 1;
- */
- private Command asLoopProcedure(GroupSymbol group, Query query,
- ProcedureContainer newUpdate) throws QueryResolverException,
- TeiidComponentException, TeiidProcessingException {
- Block b = new Block();
- b.addStatement(new CommandStatement(newUpdate));
- CreateUpdateProcedureCommand cupc = new CreateUpdateProcedureCommand();
- Block parent = new Block();
- LoopStatement ls = new LoopStatement(b, query, "X"); //$NON-NLS-1$
- parent.addStatement(ls);
- AssignmentStatement as = new AssignmentStatement();
- ElementSymbol rowsUpdate = new ElementSymbol(ProcedureReservedWords.VARIABLES+ElementSymbol.SEPARATOR+ProcedureReservedWords.ROWS_UPDATED);
- as.setVariable(rowsUpdate);
- as.setExpression(new Function("+", new Expression[] {rowsUpdate, new Constant(1)})); //$NON-NLS-1$
- b.addStatement(as);
- cupc.setBlock(parent);
- cupc.setVirtualGroup(group);
- QueryResolver.resolveCommand(cupc, metadata);
- return rewrite(cupc, metadata, context);
- }
-
- private List<Criteria> createPkCriteria(GroupSymbol group, String correlationName, Query query) throws TeiidComponentException, QueryMetadataException {
- Object pk = metadata.getPrimaryKey(group.getMetadataID());
- if (pk == null) {
- pk = metadata.getUniqueKeysInGroup(group.getMetadataID()).iterator().next();
- }
- int i = query.getSelect().getSymbols().size();
- List<Object> ids = metadata.getElementIDsInKey(pk);
- List<Criteria> pkCriteria = new ArrayList<Criteria>(ids.size());
- for (Object object : ids) {
- ElementSymbol es = new ElementSymbol(correlationName + ElementSymbol.SEPARATOR + metadata.getName(object));
- query.getSelect().addSymbol(new AliasSymbol("s_" +i, es)); //$NON-NLS-1$
- es = new ElementSymbol(group.getName() + ElementSymbol.SEPARATOR + metadata.getName(object));
- pkCriteria.add(new CompareCriteria(es, CompareCriteria.EQ, new ElementSymbol("X.s_" + i))); //$NON-NLS-1$
- i++;
- }
- return pkCriteria;
- }
-
- /**
- * Checks variables in an expression, if the variables are INPUT variables and if
- * none of them are changing, then this method returns a false, if all of them
- * are changing this returns a true, if some are changing and some are not, then
- * that is an invalid case and the method adds to the list of invalid variables.
- * @throws TeiidComponentException, MetaMatrixProcessingException
- */
- private boolean checkInputVariables(Expression expr) throws TeiidComponentException, TeiidProcessingException{
- Boolean result = null;
- for (ElementSymbol var : ElementCollectorVisitor.getElements(expr, false)) {
- if (var.isExternalReference() && var.getGroupSymbol().getSchema() == null && var.getGroupSymbol().getShortName().equalsIgnoreCase(ProcedureReservedWords.INPUTS)) {
-
- var = var.clone();
- var.getGroupSymbol().setShortName(ProcedureReservedWords.CHANGING);
-
- Boolean changingValue = (Boolean)((Constant)variables.get(var)).getValue();
-
- if (result == null) {
- result = changingValue;
- } else if (!result.equals(changingValue)) {
- throw new QueryValidatorException(QueryPlugin.Util.getString("VariableSubstitutionVisitor.Input_vars_should_have_same_changing_state", expr)); //$NON-NLS-1$
- }
- }
- }
-
- if (result != null) {
- return result.booleanValue();
- }
-
- return true;
- }
-
- private Command rewriteDelete(Delete delete) throws TeiidComponentException, TeiidProcessingException{
- UpdateInfo info = delete.getUpdateInfo();
- if (info != null && info.isInherentDelete()) {
- if (!info.getUnionBranches().isEmpty()) {
- List<Command> batchedUpdates = new ArrayList<Command>(info.getUnionBranches().size() + 1);
- for (UpdateInfo branchInfo : info.getUnionBranches()) {
- batchedUpdates.add(rewriteInherentDelete((Delete)delete.clone(), branchInfo));
- }
- batchedUpdates.add(0, rewriteInherentDelete(delete, info));
- return new BatchedUpdateCommand(batchedUpdates);
- }
- return rewriteInherentDelete(delete, info);
- }
- // Rewrite criteria
- Criteria crit = delete.getCriteria();
- if(crit != null) {
- delete.setCriteria(rewriteCriteria(crit));
- }
-
- return delete;
- }
-
- private Command rewriteInherentDelete(Delete delete, UpdateInfo info)
- throws QueryMetadataException, TeiidComponentException,
- QueryResolverException, TeiidProcessingException {
- UpdateMapping mapping = info.getDeleteTarget();
- if (info.isSimple()) {
- delete.setGroup(mapping.getGroup().clone());
- //TODO: properly handle correlated references
- DeepPostOrderNavigator.doVisit(delete, new ExpressionMappingVisitor(mapping.getUpdatableViewSymbols(), true));
- delete.setUpdateInfo(ProcedureContainerResolver.getUpdateInfo(delete.getGroup(), metadata, Command.TYPE_DELETE));
- if (info.getViewDefinition().getCriteria() != null) {
- delete.setCriteria(Criteria.combineCriteria(delete.getCriteria(), (Criteria)info.getViewDefinition().getCriteria().clone()));
- }
- return rewriteDelete(delete);
- }
-
- Query query = (Query)info.getViewDefinition().clone();
- query.setOrderBy(null);
- SymbolMap expressionMapping = SymbolMap.createSymbolMap(delete.getGroup(), query.getProjectedSymbols(), metadata);
-
- query.setSelect(new Select());
- ExpressionMappingVisitor emv = new ExpressionMappingVisitor(expressionMapping.asMap(), true);
-
- Criteria crit = delete.getCriteria();
- if (crit != null) {
- PostOrderNavigator.doVisit(crit, emv);
- query.setCriteria(Criteria.combineCriteria(query.getCriteria(), crit));
- }
- GroupSymbol group = mapping.getGroup();
- String correlationName = mapping.getCorrelatedName().getName();
- return createDeleteProcedure(delete, query, group, correlationName);
- }
-
- public static Command createDeleteProcedure(Delete delete, QueryMetadataInterface metadata, CommandContext context) throws QueryResolverException, QueryMetadataException, TeiidComponentException, TeiidProcessingException {
- QueryRewriter rewriter = new QueryRewriter(metadata, context, null);
- Criteria crit = delete.getCriteria();
- Query query = new Query(new Select(), new From(Arrays.asList(new UnaryFromClause(delete.getGroup()))), crit, null, null);
- return rewriter.createDeleteProcedure(delete, query, delete.getGroup(), delete.getGroup().getName());
- }
-
- public static Command createUpdateProcedure(Update update, QueryMetadataInterface metadata, CommandContext context) throws QueryResolverException, QueryMetadataException, TeiidComponentException, TeiidProcessingException {
- QueryRewriter rewriter = new QueryRewriter(metadata, context, null);
- Criteria crit = update.getCriteria();
- ArrayList<SingleElementSymbol> selectSymbols = rewriter.mapChangeList(update, null);
- Query query = new Query(new Select(selectSymbols), new From(Arrays.asList(new UnaryFromClause(update.getGroup()))), crit, null, null);
- return rewriter.createUpdateProcedure(update, query, update.getGroup(), update.getGroup().getName());
- }
-
- private Command createDeleteProcedure(Delete delete, Query query,
- GroupSymbol group, String correlationName)
- throws TeiidComponentException, QueryMetadataException,
- QueryResolverException, TeiidProcessingException {
- Delete newUpdate = new Delete();
- newUpdate.setGroup(group.clone());
- List<Criteria> pkCriteria = createPkCriteria(group, correlationName, query);
- newUpdate.setCriteria(new CompoundCriteria(pkCriteria));
- return asLoopProcedure(delete.getGroup(), query, newUpdate);
- }
-
- private Limit rewriteLimitClause(Limit limit) throws TeiidComponentException, TeiidProcessingException{
- if (limit.getOffset() != null) {
- limit.setOffset(rewriteExpressionDirect(limit.getOffset()));
- if (new Constant(0).equals(limit.getOffset())) {
- limit.setOffset(null);
- }
- }
- if (limit.getRowLimit() != null) {
- limit.setRowLimit(rewriteExpressionDirect(limit.getRowLimit()));
- }
- return limit;
- }
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,3135 @@
+/*
+ * 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.rewriter;
+
+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.Collection;
+import java.util.Collections;
+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;
+import java.util.StringTokenizer;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.FunctionExecutionException;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.common.buffer.BlockedException;
+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.util.Assertion;
+import org.teiid.core.util.TimestampWithTimezone;
+import org.teiid.language.SQLConstants.NonReserved;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.eval.Evaluator;
+import org.teiid.query.function.FunctionDescriptor;
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.function.FunctionMethods;
+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.relational.rules.RuleMergeCriteria;
+import org.teiid.query.optimizer.relational.rules.RulePlaceAccess;
+import org.teiid.query.optimizer.relational.rules.RuleMergeCriteria.PlannedResult;
+import org.teiid.query.processor.relational.RelationalNodeUtil;
+import org.teiid.query.resolver.ProcedureContainerResolver;
+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.ProcedureReservedWords;
+import org.teiid.query.sql.LanguageObject.Util;
+import org.teiid.query.sql.lang.AbstractSetCriteria;
+import org.teiid.query.sql.lang.ArrayTable;
+import org.teiid.query.sql.lang.BatchedUpdateCommand;
+import org.teiid.query.sql.lang.BetweenCriteria;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.DependentSetCriteria;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.ExpressionCriteria;
+import org.teiid.query.sql.lang.From;
+import org.teiid.query.sql.lang.FromClause;
+import org.teiid.query.sql.lang.GroupBy;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.Into;
+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;
+import org.teiid.query.sql.lang.OrderByItem;
+import org.teiid.query.sql.lang.ProcedureContainer;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.SetClause;
+import org.teiid.query.sql.lang.SetClauseList;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.SubqueryCompareCriteria;
+import org.teiid.query.sql.lang.SubqueryContainer;
+import org.teiid.query.sql.lang.SubqueryFromClause;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.lang.TextTable;
+import org.teiid.query.sql.lang.TranslatableProcedureContainer;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.lang.WithQueryCommand;
+import org.teiid.query.sql.lang.XMLTable;
+import org.teiid.query.sql.lang.PredicateCriteria.Negatable;
+import org.teiid.query.sql.navigator.DeepPostOrderNavigator;
+import org.teiid.query.sql.navigator.PostOrderNavigator;
+import org.teiid.query.sql.proc.AssignmentStatement;
+import org.teiid.query.sql.proc.Block;
+import org.teiid.query.sql.proc.CommandStatement;
+import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
+import org.teiid.query.sql.proc.CriteriaSelector;
+import org.teiid.query.sql.proc.ExpressionStatement;
+import org.teiid.query.sql.proc.HasCriteria;
+import org.teiid.query.sql.proc.IfStatement;
+import org.teiid.query.sql.proc.LoopStatement;
+import org.teiid.query.sql.proc.Statement;
+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.symbol.AggregateSymbol;
+import org.teiid.query.sql.symbol.AliasSymbol;
+import org.teiid.query.sql.symbol.CaseExpression;
+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.Reference;
+import org.teiid.query.sql.symbol.ScalarSubquery;
+import org.teiid.query.sql.symbol.SearchedCaseExpression;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+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.CorrelatedReferenceCollectorVisitor;
+import org.teiid.query.sql.visitor.CriteriaTranslatorVisitor;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.sql.visitor.EvaluatableVisitor;
+import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
+import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
+import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
+import org.teiid.query.sql.visitor.EvaluatableVisitor.EvaluationLevel;
+import org.teiid.query.util.CommandContext;
+import org.teiid.query.validator.UpdateValidator.UpdateInfo;
+import org.teiid.query.validator.UpdateValidator.UpdateMapping;
+import org.teiid.translator.SourceSystemFunctions;
+
+
+/**
+ * Rewrites commands and command fragments to a form that is better for planning and execution. There is a current limitation that
+ * command objects themselves cannot change type, since the same object is always used.
+ */
+public class QueryRewriter {
+
+ public static final CompareCriteria TRUE_CRITERIA = new CompareCriteria(new Constant(1, DataTypeManager.DefaultDataClasses.INTEGER), CompareCriteria.EQ, new Constant(1, DataTypeManager.DefaultDataClasses.INTEGER));
+ public static final CompareCriteria FALSE_CRITERIA = new CompareCriteria(new Constant(1, DataTypeManager.DefaultDataClasses.INTEGER), CompareCriteria.EQ, new Constant(0, DataTypeManager.DefaultDataClasses.INTEGER));
+ public static final CompareCriteria UNKNOWN_CRITERIA = new CompareCriteria(new Constant(null, DataTypeManager.DefaultDataClasses.STRING), CompareCriteria.NE, new Constant(null, DataTypeManager.DefaultDataClasses.STRING));
+
+ private static final Map<String, String> ALIASED_FUNCTIONS = new HashMap<String, String>();
+
+ static {
+ ALIASED_FUNCTIONS.put("lower", SourceSystemFunctions.LCASE); //$NON-NLS-1$
+ ALIASED_FUNCTIONS.put("upper", SourceSystemFunctions.UCASE); //$NON-NLS-1$
+ ALIASED_FUNCTIONS.put("cast", SourceSystemFunctions.CONVERT); //$NON-NLS-1$
+ ALIASED_FUNCTIONS.put("nvl", SourceSystemFunctions.IFNULL); //$NON-NLS-1$
+ ALIASED_FUNCTIONS.put("||", SourceSystemFunctions.CONCAT); //$NON-NLS-1$
+ ALIASED_FUNCTIONS.put("chr", SourceSystemFunctions.CHAR); //$NON-NLS-1$
+ }
+
+ private static final Set<String> PARSE_FORMAT_TYPES = new HashSet<String>(Arrays.asList(DataTypeManager.DefaultDataTypes.TIME,
+ DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.DefaultDataTypes.BIG_DECIMAL,
+ DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.LONG,
+ DataTypeManager.DefaultDataTypes.FLOAT, DataTypeManager.DefaultDataTypes.DOUBLE));
+
+ private QueryMetadataInterface metadata;
+ private CommandContext context;
+ private CreateUpdateProcedureCommand procCommand;
+
+ private boolean rewriteSubcommands;
+ private boolean processing;
+ private Evaluator evaluator;
+ private Map<ElementSymbol, Expression> variables; //constant propagation
+ private int commandType;
+
+ private QueryRewriter(QueryMetadataInterface metadata,
+ CommandContext context, CreateUpdateProcedureCommand procCommand) {
+ this.metadata = metadata;
+ this.context = context;
+ this.procCommand = procCommand;
+ this.evaluator = new Evaluator(Collections.emptyMap(), null, context);
+ }
+
+ public static Command evaluateAndRewrite(Command command, Evaluator eval, CommandContext context, QueryMetadataInterface metadata) throws TeiidProcessingException, TeiidComponentException {
+ QueryRewriter queryRewriter = new QueryRewriter(metadata, context, null);
+ queryRewriter.evaluator = eval;
+ queryRewriter.rewriteSubcommands = true;
+ queryRewriter.processing = true;
+ return queryRewriter.rewriteCommand(command, false);
+ }
+
+ public static Command rewrite(Command command, CreateUpdateProcedureCommand procCommand, QueryMetadataInterface metadata, CommandContext context, Map<ElementSymbol, Expression> variableValues, int commandType) throws TeiidComponentException, TeiidProcessingException{
+ QueryRewriter rewriter = new QueryRewriter(metadata, context, procCommand);
+ rewriter.rewriteSubcommands = true;
+ rewriter.variables = variableValues;
+ rewriter.commandType = commandType;
+ return rewriter.rewriteCommand(command, false);
+ }
+
+ public static Command rewrite(Command command, QueryMetadataInterface metadata, CommandContext context) throws TeiidComponentException, TeiidProcessingException{
+ return rewrite(command, null, metadata, context, null, Command.TYPE_UNKNOWN);
+ }
+
+ /**
+ * Rewrites the command and all of its subcommands (both embedded and non-embedded)
+ *
+ * @param command
+ * @param removeOrderBy
+ * @return
+ * @throws QueryValidatorException
+ */
+ private Command rewriteCommand(Command command, boolean removeOrderBy) throws TeiidComponentException, TeiidProcessingException{
+ QueryMetadataInterface oldMetadata = metadata;
+ CreateUpdateProcedureCommand oldProcCommand = procCommand;
+
+ Map tempMetadata = command.getTemporaryMetadata();
+ if(tempMetadata != null) {
+ metadata = new TempMetadataAdapter(metadata, new TempMetadataStore(tempMetadata));
+ }
+
+ switch(command.getType()) {
+ case Command.TYPE_QUERY:
+ QueryCommand queryCommand = (QueryCommand)command;
+ if (removeOrderBy && queryCommand.getLimit() == null) {
+ queryCommand.setOrderBy(null);
+ }
+ if (queryCommand.getWith() != null) {
+ for (WithQueryCommand withQueryCommand : queryCommand.getWith()) {
+ if (withQueryCommand.getColumns() == null) {
+ List<ElementSymbol> columns = ResolverUtil.resolveElementsInGroup(withQueryCommand.getGroupSymbol(), metadata);
+ withQueryCommand.setColumns(LanguageObject.Util.deepClone(columns, ElementSymbol.class));
+ }
+ rewriteSubqueryContainer(withQueryCommand, true);
+ }
+ }
+ if(command instanceof Query) {
+ command = rewriteQuery((Query) command);
+ }else {
+ command = rewriteSetQuery((SetQuery) command);
+ }
+ break;
+ case Command.TYPE_STORED_PROCEDURE:
+ command = rewriteExec((StoredProcedure) command);
+ break;
+ case Command.TYPE_INSERT:
+ command = rewriteInsert((Insert) command);
+ break;
+ case Command.TYPE_UPDATE:
+ command = rewriteUpdate((Update) command);
+ break;
+ case Command.TYPE_DELETE:
+ command = rewriteDelete((Delete) command);
+ break;
+ case Command.TYPE_UPDATE_PROCEDURE:
+ procCommand = (CreateUpdateProcedureCommand) command;
+ command = rewriteUpdateProcedure((CreateUpdateProcedureCommand) command);
+ break;
+ case Command.TYPE_BATCHED_UPDATE:
+ List subCommands = ((BatchedUpdateCommand)command).getUpdateCommands();
+ for (int i = 0; i < subCommands.size(); i++) {
+ Command subCommand = (Command)subCommands.get(i);
+ subCommand = rewriteCommand(subCommand, false);
+ subCommands.set(i, subCommand);
+ }
+ break;
+ case Command.TYPE_TRIGGER_ACTION:
+ TriggerAction ta = (TriggerAction)command;
+ ta.setBlock(rewriteBlock(ta.getBlock()));
+ break;
+ }
+
+ this.metadata = oldMetadata;
+ this.procCommand = oldProcCommand;
+ return command;
+ }
+
+ private Command rewriteUpdateProcedure(CreateUpdateProcedureCommand command)
+ throws TeiidComponentException, TeiidProcessingException{
+ Map<ElementSymbol, Expression> oldVariables = variables;
+ if (command.getUserCommand() != null) {
+ variables = QueryResolver.getVariableValues(command.getUserCommand(), false, metadata);
+ commandType = command.getUserCommand().getType();
+ }
+
+ Block block = rewriteBlock(command.getBlock());
+ command.setBlock(block);
+
+ variables = oldVariables;
+
+ return command;
+ }
+
+ private Block rewriteBlock(Block block)
+ throws TeiidComponentException, TeiidProcessingException{
+ List statements = block.getStatements();
+ Iterator stmtIter = statements.iterator();
+
+ List newStmts = new ArrayList(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);
+ }
+ }
+
+ block.setStatements(newStmts);
+
+ return block;
+ }
+
+ private Object rewriteStatement(Statement statement)
+ throws TeiidComponentException, TeiidProcessingException{
+
+ // evaluate the HAS Criteria on the procedure and rewrite
+ int stmtType = statement.getType();
+ switch(stmtType) {
+ case Statement.TYPE_IF:
+ IfStatement ifStmt = (IfStatement) statement;
+ Criteria ifCrit = ifStmt.getCondition();
+ Criteria evalCrit = rewriteCriteria(ifCrit);
+
+ ifStmt.setCondition(evalCrit);
+ if(evalCrit.equals(TRUE_CRITERIA)) {
+ Block ifblock = rewriteBlock(ifStmt.getIfBlock());
+ return ifblock.getStatements();
+ } else if(evalCrit.equals(FALSE_CRITERIA) || evalCrit.equals(UNKNOWN_CRITERIA)) {
+ if(ifStmt.hasElseBlock()) {
+ Block elseBlock = rewriteBlock(ifStmt.getElseBlock());
+ return elseBlock.getStatements();
+ }
+ return null;
+ } else {
+ Block ifblock = rewriteBlock(ifStmt.getIfBlock());
+ ifStmt.setIfBlock(ifblock);
+ if(ifStmt.hasElseBlock()) {
+ Block elseBlock = rewriteBlock(ifStmt.getElseBlock());
+ ifStmt.setElseBlock(elseBlock);
+ }
+ }
+ return ifStmt;
+ case Statement.TYPE_ERROR:
+ case Statement.TYPE_DECLARE:
+ case Statement.TYPE_ASSIGNMENT:
+ ExpressionStatement exprStmt = (ExpressionStatement) statement;
+ // replace variables to references, these references are later
+ // replaced in the processor with variable values
+ Expression expr = exprStmt.getExpression();
+ if (expr != null) {
+ expr = rewriteExpressionDirect(expr);
+ exprStmt.setExpression(expr);
+ }
+ return exprStmt;
+ case Statement.TYPE_COMMAND:
+ CommandStatement cmdStmt = (CommandStatement) statement;
+ rewriteSubqueryContainer(cmdStmt, false);
+
+ if(cmdStmt.getCommand().getType() == Command.TYPE_UPDATE) {
+ Update update = (Update)cmdStmt.getCommand();
+ if (update.getChangeList().isEmpty()) {
+ return null;
+ }
+ }
+ return statement;
+ case Statement.TYPE_LOOP:
+ LoopStatement loop = (LoopStatement)statement;
+
+ rewriteSubqueryContainer(loop, false);
+
+ rewriteBlock(loop.getBlock());
+
+ if (loop.getBlock().getStatements().isEmpty()) {
+ return null;
+ }
+
+ return loop;
+ case Statement.TYPE_WHILE:
+ WhileStatement whileStatement = (WhileStatement) statement;
+ Criteria crit = whileStatement.getCondition();
+ crit = rewriteCriteria(crit);
+
+ whileStatement.setCondition(crit);
+ 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;
+ }
+ whileStatement.setBlock(rewriteBlock(whileStatement.getBlock()));
+
+ if (whileStatement.getBlock().getStatements().isEmpty()) {
+ return null;
+ }
+
+ return whileStatement;
+ default:
+ return statement;
+ }
+ }
+
+ /**
+ * @param removeOrderBy
+ * @param assStmt
+ * @throws QueryValidatorException
+ */
+ private void rewriteSubqueryContainer(SubqueryContainer container, boolean removeOrderBy) throws TeiidComponentException, TeiidProcessingException{
+ if (rewriteSubcommands && container.getCommand() != null && (container.getCommand().getProcessorPlan() == null || processing)) {
+ container.setCommand(rewriteCommand(container.getCommand(), removeOrderBy));
+ }
+ }
+
+ /**
+ * <p>The HasCriteria evaluates to a TRUE_CRITERIA or a FALSE_CRITERIA, it checks to see
+ * if type of criteria on the elements specified by the CriteriaSelector is specified on
+ * the user's command.</p>
+ */
+ private Criteria rewriteCriteria(HasCriteria hasCrit) {
+ Criteria userCrit = null;
+ Command userCommand = procCommand.getUserCommand();
+ int cmdType = userCommand.getType();
+ switch(cmdType) {
+ case Command.TYPE_DELETE:
+ userCrit = ((Delete)userCommand).getCriteria();
+ break;
+ case Command.TYPE_UPDATE:
+ userCrit = ((Update)userCommand).getCriteria();
+ break;
+ default:
+ return FALSE_CRITERIA;
+ }
+
+ if(userCrit == null) {
+ return FALSE_CRITERIA;
+ }
+
+ // get the CriteriaSelector, elements on the selector and the selector type
+ CriteriaSelector selector = hasCrit.getSelector();
+
+ Collection hasCritElmts = null;
+ if(selector.hasElements()) {
+ hasCritElmts = selector.getElements();
+ // collect elements present on the user's criteria and check if
+ // all of the hasCriteria elements are among them
+ Collection<ElementSymbol> userElmnts = ElementCollectorVisitor.getElements(userCrit, true);
+ if(!userElmnts.containsAll(hasCritElmts)) {
+ return FALSE_CRITERIA;
+ }
+ }
+
+ int selectorType = selector.getSelectorType();
+ // if no selector type specified return true
+ // already checked all HAS elements present on user criteria
+ if(selectorType == CriteriaSelector.NO_TYPE) {
+ return TRUE_CRITERIA;
+ }
+
+ // collect all predicate criteria present on the user's criteria
+ for (Criteria predicateCriteria : Criteria.separateCriteriaByAnd(userCrit)) {
+ // atleast one of the hasElemnets should be on this predicate else
+ // proceed to the next predicate
+ Collection<ElementSymbol> predElmnts = ElementCollectorVisitor.getElements(predicateCriteria, true);
+ if(selector.hasElements()) {
+ Iterator hasIter = hasCritElmts.iterator();
+ boolean containsElmnt = false;
+ while(hasIter.hasNext()) {
+ ElementSymbol hasElmnt = (ElementSymbol) hasIter.next();
+ if(predElmnts.contains(hasElmnt)) {
+ containsElmnt = true;
+ }
+ }
+
+ if(!containsElmnt) {
+ continue;
+ }
+ }
+
+ // check if the predicate criteria type maches the type specified
+ // by the criteria selector
+ switch(selectorType) {
+ case CriteriaSelector.IN:
+ if(predicateCriteria instanceof SetCriteria) {
+ return TRUE_CRITERIA;
+ }
+ break;
+ case CriteriaSelector.LIKE:
+ if(predicateCriteria instanceof MatchCriteria) {
+ return TRUE_CRITERIA;
+ }
+ break;
+ case CriteriaSelector.IS_NULL:
+ if(predicateCriteria instanceof IsNullCriteria) {
+ return TRUE_CRITERIA;
+ }
+ break;
+ case CriteriaSelector.BETWEEN:
+ if(predicateCriteria instanceof BetweenCriteria) {
+ return TRUE_CRITERIA;
+ }
+ break;
+ default: // EQ, GT, LT, GE, LE criteria
+ if(predicateCriteria instanceof CompareCriteria) {
+ CompareCriteria compCrit = (CompareCriteria) predicateCriteria;
+ if(compCrit.getOperator() == selectorType) {
+ return TRUE_CRITERIA;
+ }
+ }
+ break;
+ }
+ }
+
+ return FALSE_CRITERIA;
+ }
+
+ /**
+ * <p>TranslateCriteria is evaluated by translating elements on parts(restricted by the type
+ * of criteria and elements specified on the CriteriaSelector) the user's criteria
+ * using the translations provided on the TranslateCriteria and symbol mapping between
+ * virtual group elements and the expressions on the query transformation defining the
+ * virtual group.</p>
+ */
+ private Criteria rewriteCriteria(TranslateCriteria transCrit)
+ throws TeiidComponentException, TeiidProcessingException{
+
+ // criteria translated
+ Criteria translatedCriteria = null;
+
+ // get the user's command from the procedure
+ Command userCmd = procCommand.getUserCommand();
+
+ if (!(userCmd instanceof TranslatableProcedureContainer)) {
+ return FALSE_CRITERIA;
+ }
+
+ Criteria userCriteria = ((TranslatableProcedureContainer)userCmd).getCriteria();
+
+ if (userCriteria == null) {
+ return TRUE_CRITERIA;
+ }
+
+ // get the symbolmap between virtual elements and theie counterpart expressions
+ // from the virtual group's query transform
+ CriteriaTranslatorVisitor translateVisitor = new CriteriaTranslatorVisitor(procCommand.getSymbolMap());
+
+ translateVisitor.setCriteriaSelector(transCrit.getSelector());
+ if(transCrit.hasTranslations()) {
+ translateVisitor.setTranslations(transCrit.getTranslations());
+ }
+
+ // create a clone of user's criteria that is then translated
+ Criteria userClone = (Criteria) userCriteria.clone();
+
+ userClone = translateVisitor.translate(userClone);
+
+ // translated criteria
+ ((TranslatableProcedureContainer)userCmd).addImplicitParameters(translateVisitor.getImplicitParams());
+
+ translatedCriteria = rewriteCriteria(userClone);
+
+ // apply any implicit conversions
+ try {
+ ResolverVisitor.resolveLanguageObject(translatedCriteria, metadata);
+ } catch(TeiidException ex) {
+ throw new QueryValidatorException(ex, "ERR.015.009.0002", QueryPlugin.Util.getString("ERR.015.009.0002", translatedCriteria)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ return translatedCriteria;
+ }
+
+ private Command rewriteQuery(Query query)
+ throws TeiidComponentException, TeiidProcessingException{
+
+ // Rewrite from clause
+ From from = query.getFrom();
+ if(from != null){
+ List<FromClause> clauses = new ArrayList<FromClause>(from.getClauses().size());
+ Iterator clauseIter = from.getClauses().iterator();
+ while(clauseIter.hasNext()) {
+ clauses.add( rewriteFromClause(query, (FromClause) clauseIter.next()) );
+ }
+ from.setClauses(clauses);
+ } else {
+ query.setOrderBy(null);
+ }
+
+ // Rewrite criteria
+ Criteria crit = query.getCriteria();
+ if(crit != null) {
+ if (query.getIsXML()) {
+ //only rewrite expressions, removing whole predicates could change the nature of the query,
+ //because we aren't considering the xml pseudo-functions context, row limit, etc.
+ rewriteExpressions(crit);
+ } else {
+ crit = rewriteCriteria(crit);
+ }
+ if(crit == TRUE_CRITERIA) {
+ query.setCriteria(null);
+ } else if (crit == UNKNOWN_CRITERIA) {
+ query.setCriteria(FALSE_CRITERIA);
+ } else {
+ query.setCriteria(crit);
+ }
+ }
+
+ if (from != null && !query.getIsXML()) {
+ rewriteSubqueriesAsJoins(query);
+ }
+
+ query = rewriteGroupBy(query);
+
+ // Rewrite having
+ Criteria having = query.getHaving();
+ if(having != null) {
+ crit = rewriteCriteria(having);
+ if(crit == TRUE_CRITERIA) {
+ query.setHaving(null);
+ } else {
+ query.setHaving(crit);
+ }
+ }
+
+ rewriteExpressions(query.getSelect());
+
+ if (!query.getIsXML()) {
+ query = (Query)rewriteOrderBy(query);
+ }
+
+ if (query.getLimit() != null) {
+ query.setLimit(rewriteLimitClause(query.getLimit()));
+ }
+
+ if (query.getInto() != null) {
+ return rewriteSelectInto(query);
+ }
+
+ return query;
+ }
+
+ private void rewriteSubqueriesAsJoins(Query query)
+ throws TeiidComponentException, QueryMetadataException,
+ QueryResolverException {
+ if (query.getCriteria() == null) {
+ return;
+ }
+ RuleMergeCriteria rmc = new RuleMergeCriteria(null, null, null, this.context, this.metadata);
+ List<Criteria> current = Criteria.separateCriteriaByAnd(query.getCriteria());
+ query.setCriteria(null);
+ List<GroupSymbol> groups = query.getFrom().getGroups();
+ HashSet<String> names = new HashSet<String>();
+ for (GroupSymbol gs : groups) {
+ names.add(gs.getCanonicalName());
+ }
+ for (Iterator<Criteria> crits = current.iterator(); crits.hasNext();) {
+ PlannedResult plannedResult = rmc.findSubquery(crits.next());
+ if (plannedResult.not || plannedResult.query == null || plannedResult.query.getProcessorPlan() != null
+ || plannedResult.query.getWith() != null) {
+ continue;
+ }
+ if (plannedResult.query.getCorrelatedReferences() == null) {
+ //create the correlated refs if they exist
+ //there is a little bit of a design problem here that null usually means no refs.
+ ArrayList<Reference> correlatedReferences = new ArrayList<Reference>();
+ CorrelatedReferenceCollectorVisitor.collectReferences(plannedResult.query, groups, correlatedReferences);
+ if (!correlatedReferences.isEmpty()) {
+ SymbolMap map = new SymbolMap();
+ for (Reference reference : correlatedReferences) {
+ map.addMapping(reference.getExpression(), reference.getExpression());
+ }
+ plannedResult.query.setCorrelatedReferences(map);
+ }
+ }
+ boolean requiresDistinct = requiresDistinctRows(query);
+ if (!rmc.planQuery(groups, requiresDistinct, plannedResult)) {
+ continue;
+ }
+ crits.remove();
+
+ GroupSymbol viewName = RulePlaceAccess.recontextSymbol(new GroupSymbol("X"), names); //$NON-NLS-1$
+ viewName.setName(viewName.getCanonicalName());
+ viewName.setDefinition(null);
+ Query q = createInlineViewQuery(viewName, plannedResult.query, metadata, plannedResult.query.getSelect().getProjectedSymbols());
+
+ Iterator<SingleElementSymbol> iter = q.getSelect().getProjectedSymbols().iterator();
+ HashMap<Expression, Expression> expressionMap = new HashMap<Expression, Expression>();
+ for (SingleElementSymbol symbol : plannedResult.query.getSelect().getProjectedSymbols()) {
+ 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)));
+ }
+ Criteria mappedCriteria = Criteria.combineCriteria(plannedResult.nonEquiJoinCriteria);
+ ExpressionMappingVisitor.mapExpressions(mappedCriteria, expressionMap);
+ query.setCriteria(Criteria.combineCriteria(query.getCriteria(), mappedCriteria));
+ 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
+ }
+ query.setCriteria(Criteria.combineCriteria(query.getCriteria(), Criteria.combineCriteria(current)));
+ }
+
+ private boolean requiresDistinctRows(Query query) {
+ Set<AggregateSymbol> aggs = new HashSet<AggregateSymbol>();
+ aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(query.getSelect(), false));
+ aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(query.getHaving(), false));
+ if (!aggs.isEmpty() || query.getGroupBy() != null) {
+ if (!AggregateSymbol.areAggregatesCardinalityDependent(aggs)) {
+ return false;
+ }
+ } else if (query.getSelect().isDistinct()) {
+ for (SingleElementSymbol projectSymbol : query.getSelect().getProjectedSymbols()) {
+ Expression ex = SymbolMap.getExpression(projectSymbol);
+ if (FunctionCollectorVisitor.isNonDeterministic(ex)) {
+ return true;
+ }
+ if (!ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(ex).isEmpty()) {
+ return true;
+ }
+ }
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Converts a group by with expressions into a group by with only element symbols and an inline view
+ * @param query
+ * @return
+ * @throws QueryValidatorException
+ */
+ private Query rewriteGroupBy(Query query) throws TeiidComponentException, TeiidProcessingException{
+ if (query.getGroupBy() == null) {
+ 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);
+ return query;
+ }
+
+ public static boolean isDistinctWithGroupBy(Query query) {
+ GroupBy groupBy = query.getGroupBy();
+ if (groupBy == null) {
+ return false;
+ }
+ HashSet<Expression> selectExpressions = new HashSet<Expression>();
+ for (SingleElementSymbol selectExpr : query.getSelect().getProjectedSymbols()) {
+ selectExpressions.add(SymbolMap.getExpression(selectExpr));
+ }
+ for (SingleElementSymbol groupByExpr : (List<SingleElementSymbol>)groupBy.getSymbols()) {
+ if (!selectExpressions.contains(groupByExpr)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private void rewriteExpressions(LanguageObject obj) throws TeiidComponentException, TeiidProcessingException{
+ if (obj == null) {
+ return;
+ }
+ ExpressionMappingVisitor visitor = new ExpressionMappingVisitor(null) {
+ /**
+ * @see org.teiid.query.sql.visitor.ExpressionMappingVisitor#replaceExpression(org.teiid.query.sql.symbol.Expression)
+ */
+ @Override
+ public Expression replaceExpression(Expression element) {
+ try {
+ return rewriteExpressionDirect(element);
+ } catch (TeiidException err) {
+ throw new TeiidRuntimeException(err);
+ }
+ }
+ };
+ try {
+ PostOrderNavigator.doVisit(obj, visitor);
+ } catch (TeiidRuntimeException err) {
+ if (err.getChild() instanceof TeiidComponentException) {
+ throw (TeiidComponentException)err.getChild();
+ }
+ if (err.getChild() instanceof TeiidProcessingException) {
+ throw (TeiidProcessingException)err.getChild();
+ }
+ throw err;
+ }
+ }
+
+ /**
+ * Rewrite the order by clause.
+ * Unrelated order by expressions will cause the creation of nested inline views.
+ *
+ * @param query
+ * @throws TeiidComponentException, MetaMatrixProcessingException
+ */
+ public QueryCommand rewriteOrderBy(QueryCommand queryCommand) throws TeiidComponentException {
+ final OrderBy orderBy = queryCommand.getOrderBy();
+ if (orderBy == null) {
+ return queryCommand;
+ }
+ Select select = queryCommand.getProjectedQuery().getSelect();
+ final List<SingleElementSymbol> projectedSymbols = select.getProjectedSymbols();
+
+ LinkedList<OrderByItem> unrelatedItems = new LinkedList<OrderByItem>();
+
+ boolean hasUnrelatedExpression = 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;
+ }
+
+ public static boolean 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);
+ int index = orderBy.getExpressionPosition(i);
+ boolean isUnrelated = false;
+ if (index == -1) {
+ unrelatedItems.add(orderBy.getOrderByItems().get(i));
+ isUnrelated = (querySymbol instanceof ExpressionSymbol);
+ } else {
+ querySymbol = (SingleElementSymbol)projectedSymbols.get(index);
+ }
+ Expression expr = SymbolMap.getExpression(querySymbol);
+ if (!previousExpressions.add(expr) || (queryCommand instanceof Query && EvaluatableVisitor.willBecomeConstant(expr))) {
+ 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;
+ }
+
+ /**
+ * This method will alias each of the select into elements to the corresponding column name in the
+ * target table. This ensures that they will all be uniquely named.
+ *
+ * @param query
+ * @throws QueryValidatorException
+ */
+ private Insert rewriteSelectInto(Query query) throws TeiidProcessingException{
+ Into into = query.getInto();
+ try {
+ List<ElementSymbol> allIntoElements = Util.deepClone(ResolverUtil.resolveElementsInGroup(into.getGroup(), metadata), ElementSymbol.class);
+ Insert insert = new Insert(into.getGroup(), allIntoElements, Collections.emptyList());
+ query.setInto(null);
+ insert.setQueryExpression(query);
+ return rewriteInsert(correctDatatypes(insert));
+ } catch (QueryMetadataException err) {
+ throw new QueryValidatorException(err, err.getMessage());
+ } catch (TeiidComponentException err) {
+ throw new QueryValidatorException(err, err.getMessage());
+ }
+ }
+
+ private Insert correctDatatypes(Insert insert) {
+ boolean needsView = false;
+ for (int i = 0; !needsView && i < insert.getVariables().size(); i++) {
+ SingleElementSymbol ses = insert.getVariables().get(i);
+ if (ses.getType() != insert.getQueryExpression().getProjectedSymbols().get(i).getType()) {
+ needsView = true;
+ }
+ }
+ if (needsView) {
+ try {
+ insert.setQueryExpression(createInlineViewQuery(new GroupSymbol("X"), insert.getQueryExpression(), metadata, insert.getVariables())); //$NON-NLS-1$
+ } catch (TeiidException err) {
+ throw new TeiidRuntimeException(err);
+ }
+ }
+ return insert;
+ }
+
+ private void correctProjectedTypes(List actualSymbolTypes, Query query) {
+
+ List symbols = query.getSelect().getProjectedSymbols();
+
+ List newSymbols = SetQuery.getTypedProjectedSymbols(symbols, actualSymbolTypes, this.metadata);
+
+ query.getSelect().setSymbols(newSymbols);
+ }
+
+ private SetQuery rewriteSetQuery(SetQuery setQuery)
+ throws TeiidComponentException, TeiidProcessingException{
+
+ if (setQuery.getProjectedTypes() != null) {
+ for (QueryCommand command : setQuery.getQueryCommands()) {
+ if (!(command instanceof Query)) {
+ continue;
+ }
+ correctProjectedTypes(setQuery.getProjectedTypes(), (Query)command);
+ }
+ setQuery.setProjectedTypes(null, null);
+ }
+
+ setQuery.setLeftQuery((QueryCommand)rewriteCommand(setQuery.getLeftQuery(), true));
+ setQuery.setRightQuery((QueryCommand)rewriteCommand(setQuery.getRightQuery(), true));
+
+ rewriteOrderBy(setQuery);
+
+ if (setQuery.getLimit() != null) {
+ setQuery.setLimit(rewriteLimitClause(setQuery.getLimit()));
+ }
+
+ return setQuery;
+ }
+
+ private FromClause rewriteFromClause(Query parent, FromClause clause)
+ throws TeiidComponentException, TeiidProcessingException{
+ if(clause instanceof JoinPredicate) {
+ return rewriteJoinPredicate(parent, (JoinPredicate) clause);
+ } else if (clause instanceof SubqueryFromClause) {
+ rewriteSubqueryContainer((SubqueryFromClause)clause, true);
+ } else if (clause instanceof TextTable) {
+ TextTable tt = (TextTable)clause;
+ tt.setFile(rewriteExpressionDirect(tt.getFile()));
+ } else if (clause instanceof XMLTable) {
+ XMLTable xt = (XMLTable)clause;
+ xt.rewriteDefaultColumn();
+ rewriteExpressions(clause);
+ } else if (clause instanceof ArrayTable) {
+ ArrayTable at = (ArrayTable)clause;
+ at.setArrayValue(rewriteExpressionDirect(at.getArrayValue()));
+ }
+ return clause;
+ }
+
+ private JoinPredicate rewriteJoinPredicate(Query parent, JoinPredicate predicate)
+ throws TeiidComponentException, TeiidProcessingException{
+ List joinCrits = predicate.getJoinCriteria();
+ if(joinCrits != null && joinCrits.size() > 0) {
+ //rewrite join crits by rewriting a compound criteria
+ Criteria criteria = new CompoundCriteria(new ArrayList(joinCrits));
+ joinCrits.clear();
+ criteria = rewriteCriteria(criteria);
+ if (criteria instanceof CompoundCriteria && ((CompoundCriteria)criteria).getOperator() == CompoundCriteria.AND) {
+ joinCrits.addAll(((CompoundCriteria)criteria).getCriteria());
+ } else {
+ joinCrits.add(criteria);
+ }
+ predicate.setJoinCriteria(joinCrits);
+ }
+
+ if (predicate.getJoinType() == JoinType.JOIN_UNION) {
+ predicate.setJoinType(JoinType.JOIN_FULL_OUTER);
+ predicate.setJoinCriteria(new ArrayList<Criteria>(Arrays.asList(FALSE_CRITERIA)));
+ } else if (predicate.getJoinType() == JoinType.JOIN_RIGHT_OUTER) {
+ predicate.setJoinType(JoinType.JOIN_LEFT_OUTER);
+ FromClause leftClause = predicate.getLeftClause();
+ predicate.setLeftClause(predicate.getRightClause());
+ predicate.setRightClause(leftClause);
+ }
+
+ predicate.setLeftClause( rewriteFromClause(parent, predicate.getLeftClause() ));
+ predicate.setRightClause( rewriteFromClause(parent, predicate.getRightClause() ));
+
+ return predicate;
+ }
+
+ /**
+ * Rewrite the criteria by evaluating some trivial cases.
+ * @param criteria The criteria to rewrite
+ * @param metadata
+ * @param userCriteria The criteria on user's command, used in rewriting HasCriteria
+ * in the procedural language.
+ * @return The re-written criteria
+ */
+ public static Criteria rewriteCriteria(Criteria criteria, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException{
+ return new QueryRewriter(metadata, context, procCommand).rewriteCriteria(criteria);
+ }
+
+ /**
+ * Rewrite the criteria by evaluating some trivial cases.
+ * @param criteria The criteria to rewrite
+ * @param userCriteria The criteria on user's command, used in rewriting HasCriteria
+ * in the procedural language.
+ * @return The re-written criteria
+ */
+ private Criteria rewriteCriteria(Criteria criteria) throws TeiidComponentException, TeiidProcessingException{
+ if(criteria instanceof CompoundCriteria) {
+ return rewriteCriteria((CompoundCriteria)criteria, true);
+ } else if(criteria instanceof NotCriteria) {
+ criteria = rewriteCriteria((NotCriteria)criteria);
+ } else if(criteria instanceof CompareCriteria) {
+ criteria = rewriteCriteria((CompareCriteria)criteria);
+ } else if(criteria instanceof SubqueryCompareCriteria) {
+ criteria = rewriteCriteria((SubqueryCompareCriteria)criteria);
+ } else if(criteria instanceof MatchCriteria) {
+ criteria = rewriteCriteria((MatchCriteria)criteria);
+ } else if(criteria instanceof SetCriteria) {
+ criteria = rewriteCriteria((SetCriteria)criteria);
+ } else if(criteria instanceof IsNullCriteria) {
+ criteria = rewriteCriteria((IsNullCriteria)criteria);
+ } else if(criteria instanceof BetweenCriteria) {
+ criteria = rewriteCriteria((BetweenCriteria)criteria);
+ } else if(criteria instanceof HasCriteria) {
+ criteria = rewriteCriteria((HasCriteria)criteria);
+ } else if(criteria instanceof TranslateCriteria) {
+ criteria = rewriteCriteria((TranslateCriteria)criteria);
+ } else if (criteria instanceof ExistsCriteria) {
+ ExistsCriteria exists = (ExistsCriteria)criteria;
+ if (exists.shouldEvaluate() && processing) {
+ return getCriteria(evaluator.evaluate(exists, null));
+ }
+ rewriteSubqueryContainer((SubqueryContainer)criteria, true);
+ if (!RelationalNodeUtil.shouldExecute(exists.getCommand(), false, true)) {
+ return exists.isNegated()?TRUE_CRITERIA:FALSE_CRITERIA;
+ }
+ if (exists.getCommand().getProcessorPlan() == null) {
+ if (exists.getCommand() instanceof Query) {
+ Query query = (Query)exists.getCommand();
+ if ((query.getLimit() == null || query.getOrderBy() == null) && query.getSelect().getProjectedSymbols().size() > 1) {
+ query.getSelect().clearSymbols();
+ query.getSelect().addSymbol(new ExpressionSymbol("x", new Constant(1))); //$NON-NLS-1$
+ }
+ }
+ addImplicitLimit(exists, 1);
+ }
+ } else if (criteria instanceof SubquerySetCriteria) {
+ SubquerySetCriteria sub = (SubquerySetCriteria)criteria;
+ if (rewriteLeftExpression(sub)) {
+ return UNKNOWN_CRITERIA;
+ }
+ rewriteSubqueryContainer(sub, true);
+ if (!RelationalNodeUtil.shouldExecute(sub.getCommand(), false, true)) {
+ return getSimpliedCriteria(criteria, sub.getExpression(), !sub.isNegated(), true);
+ }
+ } else if (criteria instanceof DependentSetCriteria) {
+ criteria = rewriteDependentSetCriteria((DependentSetCriteria)criteria);
+ } else if (criteria instanceof ExpressionCriteria) {
+ return new CompareCriteria(((ExpressionCriteria) criteria).getExpression(), CompareCriteria.EQ, new Constant(Boolean.TRUE));
+ }
+
+ return evaluateCriteria(criteria);
+ }
+
+ private void addImplicitLimit(SubqueryContainer<QueryCommand> container, int rowLimit) {
+ if (container.getCommand().getLimit() != null) {
+ Limit lim = container.getCommand().getLimit();
+ if (lim.getRowLimit() instanceof Constant) {
+ Constant c = (Constant)lim.getRowLimit();
+ if (!c.isMultiValued() && Integer.valueOf(rowLimit).compareTo((Integer) c.getValue()) <= 0) {
+ lim.setRowLimit(new Constant(rowLimit));
+ if (lim.getRowLimit() == null) {
+ lim.setImplicit(true);
+ container.getCommand().setOrderBy(null);
+ }
+ }
+ }
+ return;
+ }
+ boolean addLimit = true;
+ if (container.getCommand() instanceof Query) {
+ Query query = (Query)container.getCommand();
+ addLimit = !(query.hasAggregates() && query.getGroupBy() == null);
+ }
+ if (addLimit) {
+ Limit lim = new Limit(null, new Constant(rowLimit));
+ lim.setImplicit(true);
+ container.getCommand().setLimit(lim);
+ }
+ }
+
+ private Criteria rewriteDependentSetCriteria(DependentSetCriteria dsc)
+ throws TeiidComponentException, TeiidProcessingException{
+ if (!processing) {
+ if (rewriteLeftExpression(dsc)) {
+ return UNKNOWN_CRITERIA;
+ }
+ }
+ return dsc;
+ }
+
+ /**
+ * Performs simple expression flattening
+ *
+ * @param criteria
+ * @return
+ */
+ public static Criteria optimizeCriteria(CompoundCriteria criteria, QueryMetadataInterface metadata) {
+ try {
+ return new QueryRewriter(metadata, null, null).rewriteCriteria(criteria, false);
+ } catch (TeiidException err) {
+ //shouldn't happen
+ return criteria;
+ }
+ }
+
+ /** May be simplified if this is an AND and a sub criteria is always
+ * false or if this is an OR and a sub criteria is always true
+ */
+ private Criteria rewriteCriteria(CompoundCriteria criteria, boolean rewrite) throws TeiidComponentException, TeiidProcessingException{
+ List<Criteria> crits = criteria.getCriteria();
+ int operator = criteria.getOperator();
+
+ // Walk through crits and collect converted ones
+ LinkedHashSet<Criteria> newCrits = new LinkedHashSet<Criteria>(crits.size());
+ HashMap<Expression, Criteria> exprMap = new HashMap<Expression, Criteria>();
+ for (Criteria converted : crits) {
+ if (rewrite) {
+ converted = rewriteCriteria(converted);
+ } else if (converted instanceof CompoundCriteria) {
+ converted = rewriteCriteria((CompoundCriteria)converted, false);
+ }
+ List<Criteria> critList = null;
+ if (converted instanceof CompoundCriteria) {
+ CompoundCriteria other = (CompoundCriteria)converted;
+ if (other.getOperator() == criteria.getOperator()) {
+ critList = other.getCriteria();
+ }
+ }
+ if (critList == null) {
+ critList = Arrays.asList(converted);
+ }
+ for (Criteria criteria2 : critList) {
+ converted = criteria2;
+ //begin boolean optimizations
+ if(TRUE_CRITERIA.equals(converted)) {
+ if(operator == CompoundCriteria.OR) {
+ // this OR must be true as at least one branch is always true
+ return converted;
+ }
+ } else if(FALSE_CRITERIA.equals(converted)) {
+ if(operator == CompoundCriteria.AND) {
+ // this AND must be false as at least one branch is always false
+ return converted;
+ }
+ } else if (UNKNOWN_CRITERIA.equals(converted)) {
+ if (operator == CompoundCriteria.AND) {
+ return FALSE_CRITERIA;
+ }
+ } else {
+ if (operator == CompoundCriteria.AND) {
+ converted = rewriteAndConjunct(converted, exprMap, newCrits);
+ if (converted != null) {
+ return converted;
+ }
+ } else {
+ //or
+ if (converted instanceof SetCriteria) {
+ SetCriteria sc = (SetCriteria)converted;
+ if (!sc.isNegated() && sc.isAllConstants()) {
+ Criteria crit = exprMap.get(sc.getExpression());
+ if (crit == null) {
+ exprMap.put(sc.getExpression(), sc);
+ } else if (crit instanceof SetCriteria) {
+ SetCriteria other = (SetCriteria)crit;
+ other.getValues().addAll(sc.getValues());
+ continue;
+ } else {
+ newCrits.remove(crit);
+ CompareCriteria cc = (CompareCriteria)crit;
+ sc.getValues().add(cc.getRightExpression());
+ }
+ }
+ } else if (converted instanceof CompareCriteria) {
+ CompareCriteria cc = (CompareCriteria)converted;
+ if (cc.getOperator() == CompareCriteria.EQ && cc.getRightExpression() instanceof Constant) {
+ Criteria crit = exprMap.get(cc.getLeftExpression());
+ if (crit == null) {
+ exprMap.put(cc.getLeftExpression(), cc);
+ } else if (crit instanceof SetCriteria) {
+ SetCriteria other = (SetCriteria)crit;
+ other.getValues().add(cc.getRightExpression());
+ continue;
+ } else {
+ newCrits.remove(crit);
+ CompareCriteria other = (CompareCriteria)crit;
+ SetCriteria sc = new SetCriteria(cc.getLeftExpression(), new LinkedHashSet<Expression>());
+ sc.setAllConstants(true);
+ sc.getValues().add(cc.getRightExpression());
+ sc.getValues().add(other.getRightExpression());
+ exprMap.put(sc.getExpression(), sc);
+ converted = sc;
+ }
+ }
+ }
+ newCrits.add(converted);
+ }
+ }
+ }
+ }
+
+ if(newCrits.size() == 0) {
+ if(operator == CompoundCriteria.AND) {
+ return TRUE_CRITERIA;
+ }
+ return FALSE_CRITERIA;
+ } else if(newCrits.size() == 1) {
+ // Only one sub crit now, so just return it
+ return newCrits.iterator().next();
+ } else {
+ criteria.getCriteria().clear();
+ criteria.getCriteria().addAll(newCrits);
+ return criteria;
+ }
+ }
+
+ /**
+ * Rewrite the given conjunct
+ * @return null if the conjunct was internally handled
+ */
+ private Criteria rewriteAndConjunct(Criteria converted, Map<Expression, Criteria> exprMap, LinkedHashSet<Criteria> newCrits) throws ExpressionEvaluationException {
+ if (converted instanceof IsNullCriteria) {
+ IsNullCriteria inc = (IsNullCriteria)converted;
+ if (!inc.isNegated()) {
+ Criteria crit = exprMap.get(inc.getExpression());
+ if (crit == null) {
+ exprMap.put(inc.getExpression(), converted);
+ } else if (!(crit instanceof IsNullCriteria)) {
+ return FALSE_CRITERIA;
+ }
+ }
+ } else if (converted instanceof SetCriteria) {
+ SetCriteria sc = (SetCriteria)converted;
+ Criteria crit = exprMap.get(sc.getExpression());
+ if (crit instanceof IsNullCriteria) {
+ return FALSE_CRITERIA;
+ }
+ if (!sc.isNegated() && sc.isAllConstants()) {
+ if (crit == null) {
+ exprMap.put(sc.getExpression(), converted);
+ } else if (crit instanceof SetCriteria) {
+ SetCriteria sc1 = (SetCriteria)crit;
+ newCrits.remove(sc1);
+ sc1.getValues().retainAll(sc.getValues());
+ if (sc1.getValues().isEmpty()) {
+ return FALSE_CRITERIA;
+ }
+ //TODO: single value as compare criteria
+ newCrits.add(sc1);
+ exprMap.put(sc1.getExpression(), sc1);
+ return null;
+ } else {
+ CompareCriteria cc = (CompareCriteria)crit;
+ for (Iterator<Constant> exprIter = sc.getValues().iterator(); exprIter.hasNext();) {
+ if (!Evaluator.compare(cc, exprIter.next().getValue(), ((Constant)cc.getRightExpression()).getValue())) {
+ exprIter.remove();
+ }
+ }
+ if (sc.getValues().isEmpty()) {
+ return FALSE_CRITERIA;
+ }
+ if (cc.getOperator() != CompareCriteria.EQ) {
+ newCrits.remove(cc);
+ //TODO: single value as compare criteria
+ exprMap.put(sc.getExpression(), sc);
+ } else {
+ return null;
+ }
+ }
+ }
+ } else if (converted instanceof CompareCriteria) {
+ CompareCriteria cc = (CompareCriteria)converted;
+ Criteria crit = exprMap.get(cc.getLeftExpression());
+ if (crit instanceof IsNullCriteria) {
+ return FALSE_CRITERIA;
+ }
+ if (cc.getRightExpression() instanceof Constant) {
+ if (crit == null) {
+ exprMap.put(cc.getLeftExpression(), cc);
+ } else if (crit instanceof SetCriteria) {
+ SetCriteria sc = (SetCriteria)crit;
+ boolean modified = false;
+ for (Iterator<Constant> exprIter = sc.getValues().iterator(); exprIter.hasNext();) {
+ if (!Evaluator.compare(cc, exprIter.next().getValue(), ((Constant)cc.getRightExpression()).getValue())) {
+ if (!modified) {
+ modified = true;
+ newCrits.remove(sc);
+ }
+ exprIter.remove();
+ }
+ }
+ //TODO: single value as compare criteria
+ if (sc.getValues().isEmpty()) {
+ return FALSE_CRITERIA;
+ }
+ if (cc.getOperator() == CompareCriteria.EQ) {
+ exprMap.put(cc.getLeftExpression(), cc);
+ } else if (modified) {
+ newCrits.add(sc);
+ exprMap.put(sc.getExpression(), sc);
+ return null;
+ }
+ } else {
+ CompareCriteria cc1 = (CompareCriteria)crit;
+ if (cc1.getOperator() == CompareCriteria.NE) {
+ exprMap.put(cc.getLeftExpression(), cc);
+ } else if (cc1.getOperator() == CompareCriteria.EQ) {
+ if (!Evaluator.compare(cc1, ((Constant)cc1.getRightExpression()).getValue(), ((Constant)cc.getRightExpression()).getValue())) {
+ return FALSE_CRITERIA;
+ }
+ return null;
+ }
+ if (cc.getOperator() == CompareCriteria.EQ) {
+ if (!Evaluator.compare(cc1, ((Constant)cc.getRightExpression()).getValue(), ((Constant)cc1.getRightExpression()).getValue())) {
+ return FALSE_CRITERIA;
+ }
+ exprMap.put(cc.getLeftExpression(), cc);
+ newCrits.remove(cc1);
+ }
+ }
+ }
+ }
+ newCrits.add(converted);
+ return null;
+ }
+
+ private Criteria evaluateCriteria(Criteria crit) throws TeiidComponentException, TeiidProcessingException{
+ if(EvaluatableVisitor.isFullyEvaluatable(crit, !processing)) {
+ try {
+ Boolean eval = evaluator.evaluateTVL(crit, Collections.emptyList());
+
+ return getCriteria(eval);
+
+ } catch(ExpressionEvaluationException e) {
+ throw new QueryValidatorException(e, "ERR.015.009.0001", QueryPlugin.Util.getString("ERR.015.009.0001", crit)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ return crit;
+ }
+
+ private Criteria getCriteria(Boolean eval) {
+ if (eval == null) {
+ return UNKNOWN_CRITERIA;
+ }
+
+ if(Boolean.TRUE.equals(eval)) {
+ return TRUE_CRITERIA;
+ }
+
+ return FALSE_CRITERIA;
+ }
+
+ private Criteria rewriteCriteria(NotCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+ Criteria innerCrit = criteria.getCriteria();
+ if (innerCrit instanceof CompoundCriteria) {
+ //reduce to only negation of predicates, so that the null/unknown handling criteria is applied appropriately
+ return rewriteCriteria(Criteria.applyDemorgan(innerCrit));
+ }
+ if (innerCrit instanceof Negatable) {
+ ((Negatable) innerCrit).negate();
+ return rewriteCriteria(innerCrit);
+ }
+ if (innerCrit instanceof NotCriteria) {
+ return rewriteCriteria(((NotCriteria)innerCrit).getCriteria());
+ }
+ innerCrit = rewriteCriteria(innerCrit);
+ if(innerCrit == TRUE_CRITERIA) {
+ return FALSE_CRITERIA;
+ } else if(innerCrit == FALSE_CRITERIA) {
+ return TRUE_CRITERIA;
+ } else if (innerCrit == UNKNOWN_CRITERIA) {
+ return UNKNOWN_CRITERIA;
+ }
+ criteria.setCriteria(innerCrit);
+ return criteria;
+ }
+
+ /**
+ * Rewrites "a [NOT] BETWEEN b AND c" as "a >= b AND a <= c", or as "a <= b OR a>= c"
+ * @param criteria
+ * @return
+ * @throws QueryValidatorException
+ */
+ private Criteria rewriteCriteria(BetweenCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+ CompareCriteria lowerCriteria = new CompareCriteria(criteria.getExpression(),
+ criteria.isNegated() ? CompareCriteria.LT: CompareCriteria.GE,
+ criteria.getLowerExpression());
+ CompareCriteria upperCriteria = new CompareCriteria(criteria.getExpression(),
+ criteria.isNegated() ? CompareCriteria.GT: CompareCriteria.LE,
+ criteria.getUpperExpression());
+ CompoundCriteria newCriteria = new CompoundCriteria(criteria.isNegated() ? CompoundCriteria.OR : CompoundCriteria.AND,
+ lowerCriteria,
+ upperCriteria);
+
+ return rewriteCriteria(newCriteria);
+ }
+
+ private Criteria rewriteCriteria(CompareCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+ Expression leftExpr = rewriteExpressionDirect(criteria.getLeftExpression());
+ Expression rightExpr = rewriteExpressionDirect(criteria.getRightExpression());
+ criteria.setLeftExpression(leftExpr);
+ criteria.setRightExpression(rightExpr);
+
+ if (isNull(leftExpr) || isNull(rightExpr)) {
+ return UNKNOWN_CRITERIA;
+ }
+
+ boolean rightConstant = false;
+ if(EvaluatableVisitor.willBecomeConstant(rightExpr)) {
+ rightConstant = true;
+ } else if (EvaluatableVisitor.willBecomeConstant(leftExpr)) {
+ // Swap in this particular case for connectors
+ criteria.setLeftExpression(rightExpr);
+ criteria.setRightExpression(leftExpr);
+
+ // Check for < or > operator as we have to switch it
+ switch(criteria.getOperator()) {
+ case CompareCriteria.LT: criteria.setOperator(CompareCriteria.GT); break;
+ case CompareCriteria.LE: criteria.setOperator(CompareCriteria.GE); break;
+ case CompareCriteria.GT: criteria.setOperator(CompareCriteria.LT); break;
+ case CompareCriteria.GE: criteria.setOperator(CompareCriteria.LE); break;
+ }
+ rightConstant = true;
+ }
+
+ Function f = null;
+ while (rightConstant && f != criteria.getLeftExpression() && criteria.getLeftExpression() instanceof Function) {
+ f = (Function)criteria.getLeftExpression();
+ Criteria result = simplifyWithInverse(criteria);
+ if (!(result instanceof CompareCriteria)) {
+ return result;
+ }
+ criteria = (CompareCriteria)result;
+ }
+
+ Criteria modCriteria = simplifyTimestampMerge(criteria);
+ if(modCriteria instanceof CompareCriteria) {
+ modCriteria = simplifyTimestampMerge2((CompareCriteria)modCriteria);
+ }
+ return modCriteria;
+ }
+
+ public static boolean isNull(Expression expr) {
+ return expr instanceof Constant && ((Constant)expr).isNull();
+ }
+
+ /*
+ * The thing of primary importance here is that the use of the 'ANY' predicate
+ * quantifier is replaced with the canonical and equivalent 'SOME'
+ */
+ private Criteria rewriteCriteria(SubqueryCompareCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+
+ 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);
+ }
+ 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);
+ }
+ }
+
+ Expression leftExpr = rewriteExpressionDirect(criteria.getLeftExpression());
+
+ if (isNull(leftExpr)) {
+ return UNKNOWN_CRITERIA;
+ }
+
+ criteria.setLeftExpression(leftExpr);
+
+ if (criteria.getPredicateQuantifier() == SubqueryCompareCriteria.ANY){
+ criteria.setPredicateQuantifier(SubqueryCompareCriteria.SOME);
+ }
+
+ rewriteSubqueryContainer(criteria, true);
+
+ if (!RelationalNodeUtil.shouldExecute(criteria.getCommand(), false, true)) {
+ return getSimpliedCriteria(criteria, criteria.getLeftExpression(), criteria.getPredicateQuantifier()==SubqueryCompareCriteria.ALL, true);
+ }
+
+ return criteria;
+ }
+
+ private Criteria simplifyWithInverse(CompareCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+ Expression leftExpr = criteria.getLeftExpression();
+
+ Function leftFunction = (Function) leftExpr;
+ if(isSimpleMathematicalFunction(leftFunction)) {
+ return simplifyMathematicalCriteria(criteria);
+ }
+ if (FunctionLibrary.isConvert(leftFunction)) {
+ return simplifyConvertFunction(criteria);
+ }
+ return simplifyParseFormatFunction(criteria);
+ }
+
+ private boolean isSimpleMathematicalFunction(Function function) {
+ String funcName = function.getName();
+ if(funcName.equals("+") || funcName.equals("-") || funcName.equals("*") || funcName.equals("/")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Expression[] args = function.getArgs();
+ if(args[0] instanceof Constant || args[1] instanceof Constant) {
+ return true;
+ }
+ }
+
+ // fall through - not simple mathematical
+ return false;
+ }
+
+ // Constants used in simplifying mathematical criteria
+ private Integer INTEGER_ZERO = new Integer(0);
+ private Double DOUBLE_ZERO = new Double(0);
+ private Float FLOAT_ZERO = new Float(0);
+ private Long LONG_ZERO = new Long(0);
+ private BigInteger BIG_INTEGER_ZERO = new BigInteger("0"); //$NON-NLS-1$
+ private BigDecimal BIG_DECIMAL_ZERO = new BigDecimal("0"); //$NON-NLS-1$
+ private Short SHORT_ZERO = new Short((short)0);
+ private Byte BYTE_ZERO = new Byte((byte)0);
+
+ /**
+ * @param criteria
+ * @return CompareCriteria
+ */
+ private CompareCriteria simplifyMathematicalCriteria(CompareCriteria criteria)
+ throws TeiidComponentException, TeiidProcessingException{
+
+ Expression leftExpr = criteria.getLeftExpression();
+ Expression rightExpr = criteria.getRightExpression();
+
+ // Identify all the pieces of this criteria
+ Function function = (Function) leftExpr;
+ String funcName = function.getName();
+ Expression[] args = function.getArgs();
+ Constant const1 = null;
+ Expression expr = null;
+ if(args[1] instanceof Constant) {
+ const1 = (Constant) args[1];
+ expr = args[0];
+ } else {
+ if(funcName.equals("+") || funcName.equals("*")) { //$NON-NLS-1$ //$NON-NLS-2$
+ const1 = (Constant) args[0];
+ expr = args[1];
+ } else {
+ // If we have "5 - x = 10" or "5 / x = 10", abort!
+ return criteria;
+ }
+ }
+ int operator = criteria.getOperator();
+
+ // Determine opposite function
+ String oppFunc = null;
+ switch(funcName.charAt(0)) {
+ case '+': oppFunc = "-"; break; //$NON-NLS-1$
+ case '-': oppFunc = "+"; break; //$NON-NLS-1$
+ case '*': oppFunc = "/"; break; //$NON-NLS-1$
+ case '/': oppFunc = "*"; break; //$NON-NLS-1$
+ }
+
+ // Create a function of the two constants and evaluate it
+ Expression combinedConst = null;
+ FunctionLibrary funcLib = this.metadata.getFunctionLibrary();
+ FunctionDescriptor descriptor = funcLib.findFunction(oppFunc, new Class[] { rightExpr.getType(), const1.getType() });
+ if (descriptor == null){
+ //See defect 9380 - this can be caused by const2 being a null Constant, for example (? + 1) < null
+ return criteria;
+ }
+
+
+ if (rightExpr instanceof Constant) {
+ Constant const2 = (Constant)rightExpr;
+ try {
+ Object result = descriptor.invokeFunction(new Object[] { const2.getValue(), const1.getValue() } );
+ combinedConst = new Constant(result, descriptor.getReturnType());
+ } catch(FunctionExecutionException e) {
+ throw new QueryValidatorException(e, "ERR.015.009.0003", QueryPlugin.Util.getString("ERR.015.009.0003", e.getMessage())); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ } else {
+ Function conversion = new Function(descriptor.getName(), new Expression[] { rightExpr, const1 });
+ conversion.setType(leftExpr.getType());
+ conversion.setFunctionDescriptor(descriptor);
+ combinedConst = conversion;
+
+ }
+
+ // Flip operator if necessary
+ if(! (operator == CompareCriteria.EQ || operator == CompareCriteria.NE) &&
+ (oppFunc.equals("*") || oppFunc.equals("/")) ) { //$NON-NLS-1$ //$NON-NLS-2$
+
+ Object value = const1.getValue();
+ if(value != null) {
+ Class type = const1.getType();
+ Comparable comparisonObject = null;
+ if(type.equals(DataTypeManager.DefaultDataClasses.INTEGER)) {
+ comparisonObject = INTEGER_ZERO;
+ } else if(type.equals(DataTypeManager.DefaultDataClasses.DOUBLE)) {
+ comparisonObject = DOUBLE_ZERO;
+ } else if(type.equals(DataTypeManager.DefaultDataClasses.FLOAT)) {
+ comparisonObject = FLOAT_ZERO;
+ } else if(type.equals(DataTypeManager.DefaultDataClasses.LONG)) {
+ comparisonObject = LONG_ZERO;
+ } else if(type.equals(DataTypeManager.DefaultDataClasses.BIG_INTEGER)) {
+ comparisonObject = BIG_INTEGER_ZERO;
+ } else if(type.equals(DataTypeManager.DefaultDataClasses.BIG_DECIMAL)) {
+ comparisonObject = BIG_DECIMAL_ZERO;
+ } else if(type.equals(DataTypeManager.DefaultDataClasses.SHORT)) {
+ comparisonObject = SHORT_ZERO;
+ } else if(type.equals(DataTypeManager.DefaultDataClasses.BYTE)) {
+ comparisonObject = BYTE_ZERO;
+ } else {
+ // Unknown type
+ return criteria;
+ }
+
+ // If value is less than comparison object (which is zero),
+ // then need to switch operator.
+ if(comparisonObject.compareTo(value) > 0) {
+ switch(operator) {
+ case CompareCriteria.LE: operator = CompareCriteria.GE; break;
+ case CompareCriteria.LT: operator = CompareCriteria.GT; break;
+ case CompareCriteria.GE: operator = CompareCriteria.LE; break;
+ case CompareCriteria.GT: operator = CompareCriteria.LT; break;
+ }
+ }
+ }
+ }
+
+ criteria.setLeftExpression(expr);
+ criteria.setRightExpression(combinedConst);
+ criteria.setOperator(operator);
+
+ // Return new simplified criteria
+ return criteria;
+ }
+
+ /**
+ * This method attempts to rewrite compare criteria of the form
+ *
+ * <code>convert(typedColumn, string) = '5'</code>
+ *
+ * into
+ *
+ * <code>typedColumn = convert('5', typeOfColumn)</code>
+ * where 'typeOfColumn' is the type of 'typedColumn'
+ *
+ * if, for example, the type of the column is integer, than the above
+ * can be pre-evaluated to
+ *
+ * <code>typedColumn = 5 </code>
+ *
+ * Right expression has already been checked to be a Constant, left expression to be
+ * a function. Function is known to be "convert" or "cast".
+ *
+ * @param crit CompareCriteria
+ * @return same Criteria instance (possibly optimized)
+ * @throws QueryValidatorException
+ * @since 4.2
+ */
+ private Criteria simplifyConvertFunction(CompareCriteria crit) {
+ Function leftFunction = (Function) crit.getLeftExpression();
+ Expression leftExpr = leftFunction.getArgs()[0];
+
+ if(!(crit.getRightExpression() instanceof Constant)
+ //TODO: this can be relaxed for order preserving operations
+ || !(crit.getOperator() == CompareCriteria.EQ || crit.getOperator() == CompareCriteria.NE)) {
+ return crit;
+ }
+
+ Constant rightConstant = (Constant) crit.getRightExpression();
+
+ String leftExprTypeName = DataTypeManager.getDataTypeName(leftExpr.getType());
+
+ Constant result = ResolverUtil.convertConstant(DataTypeManager.getDataTypeName(rightConstant.getType()), leftExprTypeName, rightConstant);
+ if (result == null) {
+ return getSimpliedCriteria(crit, leftExpr, crit.getOperator() != CompareCriteria.EQ, true);
+ }
+ Constant other = ResolverUtil.convertConstant(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()), result);
+ if (other == null || ((Comparable)rightConstant.getValue()).compareTo(other.getValue()) != 0) {
+ return getSimpliedCriteria(crit, leftExpr, crit.getOperator() != CompareCriteria.EQ, true);
+ }
+
+ if (!DataTypeManager.isImplicitConversion(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()))) {
+ return crit;
+ }
+
+ crit.setRightExpression(result);
+ crit.setLeftExpression(leftExpr);
+
+ return crit;
+ }
+
+
+ /**
+ * This method attempts to rewrite set criteria of the form
+ *
+ * <code>convert(typedColumn, string) in ('5', '6')</code>
+ *
+ * into
+ *
+ * <code>typedColumn in (convert('5', typeOfColumn), convert('6', typeOfColumn)) </code>
+ * where 'typeOfColumn' is the type of 'typedColumn'
+ *
+ * if, for example, the type of the column is integer, than the above
+ * can be pre-evaluated to
+ *
+ * <code>typedColumn in (5,6) </code>
+ *
+ * Right expression has already been checked to be a Constant, left expression to be
+ * a function. Function is known to be "convert" or "cast". The scope of this change
+ * will be limited to the case where the left expression is attempting to convert to
+ * 'string'.
+ *
+ * @param crit CompareCriteria
+ * @return same Criteria instance (possibly optimized)
+ * @throws QueryValidatorException
+ * @since 4.2
+ */
+ private Criteria simplifyConvertFunction(SetCriteria crit) throws TeiidComponentException, TeiidProcessingException{
+ Function leftFunction = (Function) crit.getExpression();
+ Expression leftExpr = leftFunction.getArgs()[0];
+ String leftExprTypeName = DataTypeManager.getDataTypeName(leftExpr.getType());
+
+ Iterator i = crit.getValues().iterator();
+ Collection newValues = new ArrayList(crit.getNumberOfValues());
+
+ boolean convertedAll = true;
+ boolean removedSome = false;
+ while (i.hasNext()) {
+ Object next = i.next();
+ if (!(next instanceof Constant)) {
+ convertedAll = false;
+ continue;
+ }
+
+ Constant rightConstant = (Constant) next;
+
+ Constant result = ResolverUtil.convertConstant(DataTypeManager.getDataTypeName(rightConstant.getType()), leftExprTypeName, rightConstant);
+ if (result != null) {
+ Constant other = ResolverUtil.convertConstant(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()), result);
+ if (other == null || ((Comparable)rightConstant.getValue()).compareTo(other.getValue()) != 0) {
+ result = null;
+ }
+ }
+
+ if (result == null) {
+ removedSome = true;
+ i.remove();
+ } else if (DataTypeManager.isImplicitConversion(leftExprTypeName, DataTypeManager.getDataTypeName(rightConstant.getType()))) {
+ newValues.add(result);
+ } else {
+ convertedAll = false;
+ }
+ }
+
+ if (!convertedAll) {
+ if (!removedSome) {
+ return crit; //just return as is
+ }
+ } else {
+ if (newValues.isEmpty()) {
+ return getSimpliedCriteria(crit, leftExpr, !crit.isNegated(), true);
+ }
+ crit.setExpression(leftExpr);
+ crit.setValues(newValues);
+ }
+ return rewriteCriteria(crit);
+ }
+
+ private Criteria simplifyParseFormatFunction(CompareCriteria crit) {
+ //TODO: this can be relaxed for order preserving operations
+ if(!(crit.getOperator() == CompareCriteria.EQ || crit.getOperator() == CompareCriteria.NE)) {
+ return crit;
+ }
+ boolean isFormat = false;
+ Function leftFunction = (Function) crit.getLeftExpression();
+ String funcName = leftFunction.getName().toLowerCase();
+ String inverseFunction = null;
+ if(funcName.startsWith("parse")) { //$NON-NLS-1$
+ String type = funcName.substring(5);
+ if (!PARSE_FORMAT_TYPES.contains(type)) {
+ return crit;
+ }
+ inverseFunction = "format" + type; //$NON-NLS-1$
+ } else if(funcName.startsWith("format")) { //$NON-NLS-1$
+ String type = funcName.substring(6);
+ if (!PARSE_FORMAT_TYPES.contains(type)) {
+ return crit;
+ }
+ inverseFunction = "parse" + type; //$NON-NLS-1$
+ isFormat = true;
+ } else {
+ return crit;
+ }
+ Expression rightExpr = crit.getRightExpression();
+ if (!(rightExpr instanceof Constant)) {
+ return crit;
+ }
+ Expression leftExpr = leftFunction.getArgs()[0];
+ Expression formatExpr = leftFunction.getArgs()[1];
+ if(!(formatExpr instanceof Constant)) {
+ return crit;
+ }
+ String format = (String)((Constant)formatExpr).getValue();
+ FunctionLibrary funcLib = this.metadata.getFunctionLibrary();
+ FunctionDescriptor descriptor = funcLib.findFunction(inverseFunction, new Class[] { rightExpr.getType(), formatExpr.getType() });
+ if(descriptor == null){
+ return crit;
+ }
+ Object value = ((Constant)rightExpr).getValue();
+ try {
+ Object result = descriptor.invokeFunction(new Object[] {((Constant)rightExpr).getValue(), format});
+ result = leftFunction.getFunctionDescriptor().invokeFunction(new Object[] { result, format } );
+ if (((Comparable)value).compareTo(result) != 0) {
+ return getSimpliedCriteria(crit, leftExpr, crit.getOperator() != CompareCriteria.EQ, true);
+ }
+ } catch(FunctionExecutionException e) {
+ //Not all numeric formats are invertable, so just return the criteria as it may still be valid
+ return crit;
+ }
+ //parseFunctions are all potentially narrowing
+ if (!isFormat) {
+ return crit;
+ }
+ //TODO: if format is not lossy, then invert the function
+ return crit;
+ }
+
+ /**
+ * This method applies a similar simplification as the previous method for Case 1829. This is conceptually
+ * the same thing but done using the timestampCreate system function.
+ *
+ * TIMESTAMPCREATE(rpcolli_physical.RPCOLLI.Table_B.date_field, rpcolli_physical.RPCOLLI.Table_B.time_field)
+ * = {ts'1969-09-20 18:30:45.0'}
+ *
+ * -------------
+ *
+ * rpcolli_physical.RPCOLLI.Table_B.date_field = {d'1969-09-20'}
+ * AND
+ * rpcolli_physical.RPCOLLI.Table_B.time_field = {t'18:30:45'}
+ *
+ *
+ * @param criteria Compare criteria
+ * @return Simplified criteria, if possible
+ */
+ private Criteria simplifyTimestampMerge2(CompareCriteria criteria) {
+ if(criteria.getOperator() != CompareCriteria.EQ) {
+ return criteria;
+ }
+
+ Expression leftExpr = criteria.getLeftExpression();
+ Expression rightExpr = criteria.getRightExpression();
+
+ // Allow for concat and string literal to be on either side
+ Function tsCreateFunction = null;
+ Constant timestampConstant = null;
+ if(leftExpr instanceof Function && rightExpr instanceof Constant) {
+ tsCreateFunction = (Function) leftExpr;
+ timestampConstant = (Constant) rightExpr;
+ } else {
+ return criteria;
+ }
+
+ // Verify data type of constant and that constant has a value
+ if(! timestampConstant.getType().equals(DataTypeManager.DefaultDataClasses.TIMESTAMP)) {
+ return criteria;
+ }
+
+ // Verify function is timestampCreate function
+ if(! (tsCreateFunction.getName().equalsIgnoreCase("timestampCreate"))) { //$NON-NLS-1$
+ return criteria;
+ }
+
+ // Get timestamp literal and break into pieces
+ Timestamp ts = (Timestamp) timestampConstant.getValue();
+ String tsStr = ts.toString();
+ Date date = Date.valueOf(tsStr.substring(0, 10));
+ Time time = Time.valueOf(tsStr.substring(11, 19));
+
+ // Get timestampCreate args
+ Expression[] args = tsCreateFunction.getArgs();
+
+ // Rebuild the function
+ CompareCriteria dateCrit = new CompareCriteria(args[0], CompareCriteria.EQ, new Constant(date, DataTypeManager.DefaultDataClasses.DATE));
+ CompareCriteria timeCrit = new CompareCriteria(args[1], CompareCriteria.EQ, new Constant(time, DataTypeManager.DefaultDataClasses.TIME));
+ CompoundCriteria compCrit = new CompoundCriteria(CompoundCriteria.AND, dateCrit, timeCrit);
+ return compCrit;
+ }
+
+ /**
+ * This method also applies the same simplification for Case 1829. This is conceptually
+ * the same thing but done using the timestampCreate system function.
+ *
+ * formatDate(rpcolli_physical.RPCOLLI.Table_B.date_field, 'yyyy-MM-dd')
+ * || formatTime(rpcolli_physical.RPCOLLI.Table_B.time_field, ' HH:mm:ss') = '1969-09-20 18:30:45'
+ *
+ * -------------
+ *
+ * rpcolli_physical.RPCOLLI.Table_B.date_field = {d'1969-09-20'}
+ * AND
+ * rpcolli_physical.RPCOLLI.Table_B.time_field = {t'18:30:45'}
+ *
+ *
+ * @param criteria Compare criteria
+ * @return Simplified criteria, if possible
+ */
+
+ private Criteria simplifyTimestampMerge(CompareCriteria criteria) {
+ if(criteria.getOperator() != CompareCriteria.EQ) {
+ return criteria;
+ }
+
+ Expression leftExpr = criteria.getLeftExpression();
+ Expression rightExpr = criteria.getRightExpression();
+
+ // Allow for concat and string literal to be on either side
+ Function concatFunction = null;
+ Constant timestampConstant = null;
+ if(leftExpr instanceof Function && rightExpr instanceof Constant) {
+ concatFunction = (Function) leftExpr;
+ timestampConstant = (Constant) rightExpr;
+ } else {
+ return criteria;
+ }
+
+ // Verify data type of string constant and that constant has a value
+ if(! timestampConstant.getType().equals(DataTypeManager.DefaultDataClasses.STRING)) {
+ return criteria;
+ }
+
+ // Verify function is concat function
+ if(! (concatFunction.getName().equalsIgnoreCase("concat") || concatFunction.getName().equals("||"))) { //$NON-NLS-1$ //$NON-NLS-2$
+ return criteria;
+ }
+
+ // Verify concat has formatdate and formattime functions
+ Expression[] args = concatFunction.getArgs();
+ if(! (args[0] instanceof Function && args[1] instanceof Function)) {
+ return criteria;
+ }
+ Function formatDateFunction = (Function) args[0];
+ Function formatTimeFunction = (Function) args[1];
+ if(! (formatDateFunction.getName().equalsIgnoreCase("formatdate") && formatTimeFunction.getName().equalsIgnoreCase("formattime"))) { //$NON-NLS-1$ //$NON-NLS-2$
+ return criteria;
+ }
+
+ // Verify format functions have constants
+ if(! (formatDateFunction.getArgs()[1] instanceof Constant && formatTimeFunction.getArgs()[1] instanceof Constant)) {
+ return criteria;
+ }
+
+ // Verify length of combined date/time constants == timestamp constant
+ String dateFormat = (String) ((Constant)formatDateFunction.getArgs()[1]).getValue();
+ String timeFormat = (String) ((Constant)formatTimeFunction.getArgs()[1]).getValue();
+ String timestampValue = (String) timestampConstant.getValue();
+
+ // Passed all the checks, so build the optimized version
+ try {
+ Timestamp ts = FunctionMethods.parseTimestamp(timestampValue, dateFormat + timeFormat);
+ Constant dateConstant = new Constant(TimestampWithTimezone.createDate(ts));
+ CompareCriteria dateCompare = new CompareCriteria(formatDateFunction.getArgs()[0], CompareCriteria.EQ, dateConstant);
+
+ Constant timeConstant = new Constant(TimestampWithTimezone.createTime(ts));
+ CompareCriteria timeCompare = new CompareCriteria(formatTimeFunction.getArgs()[0], CompareCriteria.EQ, timeConstant);
+
+ CompoundCriteria compCrit = new CompoundCriteria(CompoundCriteria.AND, dateCompare, timeCompare);
+ return compCrit;
+
+ } catch(FunctionExecutionException e) {
+ return criteria;
+ }
+ }
+
+ private Criteria rewriteCriteria(MatchCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+ criteria.setLeftExpression( rewriteExpressionDirect(criteria.getLeftExpression()));
+ criteria.setRightExpression( rewriteExpressionDirect(criteria.getRightExpression()));
+
+ if (isNull(criteria.getLeftExpression()) || isNull(criteria.getRightExpression())) {
+ return UNKNOWN_CRITERIA;
+ }
+
+ Expression rightExpr = criteria.getRightExpression();
+ if(rightExpr instanceof Constant && rightExpr.getType().equals(DataTypeManager.DefaultDataClasses.STRING)) {
+ 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 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;
+ }
+
+ private Criteria getSimpliedCriteria(Criteria crit, Expression a, boolean outcome, boolean nullPossible) {
+ if (nullPossible) {
+ if (outcome) {
+ if (processing) {
+ return crit;
+ }
+ IsNullCriteria inc = new IsNullCriteria(a);
+ inc.setNegated(true);
+ return inc;
+ }
+ } else if (outcome) {
+ return TRUE_CRITERIA;
+ }
+ return FALSE_CRITERIA;
+ }
+
+ private boolean rewriteLeftExpression(AbstractSetCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+ criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
+
+ if (isNull(criteria.getExpression())) {
+ return true;
+ }
+
+ return false;
+ }
+
+ private Criteria rewriteCriteria(SetCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+ if (criteria.isAllConstants() && criteria.getValues().size() > 1) {
+ return criteria;
+ }
+
+ criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
+
+ if (rewriteLeftExpression(criteria)) {
+ return UNKNOWN_CRITERIA;
+ }
+
+ Collection vals = criteria.getValues();
+
+ LinkedHashSet newVals = new LinkedHashSet(vals.size());
+ Iterator valIter = vals.iterator();
+ boolean allConstants = true;
+ boolean hasNull = false;
+ while(valIter.hasNext()) {
+ Expression value = rewriteExpressionDirect( (Expression) valIter.next());
+ if (isNull(value)) {
+ hasNull = true;
+ continue;
+ }
+ allConstants &= value instanceof Constant;
+ newVals.add(value);
+ }
+
+ int size = newVals.size();
+ if (size == 1) {
+ Expression value = (Expression)newVals.iterator().next();
+ return rewriteCriteria(new CompareCriteria(criteria.getExpression(), criteria.isNegated()?CompareCriteria.NE:CompareCriteria.EQ, value));
+ }
+
+ criteria.setValues(newVals);
+ if (allConstants) {
+ criteria.setAllConstants(true);
+ }
+
+ if (size == 0) {
+ if (hasNull) {
+ return UNKNOWN_CRITERIA;
+ }
+ return getSimpliedCriteria(criteria, criteria.getExpression(), !criteria.isNegated(), true);
+ }
+
+ if(criteria.getExpression() instanceof Function ) {
+ Function leftFunction = (Function)criteria.getExpression();
+ if(FunctionLibrary.isConvert(leftFunction)) {
+ return simplifyConvertFunction(criteria);
+ }
+ }
+
+ return criteria;
+ }
+
+ private Criteria rewriteCriteria(IsNullCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
+ criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
+ return criteria;
+ }
+
+ public static Expression rewriteExpression(Expression expression, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException{
+ return new QueryRewriter(metadata, context, procCommand).rewriteExpressionDirect(expression);
+ }
+
+ private Expression rewriteExpressionDirect(Expression expression) throws TeiidComponentException, TeiidProcessingException{
+ if (expression instanceof Constant) {
+ return expression;
+ }
+ if (expression instanceof ElementSymbol) {
+ ElementSymbol es = (ElementSymbol)expression;
+ Class<?> type = es.getType();
+ if (!processing && es.isExternalReference()) {
+ if (variables == null) {
+ return new Reference(es);
+ }
+ Expression value = variables.get(es);
+
+ if (value == null) {
+ if (es.getGroupSymbol().getSchema() == null) {
+ String grpName = es.getGroupSymbol().getShortCanonicalName();
+ if (grpName.equals(ProcedureReservedWords.INPUTS)) {
+ return new Constant(null, es.getType());
+ }
+ if (grpName.equals(ProcedureReservedWords.CHANGING)) {
+ Assertion.failed("Changing value should not be null"); //$NON-NLS-1$
+ }
+ }
+ } else if (value instanceof Constant) {
+ if (value.getType() == type) {
+ return value;
+ }
+ try {
+ return new Constant(FunctionMethods.convert(((Constant)value).getValue(), DataTypeManager.getDataTypeName(type)), es.getType());
+ } catch (FunctionExecutionException e) {
+ throw new QueryValidatorException(e, e.getMessage());
+ }
+ }
+ return new Reference(es);
+ }
+ return expression;
+ }
+ boolean isBindEligible = true;
+ if(expression instanceof Function) {
+ isBindEligible = !isConstantConvert(expression);
+ expression = rewriteFunction((Function) expression);
+ } else if (expression instanceof CaseExpression) {
+ expression = rewriteCaseExpression((CaseExpression)expression);
+ } else if (expression instanceof SearchedCaseExpression) {
+ expression = rewriteCaseExpression((SearchedCaseExpression)expression);
+ } else if (expression instanceof ScalarSubquery) {
+ ScalarSubquery subquery = (ScalarSubquery)expression;
+ if (subquery.shouldEvaluate() && processing) {
+ return new Constant(evaluator.evaluate(subquery, null), subquery.getType());
+ }
+ rewriteSubqueryContainer(subquery, true);
+ if (!RelationalNodeUtil.shouldExecute(subquery.getCommand(), false, true)) {
+ return new Constant(null, subquery.getType());
+ }
+ if (subquery.getCommand().getProcessorPlan() == null) {
+ addImplicitLimit(subquery, 2);
+ }
+ return expression;
+ } else if (expression instanceof ExpressionSymbol) {
+ if (expression instanceof AggregateSymbol) {
+ expression = rewriteExpression((AggregateSymbol)expression);
+ } else {
+ expression = rewriteExpressionDirect(((ExpressionSymbol)expression).getExpression());
+ }
+ } else if (expression instanceof Criteria) {
+ expression = rewriteCriteria((Criteria)expression);
+ } else {
+ rewriteExpressions(expression);
+ }
+
+ if(!processing) {
+ if (!EvaluatableVisitor.isFullyEvaluatable(expression, true)) {
+ return expression;
+ }
+ } else if (!(expression instanceof Reference) && !EvaluatableVisitor.isEvaluatable(expression, EvaluationLevel.PROCESSING)) {
+ return expression;
+ }
+
+ return evaluate(expression, isBindEligible);
+ }
+
+ private Constant evaluate(Expression expression, boolean isBindEligible)
+ throws ExpressionEvaluationException, BlockedException,
+ TeiidComponentException {
+ Object value = evaluator.evaluate(expression, Collections.emptyList());
+ if (value instanceof Constant) {
+ return (Constant)value; //multi valued substitution
+ }
+ Constant result = new Constant(value, expression.getType());
+ result.setBindEligible(isBindEligible);
+ return result;
+ }
+
+ private boolean isConstantConvert(Expression ex) {
+ if (ex instanceof Constant) {
+ return true;
+ }
+ if (!(ex instanceof Function)) {
+ return false;
+ }
+ Function f = (Function)ex;
+ if (!FunctionLibrary.isConvert(f)) {
+ return false;
+ }
+ return isConstantConvert(f.getArg(0));
+ }
+
+ private Expression rewriteExpression(AggregateSymbol expression) {
+ if (expression.isBoolean()) {
+ if (expression.getAggregateFunction() == Type.EVERY) {
+ expression.setAggregateFunction(Type.MIN);
+ } else {
+ 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);
+ }
+ }
+ return expression;
+ }
+
+ private static Map<String, Integer> FUNCTION_MAP = new HashMap<String, Integer>();
+
+ static {
+ FUNCTION_MAP.put(FunctionLibrary.SPACE.toLowerCase(), 0);
+ FUNCTION_MAP.put(FunctionLibrary.FROM_UNIXTIME.toLowerCase(), 1);
+ FUNCTION_MAP.put(FunctionLibrary.NULLIF.toLowerCase(), 2);
+ FUNCTION_MAP.put(FunctionLibrary.COALESCE.toLowerCase(), 3);
+ FUNCTION_MAP.put(FunctionLibrary.CONCAT2.toLowerCase(), 4);
+ FUNCTION_MAP.put(FunctionLibrary.TIMESTAMPADD.toLowerCase(), 5);
+ FUNCTION_MAP.put(FunctionLibrary.PARSEDATE.toLowerCase(), 6);
+ FUNCTION_MAP.put(FunctionLibrary.PARSETIME.toLowerCase(), 7);
+ FUNCTION_MAP.put(FunctionLibrary.FORMATDATE.toLowerCase(), 8);
+ FUNCTION_MAP.put(FunctionLibrary.FORMATTIME.toLowerCase(), 9);
+ }
+
+ private Expression rewriteFunction(Function function) throws TeiidComponentException, TeiidProcessingException{
+ //rewrite alias functions
+ String functionLowerName = function.getName().toLowerCase();
+ String actualName =ALIASED_FUNCTIONS.get(functionLowerName);
+ FunctionLibrary funcLibrary = this.metadata.getFunctionLibrary();
+
+ if (actualName != null) {
+ function.setName(actualName);
+ Expression[] args = function.getArgs();
+ Class<?>[] types = new Class[args.length];
+ for(int i=0; i<args.length; i++) {
+ types[i] = args[i].getType();
+ }
+ FunctionDescriptor descriptor = funcLibrary.findFunction(actualName, types);
+ function.setFunctionDescriptor(descriptor);
+ }
+
+ Integer code = FUNCTION_MAP.get(functionLowerName);
+ if (code != null) {
+ switch (code) {
+ case 0: { //space(x) => repeat(' ', x)
+ Function result = new Function(SourceSystemFunctions.REPEAT,
+ new Expression[] {new Constant(" "), function.getArg(0)}); //$NON-NLS-1$
+ //resolve the function
+ FunctionDescriptor descriptor =
+ funcLibrary.findFunction(SourceSystemFunctions.REPEAT, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER});
+ result.setFunctionDescriptor(descriptor);
+ result.setType(DataTypeManager.DefaultDataClasses.STRING);
+ function = result;
+ break;
+ }
+ case 1: {//from_unixtime(a) => timestampadd(SQL_TSI_SECOND, a, new Timestamp(0))
+ Function result = new Function(FunctionLibrary.TIMESTAMPADD,
+ new Expression[] {new Constant(NonReserved.SQL_TSI_SECOND), function.getArg(0), new Constant(new Timestamp(0)) });
+ //resolve the function
+ FunctionDescriptor descriptor =
+ funcLibrary.findFunction(FunctionLibrary.TIMESTAMPADD, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER, DataTypeManager.DefaultDataClasses.TIMESTAMP });
+ result.setFunctionDescriptor(descriptor);
+ result.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
+ function = result;
+ break;
+ }
+ case 2: { //rewrite nullif(a, b) => case when (a = b) then null else a
+ List when = Arrays.asList(new Criteria[] {new CompareCriteria(function.getArg(0), CompareCriteria.EQ, function.getArg(1))});
+ Constant nullConstant = new Constant(null, function.getType());
+ List then = Arrays.asList(new Expression[] {nullConstant});
+ SearchedCaseExpression caseExpr = new SearchedCaseExpression(when, then);
+ caseExpr.setElseExpression(function.getArg(0));
+ caseExpr.setType(function.getType());
+ return rewriteExpressionDirect(caseExpr);
+ }
+ case 3: {
+ Expression[] args = function.getArgs();
+ if (args.length == 2) {
+ Function result = new Function(SourceSystemFunctions.IFNULL,
+ new Expression[] {function.getArg(0), function.getArg(1) });
+ //resolve the function
+ FunctionDescriptor descriptor =
+ funcLibrary.findFunction(SourceSystemFunctions.IFNULL, new Class[] { function.getType(), function.getType() });
+ result.setFunctionDescriptor(descriptor);
+ result.setType(function.getType());
+ function = result;
+ }
+ break;
+ }
+ case 4: { //rewrite concat2 - CONCAT2(a, b) ==> CASE WHEN (a is NULL AND b is NULL) THEN NULL ELSE CONCAT( NVL(a, ''), NVL(b, '') )
+ Expression[] args = function.getArgs();
+ Function[] newArgs = new Function[args.length];
+
+ for(int i=0; i<args.length; i++) {
+ newArgs[i] = new Function(SourceSystemFunctions.IFNULL, new Expression[] {args[i], new Constant("")}); //$NON-NLS-1$
+ newArgs[i].setType(args[i].getType());
+ Assertion.assertTrue(args[i].getType() == DataTypeManager.DefaultDataClasses.STRING);
+ FunctionDescriptor descriptor =
+ funcLibrary.findFunction(SourceSystemFunctions.IFNULL, new Class[] { args[i].getType(), DataTypeManager.DefaultDataClasses.STRING });
+ newArgs[i].setFunctionDescriptor(descriptor);
+ }
+
+ Function concat = new Function(SourceSystemFunctions.CONCAT, newArgs);
+ concat.setType(DataTypeManager.DefaultDataClasses.STRING);
+ FunctionDescriptor descriptor =
+ funcLibrary.findFunction(SourceSystemFunctions.CONCAT, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING });
+ concat.setFunctionDescriptor(descriptor);
+
+ List when = Arrays.asList(new Criteria[] {new CompoundCriteria(CompoundCriteria.AND, new IsNullCriteria(args[0]), new IsNullCriteria(args[1]))});
+ Constant nullConstant = new Constant(null, DataTypeManager.DefaultDataClasses.STRING);
+ List then = Arrays.asList(new Expression[] {nullConstant});
+ SearchedCaseExpression caseExpr = new SearchedCaseExpression(when, then);
+ caseExpr.setElseExpression(concat);
+ caseExpr.setType(DataTypeManager.DefaultDataClasses.STRING);
+ return rewriteExpressionDirect(caseExpr);
+ }
+ case 5: {
+ if (function.getType() != DataTypeManager.DefaultDataClasses.TIMESTAMP) {
+ FunctionDescriptor descriptor =
+ funcLibrary.findFunction(SourceSystemFunctions.TIMESTAMPADD, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER, DataTypeManager.DefaultDataClasses.TIMESTAMP });
+ function.setFunctionDescriptor(descriptor);
+ Class<?> type = function.getType();
+ function.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
+ function.getArgs()[2] = ResolverUtil.getConversion(function.getArg(2), DataTypeManager.getDataTypeName(type), DataTypeManager.DefaultDataTypes.TIMESTAMP, false, funcLibrary);
+ function = ResolverUtil.getConversion(function, DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.getDataTypeName(type), false, funcLibrary);
+ }
+ break;
+ }
+ case 6:
+ case 7: {
+ FunctionDescriptor descriptor =
+ funcLibrary.findFunction(SourceSystemFunctions.PARSETIMESTAMP, new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING });
+ function.setName(SourceSystemFunctions.PARSETIMESTAMP);
+ function.setFunctionDescriptor(descriptor);
+ Class<?> type = function.getType();
+ function.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
+ function = ResolverUtil.getConversion(function, DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.getDataTypeName(type), false, funcLibrary);
+ break;
+ }
+ case 8:
+ case 9: {
+ FunctionDescriptor descriptor =
+ funcLibrary.findFunction(SourceSystemFunctions.FORMATTIMESTAMP, new Class[] { DataTypeManager.DefaultDataClasses.TIMESTAMP, DataTypeManager.DefaultDataClasses.STRING });
+ function.setName(SourceSystemFunctions.FORMATTIMESTAMP);
+ function.setFunctionDescriptor(descriptor);
+ function.getArgs()[0] = ResolverUtil.getConversion(function.getArg(0), DataTypeManager.getDataTypeName(function.getArg(0).getType()), DataTypeManager.DefaultDataTypes.TIMESTAMP, false, funcLibrary);
+ break;
+ }
+ }
+ }
+
+ Expression[] args = function.getArgs();
+ Expression[] newArgs = new Expression[args.length];
+
+ // Rewrite args
+ for(int i=0; i<args.length; i++) {
+ newArgs[i] = rewriteExpressionDirect(args[i]);
+ if (isNull(newArgs[i]) && !function.getFunctionDescriptor().isNullDependent()) {
+ return new Constant(null, function.getType());
+ }
+ }
+ 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(srcType != null && tgtType != null && srcType.equals(tgtType)) {
+ return newArgs[0];
+ }
+
+ }
+
+ //convert DECODESTRING function to CASE expression
+ if( function.getName().equalsIgnoreCase(FunctionLibrary.DECODESTRING)
+ || function.getName().equalsIgnoreCase(FunctionLibrary.DECODEINTEGER)) {
+ return convertDecodeFunction(function);
+ }
+
+ return function;
+ }
+
+ private Expression convertDecodeFunction(Function function){
+ Expression exprs[] = function.getArgs();
+ String decodeString = (String)((Constant)exprs[1]).getValue();
+ String decodeDelimiter = ","; //$NON-NLS-1$
+ if(exprs.length == 3){
+ decodeDelimiter = (String)((Constant)exprs[2]).getValue();
+ }
+ List<Criteria> newWhens = new ArrayList<Criteria>();
+ List<Constant> newThens = new ArrayList<Constant>();
+ Constant elseConst = null;
+ StringTokenizer tokenizer = new StringTokenizer(decodeString, decodeDelimiter);
+ while (tokenizer.hasMoreTokens()) {
+ String resultString;
+ String compareString =
+ convertString(tokenizer.nextToken().trim());
+ if (tokenizer.hasMoreTokens()) {
+ resultString = convertString(tokenizer.nextToken().trim());
+ Criteria crit;
+ if (compareString == null) {
+ crit = new IsNullCriteria((Expression) exprs[0].clone());
+ } else {
+ crit = new CompareCriteria((Expression) exprs[0].clone(), CompareCriteria.EQ, new Constant(compareString));
+ }
+ newWhens.add(crit);
+ newThens.add(new Constant(resultString));
+ }else {
+ elseConst = new Constant(compareString);
+ }
+ }
+ SearchedCaseExpression newCaseExpr = new SearchedCaseExpression(newWhens, newThens);
+ if(elseConst != null) {
+ newCaseExpr.setElseExpression(elseConst);
+ }else {
+ newCaseExpr.setElseExpression(exprs[0]);
+ }
+
+ newCaseExpr.setType(function.getType());
+ return newCaseExpr;
+ }
+
+ private static String convertString(String string) {
+ /*
+ * if there are no characters in the compare string we designate that as
+ * an indication of null. ie if the decode string looks like this:
+ *
+ * "'this', 1,,'null'"
+ *
+ * Then if the value in the first argument is null then the String 'null' is
+ * returned from the function.
+ */
+ if (string.equals("")) { //$NON-NLS-1$
+ return null;
+ }
+
+ /*
+ * we also allow the use of the keyword null in the decode string. if it
+ * wished to match on the string 'null' then the string must be qualified by
+ * ' designators.
+ */
+ if(string.equalsIgnoreCase("null")){ //$NON-NLS-1$
+ return null;
+ }
+
+ /*
+ * Here we check to see if the String in the decode String submitted
+ * was surrounded by String literal characters. In this case we strip
+ * these literal characters from the String.
+ */
+ if ((string.startsWith("\"") && string.endsWith("\"")) //$NON-NLS-1$ //$NON-NLS-2$
+ || (string.startsWith("'") && string.endsWith("'"))) { //$NON-NLS-1$ //$NON-NLS-2$
+ if (string.length() == 2) {
+ /*
+ * This is an indication that the desired string to be compared is
+ * the "" empty string, so we return it as such.
+ */
+ string = ""; //$NON-NLS-1$
+ } else if (!string.equalsIgnoreCase("'") && !string.equalsIgnoreCase("\"")){ //$NON-NLS-1$ //$NON-NLS-2$
+ string = string.substring(1);
+ string = string.substring(0, string.length()-1);
+ }
+ }
+
+ return string;
+ }
+
+ private Expression rewriteCaseExpression(CaseExpression expr)
+ throws TeiidComponentException, TeiidProcessingException{
+ List<CompareCriteria> whens = new ArrayList<CompareCriteria>(expr.getWhenCount());
+ for (Expression expression: (List<Expression>)expr.getWhen()) {
+ whens.add(new CompareCriteria((Expression)expr.getExpression().clone(), CompareCriteria.EQ, expression));
+ }
+ SearchedCaseExpression sce = new SearchedCaseExpression(whens, expr.getThen());
+ sce.setElseExpression(expr.getElseExpression());
+ sce.setType(expr.getType());
+ return rewriteCaseExpression(sce);
+ }
+
+ private Expression rewriteCaseExpression(SearchedCaseExpression expr)
+ throws TeiidComponentException, TeiidProcessingException{
+ int whenCount = expr.getWhenCount();
+ ArrayList<Criteria> whens = new ArrayList<Criteria>(whenCount);
+ ArrayList<Expression> thens = new ArrayList<Expression>(whenCount);
+
+ for (int i = 0; i < whenCount; i++) {
+
+ // Check the when to see if this CASE can be rewritten due to an always true/false when
+ Criteria rewrittenWhen = rewriteCriteria(expr.getWhenCriteria(i));
+ if(rewrittenWhen == TRUE_CRITERIA) {
+ // WHEN is always true, so just return the THEN
+ return rewriteExpressionDirect(expr.getThenExpression(i));
+ }
+ if (rewrittenWhen == FALSE_CRITERIA || rewrittenWhen == UNKNOWN_CRITERIA) {
+ continue;
+ }
+
+ whens.add(rewrittenWhen);
+ thens.add(rewriteExpressionDirect(expr.getThenExpression(i)));
+ }
+
+ if (expr.getElseExpression() != null) {
+ expr.setElseExpression(rewriteExpressionDirect(expr.getElseExpression()));
+ }
+
+ Expression elseExpr = expr.getElseExpression();
+ if(whens.size() == 0) {
+ // No WHENs left, so just return the ELSE
+ if(elseExpr == null) {
+ // No else, no valid whens, just return null constant typed same as CASE
+ return new Constant(null, expr.getType());
+ }
+
+ // Rewrite the else and return
+ return elseExpr;
+ }
+
+ expr.setWhen(whens, thens);
+
+ /* optimization for case 5413:
+ * If all of the remaining 'thens' and the 'else' evaluate to the same value,
+ * just return the 'else' expression.
+ */
+
+ if ( elseExpr != null ) {
+ boolean bAllMatch = true;
+
+ for (int i = 0; i < whenCount; i++) {
+ if ( !thens.get( i ).equals(elseExpr) ) {
+ bAllMatch = false;
+ break;
+ }
+ }
+
+ if ( bAllMatch ) {
+ return elseExpr;
+ }
+ }
+
+ return expr;
+ }
+
+ private Command rewriteExec(StoredProcedure storedProcedure) throws TeiidComponentException, TeiidProcessingException{
+ //After this method, no longer need to display named parameters
+ storedProcedure.setDisplayNamedParameters(false);
+
+ for (SPParameter param : storedProcedure.getInputParameters()) {
+ if (!processing) {
+ param.setExpression(rewriteExpressionDirect(param.getExpression()));
+ } else if (!(param.getExpression() instanceof Constant)) {
+ boolean isBindEligible = !isConstantConvert(param.getExpression());
+ param.setExpression(evaluate(param.getExpression(), isBindEligible));
+ }
+ }
+ return storedProcedure;
+ }
+
+ private Insert rewriteInsert(Insert insert) throws TeiidComponentException, TeiidProcessingException{
+ UpdateInfo info = insert.getUpdateInfo();
+ if (info != null && info.isInherentInsert()) {
+ //TODO: update error messages
+ UpdateMapping mapping = info.findInsertUpdateMapping(insert, true);
+ if (mapping == null) {
+ throw new QueryValidatorException(QueryPlugin.Util.getString("ValidationVisitor.nonUpdatable", insert.getVariables())); //$NON-NLS-1$
+ }
+ Map<ElementSymbol, ElementSymbol> symbolMap = mapping.getUpdatableViewSymbols();
+ List<ElementSymbol> mappedSymbols = new ArrayList<ElementSymbol>(insert.getVariables().size());
+ for (ElementSymbol symbol : insert.getVariables()) {
+ mappedSymbols.add(symbolMap.get(symbol));
+ }
+ insert.setVariables(mappedSymbols);
+ insert.setGroup(mapping.getGroup().clone());
+ insert.setUpdateInfo(ProcedureContainerResolver.getUpdateInfo(insert.getGroup(), metadata, Command.TYPE_INSERT));
+ return rewriteInsert(insert);
+ }
+
+ if ( insert.getQueryExpression() != null ) {
+ insert.setQueryExpression((QueryCommand)rewriteCommand(insert.getQueryExpression(), true));
+ return correctDatatypes(insert);
+ }
+ // Evaluate any function / constant trees in the insert values
+ List expressions = insert.getValues();
+ List evalExpressions = new ArrayList(expressions.size());
+ Iterator expIter = expressions.iterator();
+ while(expIter.hasNext()) {
+ Expression exp = (Expression) expIter.next();
+ evalExpressions.add( rewriteExpressionDirect( exp ));
+ }
+
+ insert.setValues(evalExpressions);
+ return insert;
+ }
+
+ public static Query createInlineViewQuery(GroupSymbol inlineGroup,
+ Command nested,
+ QueryMetadataInterface metadata,
+ List<? extends SingleElementSymbol> actualSymbols) throws QueryMetadataException,
+ QueryResolverException,
+ TeiidComponentException {
+ Query query = new Query();
+ Select select = new Select();
+ query.setSelect(select);
+ From from = new From();
+ from.addClause(new UnaryFromClause(inlineGroup));
+ TempMetadataStore store = new TempMetadataStore();
+ TempMetadataAdapter tma = new TempMetadataAdapter(metadata, store);
+ if (nested instanceof QueryCommand) {
+ Query firstProject = ((QueryCommand)nested).getProjectedQuery();
+ makeSelectUnique(firstProject.getSelect(), false);
+ }
+ TempMetadataID gid = store.addTempGroup(inlineGroup.getName(), nested.getProjectedSymbols());
+ inlineGroup.setMetadataID(gid);
+
+ List<Class<?>> actualTypes = new ArrayList<Class<?>>(nested.getProjectedSymbols().size());
+ for (SingleElementSymbol ses : actualSymbols) {
+ actualTypes.add(ses.getType());
+ }
+ List<SingleElementSymbol> selectSymbols = SetQuery.getTypedProjectedSymbols(ResolverUtil.resolveElementsInGroup(inlineGroup, tma), actualTypes, tma);
+ Iterator<? extends SingleElementSymbol> iter = actualSymbols.iterator();
+ for (SingleElementSymbol ses : selectSymbols) {
+ ses = (SingleElementSymbol)ses.clone();
+ SingleElementSymbol actual = iter.next();
+ if (!ses.getShortCanonicalName().equals(actual.getShortCanonicalName())) {
+ if (ses instanceof AliasSymbol) {
+ ((AliasSymbol)ses).setShortName(actual.getShortName());
+ } else {
+ ses = new AliasSymbol(actual.getShortName(), ses);
+ }
+ }
+ select.addSymbol(ses);
+ }
+ query.setFrom(from);
+ QueryResolver.resolveCommand(query, tma);
+ query.setOption(nested.getOption());
+ from.getClauses().clear();
+ SubqueryFromClause sqfc = new SubqueryFromClause(inlineGroup.getName());
+ sqfc.setCommand(nested);
+ sqfc.getGroupSymbol().setMetadataID(inlineGroup.getMetadataID());
+ from.addClause(sqfc);
+ //copy the metadata onto the new query so that temp metadata adapters will be used in later calls
+ query.getTemporaryMetadata().putAll(store.getData());
+ return query;
+ }
+
+ public static void makeSelectUnique(Select select, boolean expressionSymbolsOnly) {
+
+ select.setSymbols(select.getProjectedSymbols());
+
+ List symbols = select.getSymbols();
+
+ HashSet<String> uniqueNames = new HashSet<String>();
+
+ for(int i = 0; i < symbols.size(); i++) {
+
+ SingleElementSymbol symbol = (SingleElementSymbol)symbols.get(i);
+
+ String baseName = symbol.getShortCanonicalName();
+ String name = baseName;
+
+ int exprID = 0;
+ while (true) {
+ if (uniqueNames.add(name)) {
+ break;
+ }
+ name = baseName + '_' + (exprID++);
+ }
+
+ if (expressionSymbolsOnly && !(symbol instanceof ExpressionSymbol)) {
+ continue;
+ }
+
+ boolean hasAlias = false;
+ // Strip alias if it exists
+ if(symbol instanceof AliasSymbol) {
+ symbol = ((AliasSymbol)symbol).getSymbol();
+ hasAlias = true;
+ }
+
+ if (((symbol instanceof ExpressionSymbol) && !hasAlias) || !name.equalsIgnoreCase(baseName)) {
+ symbols.set(i, new AliasSymbol(name, symbol));
+ }
+ }
+ }
+
+ private Command rewriteUpdate(Update update) throws TeiidComponentException, TeiidProcessingException{
+ UpdateInfo info = update.getUpdateInfo();
+ if (info != null && info.isInherentUpdate()) {
+ if (!info.getUnionBranches().isEmpty()) {
+ List<Command> batchedUpdates = new ArrayList<Command>(info.getUnionBranches().size() + 1);
+ for (UpdateInfo branchInfo : info.getUnionBranches()) {
+ batchedUpdates.add(rewriteInherentUpdate((Update)update.clone(), branchInfo));
+ }
+ batchedUpdates.add(0, rewriteInherentUpdate(update, info));
+ return new BatchedUpdateCommand(batchedUpdates);
+ }
+ return rewriteInherentUpdate(update, info);
+ }
+
+ if (commandType == Command.TYPE_UPDATE && variables != null) {
+ SetClauseList newChangeList = new SetClauseList();
+ for (SetClause entry : update.getChangeList().getClauses()) {
+ Expression rightExpr = entry.getValue();
+ boolean retainChange = checkInputVariables(rightExpr);
+ if (retainChange) {
+ newChangeList.addClause(entry.getSymbol(), entry.getValue());
+ }
+ }
+ update.setChangeList(newChangeList);
+ }
+
+ // Evaluate any function on the right side of set clauses
+ for (SetClause entry : update.getChangeList().getClauses()) {
+ entry.setValue(rewriteExpressionDirect(entry.getValue()));
+ }
+
+ // Rewrite criteria
+ Criteria crit = update.getCriteria();
+ if(crit != null) {
+ update.setCriteria(rewriteCriteria(crit));
+ }
+
+ return update;
+ }
+
+ private Command rewriteInherentUpdate(Update update, UpdateInfo info)
+ throws QueryValidatorException, QueryMetadataException,
+ TeiidComponentException, QueryResolverException,
+ TeiidProcessingException {
+ UpdateMapping mapping = info.findUpdateMapping(update.getChangeList().getClauseMap().keySet(), false);
+ if (mapping == null) {
+ throw new QueryValidatorException(QueryPlugin.Util.getString("ValidationVisitor.nonUpdatable", update.getChangeList().getClauseMap().keySet())); //$NON-NLS-1$
+ }
+ Map<ElementSymbol, ElementSymbol> symbolMap = mapping.getUpdatableViewSymbols();
+ if (info.isSimple()) {
+ update.setGroup(mapping.getGroup().clone());
+ for (SetClause clause : update.getChangeList().getClauses()) {
+ clause.setSymbol(symbolMap.get(clause.getSymbol()));
+ }
+ //TODO: properly handle correlated references
+ DeepPostOrderNavigator.doVisit(update, new ExpressionMappingVisitor(symbolMap, true));
+ if (info.getViewDefinition().getCriteria() != null) {
+ update.setCriteria(Criteria.combineCriteria(update.getCriteria(), (Criteria)info.getViewDefinition().getCriteria().clone()));
+ }
+ //resolve
+ update.setUpdateInfo(ProcedureContainerResolver.getUpdateInfo(update.getGroup(), metadata, Command.TYPE_UPDATE));
+ return rewriteUpdate(update);
+ }
+ Query query = (Query)info.getViewDefinition().clone();
+ query.setOrderBy(null);
+ SymbolMap expressionMapping = SymbolMap.createSymbolMap(update.getGroup(), query.getProjectedSymbols(), metadata);
+
+ ArrayList<SingleElementSymbol> selectSymbols = mapChangeList(update, symbolMap);
+ query.setSelect(new Select(selectSymbols));
+ ExpressionMappingVisitor emv = new ExpressionMappingVisitor(expressionMapping.asMap(), true);
+ PostOrderNavigator.doVisit(query.getSelect(), emv);
+
+ Criteria crit = update.getCriteria();
+ if (crit != null) {
+ PostOrderNavigator.doVisit(crit, emv);
+ query.setCriteria(Criteria.combineCriteria(query.getCriteria(), crit));
+ }
+ GroupSymbol group = mapping.getGroup();
+ String correlationName = mapping.getCorrelatedName().getName();
+
+ return createUpdateProcedure(update, query, group, correlationName);
+ }
+
+ private ArrayList<SingleElementSymbol> mapChangeList(Update update,
+ Map<ElementSymbol, ElementSymbol> symbolMap) {
+ ArrayList<SingleElementSymbol> selectSymbols = new ArrayList<SingleElementSymbol>(update.getChangeList().getClauses().size());
+ int i = 0;
+ for (SetClause clause : update.getChangeList().getClauses()) {
+ Expression ex = clause.getValue();
+ SingleElementSymbol selectSymbol = null;
+ if (!EvaluatableVisitor.willBecomeConstant(ex)) {
+ if (!(ex instanceof SingleElementSymbol)) {
+ selectSymbol = new ExpressionSymbol("expr", ex); //$NON-NLS-1$
+ } else {
+ selectSymbol = (SingleElementSymbol)ex;
+ }
+ selectSymbols.add(new AliasSymbol("s_" +i, selectSymbol)); //$NON-NLS-1$
+ ex = new ElementSymbol("s_" +i); //$NON-NLS-1$
+ }
+ if (symbolMap != null) {
+ clause.setSymbol(symbolMap.get(clause.getSymbol()));
+ }
+ i++;
+ }
+ return selectSymbols;
+ }
+
+ private Command createUpdateProcedure(Update update, Query query,
+ GroupSymbol group, String correlationName)
+ throws TeiidComponentException, QueryMetadataException,
+ QueryResolverException, TeiidProcessingException {
+ Update newUpdate = new Update();
+ newUpdate.setChangeList(update.getChangeList());
+ newUpdate.setGroup(group.clone());
+ List<Criteria> pkCriteria = createPkCriteria(group, correlationName, query);
+ newUpdate.setCriteria(new CompoundCriteria(pkCriteria));
+ return asLoopProcedure(update.getGroup(), query, newUpdate);
+ }
+
+ /**
+ * rewrite as loop on (query) as X begin newupdate; rows_updated = rows_updated + 1;
+ */
+ private Command asLoopProcedure(GroupSymbol group, Query query,
+ ProcedureContainer newUpdate) throws QueryResolverException,
+ TeiidComponentException, TeiidProcessingException {
+ Block b = new Block();
+ b.addStatement(new CommandStatement(newUpdate));
+ CreateUpdateProcedureCommand cupc = new CreateUpdateProcedureCommand();
+ Block parent = new Block();
+ LoopStatement ls = new LoopStatement(b, query, "X"); //$NON-NLS-1$
+ parent.addStatement(ls);
+ AssignmentStatement as = new AssignmentStatement();
+ ElementSymbol rowsUpdate = new ElementSymbol(ProcedureReservedWords.VARIABLES+ElementSymbol.SEPARATOR+ProcedureReservedWords.ROWS_UPDATED);
+ as.setVariable(rowsUpdate);
+ as.setExpression(new Function("+", new Expression[] {rowsUpdate, new Constant(1)})); //$NON-NLS-1$
+ b.addStatement(as);
+ cupc.setBlock(parent);
+ cupc.setVirtualGroup(group);
+ QueryResolver.resolveCommand(cupc, metadata);
+ return rewrite(cupc, metadata, context);
+ }
+
+ private List<Criteria> createPkCriteria(GroupSymbol group, String correlationName, Query query) throws TeiidComponentException, QueryMetadataException {
+ Object pk = metadata.getPrimaryKey(group.getMetadataID());
+ if (pk == null) {
+ pk = metadata.getUniqueKeysInGroup(group.getMetadataID()).iterator().next();
+ }
+ int i = query.getSelect().getSymbols().size();
+ List<Object> ids = metadata.getElementIDsInKey(pk);
+ List<Criteria> pkCriteria = new ArrayList<Criteria>(ids.size());
+ for (Object object : ids) {
+ ElementSymbol es = new ElementSymbol(correlationName + ElementSymbol.SEPARATOR + metadata.getName(object));
+ query.getSelect().addSymbol(new AliasSymbol("s_" +i, es)); //$NON-NLS-1$
+ es = new ElementSymbol(group.getName() + ElementSymbol.SEPARATOR + metadata.getName(object));
+ pkCriteria.add(new CompareCriteria(es, CompareCriteria.EQ, new ElementSymbol("X.s_" + i))); //$NON-NLS-1$
+ i++;
+ }
+ return pkCriteria;
+ }
+
+ /**
+ * Checks variables in an expression, if the variables are INPUT variables and if
+ * none of them are changing, then this method returns a false, if all of them
+ * are changing this returns a true, if some are changing and some are not, then
+ * that is an invalid case and the method adds to the list of invalid variables.
+ * @throws TeiidComponentException, MetaMatrixProcessingException
+ */
+ private boolean checkInputVariables(Expression expr) throws TeiidComponentException, TeiidProcessingException{
+ Boolean result = null;
+ for (ElementSymbol var : ElementCollectorVisitor.getElements(expr, false)) {
+ if (var.isExternalReference() && var.getGroupSymbol().getSchema() == null && var.getGroupSymbol().getShortName().equalsIgnoreCase(ProcedureReservedWords.INPUTS)) {
+
+ var = var.clone();
+ var.getGroupSymbol().setShortName(ProcedureReservedWords.CHANGING);
+
+ Boolean changingValue = (Boolean)((Constant)variables.get(var)).getValue();
+
+ if (result == null) {
+ result = changingValue;
+ } else if (!result.equals(changingValue)) {
+ throw new QueryValidatorException(QueryPlugin.Util.getString("VariableSubstitutionVisitor.Input_vars_should_have_same_changing_state", expr)); //$NON-NLS-1$
+ }
+ }
+ }
+
+ if (result != null) {
+ return result.booleanValue();
+ }
+
+ return true;
+ }
+
+ private Command rewriteDelete(Delete delete) throws TeiidComponentException, TeiidProcessingException{
+ UpdateInfo info = delete.getUpdateInfo();
+ if (info != null && info.isInherentDelete()) {
+ if (!info.getUnionBranches().isEmpty()) {
+ List<Command> batchedUpdates = new ArrayList<Command>(info.getUnionBranches().size() + 1);
+ for (UpdateInfo branchInfo : info.getUnionBranches()) {
+ batchedUpdates.add(rewriteInherentDelete((Delete)delete.clone(), branchInfo));
+ }
+ batchedUpdates.add(0, rewriteInherentDelete(delete, info));
+ return new BatchedUpdateCommand(batchedUpdates);
+ }
+ return rewriteInherentDelete(delete, info);
+ }
+ // Rewrite criteria
+ Criteria crit = delete.getCriteria();
+ if(crit != null) {
+ delete.setCriteria(rewriteCriteria(crit));
+ }
+
+ return delete;
+ }
+
+ private Command rewriteInherentDelete(Delete delete, UpdateInfo info)
+ throws QueryMetadataException, TeiidComponentException,
+ QueryResolverException, TeiidProcessingException {
+ UpdateMapping mapping = info.getDeleteTarget();
+ if (info.isSimple()) {
+ delete.setGroup(mapping.getGroup().clone());
+ //TODO: properly handle correlated references
+ DeepPostOrderNavigator.doVisit(delete, new ExpressionMappingVisitor(mapping.getUpdatableViewSymbols(), true));
+ delete.setUpdateInfo(ProcedureContainerResolver.getUpdateInfo(delete.getGroup(), metadata, Command.TYPE_DELETE));
+ if (info.getViewDefinition().getCriteria() != null) {
+ delete.setCriteria(Criteria.combineCriteria(delete.getCriteria(), (Criteria)info.getViewDefinition().getCriteria().clone()));
+ }
+ return rewriteDelete(delete);
+ }
+
+ Query query = (Query)info.getViewDefinition().clone();
+ query.setOrderBy(null);
+ SymbolMap expressionMapping = SymbolMap.createSymbolMap(delete.getGroup(), query.getProjectedSymbols(), metadata);
+
+ query.setSelect(new Select());
+ ExpressionMappingVisitor emv = new ExpressionMappingVisitor(expressionMapping.asMap(), true);
+
+ Criteria crit = delete.getCriteria();
+ if (crit != null) {
+ PostOrderNavigator.doVisit(crit, emv);
+ query.setCriteria(Criteria.combineCriteria(query.getCriteria(), crit));
+ }
+ GroupSymbol group = mapping.getGroup();
+ String correlationName = mapping.getCorrelatedName().getName();
+ return createDeleteProcedure(delete, query, group, correlationName);
+ }
+
+ public static Command createDeleteProcedure(Delete delete, QueryMetadataInterface metadata, CommandContext context) throws QueryResolverException, QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+ QueryRewriter rewriter = new QueryRewriter(metadata, context, null);
+ Criteria crit = delete.getCriteria();
+ Query query = new Query(new Select(), new From(Arrays.asList(new UnaryFromClause(delete.getGroup()))), crit, null, null);
+ return rewriter.createDeleteProcedure(delete, query, delete.getGroup(), delete.getGroup().getName());
+ }
+
+ public static Command createUpdateProcedure(Update update, QueryMetadataInterface metadata, CommandContext context) throws QueryResolverException, QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+ QueryRewriter rewriter = new QueryRewriter(metadata, context, null);
+ Criteria crit = update.getCriteria();
+ ArrayList<SingleElementSymbol> selectSymbols = rewriter.mapChangeList(update, null);
+ Query query = new Query(new Select(selectSymbols), new From(Arrays.asList(new UnaryFromClause(update.getGroup()))), crit, null, null);
+ return rewriter.createUpdateProcedure(update, query, update.getGroup(), update.getGroup().getName());
+ }
+
+ private Command createDeleteProcedure(Delete delete, Query query,
+ GroupSymbol group, String correlationName)
+ throws TeiidComponentException, QueryMetadataException,
+ QueryResolverException, TeiidProcessingException {
+ Delete newUpdate = new Delete();
+ newUpdate.setGroup(group.clone());
+ List<Criteria> pkCriteria = createPkCriteria(group, correlationName, query);
+ newUpdate.setCriteria(new CompoundCriteria(pkCriteria));
+ return asLoopProcedure(delete.getGroup(), query, newUpdate);
+ }
+
+ private Limit rewriteLimitClause(Limit limit) throws TeiidComponentException, TeiidProcessingException{
+ if (limit.getOffset() != null) {
+ limit.setOffset(rewriteExpressionDirect(limit.getOffset()));
+ if (new Constant(0).equals(limit.getOffset())) {
+ limit.setOffset(null);
+ }
+ }
+ if (limit.getRowLimit() != null) {
+ limit.setRowLimit(rewriteExpressionDirect(limit.getRowLimit()));
+ }
+ return limit;
+ }
+}
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/LanguageObject.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/LanguageObject.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/LanguageObject.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.query.sql;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * This is the primary interface for all language objects. It extends a few
- * key interfaces and adds some additional methods to allow the {@link LanguageVisitor}
- * to work.
- */
-public interface LanguageObject extends Cloneable {
-
- /**
- * Method for accepting a visitor. It is the responsibility of the
- * language object to call back on the visitor.
- * @param visitor Visitor being used
- */
- void acceptVisitor(LanguageVisitor visitor);
-
- /**
- * Implement clone to make objects cloneable.
- * @return Deep clone of this object
- */
- Object clone();
-
- public static class Util {
-
- public static <S extends LanguageObject, T extends S> ArrayList<S> deepClone(List<T> collection, Class<S> type) {
- if (collection == null) {
- return null;
- }
- ArrayList<S> result = new ArrayList<S>(collection.size());
- for (LanguageObject obj : collection) {
- result.add(type.cast(obj.clone()));
- }
- return result;
- }
-
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/LanguageObject.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/LanguageObject.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/LanguageObject.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/LanguageObject.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,63 @@
+/*
+ * 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;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * This is the primary interface for all language objects. It extends a few
+ * key interfaces and adds some additional methods to allow the {@link LanguageVisitor}
+ * to work.
+ */
+public interface LanguageObject extends Cloneable {
+
+ /**
+ * Method for accepting a visitor. It is the responsibility of the
+ * language object to call back on the visitor.
+ * @param visitor Visitor being used
+ */
+ void acceptVisitor(LanguageVisitor visitor);
+
+ /**
+ * Implement clone to make objects cloneable.
+ * @return Deep clone of this object
+ */
+ Object clone();
+
+ public static class Util {
+
+ public static <S extends LanguageObject, T extends S> ArrayList<S> deepClone(Collection<T> collection, Class<S> type) {
+ if (collection == null) {
+ return null;
+ }
+ ArrayList<S> result = new ArrayList<S>(collection.size());
+ for (LanguageObject obj : collection) {
+ result.add(type.cast(obj.clone()));
+ }
+ return result;
+ }
+
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ArrayTable.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/lang/ArrayTable.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ArrayTable.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,85 +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.lang;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.teiid.core.util.EquivalenceUtil;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.symbol.Expression;
-
-/**
- * Represents the ArrayTable table function.
- */
-public class ArrayTable extends TableFunctionReference {
-
- private Expression arrayValue;
- private List<ProjectedColumn> columns = new ArrayList<ProjectedColumn>();
-
- public List<ProjectedColumn> getColumns() {
- return columns;
- }
-
- public void setColumns(List<ProjectedColumn> columns) {
- this.columns = columns;
- }
-
- public Expression getArrayValue() {
- return arrayValue;
- }
-
- public void setArrayValue(Expression arrayValue) {
- this.arrayValue = arrayValue;
- }
-
- @Override
- public void acceptVisitor(LanguageVisitor visitor) {
- visitor.visit(this);
- }
-
- @Override
- public ArrayTable clone() {
- ArrayTable clone = new ArrayTable();
- this.copy(clone);
- clone.setArrayValue((Expression)this.arrayValue.clone());
- for (ProjectedColumn column : columns) {
- clone.getColumns().add(column.copyTo(new ProjectedColumn()));
- }
- return clone;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (!super.equals(obj) || !(obj instanceof ArrayTable)) {
- return false;
- }
- ArrayTable other = (ArrayTable)obj;
- return this.columns.equals(other.columns)
- && EquivalenceUtil.areEqual(arrayValue, other.arrayValue);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ArrayTable.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/lang/ArrayTable.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ArrayTable.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ArrayTable.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,85 @@
+/*
+ * 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.lang;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.symbol.Expression;
+
+/**
+ * Represents the ArrayTable table function.
+ */
+public class ArrayTable extends TableFunctionReference {
+
+ private Expression arrayValue;
+ private List<ProjectedColumn> columns = new ArrayList<ProjectedColumn>();
+
+ public List<ProjectedColumn> getColumns() {
+ return columns;
+ }
+
+ public void setColumns(List<ProjectedColumn> columns) {
+ this.columns = columns;
+ }
+
+ public Expression getArrayValue() {
+ return arrayValue;
+ }
+
+ public void setArrayValue(Expression arrayValue) {
+ this.arrayValue = arrayValue;
+ }
+
+ @Override
+ public void acceptVisitor(LanguageVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ @Override
+ protected ArrayTable cloneDirect() {
+ ArrayTable clone = new ArrayTable();
+ this.copy(clone);
+ clone.setArrayValue((Expression)this.arrayValue.clone());
+ for (ProjectedColumn column : columns) {
+ clone.getColumns().add(column.copyTo(new ProjectedColumn()));
+ }
+ return clone;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (!super.equals(obj) || !(obj instanceof ArrayTable)) {
+ return false;
+ }
+ ArrayTable other = (ArrayTable)obj;
+ return this.columns.equals(other.columns)
+ && EquivalenceUtil.areEqual(arrayValue, other.arrayValue);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ExistsCriteria.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/lang/ExistsCriteria.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ExistsCriteria.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,203 +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.lang;
-
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.teiid.core.util.EquivalenceUtil;
-import org.teiid.core.util.HashCodeUtil;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.lang.PredicateCriteria.Negatable;
-import org.teiid.query.sql.symbol.ContextReference;
-import org.teiid.query.sql.symbol.Expression;
-
-
-/**
- * This predicate criteria implements the "exists" predicate, which has
- * a subquery in it. For example,
- * "EXISTS (Select EmployeeID FROM Employees WHERE EmployeeName = 'Smith')".
- */
-public class ExistsCriteria extends PredicateCriteria
-implements SubqueryContainer<QueryCommand>, ContextReference, Negatable {
-
- public static class SubqueryHint {
- public static String MJ = "MJ"; //$NON-NLS-1$
- public static String NOUNNEST = "NO_UNNEST"; //$NON-NLS-1$
-
- private boolean mergeJoin;
- private boolean noUnnest;
-
- public void setMergeJoin(boolean semiJoin) {
- this.mergeJoin = semiJoin;
- }
-
- public boolean isMergeJoin() {
- return mergeJoin;
- }
-
- public void setNoUnnest(boolean noUnnest) {
- this.noUnnest = noUnnest;
- }
-
- public boolean isNoUnnest() {
- return noUnnest;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof SubqueryHint)) {
- return false;
- }
- SubqueryHint other = (SubqueryHint) obj;
- return mergeJoin == other.mergeJoin && noUnnest == other.noUnnest;
- }
-
- public SubqueryHint clone() {
- SubqueryHint clone = new SubqueryHint();
- clone.mergeJoin = this.mergeJoin;
- clone.noUnnest = this.noUnnest;
- return clone;
- }
-
- }
-
- private static AtomicInteger ID = new AtomicInteger();
-
- private QueryCommand command;
- private String id = "$ec/id" + ID.getAndIncrement(); //$NON-NLS-1$
- private boolean shouldEvaluate;
- private boolean negated;
- private SubqueryHint subqueryHint = new SubqueryHint();
-
- /**
- * Default constructor
- */
- public ExistsCriteria() {
- super();
- }
-
- public ExistsCriteria(QueryCommand subqueryCommand){
- this.command = subqueryCommand;
- }
-
- public boolean shouldEvaluate() {
- return shouldEvaluate;
- }
-
- public void setShouldEvaluate(boolean shouldEvaluate) {
- this.shouldEvaluate = shouldEvaluate;
- }
-
- @Override
- public String getContextSymbol() {
- return id;
- }
-
- @Override
- public Expression getValueExpression() {
- return null;
- }
-
- public QueryCommand getCommand() {
- return this.command;
- }
-
- public void setCommand(QueryCommand subqueryCommand){
- this.command = subqueryCommand;
- }
-
- public void acceptVisitor(LanguageVisitor visitor) {
- visitor.visit(this);
- }
-
- /**
- * Get hash code. WARNING: The hash code is based on data in the criteria.
- * If data values are changed, the hash code will change - don't hash this
- * object and change values.
- * @return Hash code
- */
- public int hashCode() {
- int hc = 0;
- hc = HashCodeUtil.hashCode(hc, getCommand());
- return hc;
- }
-
- /**
- * Override equals() method.
- * @param obj Other object
- * @return True if equal
- */
- public boolean equals(Object obj) {
- if(obj == this) {
- return true;
- }
-
- if(!(obj instanceof ExistsCriteria)) {
- return false;
- }
-
- ExistsCriteria other = (ExistsCriteria)obj;
-
- return EquivalenceUtil.areEqual(getCommand(), other.getCommand()) &&
- this.negated == other.negated &&
- this.subqueryHint.equals(other.subqueryHint);
- }
-
- public SubqueryHint getSubqueryHint() {
- return subqueryHint;
- }
-
- public void setSubqueryHint(SubqueryHint subqueryHint) {
- this.subqueryHint = subqueryHint;
- }
-
- /**
- * Deep copy of object. The values Iterator of this object
- * will not be cloned - it will be null in the new object
- * (see #setValueIterator setValueIterator}).
- * @return Deep copy of object
- * @see java.lang.Object#clone()
- */
- public Object clone() {
- ExistsCriteria ec = new ExistsCriteria((QueryCommand) this.command.clone());
- ec.subqueryHint = this.subqueryHint.clone();
- ec.setNegated(this.negated);
- return ec;
- }
-
- public boolean isNegated() {
- return negated;
- }
-
- public void setNegated(boolean negated) {
- this.negated = negated;
- }
-
- @Override
- public void negate() {
- this.negated = !this.negated;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ExistsCriteria.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/lang/ExistsCriteria.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ExistsCriteria.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/ExistsCriteria.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,217 @@
+/*
+ * 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.lang;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.core.util.HashCodeUtil;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.lang.PredicateCriteria.Negatable;
+import org.teiid.query.sql.symbol.ContextReference;
+import org.teiid.query.sql.symbol.Expression;
+
+
+/**
+ * This predicate criteria implements the "exists" predicate, which has
+ * a subquery in it. For example,
+ * "EXISTS (Select EmployeeID FROM Employees WHERE EmployeeName = 'Smith')".
+ */
+public class ExistsCriteria extends PredicateCriteria
+implements SubqueryContainer<QueryCommand>, ContextReference, Negatable {
+
+ 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;
+ }
+
+ public boolean isMergeJoin() {
+ return mergeJoin;
+ }
+
+ public void setNoUnnest(boolean noUnnest) {
+ this.noUnnest = noUnnest;
+ }
+
+ public boolean isNoUnnest() {
+ 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) {
+ return true;
+ }
+ if (!(obj instanceof SubqueryHint)) {
+ return false;
+ }
+ SubqueryHint other = (SubqueryHint) obj;
+ 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;
+ }
+
+ }
+
+ private static AtomicInteger ID = new AtomicInteger();
+
+ private QueryCommand command;
+ private String id = "$ec/id" + ID.getAndIncrement(); //$NON-NLS-1$
+ private boolean shouldEvaluate;
+ private boolean negated;
+ private SubqueryHint subqueryHint = new SubqueryHint();
+
+ /**
+ * Default constructor
+ */
+ public ExistsCriteria() {
+ super();
+ }
+
+ public ExistsCriteria(QueryCommand subqueryCommand){
+ this.command = subqueryCommand;
+ }
+
+ public boolean shouldEvaluate() {
+ return shouldEvaluate;
+ }
+
+ public void setShouldEvaluate(boolean shouldEvaluate) {
+ this.shouldEvaluate = shouldEvaluate;
+ }
+
+ @Override
+ public String getContextSymbol() {
+ return id;
+ }
+
+ @Override
+ public Expression getValueExpression() {
+ return null;
+ }
+
+ public QueryCommand getCommand() {
+ return this.command;
+ }
+
+ public void setCommand(QueryCommand subqueryCommand){
+ this.command = subqueryCommand;
+ }
+
+ public void acceptVisitor(LanguageVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ /**
+ * Get hash code. WARNING: The hash code is based on data in the criteria.
+ * If data values are changed, the hash code will change - don't hash this
+ * object and change values.
+ * @return Hash code
+ */
+ public int hashCode() {
+ int hc = 0;
+ hc = HashCodeUtil.hashCode(hc, getCommand());
+ return hc;
+ }
+
+ /**
+ * Override equals() method.
+ * @param obj Other object
+ * @return True if equal
+ */
+ public boolean equals(Object obj) {
+ if(obj == this) {
+ return true;
+ }
+
+ if(!(obj instanceof ExistsCriteria)) {
+ return false;
+ }
+
+ ExistsCriteria other = (ExistsCriteria)obj;
+
+ return EquivalenceUtil.areEqual(getCommand(), other.getCommand()) &&
+ this.negated == other.negated &&
+ this.subqueryHint.equals(other.subqueryHint);
+ }
+
+ public SubqueryHint getSubqueryHint() {
+ return subqueryHint;
+ }
+
+ public void setSubqueryHint(SubqueryHint subqueryHint) {
+ this.subqueryHint = subqueryHint;
+ }
+
+ /**
+ * Deep copy of object. The values Iterator of this object
+ * will not be cloned - it will be null in the new object
+ * (see #setValueIterator setValueIterator}).
+ * @return Deep copy of object
+ * @see java.lang.Object#clone()
+ */
+ public Object clone() {
+ ExistsCriteria ec = new ExistsCriteria((QueryCommand) this.command.clone());
+ ec.subqueryHint = this.subqueryHint.clone();
+ ec.setNegated(this.negated);
+ return ec;
+ }
+
+ public boolean isNegated() {
+ return negated;
+ }
+
+ public void setNegated(boolean negated) {
+ this.negated = negated;
+ }
+
+ @Override
+ public void negate() {
+ this.negated = !this.negated;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/FromClause.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/lang/FromClause.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/FromClause.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,96 +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.lang;
-
-import java.util.Collection;
-
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.visitor.SQLStringVisitor;
-
-
-/**
- * A FromClause is an interface for subparts held in a FROM clause. One
- * type of FromClause is {@link UnaryFromClause}, which is the more common
- * use and represents a single group. Another, less common type of FromClause
- * is the {@link JoinPredicate} which represents a join between two FromClauses
- * and may contain criteria.
- */
-public abstract class FromClause implements LanguageObject {
- private boolean optional;
- private boolean makeDep;
- private boolean makeNotDep;
-
- public boolean isOptional() {
- return optional;
- }
-
- public void setOptional(boolean optional) {
- this.optional = optional;
- }
-
- public abstract void acceptVisitor(LanguageVisitor visitor);
- public abstract void collectGroups(Collection groups);
- public abstract Object clone();
-
- public boolean isMakeDep() {
- return this.makeDep;
- }
-
- public void setMakeDep(boolean makeDep) {
- this.makeDep = makeDep;
- }
-
- public boolean isMakeNotDep() {
- return this.makeNotDep;
- }
-
- public void setMakeNotDep(boolean makeNotDep) {
- this.makeNotDep = makeNotDep;
- }
-
- public boolean hasHint() {
- return optional || makeDep || makeNotDep;
- }
-
- public boolean equals(Object obj) {
- if(obj == this) {
- return true;
- }
-
- if(! (obj instanceof FromClause)) {
- return false;
- }
-
- FromClause other = (FromClause)obj;
-
- return other.isOptional() == this.isOptional()
- && other.isMakeDep() == this.isMakeDep()
- && other.isMakeNotDep() == this.isMakeNotDep();
- }
-
- @Override
- public String toString() {
- return SQLStringVisitor.getSQLString(this);
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/FromClause.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/lang/FromClause.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/FromClause.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/FromClause.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,119 @@
+/*
+ * 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.lang;
+
+import java.util.Collection;
+
+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;
+
+
+/**
+ * A FromClause is an interface for subparts held in a FROM clause. One
+ * type of FromClause is {@link UnaryFromClause}, which is the more common
+ * use and represents a single group. Another, less common type of FromClause
+ * is the {@link JoinPredicate} which represents a join between two FromClauses
+ * 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;
+ }
+
+ public void setOptional(boolean optional) {
+ 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<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;
+ }
+
+ public void setMakeDep(boolean makeDep) {
+ this.makeDep = makeDep;
+ }
+
+ public boolean isMakeNotDep() {
+ return this.makeNotDep;
+ }
+
+ public void setMakeNotDep(boolean makeNotDep) {
+ this.makeNotDep = makeNotDep;
+ }
+
+ public boolean hasHint() {
+ return optional || makeDep || makeNotDep || makeInd;
+ }
+
+ public boolean equals(Object obj) {
+ if(obj == this) {
+ return true;
+ }
+
+ if(! (obj instanceof FromClause)) {
+ return false;
+ }
+
+ FromClause other = (FromClause)obj;
+
+ return other.isOptional() == this.isOptional()
+ && other.isMakeDep() == this.isMakeDep()
+ && other.isMakeNotDep() == this.isMakeNotDep()
+ && other.isMakeInd() == this.isMakeInd();
+ }
+
+ @Override
+ public String toString() {
+ return SQLStringVisitor.getSQLString(this);
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/JoinPredicate.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/lang/JoinPredicate.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/JoinPredicate.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,254 +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.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.sql.LanguageVisitor;
-
-
-/**
- * Represents a subpart of the FROM clause specifying a join within the FROM. It may
- * optionally specify criteria for the join, depending on the join type. For example,
- * these are some representations of JoinPredicates:
- * <OL>
- * <LI>GroupA CROSS JOIN GroupB</LI>
- * <LI>GroupA JOIN GroupB ON GroupA.E1=GroupB.E1 AND GroupA.E2=GroupB.E2</LI>
- * <LI>GroupA RIGHT OUTER JOIN (GroupB JOIN GroupC ON GroupB.E1=GroupC.E1) ON GroupA.E1=GroupB.E1</LI>
- * </OL>
- */
-public class JoinPredicate extends FromClause {
-
- private FromClause leftClause;
- private FromClause rightClause;
- private JoinType joinType = JoinType.JOIN_INNER;
- private List joinCriteria;
-
- /**
- * Construct a JoinPredicate
- */
- public JoinPredicate() {
- this.joinCriteria = new ArrayList();
- }
-
- /**
- * Construct a JoinPredicate between two clauses of the specified type.
- * @param leftClause Left from clause
- * @param rightClause Right from clause
- * @param type Type of join
- */
- public JoinPredicate(FromClause leftClause, FromClause rightClause, JoinType type) {
- this.leftClause = leftClause;
- this.rightClause = rightClause;
- this.joinType = type;
- this.joinCriteria = new ArrayList();
- }
-
- /**
- * Construct a JoinPredicate between two clauses of the specified type.
- * @param leftClause Left from clause
- * @param rightClause Right from clause
- * @param type Type of join
- * @param criteria List of Criteria for this join predicate
- */
- public JoinPredicate(FromClause leftClause, FromClause rightClause, JoinType type, List criteria) {
- this.leftClause = leftClause;
- this.rightClause = rightClause;
- this.joinType = type;
- this.joinCriteria = criteria;
- }
-
- /**
- * Construct a JoinPredicate between two clauses of the specified type.
- * @param leftClause Left from clause
- * @param rightClause Right from clause
- * @param type Type of join
- * @param criteria List of Criteria for this join predicate
- */
- public JoinPredicate(FromClause leftClause, FromClause rightClause, JoinType type, Criteria criteria) {
- this.leftClause = leftClause;
- this.rightClause = rightClause;
- this.joinType = type;
- this.joinCriteria = Criteria.separateCriteriaByAnd(criteria);
- }
-
- /**
- * Set left clause
- * @param predicate Left clause to set
- */
- public void setLeftClause(FromClause predicate) {
- this.leftClause = predicate;
- }
-
- /**
- * Get left clause
- * @return Left clause
- */
- public FromClause getLeftClause() {
- return this.leftClause;
- }
-
- /**
- * Set right clause
- * @param predicate Right clause to set
- */
- public void setRightClause(FromClause predicate) {
- this.rightClause = predicate;
- }
-
- /**
- * Get right clause
- * @return Right clause
- */
- public FromClause getRightClause() {
- return this.rightClause;
- }
-
- /**
- * Set join type for this predicate
- * @param type Type of join
- */
- public void setJoinType(JoinType type) {
- this.joinType = type;
- }
-
- /**
- * Get join type for this predicate
- * @return Type of join
- */
- public JoinType getJoinType() {
- return this.joinType;
- }
-
- /**
- * Set join criteria for this predicate
- * @param criteria List of {@link Criteria} set on this predicate
- */
- public void setJoinCriteria(List criteria) {
- this.joinCriteria = criteria;
- }
-
- /**
- * Get join criteria for this predicate
- * @return List of {@link Criteria}
- */
- public List getJoinCriteria() {
- return this.joinCriteria;
- }
-
- /**
- * Collect all GroupSymbols for this from clause.
- * @param groups Groups to add to
- */
- public void collectGroups(Collection groups) {
- if(this.leftClause != null) {
- this.leftClause.collectGroups(groups);
- }
- if(this.rightClause != null) {
- this.rightClause.collectGroups(groups);
- }
- }
-
- public void acceptVisitor(LanguageVisitor visitor) {
- visitor.visit(this);
- }
-
- /**
- * Compare this object to another
- * @param obj Other object
- * @return True if equal
- */
- public boolean equals(Object obj) {
- if (!super.equals(obj)) {
- return false;
- }
-
- if(!(obj instanceof JoinPredicate)) {
- return false;
- }
- JoinPredicate other = (JoinPredicate) obj;
-
- List thisCrit = this.getJoinCriteria();
- if(thisCrit != null && thisCrit.size() == 0) {
- thisCrit = null;
- }
- List otherCrit = other.getJoinCriteria();
- if(otherCrit != null && otherCrit.size() == 0) {
- otherCrit = null;
- }
-
- return EquivalenceUtil.areEqual(other.getJoinType(), this.getJoinType()) &&
- EquivalenceUtil.areEqual(other.getLeftClause(), this.getLeftClause()) &&
- EquivalenceUtil.areEqual(other.getRightClause(), this.getRightClause()) &&
- EquivalenceUtil.areEqual(otherCrit, thisCrit);
- }
-
- /**
- * Get hash code for object
- * @return Hash code
- */
- public int hashCode() {
- int hash = HashCodeUtil.hashCode(0, getLeftClause());
- hash = HashCodeUtil.hashCode(hash, getJoinType().getTypeCode());
- hash = HashCodeUtil.hashCode(hash, getRightClause());
- return hash;
- }
-
- /**
- * Return deep clone for object
- * @return Deep clone
- */
- public Object clone() {
- FromClause copyLeft = null;
- if(this.leftClause != null) {
- copyLeft = (FromClause) this.leftClause.clone();
- }
-
- FromClause copyRight = null;
- if(this.rightClause != null) {
- copyRight = (FromClause) this.rightClause.clone();
- }
-
- List copyCrits = null;
- if(this.joinCriteria != null) {
- copyCrits = new ArrayList(joinCriteria.size());
- Iterator iter = this.joinCriteria.iterator();
- while(iter.hasNext()) {
- Criteria crit = (Criteria) iter.next();
- copyCrits.add(crit.clone());
- }
- }
-
- JoinPredicate clonedJoinPredicate = new JoinPredicate(copyLeft, copyRight, this.joinType, copyCrits);
- clonedJoinPredicate.setOptional(this.isOptional());
- clonedJoinPredicate.setMakeDep(this.isMakeDep());
- clonedJoinPredicate.setMakeNotDep(this.isMakeNotDep());
- return clonedJoinPredicate;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/JoinPredicate.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/lang/JoinPredicate.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/JoinPredicate.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/JoinPredicate.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,252 @@
+/*
+ * 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.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.sql.LanguageVisitor;
+import org.teiid.query.sql.symbol.GroupSymbol;
+
+
+/**
+ * Represents a subpart of the FROM clause specifying a join within the FROM. It may
+ * optionally specify criteria for the join, depending on the join type. For example,
+ * these are some representations of JoinPredicates:
+ * <OL>
+ * <LI>GroupA CROSS JOIN GroupB</LI>
+ * <LI>GroupA JOIN GroupB ON GroupA.E1=GroupB.E1 AND GroupA.E2=GroupB.E2</LI>
+ * <LI>GroupA RIGHT OUTER JOIN (GroupB JOIN GroupC ON GroupB.E1=GroupC.E1) ON GroupA.E1=GroupB.E1</LI>
+ * </OL>
+ */
+public class JoinPredicate extends FromClause {
+
+ private FromClause leftClause;
+ private FromClause rightClause;
+ private JoinType joinType = JoinType.JOIN_INNER;
+ private List joinCriteria;
+
+ /**
+ * Construct a JoinPredicate
+ */
+ public JoinPredicate() {
+ this.joinCriteria = new ArrayList();
+ }
+
+ /**
+ * Construct a JoinPredicate between two clauses of the specified type.
+ * @param leftClause Left from clause
+ * @param rightClause Right from clause
+ * @param type Type of join
+ */
+ public JoinPredicate(FromClause leftClause, FromClause rightClause, JoinType type) {
+ this.leftClause = leftClause;
+ this.rightClause = rightClause;
+ this.joinType = type;
+ this.joinCriteria = new ArrayList();
+ }
+
+ /**
+ * Construct a JoinPredicate between two clauses of the specified type.
+ * @param leftClause Left from clause
+ * @param rightClause Right from clause
+ * @param type Type of join
+ * @param criteria List of Criteria for this join predicate
+ */
+ public JoinPredicate(FromClause leftClause, FromClause rightClause, JoinType type, List criteria) {
+ this.leftClause = leftClause;
+ this.rightClause = rightClause;
+ this.joinType = type;
+ this.joinCriteria = criteria;
+ }
+
+ /**
+ * Construct a JoinPredicate between two clauses of the specified type.
+ * @param leftClause Left from clause
+ * @param rightClause Right from clause
+ * @param type Type of join
+ * @param criteria List of Criteria for this join predicate
+ */
+ public JoinPredicate(FromClause leftClause, FromClause rightClause, JoinType type, Criteria criteria) {
+ this.leftClause = leftClause;
+ this.rightClause = rightClause;
+ this.joinType = type;
+ this.joinCriteria = Criteria.separateCriteriaByAnd(criteria);
+ }
+
+ /**
+ * Set left clause
+ * @param predicate Left clause to set
+ */
+ public void setLeftClause(FromClause predicate) {
+ this.leftClause = predicate;
+ }
+
+ /**
+ * Get left clause
+ * @return Left clause
+ */
+ public FromClause getLeftClause() {
+ return this.leftClause;
+ }
+
+ /**
+ * Set right clause
+ * @param predicate Right clause to set
+ */
+ public void setRightClause(FromClause predicate) {
+ this.rightClause = predicate;
+ }
+
+ /**
+ * Get right clause
+ * @return Right clause
+ */
+ public FromClause getRightClause() {
+ return this.rightClause;
+ }
+
+ /**
+ * Set join type for this predicate
+ * @param type Type of join
+ */
+ public void setJoinType(JoinType type) {
+ this.joinType = type;
+ }
+
+ /**
+ * Get join type for this predicate
+ * @return Type of join
+ */
+ public JoinType getJoinType() {
+ return this.joinType;
+ }
+
+ /**
+ * Set join criteria for this predicate
+ * @param criteria List of {@link Criteria} set on this predicate
+ */
+ public void setJoinCriteria(List criteria) {
+ this.joinCriteria = criteria;
+ }
+
+ /**
+ * Get join criteria for this predicate
+ * @return List of {@link Criteria}
+ */
+ public List getJoinCriteria() {
+ return this.joinCriteria;
+ }
+
+ /**
+ * Collect all GroupSymbols for this from clause.
+ * @param groups Groups to add to
+ */
+ public void collectGroups(Collection<GroupSymbol> groups) {
+ if(this.leftClause != null) {
+ this.leftClause.collectGroups(groups);
+ }
+ if(this.rightClause != null) {
+ this.rightClause.collectGroups(groups);
+ }
+ }
+
+ public void acceptVisitor(LanguageVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ /**
+ * Compare this object to another
+ * @param obj Other object
+ * @return True if equal
+ */
+ public boolean equals(Object obj) {
+ if (!super.equals(obj)) {
+ return false;
+ }
+
+ if(!(obj instanceof JoinPredicate)) {
+ return false;
+ }
+ JoinPredicate other = (JoinPredicate) obj;
+
+ List thisCrit = this.getJoinCriteria();
+ if(thisCrit != null && thisCrit.size() == 0) {
+ thisCrit = null;
+ }
+ List otherCrit = other.getJoinCriteria();
+ if(otherCrit != null && otherCrit.size() == 0) {
+ otherCrit = null;
+ }
+
+ return EquivalenceUtil.areEqual(other.getJoinType(), this.getJoinType()) &&
+ EquivalenceUtil.areEqual(other.getLeftClause(), this.getLeftClause()) &&
+ EquivalenceUtil.areEqual(other.getRightClause(), this.getRightClause()) &&
+ EquivalenceUtil.areEqual(otherCrit, thisCrit);
+ }
+
+ /**
+ * Get hash code for object
+ * @return Hash code
+ */
+ public int hashCode() {
+ int hash = HashCodeUtil.hashCode(0, getLeftClause());
+ hash = HashCodeUtil.hashCode(hash, getJoinType().getTypeCode());
+ hash = HashCodeUtil.hashCode(hash, getRightClause());
+ return hash;
+ }
+
+ /**
+ * Return deep clone for object
+ * @return Deep clone
+ */
+ protected FromClause cloneDirect() {
+ FromClause copyLeft = null;
+ if(this.leftClause != null) {
+ copyLeft = this.leftClause.clone();
+ }
+
+ FromClause copyRight = null;
+ if(this.rightClause != null) {
+ copyRight = this.rightClause.clone();
+ }
+
+ List copyCrits = null;
+ if(this.joinCriteria != null) {
+ copyCrits = new ArrayList(joinCriteria.size());
+ Iterator iter = this.joinCriteria.iterator();
+ while(iter.hasNext()) {
+ Criteria crit = (Criteria) iter.next();
+ copyCrits.add(crit.clone());
+ }
+ }
+
+ JoinPredicate clonedJoinPredicate = new JoinPredicate(copyLeft, copyRight, this.joinType, copyCrits);
+ return clonedJoinPredicate;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Select.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/lang/Select.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Select.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,293 +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.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.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;
-import org.teiid.query.sql.visitor.SQLStringVisitor;
-
-
-/**
- * This class represents the SELECT clause of a query, which defines what elements
- * or expressions are returned from the query.
- */
-public class Select implements LanguageObject {
-
- /** The set of symbols for the data elements to be selected. */
- private List symbols; // List<SelectSymbols>
-
- /** Flag for whether duplicate removal should be performed on the results */
- private boolean distinct;
-
- // =========================================================================
- // C O N S T R U C T O R S
- // =========================================================================
-
- /**
- * Constructs a default instance of this class.
- */
- public Select() {
- symbols = new ArrayList();
- }
-
- /**
- * 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 );
- }
-
- // =========================================================================
- // M E T H O D S
- // =========================================================================
-
- /**
- * Returns the number of symbols in select.
- * @return Get count of number of symbols in select
- */
- public int getCount() {
- return symbols.size();
- }
- /**
- * Checks for a Select * clause
- * @return True if Select * is used
- */
- public boolean isStar() {
- return (symbols.size() == 1 && symbols.get(0) instanceof AllSymbol);
- }
-
- /**
- * Returns an ordered list of the symbols in the select.
- * @param Get list of SelectSymbol in SELECT
- */
- public List getSymbols() {
- return symbols;
- }
-
- /**
- * 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;
- }
-
- /**
- * Returns the select symbol at the specified index.
- * @param index Index to get
- * @return The variable identifier at the index
- */
- public SelectSymbol getSymbol( int index ) {
- return (SelectSymbol) symbols.get(index);
- }
-
- /**
- * Adds a new symbol to the list of symbols.
- * @param symbol New symbol
- */
- public void addSymbol( SelectSymbol symbol ) {
- if(symbol != null) {
- symbols.add(symbol);
- }
- }
-
- /**
- * Adds a new collection of symbols to the list of symbols.
- * @param symbols Collection of SelectSymbols
- */
- public void addSymbols( Collection symbols) {
- if(symbols != null) {
- this.symbols.addAll(symbols);
- }
- }
-
- /**
- * Remove all current symbols
- */
- public void clearSymbols() {
- symbols.clear();
- }
-
- /**
- * Checks if a symbol is in the Select.
- * @param symbol Symbol to check for
- * @return True if the Select contains the symbol
- */
- public boolean containsSymbol( SelectSymbol symbol ) {
- 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
- */
- public void setDistinct(boolean isDistinct) {
- this.distinct = isDistinct;
- }
-
- /**
- * Checks whether the select is distinct
- * @return True if select is distinct
- */
- public boolean isDistinct() {
- return this.distinct;
- }
-
- public void acceptVisitor(LanguageVisitor visitor) {
- visitor.visit(this);
- }
-
- /**
- * Get the ordered list of all elements returned by this select. These elements
- * may be ElementSymbols or ExpressionSymbols but in all cases each represents a
- * single column.
- * @return Ordered list of SingleElementSymbol
- */
- public List<SingleElementSymbol> getProjectedSymbols() {
- ArrayList<SingleElementSymbol> projectedSymbols = new ArrayList<SingleElementSymbol>();
- Iterator iter = symbols.iterator();
- while(iter.hasNext()) {
- SelectSymbol symbol = (SelectSymbol) iter.next();
- if(symbol instanceof SingleElementSymbol) {
- projectedSymbols.add((SingleElementSymbol)symbol);
- } else {
- List<ElementSymbol> multiSymbols = ((MultipleElementSymbol)symbol).getElementSymbols();
- if(multiSymbols != null) {
- projectedSymbols.addAll(multiSymbols);
- }
- }
- }
- return projectedSymbols;
- }
-
- // =========================================================================
- // O V E R R I D D E N O B J E C T M E T H O D S
- // =========================================================================
-
- /**
- * Return a deep copy of this Select.
- * @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);
- copy.setDistinct( isDistinct() );
- return copy;
- }
-
- /**
- * Compare two Selects for equality. Order is important in the select (for
- * determining the order of the returned columns), so this is a compare
- * with order, not just a set comparison.
- * @param obj Other object
- * @return True if equal
- */
- public boolean equals(Object obj) {
- if(obj == this) {
- return true;
- }
-
- if(!(obj instanceof Select)) {
- return false;
- }
-
- Select other = (Select) obj;
-
- return other.isDistinct() == isDistinct() &&
- EquivalenceUtil.areEqual(getSymbols(), other.getSymbols());
- }
-
- /**
- * Get hashcode for Select. WARNING: The hash code relies on the variables
- * in the select, so changing the variables will change the hash code, causing
- * a select to be lost in a hash structure. Do not hash a Select if you plan
- * to change it.
- * @return Hash code
- */
- public int hashCode() {
- return HashCodeUtil.hashCode(0, getSymbols());
- }
-
- /**
- * Returns a string representation of an instance of this class.
- * @return String representation of object
- */
- public String toString() {
- return SQLStringVisitor.getSQLString(this);
- }
-
-} // END CLASS
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Select.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/lang/Select.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Select.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Select.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,248 @@
+/*
+ * 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.lang;
+
+import java.util.ArrayList;
+import java.util.Collection;
+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.AllSymbol;
+import org.teiid.query.sql.symbol.ElementSymbol;
+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.SQLStringVisitor;
+
+
+/**
+ * This class represents the SELECT clause of a query, which defines what elements
+ * or expressions are returned from the query.
+ */
+public class Select implements LanguageObject {
+
+ /** The set of symbols for the data elements to be selected. */
+ private List<SelectSymbol> symbols;
+
+ /** Flag for whether duplicate removal should be performed on the results */
+ private boolean distinct;
+
+ // =========================================================================
+ // C O N S T R U C T O R S
+ // =========================================================================
+
+ /**
+ * Constructs a default instance of this class.
+ */
+ public Select() {
+ 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<? extends SelectSymbol> symbols ) {
+ this.symbols = new ArrayList<SelectSymbol>( symbols );
+ }
+
+ // =========================================================================
+ // M E T H O D S
+ // =========================================================================
+
+ /**
+ * Returns the number of symbols in select.
+ * @return Get count of number of symbols in select
+ */
+ public int getCount() {
+ return symbols.size();
+ }
+ /**
+ * Checks for a Select * clause
+ * @return True if Select * is used
+ */
+ public boolean isStar() {
+ return (symbols.size() == 1 && symbols.get(0) instanceof AllSymbol);
+ }
+
+ /**
+ * Returns an ordered list of the symbols in the select.
+ * @param Get list of SelectSymbol in SELECT
+ */
+ public List<SelectSymbol> getSymbols() {
+ return symbols;
+ }
+
+ /**
+ * Sets an ordered list of the symbols in the select.
+ * @param symbols list of SelectSymbol in SELECT
+ */
+ public void setSymbols(List<? extends SelectSymbol> symbols) {
+ this.symbols = new ArrayList<SelectSymbol>(symbols);
+ }
+
+ /**
+ * Returns the select symbol at the specified index.
+ * @param index Index to get
+ * @return The variable identifier at the index
+ */
+ public SelectSymbol getSymbol( int index ) {
+ return symbols.get(index);
+ }
+
+ /**
+ * Adds a new symbol to the list of symbols.
+ * @param symbol New symbol
+ */
+ public void addSymbol( SelectSymbol symbol ) {
+ if(symbol != null) {
+ symbols.add(symbol);
+ }
+ }
+
+ /**
+ * Adds a new collection of symbols to the list of symbols.
+ * @param symbols Collection of SelectSymbols
+ */
+ public void addSymbols( Collection<? extends SelectSymbol> toAdd) {
+ if(symbols != null) {
+ this.symbols.addAll(toAdd);
+ }
+ }
+
+ /**
+ * Remove all current symbols
+ */
+ public void clearSymbols() {
+ symbols.clear();
+ }
+
+ /**
+ * Checks if a symbol is in the Select.
+ * @param symbol Symbol to check for
+ * @return True if the Select contains the symbol
+ */
+ public boolean containsSymbol( SelectSymbol symbol ) {
+ return symbols.contains(symbol);
+ }
+
+ /**
+ * Set whether select is distinct.
+ * @param isDistinct True if SELECT is distinct
+ */
+ public void setDistinct(boolean isDistinct) {
+ this.distinct = isDistinct;
+ }
+
+ /**
+ * Checks whether the select is distinct
+ * @return True if select is distinct
+ */
+ public boolean isDistinct() {
+ return this.distinct;
+ }
+
+ public void acceptVisitor(LanguageVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ /**
+ * Get the ordered list of all elements returned by this select. These elements
+ * may be ElementSymbols or ExpressionSymbols but in all cases each represents a
+ * single column.
+ * @return Ordered list of SingleElementSymbol
+ */
+ public List<SingleElementSymbol> getProjectedSymbols() {
+ ArrayList<SingleElementSymbol> projectedSymbols = new ArrayList<SingleElementSymbol>();
+ for (SelectSymbol symbol : symbols) {
+ if(symbol instanceof SingleElementSymbol) {
+ projectedSymbols.add((SingleElementSymbol)symbol);
+ } else {
+ List<ElementSymbol> multiSymbols = ((MultipleElementSymbol)symbol).getElementSymbols();
+ if(multiSymbols != null) {
+ projectedSymbols.addAll(multiSymbols);
+ }
+ }
+ }
+ return projectedSymbols;
+ }
+
+ // =========================================================================
+ // O V E R R I D D E N O B J E C T M E T H O D S
+ // =========================================================================
+
+ /**
+ * Return a deep copy of this Select.
+ * @return Deep clone
+ */
+ public Object clone() {
+ Select copy = new Select(LanguageObject.Util.deepClone(this.symbols, SelectSymbol.class));
+ copy.setDistinct( isDistinct() );
+ return copy;
+ }
+
+ /**
+ * Compare two Selects for equality. Order is important in the select (for
+ * determining the order of the returned columns), so this is a compare
+ * with order, not just a set comparison.
+ * @param obj Other object
+ * @return True if equal
+ */
+ public boolean equals(Object obj) {
+ if(obj == this) {
+ return true;
+ }
+
+ if(!(obj instanceof Select)) {
+ return false;
+ }
+
+ Select other = (Select) obj;
+
+ return other.isDistinct() == isDistinct() &&
+ EquivalenceUtil.areEqual(getSymbols(), other.getSymbols());
+ }
+
+ /**
+ * Get hashcode for Select. WARNING: The hash code relies on the variables
+ * in the select, so changing the variables will change the hash code, causing
+ * a select to be lost in a hash structure. Do not hash a Select if you plan
+ * to change it.
+ * @return Hash code
+ */
+ public int hashCode() {
+ return HashCodeUtil.hashCode(0, getSymbols());
+ }
+
+ /**
+ * Returns a string representation of an instance of this class.
+ * @return String representation of object
+ */
+ public String toString() {
+ return SQLStringVisitor.getSQLString(this);
+ }
+
+} // END CLASS
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/SubqueryFromClause.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/lang/SubqueryFromClause.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/SubqueryFromClause.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,176 +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.lang;
-
-import java.util.Collection;
-
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.symbol.GroupSymbol;
-
-
-/**
- * A FROM subpart that represents a subquery. For example, the FROM clause:
- * "FROM (SELECT a FROM b)" will have a SubqueryFromClause referencing the subquery.
- */
-public class SubqueryFromClause extends FromClause implements SubqueryContainer{
-
- private GroupSymbol symbol;
- private Command command;
- private boolean table;
-
- /**
- * Construct default object
- */
- public SubqueryFromClause(String name) {
- setName(name);
- }
-
- /**
- * Construct object with specified command and name
- * @param command Command representing subquery, or stored procedure
- * @param name Alias of the subquery
- */
- public SubqueryFromClause(String name, Command command) {
- this(name);
- this.command = command;
- }
-
- public SubqueryFromClause(GroupSymbol symbol, Command command) {
- this.symbol = symbol;
- this.command = command;
- }
-
- public boolean isTable() {
- return table;
- }
-
- public void setTable(boolean table) {
- this.table = table;
- }
-
- /**
- * Reset the alias for this subquery from clause and it's pseudo-GroupSymbol.
- * WARNING: this will modify the hashCode and equals semantics and will cause this object
- * to be lost if currently in a HashMap or HashSet.
- * @param name New name
- * @since 4.3
- */
- public void setName(String name) {
- this.symbol = new GroupSymbol(name);
- }
-
- /**
- * Set the command held by the clause
- * @param command Command to hold
- */
- public void setCommand(Command command) {
- this.command = command;
- }
-
- /**
- * Get command held by clause
- * @return Command held by clause
- */
- public Command getCommand() {
- return this.command;
- }
-
- /**
- * Get name of this clause.
- * @return Name of clause
- */
- public String getName() {
- return this.symbol.getName();
- }
-
- public String getOutputName() {
- return this.symbol.getOutputName();
- }
-
- /**
- * Get GroupSymbol representing the named subquery
- * @return GroupSymbol representing the subquery
- */
- public GroupSymbol getGroupSymbol() {
- return this.symbol;
- }
-
- /**
- * Collect all GroupSymbols for this from clause.
- * @param groups Groups to add to
- */
- public void collectGroups(Collection groups) {
- groups.add(getGroupSymbol());
- }
-
- public void acceptVisitor(LanguageVisitor visitor) {
- visitor.visit(this);
- }
-
- /**
- * Check whether objects are equal
- * @param obj Other object
- * @return True if equal
- */
- public boolean equals(Object obj) {
- if (!super.equals(obj)) {
- return false;
- }
-
- if(! (obj instanceof SubqueryFromClause)) {
- return false;
- }
- SubqueryFromClause sfc = (SubqueryFromClause) obj;
-
- return this.getName().equalsIgnoreCase(sfc.getName()) &&
- sfc.isOptional() == this.isOptional() && this.command.equals(sfc.command)
- && this.table == sfc.table;
- }
-
- /**
- * Get hash code of object
- * @return Hash code
- */
- public int hashCode() {
- return this.symbol.hashCode();
- }
-
- /**
- * Get deep clone of object
- * @return Deep copy of the object
- */
- public Object clone() {
- 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());
- clause.setTable(this.isTable());
- return clause;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/SubqueryFromClause.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/lang/SubqueryFromClause.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/SubqueryFromClause.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/SubqueryFromClause.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,173 @@
+/*
+ * 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.lang;
+
+import java.util.Collection;
+
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.symbol.GroupSymbol;
+
+
+/**
+ * A FROM subpart that represents a subquery. For example, the FROM clause:
+ * "FROM (SELECT a FROM b)" will have a SubqueryFromClause referencing the subquery.
+ */
+public class SubqueryFromClause extends FromClause implements SubqueryContainer{
+
+ private GroupSymbol symbol;
+ private Command command;
+ private boolean table;
+
+ /**
+ * Construct default object
+ */
+ public SubqueryFromClause(String name) {
+ setName(name);
+ }
+
+ /**
+ * Construct object with specified command and name
+ * @param command Command representing subquery, or stored procedure
+ * @param name Alias of the subquery
+ */
+ public SubqueryFromClause(String name, Command command) {
+ this(name);
+ this.command = command;
+ }
+
+ public SubqueryFromClause(GroupSymbol symbol, Command command) {
+ this.symbol = symbol;
+ this.command = command;
+ }
+
+ public boolean isTable() {
+ return table;
+ }
+
+ public void setTable(boolean table) {
+ this.table = table;
+ }
+
+ /**
+ * Reset the alias for this subquery from clause and it's pseudo-GroupSymbol.
+ * WARNING: this will modify the hashCode and equals semantics and will cause this object
+ * to be lost if currently in a HashMap or HashSet.
+ * @param name New name
+ * @since 4.3
+ */
+ public void setName(String name) {
+ this.symbol = new GroupSymbol(name);
+ }
+
+ /**
+ * Set the command held by the clause
+ * @param command Command to hold
+ */
+ public void setCommand(Command command) {
+ this.command = command;
+ }
+
+ /**
+ * Get command held by clause
+ * @return Command held by clause
+ */
+ public Command getCommand() {
+ return this.command;
+ }
+
+ /**
+ * Get name of this clause.
+ * @return Name of clause
+ */
+ public String getName() {
+ return this.symbol.getName();
+ }
+
+ public String getOutputName() {
+ return this.symbol.getOutputName();
+ }
+
+ /**
+ * Get GroupSymbol representing the named subquery
+ * @return GroupSymbol representing the subquery
+ */
+ public GroupSymbol getGroupSymbol() {
+ return this.symbol;
+ }
+
+ /**
+ * Collect all GroupSymbols for this from clause.
+ * @param groups Groups to add to
+ */
+ public void collectGroups(Collection groups) {
+ groups.add(getGroupSymbol());
+ }
+
+ public void acceptVisitor(LanguageVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ /**
+ * Check whether objects are equal
+ * @param obj Other object
+ * @return True if equal
+ */
+ public boolean equals(Object obj) {
+ if (!super.equals(obj)) {
+ return false;
+ }
+
+ if(! (obj instanceof SubqueryFromClause)) {
+ return false;
+ }
+ SubqueryFromClause sfc = (SubqueryFromClause) obj;
+
+ return this.getName().equalsIgnoreCase(sfc.getName()) &&
+ sfc.isOptional() == this.isOptional() && this.command.equals(sfc.command)
+ && this.table == sfc.table;
+ }
+
+ /**
+ * Get hash code of object
+ * @return Hash code
+ */
+ public int hashCode() {
+ return this.symbol.hashCode();
+ }
+
+ /**
+ * Get deep clone of object
+ * @return Deep copy of the object
+ */
+ public FromClause cloneDirect() {
+ Command commandCopy = null;
+ if(this.command != null) {
+ commandCopy = (Command) this.command.clone();
+ }
+
+ SubqueryFromClause clause = new SubqueryFromClause(this.symbol.clone(), commandCopy);
+ clause.setTable(this.isTable());
+ return clause;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TableFunctionReference.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/lang/TableFunctionReference.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TableFunctionReference.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,173 +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.lang;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.EquivalenceUtil;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.util.SymbolMap;
-
-public abstract class TableFunctionReference extends FromClause {
-
- public static class ProjectedColumn {
- private String name;
- private String type;
- private ElementSymbol symbol;
-
- public ProjectedColumn(String name, String type) {
- this.name = name;
- this.type = type;
- this.symbol = new ElementSymbol(name);
- symbol.setType(DataTypeManager.getDataTypeClass(type));
- }
-
- protected ProjectedColumn() {
-
- }
-
- public ElementSymbol getSymbol() {
- return symbol;
- }
-
- public String getName() {
- return name;
- }
-
- public String getType() {
- return type;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (!(obj instanceof ProjectedColumn)) {
- return false;
- }
- ProjectedColumn other = (ProjectedColumn)obj;
- return this.symbol.equals(other.symbol)
- && this.name.equals(other.name)
- && this.type.equals(other.type);
- }
-
- public int hashCode() {
- return symbol.hashCode();
- }
-
- public ProjectedColumn copyTo(ProjectedColumn copy) {
- copy.name = this.name;
- copy.type = this.type;
- copy.symbol = (ElementSymbol)this.symbol.clone();
- return copy;
- }
-
- }
-
- private GroupSymbol symbol;
- private SymbolMap correlatedReferences;
-
- public SymbolMap getCorrelatedReferences() {
- return correlatedReferences;
- }
-
- public void setCorrelatedReferences(SymbolMap correlatedReferences) {
- this.correlatedReferences = correlatedReferences;
- }
-
- public void copy(TableFunctionReference copy) {
- copy.symbol = (GroupSymbol)this.symbol.clone();
- if (correlatedReferences != null) {
- copy.correlatedReferences = correlatedReferences.clone();
- }
- }
-
- @Override
- public void collectGroups(Collection groups) {
- groups.add(getGroupSymbol());
- }
-
- /**
- * Get name of this clause.
- * @return Name of clause
- */
- public String getName() {
- return this.symbol.getName();
- }
-
- public String getOutputName() {
- return this.symbol.getOutputName();
- }
-
- /**
- * Get GroupSymbol representing the named subquery
- * @return GroupSymbol representing the subquery
- */
- public GroupSymbol getGroupSymbol() {
- return this.symbol;
- }
-
- /**
- * Reset the alias for this subquery from clause and it's pseudo-GroupSymbol.
- * WARNING: this will modify the hashCode and equals semantics and will cause this object
- * to be lost if currently in a HashMap or HashSet.
- * @param name New name
- * @since 4.3
- */
- public void setName(String name) {
- this.symbol = new GroupSymbol(name);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (!(obj instanceof TableFunctionReference)) {
- return false;
- }
- TableFunctionReference other = (TableFunctionReference)obj;
- return EquivalenceUtil.areEqual(symbol, other.symbol);
- }
-
- @Override
- public int hashCode() {
- return this.symbol.hashCode();
- }
-
- public abstract List<? extends ProjectedColumn> getColumns();
-
- public List<ElementSymbol> getProjectedSymbols() {
- ArrayList<ElementSymbol> symbols = new ArrayList<ElementSymbol>(getColumns().size());
- for (ProjectedColumn col : getColumns()) {
- symbols.add(col.getSymbol());
- }
- return symbols;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TableFunctionReference.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/lang/TableFunctionReference.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TableFunctionReference.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TableFunctionReference.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,173 @@
+/*
+ * 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.lang;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.util.SymbolMap;
+
+public abstract class TableFunctionReference extends FromClause {
+
+ public static class ProjectedColumn {
+ private String name;
+ private String type;
+ private ElementSymbol symbol;
+
+ public ProjectedColumn(String name, String type) {
+ this.name = name;
+ this.type = type;
+ this.symbol = new ElementSymbol(name);
+ symbol.setType(DataTypeManager.getDataTypeClass(type));
+ }
+
+ protected ProjectedColumn() {
+
+ }
+
+ public ElementSymbol getSymbol() {
+ return symbol;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (!(obj instanceof ProjectedColumn)) {
+ return false;
+ }
+ ProjectedColumn other = (ProjectedColumn)obj;
+ return this.symbol.equals(other.symbol)
+ && this.name.equals(other.name)
+ && this.type.equals(other.type);
+ }
+
+ public int hashCode() {
+ return symbol.hashCode();
+ }
+
+ public ProjectedColumn copyTo(ProjectedColumn copy) {
+ copy.name = this.name;
+ copy.type = this.type;
+ copy.symbol = this.symbol.clone();
+ return copy;
+ }
+
+ }
+
+ private GroupSymbol symbol;
+ private SymbolMap correlatedReferences;
+
+ public SymbolMap getCorrelatedReferences() {
+ return correlatedReferences;
+ }
+
+ public void setCorrelatedReferences(SymbolMap correlatedReferences) {
+ this.correlatedReferences = correlatedReferences;
+ }
+
+ public void copy(TableFunctionReference copy) {
+ copy.symbol = this.symbol.clone();
+ if (correlatedReferences != null) {
+ copy.correlatedReferences = correlatedReferences.clone();
+ }
+ }
+
+ @Override
+ public void collectGroups(Collection<GroupSymbol> groups) {
+ groups.add(getGroupSymbol());
+ }
+
+ /**
+ * Get name of this clause.
+ * @return Name of clause
+ */
+ public String getName() {
+ return this.symbol.getName();
+ }
+
+ public String getOutputName() {
+ return this.symbol.getOutputName();
+ }
+
+ /**
+ * Get GroupSymbol representing the named subquery
+ * @return GroupSymbol representing the subquery
+ */
+ public GroupSymbol getGroupSymbol() {
+ return this.symbol;
+ }
+
+ /**
+ * Reset the alias for this subquery from clause and it's pseudo-GroupSymbol.
+ * WARNING: this will modify the hashCode and equals semantics and will cause this object
+ * to be lost if currently in a HashMap or HashSet.
+ * @param name New name
+ * @since 4.3
+ */
+ public void setName(String name) {
+ this.symbol = new GroupSymbol(name);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (!(obj instanceof TableFunctionReference)) {
+ return false;
+ }
+ TableFunctionReference other = (TableFunctionReference)obj;
+ return EquivalenceUtil.areEqual(symbol, other.symbol);
+ }
+
+ @Override
+ public int hashCode() {
+ return this.symbol.hashCode();
+ }
+
+ public abstract List<? extends ProjectedColumn> getColumns();
+
+ public List<ElementSymbol> getProjectedSymbols() {
+ ArrayList<ElementSymbol> symbols = new ArrayList<ElementSymbol>(getColumns().size());
+ for (ProjectedColumn col : getColumns()) {
+ symbols.add(col.getSymbol());
+ }
+ return symbols;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TextTable.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/lang/TextTable.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TextTable.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,192 +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.lang;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.teiid.core.util.EquivalenceUtil;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.symbol.Expression;
-
-/**
- * Represents the TEXTTABLE table function.
- */
-public class TextTable extends TableFunctionReference {
-
- public static class TextColumn extends ProjectedColumn {
- private Integer width;
-
- public TextColumn(String name, String type, Integer width) {
- super(name, type);
- this.width = width;
- }
-
- protected TextColumn() {
-
- }
-
- public Integer getWidth() {
- return width;
- }
-
- public void setWidth(Integer width) {
- this.width = width;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (!super.equals(obj) || !(obj instanceof TextColumn)) {
- return false;
- }
- TextColumn other = (TextColumn)obj;
- return EquivalenceUtil.areEqual(width, other.width);
- }
-
- @Override
- public TextColumn clone() {
- TextColumn clone = new TextColumn();
- clone.width = this.width;
- this.copyTo(clone);
- return clone;
- }
- }
-
- private Expression file;
- private List<TextColumn> columns = new ArrayList<TextColumn>();
- private Character delimiter;
- private Character quote;
- private boolean escape;
- private Integer header;
- private Integer skip;
-
- private boolean fixedWidth;
-
- public Character getQuote() {
- return quote;
- }
-
- public void setQuote(Character quote) {
- this.quote = quote;
- }
-
- public boolean isEscape() {
- return escape;
- }
-
- public void setEscape(boolean escape) {
- this.escape = escape;
- }
-
- public boolean isFixedWidth() {
- return fixedWidth;
- }
-
- public void setFixedWidth(boolean fixedWidth) {
- this.fixedWidth = fixedWidth;
- }
-
- public List<TextColumn> getColumns() {
- return columns;
- }
-
- public void setColumns(List<TextColumn> columns) {
- this.columns = columns;
- }
-
- public Character getDelimiter() {
- return delimiter;
- }
-
- public void setDelimiter(Character delimiter) {
- this.delimiter = delimiter;
- }
-
- public Integer getHeader() {
- return header;
- }
-
- public void setHeader(Integer header) {
- this.header = header;
- }
-
- public Integer getSkip() {
- return skip;
- }
-
- public void setSkip(Integer skip) {
- this.skip = skip;
- }
-
- public Expression getFile() {
- return file;
- }
-
- public void setFile(Expression file) {
- this.file = file;
- }
-
- @Override
- public void acceptVisitor(LanguageVisitor visitor) {
- visitor.visit(this);
- }
-
- @Override
- public TextTable clone() {
- TextTable clone = new TextTable();
- this.copy(clone);
- clone.setDelimiter(this.delimiter);
- clone.setFile((Expression)this.file.clone());
- clone.setHeader(this.header);
- clone.setSkip(this.skip);
- clone.setQuote(this.quote);
- clone.escape = this.escape;
- for (TextColumn column : columns) {
- clone.getColumns().add(column.clone());
- }
- clone.fixedWidth = this.fixedWidth;
- return clone;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (!super.equals(obj) || !(obj instanceof TextTable)) {
- return false;
- }
- TextTable other = (TextTable)obj;
- return this.columns.equals(other.columns)
- && EquivalenceUtil.areEqual(file, other.file)
- && EquivalenceUtil.areEqual(delimiter, other.delimiter)
- && EquivalenceUtil.areEqual(escape, other.escape)
- && EquivalenceUtil.areEqual(quote, other.quote)
- && EquivalenceUtil.areEqual(header, other.header)
- && EquivalenceUtil.areEqual(skip, other.skip);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TextTable.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/lang/TextTable.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TextTable.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/TextTable.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,192 @@
+/*
+ * 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.lang;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.symbol.Expression;
+
+/**
+ * Represents the TEXTTABLE table function.
+ */
+public class TextTable extends TableFunctionReference {
+
+ public static class TextColumn extends ProjectedColumn {
+ private Integer width;
+
+ public TextColumn(String name, String type, Integer width) {
+ super(name, type);
+ this.width = width;
+ }
+
+ protected TextColumn() {
+
+ }
+
+ public Integer getWidth() {
+ return width;
+ }
+
+ public void setWidth(Integer width) {
+ this.width = width;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (!super.equals(obj) || !(obj instanceof TextColumn)) {
+ return false;
+ }
+ TextColumn other = (TextColumn)obj;
+ return EquivalenceUtil.areEqual(width, other.width);
+ }
+
+ @Override
+ public TextColumn clone() {
+ TextColumn clone = new TextColumn();
+ clone.width = this.width;
+ this.copyTo(clone);
+ return clone;
+ }
+ }
+
+ private Expression file;
+ private List<TextColumn> columns = new ArrayList<TextColumn>();
+ private Character delimiter;
+ private Character quote;
+ private boolean escape;
+ private Integer header;
+ private Integer skip;
+
+ private boolean fixedWidth;
+
+ public Character getQuote() {
+ return quote;
+ }
+
+ public void setQuote(Character quote) {
+ this.quote = quote;
+ }
+
+ public boolean isEscape() {
+ return escape;
+ }
+
+ public void setEscape(boolean escape) {
+ this.escape = escape;
+ }
+
+ public boolean isFixedWidth() {
+ return fixedWidth;
+ }
+
+ public void setFixedWidth(boolean fixedWidth) {
+ this.fixedWidth = fixedWidth;
+ }
+
+ public List<TextColumn> getColumns() {
+ return columns;
+ }
+
+ public void setColumns(List<TextColumn> columns) {
+ this.columns = columns;
+ }
+
+ public Character getDelimiter() {
+ return delimiter;
+ }
+
+ public void setDelimiter(Character delimiter) {
+ this.delimiter = delimiter;
+ }
+
+ public Integer getHeader() {
+ return header;
+ }
+
+ public void setHeader(Integer header) {
+ this.header = header;
+ }
+
+ public Integer getSkip() {
+ return skip;
+ }
+
+ public void setSkip(Integer skip) {
+ this.skip = skip;
+ }
+
+ public Expression getFile() {
+ return file;
+ }
+
+ public void setFile(Expression file) {
+ this.file = file;
+ }
+
+ @Override
+ public void acceptVisitor(LanguageVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ @Override
+ protected TextTable cloneDirect() {
+ TextTable clone = new TextTable();
+ this.copy(clone);
+ clone.setDelimiter(this.delimiter);
+ clone.setFile((Expression)this.file.clone());
+ clone.setHeader(this.header);
+ clone.setSkip(this.skip);
+ clone.setQuote(this.quote);
+ clone.escape = this.escape;
+ for (TextColumn column : columns) {
+ clone.getColumns().add(column.clone());
+ }
+ clone.fixedWidth = this.fixedWidth;
+ return clone;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (!super.equals(obj) || !(obj instanceof TextTable)) {
+ return false;
+ }
+ TextTable other = (TextTable)obj;
+ return this.columns.equals(other.columns)
+ && EquivalenceUtil.areEqual(file, other.file)
+ && EquivalenceUtil.areEqual(delimiter, other.delimiter)
+ && EquivalenceUtil.areEqual(escape, other.escape)
+ && EquivalenceUtil.areEqual(quote, other.quote)
+ && EquivalenceUtil.areEqual(header, other.header)
+ && EquivalenceUtil.areEqual(skip, other.skip);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/UnaryFromClause.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/lang/UnaryFromClause.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/UnaryFromClause.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,153 +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.lang;
-
-import java.util.Collection;
-
-import org.teiid.core.util.EquivalenceUtil;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.symbol.GroupSymbol;
-
-
-/**
- * A FROM subpart that represents a single group. For example, the FROM clause:
- * "FROM a, b" will have two UnaryFromClause objects, each holding a reference to
- * a GroupSymbol (for a and b).
- */
-public class UnaryFromClause extends FromClause {
-
- private GroupSymbol group;
-
- private Command expandedCommand;
-
- /**
- * Construct default object
- */
- public UnaryFromClause() {
- }
-
- /**
- * Construct object with specified group
- * @param group Group being held
- */
- public UnaryFromClause(GroupSymbol group) {
- this.group = group;
- }
-
- /**
- * Set the group held by the clause
- * @param group Group to hold
- */
- public void setGroup(GroupSymbol group) {
- this.group = group;
- }
-
- /**
- * Get group held by clause
- * @return Group held by clause
- */
- public GroupSymbol getGroup() {
- return this.group;
- }
-
- /**
- * Collect all GroupSymbols for this from clause.
- * @param groups Groups to add to
- */
- public void collectGroups(Collection groups) {
- groups.add(this.group);
- }
-
- public void acceptVisitor(LanguageVisitor visitor) {
- visitor.visit(this);
- }
-
- /**
- * Check whether objects are equal
- * @param obj Other object
- * @return True if equal
- */
- public boolean equals(Object obj) {
- if (!super.equals(obj)) {
- return false;
- }
-
- if(! (obj instanceof UnaryFromClause)) {
- return false;
- }
-
- UnaryFromClause other = (UnaryFromClause)obj;
-
- if( (this.getGroup().getDefinition() == null && other.getGroup().getDefinition() == null) ||
- (this.getGroup().getDefinition() != null && other.getGroup().getDefinition() != null) ) {
- return EquivalenceUtil.areEqual(getGroup(), other.getGroup()) &&
- other.isOptional() == this.isOptional();
- }
- return false;
- }
-
- /**
- * Get hash code of object
- * @return Hash code
- */
- public int hashCode() {
- if(this.group == null) {
- return 0;
- }
- return this.group.hashCode();
- }
-
- /**
- * Get deep clone of object
- * @return Deep copy of the object
- */
- public Object clone() {
- GroupSymbol copyGroup = null;
- if(this.group != null) {
- copyGroup = (GroupSymbol) 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());
- }
- return clonedUnaryFromClause;
- }
-
- /**
- * @return Returns the expandedCommand.
- */
- public Command getExpandedCommand() {
- return this.expandedCommand;
- }
-
- /**
- * @param expandedCommand The expandedCommand to set.
- */
- public void setExpandedCommand(Command expandedCommand) {
- this.expandedCommand = expandedCommand;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/UnaryFromClause.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/lang/UnaryFromClause.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/UnaryFromClause.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/UnaryFromClause.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,150 @@
+/*
+ * 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.lang;
+
+import java.util.Collection;
+
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.symbol.GroupSymbol;
+
+
+/**
+ * A FROM subpart that represents a single group. For example, the FROM clause:
+ * "FROM a, b" will have two UnaryFromClause objects, each holding a reference to
+ * a GroupSymbol (for a and b).
+ */
+public class UnaryFromClause extends FromClause {
+
+ private GroupSymbol group;
+
+ private Command expandedCommand;
+
+ /**
+ * Construct default object
+ */
+ public UnaryFromClause() {
+ }
+
+ /**
+ * Construct object with specified group
+ * @param group Group being held
+ */
+ public UnaryFromClause(GroupSymbol group) {
+ this.group = group;
+ }
+
+ /**
+ * Set the group held by the clause
+ * @param group Group to hold
+ */
+ public void setGroup(GroupSymbol group) {
+ this.group = group;
+ }
+
+ /**
+ * Get group held by clause
+ * @return Group held by clause
+ */
+ public GroupSymbol getGroup() {
+ return this.group;
+ }
+
+ /**
+ * Collect all GroupSymbols for this from clause.
+ * @param groups Groups to add to
+ */
+ public void collectGroups(Collection<GroupSymbol> groups) {
+ groups.add(this.group);
+ }
+
+ public void acceptVisitor(LanguageVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ /**
+ * Check whether objects are equal
+ * @param obj Other object
+ * @return True if equal
+ */
+ public boolean equals(Object obj) {
+ if (!super.equals(obj)) {
+ return false;
+ }
+
+ if(! (obj instanceof UnaryFromClause)) {
+ return false;
+ }
+
+ UnaryFromClause other = (UnaryFromClause)obj;
+
+ if( (this.getGroup().getDefinition() == null && other.getGroup().getDefinition() == null) ||
+ (this.getGroup().getDefinition() != null && other.getGroup().getDefinition() != null) ) {
+ return EquivalenceUtil.areEqual(getGroup(), other.getGroup()) &&
+ other.isOptional() == this.isOptional();
+ }
+ return false;
+ }
+
+ /**
+ * Get hash code of object
+ * @return Hash code
+ */
+ public int hashCode() {
+ if(this.group == null) {
+ return 0;
+ }
+ return this.group.hashCode();
+ }
+
+ /**
+ * Get deep clone of object
+ * @return Deep copy of the object
+ */
+ public FromClause cloneDirect() {
+ GroupSymbol copyGroup = null;
+ if(this.group != null) {
+ copyGroup = this.group.clone();
+ }
+ UnaryFromClause clonedUnaryFromClause = new UnaryFromClause(copyGroup);
+ if (this.expandedCommand != null) {
+ clonedUnaryFromClause.setExpandedCommand((Command)this.expandedCommand.clone());
+ }
+ return clonedUnaryFromClause;
+ }
+
+ /**
+ * @return Returns the expandedCommand.
+ */
+ public Command getExpandedCommand() {
+ return this.expandedCommand;
+ }
+
+ /**
+ * @param expandedCommand The expandedCommand to set.
+ */
+ public void setExpandedCommand(Command expandedCommand) {
+ this.expandedCommand = expandedCommand;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/XMLTable.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/lang/XMLTable.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/XMLTable.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,224 +0,0 @@
-package org.teiid.query.sql.lang;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-
-import net.sf.saxon.sxpath.XPathExpression;
-
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.EquivalenceUtil;
-import org.teiid.query.sql.LanguageVisitor;
-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.XMLNamespaces;
-import org.teiid.query.xquery.saxon.SaxonXQueryExpression;
-
-public class XMLTable extends TableFunctionReference {
-
- public static class XMLColumn extends ProjectedColumn {
- private boolean ordinal;
- private String path;
- private Expression defaultExpression;
-
- private XPathExpression pathExpression;
-
- public XMLColumn(String name) {
- super(name, DataTypeManager.DefaultDataTypes.STRING);
- this.ordinal = true;
- }
-
- public XMLColumn(String name, String type, String path, Expression defaultExpression) {
- super(name, type);
- this.path = path;
- this.defaultExpression = defaultExpression;
- }
-
- protected XMLColumn() {
-
- }
-
- public Expression getDefaultExpression() {
- return defaultExpression;
- }
-
- public void setDefaultExpression(Expression defaultExpression) {
- this.defaultExpression = defaultExpression;
- }
-
- public String getPath() {
- return path;
- }
-
- public void setPath(String path) {
- this.path = path;
- }
-
- public boolean isOrdinal() {
- return ordinal;
- }
-
- public void setOrdinal(boolean ordinal) {
- this.ordinal = ordinal;
- }
-
- public void setPathExpression(XPathExpression pathExpression) {
- this.pathExpression = pathExpression;
- }
-
- public XPathExpression getPathExpression() {
- return pathExpression;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (!super.equals(obj) || !(obj instanceof XMLColumn)) {
- return false;
- }
- XMLColumn other = (XMLColumn)obj;
- return this.ordinal == other.ordinal
- && EquivalenceUtil.areEqual(this.path, other.path)
- && EquivalenceUtil.areEqual(this.defaultExpression, other.defaultExpression);
- }
-
- @Override
- public XMLColumn clone() {
- XMLColumn clone = new XMLColumn();
- super.copyTo(clone);
- clone.ordinal = this.ordinal;
- clone.path = this.path;
- if (this.defaultExpression != null) {
- clone.defaultExpression = (Expression)this.defaultExpression.clone();
- }
- clone.pathExpression = this.pathExpression;
- return clone;
- }
- }
-
- private List<XMLColumn> columns = new ArrayList<XMLColumn>();
- private XMLNamespaces namespaces;
- private String xquery;
- private List<DerivedColumn> passing = new ArrayList<DerivedColumn>();
- private XMLColumn defaultColumn;
-
- private SaxonXQueryExpression xqueryExpression;
-
- public List<DerivedColumn> getPassing() {
- return passing;
- }
-
- public void compileXqueryExpression() throws TeiidProcessingException {
- List<XMLColumn> cols = this.columns;
- if (cols.isEmpty()) {
- cols = Arrays.asList(defaultColumn);
- }
- this.xqueryExpression = new SaxonXQueryExpression(xquery, namespaces, passing, cols);
- }
-
- public SaxonXQueryExpression getXQueryExpression() {
- return xqueryExpression;
- }
-
- public void setPassing(List<DerivedColumn> passing) {
- this.passing = passing;
- }
-
- public String getXquery() {
- return xquery;
- }
-
- public void setXquery(String xquery) {
- this.xquery = xquery;
- }
-
- public List<XMLColumn> getColumns() {
- return columns;
- }
-
- public void setColumns(List<XMLColumn> columns) {
- this.columns = columns;
- }
-
- public XMLNamespaces getNamespaces() {
- return namespaces;
- }
-
- public void setNamespaces(XMLNamespaces namespaces) {
- this.namespaces = namespaces;
- }
-
- @Override
- public List<ElementSymbol> getProjectedSymbols() {
- if (!columns.isEmpty()) {
- return super.getProjectedSymbols();
- }
- if (defaultColumn == null) {
- defaultColumn = new XMLColumn("OBJECT_VALUE", DataTypeManager.DefaultDataTypes.XML, ".", null); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return Arrays.asList(defaultColumn.getSymbol());
- }
-
- @Override
- public void acceptVisitor(LanguageVisitor visitor) {
- visitor.visit(this);
- }
-
- @Override
- public XMLTable clone() {
- XMLTable clone = new XMLTable();
- this.copy(clone);
- for (XMLColumn column : columns) {
- clone.getColumns().add(column.clone());
- }
- if (defaultColumn != null) {
- clone.defaultColumn = this.defaultColumn;
- }
- if (this.namespaces != null) {
- clone.namespaces = this.namespaces.clone();
- }
- if (this.passing != null) {
- for (DerivedColumn col : this.passing) {
- clone.passing.add(col.clone());
- }
- }
- clone.xquery = this.xquery;
- if (this.xqueryExpression != null) {
- clone.xqueryExpression = this.xqueryExpression.clone();
- }
- return clone;
- }
-
- @Override
- public void collectGroups(Collection groups) {
- groups.add(getGroupSymbol());
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (!super.equals(obj) || !(obj instanceof XMLTable)) {
- return false;
- }
- XMLTable other = (XMLTable)obj;
- return this.columns.equals(other.columns)
- && EquivalenceUtil.areEqual(this.namespaces, other.namespaces)
- && this.xquery.equals(other.xquery)
- && this.passing.equals(other.passing);
- }
-
- public void rewriteDefaultColumn() {
- if (this.columns.isEmpty() && defaultColumn != null) {
- this.columns.add(defaultColumn);
- defaultColumn = null;
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/XMLTable.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/lang/XMLTable.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/XMLTable.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/XMLTable.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,218 @@
+package org.teiid.query.sql.lang;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import net.sf.saxon.sxpath.XPathExpression;
+
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.query.sql.LanguageVisitor;
+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.XMLNamespaces;
+import org.teiid.query.xquery.saxon.SaxonXQueryExpression;
+
+public class XMLTable extends TableFunctionReference {
+
+ public static class XMLColumn extends ProjectedColumn {
+ private boolean ordinal;
+ private String path;
+ private Expression defaultExpression;
+
+ private XPathExpression pathExpression;
+
+ public XMLColumn(String name) {
+ super(name, DataTypeManager.DefaultDataTypes.STRING);
+ this.ordinal = true;
+ }
+
+ public XMLColumn(String name, String type, String path, Expression defaultExpression) {
+ super(name, type);
+ this.path = path;
+ this.defaultExpression = defaultExpression;
+ }
+
+ protected XMLColumn() {
+
+ }
+
+ public Expression getDefaultExpression() {
+ return defaultExpression;
+ }
+
+ public void setDefaultExpression(Expression defaultExpression) {
+ this.defaultExpression = defaultExpression;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public void setPath(String path) {
+ this.path = path;
+ }
+
+ public boolean isOrdinal() {
+ return ordinal;
+ }
+
+ public void setOrdinal(boolean ordinal) {
+ this.ordinal = ordinal;
+ }
+
+ public void setPathExpression(XPathExpression pathExpression) {
+ this.pathExpression = pathExpression;
+ }
+
+ public XPathExpression getPathExpression() {
+ return pathExpression;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (!super.equals(obj) || !(obj instanceof XMLColumn)) {
+ return false;
+ }
+ XMLColumn other = (XMLColumn)obj;
+ return this.ordinal == other.ordinal
+ && EquivalenceUtil.areEqual(this.path, other.path)
+ && EquivalenceUtil.areEqual(this.defaultExpression, other.defaultExpression);
+ }
+
+ @Override
+ public XMLColumn clone() {
+ XMLColumn clone = new XMLColumn();
+ super.copyTo(clone);
+ clone.ordinal = this.ordinal;
+ clone.path = this.path;
+ if (this.defaultExpression != null) {
+ clone.defaultExpression = (Expression)this.defaultExpression.clone();
+ }
+ clone.pathExpression = this.pathExpression;
+ return clone;
+ }
+ }
+
+ private List<XMLColumn> columns = new ArrayList<XMLColumn>();
+ private XMLNamespaces namespaces;
+ private String xquery;
+ private List<DerivedColumn> passing = new ArrayList<DerivedColumn>();
+ private XMLColumn defaultColumn;
+
+ private SaxonXQueryExpression xqueryExpression;
+
+ public List<DerivedColumn> getPassing() {
+ return passing;
+ }
+
+ public void compileXqueryExpression() throws TeiidProcessingException {
+ List<XMLColumn> cols = this.columns;
+ if (cols.isEmpty()) {
+ cols = Arrays.asList(defaultColumn);
+ }
+ this.xqueryExpression = new SaxonXQueryExpression(xquery, namespaces, passing, cols);
+ }
+
+ public SaxonXQueryExpression getXQueryExpression() {
+ return xqueryExpression;
+ }
+
+ public void setPassing(List<DerivedColumn> passing) {
+ this.passing = passing;
+ }
+
+ public String getXquery() {
+ return xquery;
+ }
+
+ public void setXquery(String xquery) {
+ this.xquery = xquery;
+ }
+
+ public List<XMLColumn> getColumns() {
+ return columns;
+ }
+
+ public void setColumns(List<XMLColumn> columns) {
+ this.columns = columns;
+ }
+
+ public XMLNamespaces getNamespaces() {
+ return namespaces;
+ }
+
+ public void setNamespaces(XMLNamespaces namespaces) {
+ this.namespaces = namespaces;
+ }
+
+ @Override
+ public List<ElementSymbol> getProjectedSymbols() {
+ if (!columns.isEmpty()) {
+ return super.getProjectedSymbols();
+ }
+ if (defaultColumn == null) {
+ defaultColumn = new XMLColumn("OBJECT_VALUE", DataTypeManager.DefaultDataTypes.XML, ".", null); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return Arrays.asList(defaultColumn.getSymbol());
+ }
+
+ @Override
+ public void acceptVisitor(LanguageVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ @Override
+ protected XMLTable cloneDirect() {
+ XMLTable clone = new XMLTable();
+ this.copy(clone);
+ for (XMLColumn column : columns) {
+ clone.getColumns().add(column.clone());
+ }
+ if (defaultColumn != null) {
+ clone.defaultColumn = this.defaultColumn;
+ }
+ if (this.namespaces != null) {
+ clone.namespaces = this.namespaces.clone();
+ }
+ if (this.passing != null) {
+ for (DerivedColumn col : this.passing) {
+ clone.passing.add(col.clone());
+ }
+ }
+ clone.xquery = this.xquery;
+ if (this.xqueryExpression != null) {
+ clone.xqueryExpression = this.xqueryExpression.clone();
+ }
+ return clone;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (!super.equals(obj) || !(obj instanceof XMLTable)) {
+ return false;
+ }
+ XMLTable other = (XMLTable)obj;
+ return this.columns.equals(other.columns)
+ && EquivalenceUtil.areEqual(this.namespaces, other.namespaces)
+ && this.xquery.equals(other.xquery)
+ && this.passing.equals(other.passing);
+ }
+
+ public void rewriteDefaultColumn() {
+ if (this.columns.isEmpty() && defaultColumn != null) {
+ this.columns.add(defaultColumn);
+ defaultColumn = null;
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/util/ValueIteratorSource.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/util/ValueIteratorSource.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/util/ValueIteratorSource.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,54 +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.util;
-
-import java.util.Set;
-
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.query.sql.symbol.Expression;
-
-
-
-/**
- * The ValueIteratorSource lets a language object that needs a ValueIterator hold this
- * reference to the source of the ValueIterator as a reference until the ValueIterator
- * can be ready.
- *
- * @since 5.0.1
- */
-public interface ValueIteratorSource {
-
- /**
- * Attempt to obtain a ValueIterator from this source. If the iterator is
- * not ready yet, return null to indicate that.
- * @param valueExpression The expression we are retrieving an iterator for
- * @return ValueIterator if ready, null otherwise
- * @throws TeiidComponentException
- * @since 5.0.1
- */
- ValueIterator getValueIterator(Expression valueExpression) throws TeiidComponentException;
-
- Set<Object> getCachedSet(Expression valueExpression) throws TeiidComponentException, TeiidProcessingException;
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/util/ValueIteratorSource.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/util/ValueIteratorSource.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/util/ValueIteratorSource.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/util/ValueIteratorSource.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,58 @@
+/*
+ * 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.util;
+
+import java.util.Set;
+
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.query.sql.symbol.Expression;
+
+
+
+/**
+ * The ValueIteratorSource lets a language object that needs a ValueIterator hold this
+ * reference to the source of the ValueIterator as a reference until the ValueIterator
+ * can be ready.
+ *
+ * @since 5.0.1
+ */
+public interface ValueIteratorSource {
+
+ /**
+ * Attempt to obtain a ValueIterator from this source. If the iterator is
+ * not ready yet, return null to indicate that.
+ * @param valueExpression The expression we are retrieving an iterator for
+ * @return ValueIterator if ready, null otherwise
+ * @throws TeiidComponentException
+ * @since 5.0.1
+ */
+ ValueIterator getValueIterator(Expression valueExpression) throws TeiidComponentException;
+
+ Set<Object> getCachedSet(Expression valueExpression) throws TeiidComponentException, TeiidProcessingException;
+
+ void setUnused(boolean unused);
+
+ boolean isUnused();
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/PredicateCollectorVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/visitor/PredicateCollectorVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/PredicateCollectorVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,155 +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.visitor;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.lang.*;
-import org.teiid.query.sql.navigator.PreOrderNavigator;
-
-
-/**
- * <p>Walk a tree of language objects and collect any predicate criteria that are found.
- * A predicate criteria is of the following types: </p>
- *
- * <ul>
- * <li>{@link org.teiid.query.sql.lang.CompareCriteria} CompareCriteria</li>
- * <li>{@link org.teiid.query.sql.lang.MatchCriteria} MatchCriteria</li>
- * <li>{@link org.teiid.query.sql.lang.SetCriteria} SetCriteria</li>
- * <li>{@link org.teiid.query.sql.lang.SubquerySetCriteria} SubquerySetCriteria</li>
- * <li>{@link org.teiid.query.sql.lang.IsNullCriteria} IsNullCriteria</li>
- * </ul>
- */
-public class PredicateCollectorVisitor extends LanguageVisitor {
-
- private Collection predicates;
-
- /**
- * Construct a new visitor with the default collection type, which is a
- * {@link java.util.ArrayList}.
- */
- public PredicateCollectorVisitor() {
- this.predicates = new ArrayList();
- }
-
- /**
- * Visit a language object and collect criteria. This method should <b>NOT</b> be
- * called directly.
- * @param obj Language object
- */
- public void visit(BetweenCriteria obj) {
- this.predicates.add(obj);
- }
-
- /**
- * Visit a language object and collect criteria. This method should <b>NOT</b> be
- * called directly.
- * @param obj Language object
- */
- public void visit(CompareCriteria obj) {
- this.predicates.add(obj);
- }
-
- /**
- * Visit a language object and collect criteria. This method should <b>NOT</b> be
- * called directly.
- * @param obj Language object
- */
- public void visit(IsNullCriteria obj) {
- this.predicates.add(obj);
- }
-
- /**
- * Visit a language object and collect criteria. This method should <b>NOT</b> be
- * called directly.
- * @param obj Language object
- */
- public void visit(MatchCriteria obj) {
- this.predicates.add(obj);
- }
-
- /**
- * Visit a language object and collect criteria. This method should <b>NOT</b> be
- * called directly.
- * @param obj Language object
- */
- public void visit(SetCriteria obj) {
- this.predicates.add(obj);
- }
-
- /**
- * Visit a language object and collect criteria. This method should <b>NOT</b> be
- * called directly.
- * @param obj Language object
- */
- public void visit(DependentSetCriteria obj) {
- this.predicates.add(obj);
- }
-
- /**
- * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.ExistsCriteria)
- */
- public void visit(ExistsCriteria obj) {
- this.predicates.add(obj);
- }
-
- /**
- * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.SubqueryCompareCriteria)
- */
- public void visit(SubqueryCompareCriteria obj) {
- this.predicates.add(obj);
- }
-
- /**
- * Visit a language object and collect criteria. This method should <b>NOT</b> be
- * called directly.
- * @param obj Language object
- */
- public void visit(SubquerySetCriteria obj) {
- this.predicates.add(obj);
- }
-
- /**
- * Get a collection of predicates discovered while visiting.
- * @return Collection of {@link org.teiid.query.sql.lang.PredicateCriteria} subclasses.
- */
- public Collection getPredicates() {
- return this.predicates;
- }
-
- /**
- * Helper to quickly get the predicates from obj
- * @param obj Language object
- */
- public static final Collection getPredicates(LanguageObject obj) {
- PredicateCollectorVisitor visitor = new PredicateCollectorVisitor();
- if(obj != null) {
- PreOrderNavigator.doVisit(obj, visitor);
- }
- return visitor.getPredicates();
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/PredicateCollectorVisitor.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/visitor/PredicateCollectorVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/PredicateCollectorVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/PredicateCollectorVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,155 @@
+/*
+ * 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.visitor;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.lang.*;
+import org.teiid.query.sql.navigator.PreOrderNavigator;
+
+
+/**
+ * <p>Walk a tree of language objects and collect any predicate criteria that are found.
+ * A predicate criteria is of the following types: </p>
+ *
+ * <ul>
+ * <li>{@link org.teiid.query.sql.lang.CompareCriteria} CompareCriteria</li>
+ * <li>{@link org.teiid.query.sql.lang.MatchCriteria} MatchCriteria</li>
+ * <li>{@link org.teiid.query.sql.lang.SetCriteria} SetCriteria</li>
+ * <li>{@link org.teiid.query.sql.lang.SubquerySetCriteria} SubquerySetCriteria</li>
+ * <li>{@link org.teiid.query.sql.lang.IsNullCriteria} IsNullCriteria</li>
+ * </ul>
+ */
+public class PredicateCollectorVisitor extends LanguageVisitor {
+
+ 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<Criteria>();
+ }
+
+ /**
+ * Visit a language object and collect criteria. This method should <b>NOT</b> be
+ * called directly.
+ * @param obj Language object
+ */
+ public void visit(BetweenCriteria obj) {
+ this.predicates.add(obj);
+ }
+
+ /**
+ * Visit a language object and collect criteria. This method should <b>NOT</b> be
+ * called directly.
+ * @param obj Language object
+ */
+ public void visit(CompareCriteria obj) {
+ this.predicates.add(obj);
+ }
+
+ /**
+ * Visit a language object and collect criteria. This method should <b>NOT</b> be
+ * called directly.
+ * @param obj Language object
+ */
+ public void visit(IsNullCriteria obj) {
+ this.predicates.add(obj);
+ }
+
+ /**
+ * Visit a language object and collect criteria. This method should <b>NOT</b> be
+ * called directly.
+ * @param obj Language object
+ */
+ public void visit(MatchCriteria obj) {
+ this.predicates.add(obj);
+ }
+
+ /**
+ * Visit a language object and collect criteria. This method should <b>NOT</b> be
+ * called directly.
+ * @param obj Language object
+ */
+ public void visit(SetCriteria obj) {
+ this.predicates.add(obj);
+ }
+
+ /**
+ * Visit a language object and collect criteria. This method should <b>NOT</b> be
+ * called directly.
+ * @param obj Language object
+ */
+ public void visit(DependentSetCriteria obj) {
+ this.predicates.add(obj);
+ }
+
+ /**
+ * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.ExistsCriteria)
+ */
+ public void visit(ExistsCriteria obj) {
+ this.predicates.add(obj);
+ }
+
+ /**
+ * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.SubqueryCompareCriteria)
+ */
+ public void visit(SubqueryCompareCriteria obj) {
+ this.predicates.add(obj);
+ }
+
+ /**
+ * Visit a language object and collect criteria. This method should <b>NOT</b> be
+ * called directly.
+ * @param obj Language object
+ */
+ public void visit(SubquerySetCriteria obj) {
+ this.predicates.add(obj);
+ }
+
+ /**
+ * Get a collection of predicates discovered while visiting.
+ * @return Collection of {@link org.teiid.query.sql.lang.PredicateCriteria} subclasses.
+ */
+ public Collection<Criteria> getPredicates() {
+ return this.predicates;
+ }
+
+ /**
+ * Helper to quickly get the predicates from obj
+ * @param obj Language object
+ */
+ public static final Collection<Criteria> getPredicates(LanguageObject obj) {
+ PredicateCollectorVisitor visitor = new PredicateCollectorVisitor();
+ if(obj != null) {
+ PreOrderNavigator.doVisit(obj, visitor);
+ }
+ return visitor.getPredicates();
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,2052 +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.visitor;
-
-import static org.teiid.language.SQLConstants.Reserved.*;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.StringUtil;
-import org.teiid.language.SQLConstants;
-import org.teiid.language.SQLConstants.NonReserved;
-import org.teiid.language.SQLConstants.Tokens;
-import org.teiid.metadata.Column;
-import org.teiid.metadata.BaseColumn.NullType;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.lang.AlterProcedure;
-import org.teiid.query.sql.lang.AlterTrigger;
-import org.teiid.query.sql.lang.AlterView;
-import org.teiid.query.sql.lang.ArrayTable;
-import org.teiid.query.sql.lang.AtomicCriteria;
-import org.teiid.query.sql.lang.BetweenCriteria;
-import org.teiid.query.sql.lang.CacheHint;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Create;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.DependentSetCriteria;
-import org.teiid.query.sql.lang.Drop;
-import org.teiid.query.sql.lang.DynamicCommand;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.ExpressionCriteria;
-import org.teiid.query.sql.lang.From;
-import org.teiid.query.sql.lang.FromClause;
-import org.teiid.query.sql.lang.GroupBy;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.Into;
-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.Option;
-import org.teiid.query.sql.lang.OrderBy;
-import org.teiid.query.sql.lang.OrderByItem;
-import org.teiid.query.sql.lang.PredicateCriteria;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.lang.SetClause;
-import org.teiid.query.sql.lang.SetClauseList;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.SubqueryCompareCriteria;
-import org.teiid.query.sql.lang.SubqueryFromClause;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.lang.TextTable;
-import org.teiid.query.sql.lang.UnaryFromClause;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.lang.WithQueryCommand;
-import org.teiid.query.sql.lang.XMLTable;
-import org.teiid.query.sql.lang.ExistsCriteria.SubqueryHint;
-import org.teiid.query.sql.lang.TableFunctionReference.ProjectedColumn;
-import org.teiid.query.sql.lang.TextTable.TextColumn;
-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.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;
-import org.teiid.query.sql.proc.HasCriteria;
-import org.teiid.query.sql.proc.IfStatement;
-import org.teiid.query.sql.proc.LoopStatement;
-import org.teiid.query.sql.proc.RaiseErrorStatement;
-import org.teiid.query.sql.proc.Statement;
-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.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;
-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;
-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.SelectSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.symbol.TextLine;
-import org.teiid.query.sql.symbol.XMLAttributes;
-import org.teiid.query.sql.symbol.XMLElement;
-import org.teiid.query.sql.symbol.XMLForest;
-import org.teiid.query.sql.symbol.XMLNamespaces;
-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.XMLNamespaces.NamespaceItem;
-import org.teiid.translator.SourceSystemFunctions;
-
-/**
- * <p>
- * The SQLStringVisitor will visit a set of language objects and return the corresponding SQL string representation.
- * </p>
- */
-public class SQLStringVisitor extends LanguageVisitor {
-
- public static final String UNDEFINED = "<undefined>"; //$NON-NLS-1$
- private static final String SPACE = " "; //$NON-NLS-1$
- private static final String BEGIN_HINT = "/*+"; //$NON-NLS-1$
- private static final String END_HINT = "*/"; //$NON-NLS-1$
- private static final char ID_ESCAPE_CHAR = '\"';
- protected StringBuilder parts = new StringBuilder();
-
- /**
- * Helper to quickly get the parser string for an object using the visitor.
- *
- * @param obj Language object
- * @return String SQL String for obj
- */
- public static final String getSQLString( LanguageObject obj ) {
- if (obj == null) {
- return UNDEFINED;
- }
- SQLStringVisitor visitor = new SQLStringVisitor();
- obj.acceptVisitor(visitor);
- return visitor.getSQLString();
- }
-
- /**
- * Retrieve completed string from the visitor.
- *
- * @return Complete SQL string for the visited nodes
- */
- public String getSQLString() {
- return this.parts.toString();
- }
-
- protected void visitNode( LanguageObject obj ) {
- if (obj == null) {
- append(UNDEFINED);
- return;
- }
- obj.acceptVisitor(this);
- }
-
- protected void append( Object value ) {
- this.parts.append(value);
- }
-
- protected void beginClause( @SuppressWarnings("unused") int level ) {
- append(SPACE);
- }
-
- // ############ Visitor methods for language objects ####################
-
- public void visit( BetweenCriteria obj ) {
- visitNode(obj.getExpression());
- append(SPACE);
-
- if (obj.isNegated()) {
- append(NOT);
- append(SPACE);
- }
- append(BETWEEN);
- append(SPACE);
- visitNode(obj.getLowerExpression());
-
- append(SPACE);
- append(AND);
- append(SPACE);
- visitNode(obj.getUpperExpression());
- }
-
- public void visit( CaseExpression obj ) {
- append(CASE);
- append(SPACE);
- visitNode(obj.getExpression());
- append(SPACE);
-
- for (int i = 0; i < obj.getWhenCount(); i++) {
- append(WHEN);
- append(SPACE);
- visitNode(obj.getWhenExpression(i));
- append(SPACE);
- append(THEN);
- append(SPACE);
- visitNode(obj.getThenExpression(i));
- append(SPACE);
- }
-
- if (obj.getElseExpression() != null) {
- append(ELSE);
- append(SPACE);
- visitNode(obj.getElseExpression());
- append(SPACE);
- }
- append(END);
- }
-
- public void visit( CompareCriteria obj ) {
- Expression leftExpression = obj.getLeftExpression();
- visitNode(leftExpression);
- append(SPACE);
- append(obj.getOperatorAsString());
- append(SPACE);
- Expression rightExpression = obj.getRightExpression();
- visitNode(rightExpression);
- }
-
- public void visit( CompoundCriteria obj ) {
- // Get operator string
- int operator = obj.getOperator();
- String operatorStr = ""; //$NON-NLS-1$
- if (operator == CompoundCriteria.AND) {
- operatorStr = AND;
- } else if (operator == CompoundCriteria.OR) {
- operatorStr = OR;
- }
-
- // Get criteria
- List<Criteria> subCriteria = obj.getCriteria();
-
- // Build parts
- if (subCriteria.size() == 1) {
- // Special case - should really never happen, but we are tolerant
- Criteria firstChild = subCriteria.get(0);
- visitNode(firstChild);
- } else {
- // Add first criteria
- Iterator<Criteria> iter = subCriteria.iterator();
-
- while (iter.hasNext()) {
- // Add criteria
- Criteria crit = iter.next();
- append(Tokens.LPAREN);
- visitNode(crit);
- append(Tokens.RPAREN);
-
- if (iter.hasNext()) {
- // Add connector
- append(SPACE);
- append(operatorStr);
- append(SPACE);
- }
- }
- }
- }
-
- public void visit( Delete obj ) {
- // add delete clause
- append(DELETE);
- append(SPACE);
- // add from clause
- append(FROM);
- append(SPACE);
- visitNode(obj.getGroup());
-
- // add where clause
- if (obj.getCriteria() != null) {
- beginClause(0);
- visitCriteria(WHERE, obj.getCriteria());
- }
-
- // Option clause
- if (obj.getOption() != null) {
- beginClause(0);
- visitNode(obj.getOption());
- }
- }
-
- public void visit( DependentSetCriteria obj ) {
- visitNode(obj.getExpression());
-
- // operator and beginning of list
- append(SPACE);
- if (obj.isNegated()) {
- append(NOT);
- append(SPACE);
- }
- append(IN);
- append(" (<dependent values>)"); //$NON-NLS-1$
- }
-
- public void visit( From obj ) {
- append(FROM);
- beginClause(1);
- registerNodes(obj.getClauses(), 0);
- }
-
- public void visit( GroupBy obj ) {
- append(GROUP);
- append(SPACE);
- append(BY);
- append(SPACE);
- registerNodes(obj.getSymbols(), 0);
- }
-
- public void visit( Insert obj ) {
- append(INSERT);
- append(SPACE);
- append(INTO);
- append(SPACE);
- visitNode(obj.getGroup());
-
- if (!obj.getVariables().isEmpty()) {
- beginClause(2);
-
- // Columns clause
- List vars = obj.getVariables();
- if (vars != null) {
- append("("); //$NON-NLS-1$
- registerNodes(vars, 0);
- append(")"); //$NON-NLS-1$
- }
- }
- beginClause(1);
- if (obj.getQueryExpression() != null) {
- visitNode(obj.getQueryExpression());
- } else if (obj.getTupleSource() != null) {
- append(VALUES);
- append(" (...)"); //$NON-NLS-1$
- } else if (obj.getValues() != null) {
- append(VALUES);
- beginClause(2);
- append("("); //$NON-NLS-1$
- registerNodes(obj.getValues(), 0);
- append(")"); //$NON-NLS-1$
- }
-
- // Option clause
- if (obj.getOption() != null) {
- beginClause(1);
- visitNode(obj.getOption());
- }
- }
-
- public void visit( Create obj ) {
- append(CREATE);
- append(SPACE);
- append(LOCAL);
- append(SPACE);
- append(TEMPORARY);
- append(SPACE);
- append(TABLE);
- append(SPACE);
- visitNode(obj.getTable());
- append(SPACE);
-
- // Columns clause
- List<Column> columns = obj.getColumns();
- append("("); //$NON-NLS-1$
- Iterator<Column> iter = columns.iterator();
- while (iter.hasNext()) {
- Column element = iter.next();
- outputDisplayName(element.getName());
- append(SPACE);
- if (element.isAutoIncremented()) {
- append(NonReserved.SERIAL);
- } else {
- append(element.getRuntimeType());
- if (element.getNullType() == NullType.No_Nulls) {
- append(NOT);
- append(SPACE);
- append(NULL);
- }
- }
- if (iter.hasNext()) {
- append(", "); //$NON-NLS-1$
- }
- }
- if (!obj.getPrimaryKey().isEmpty()) {
- append(", "); //$NON-NLS-1$
- append(PRIMARY);
- append(" "); //$NON-NLS-1$
- append(NonReserved.KEY);
- append(Tokens.LPAREN);
- Iterator<ElementSymbol> pkiter = obj.getPrimaryKey().iterator();
- while (pkiter.hasNext()) {
- outputShortName(pkiter.next());
- if (pkiter.hasNext()) {
- append(", "); //$NON-NLS-1$
- }
- }
- append(Tokens.RPAREN);
- }
- append(")"); //$NON-NLS-1$
- }
-
- public void visit( Drop obj ) {
- append(DROP);
- append(SPACE);
- append(TABLE);
- append(SPACE);
- visitNode(obj.getTable());
- }
-
- public void visit( IsNullCriteria obj ) {
- Expression expr = obj.getExpression();
- visitNode(expr);
- append(SPACE);
- append(IS);
- append(SPACE);
- if (obj.isNegated()) {
- append(NOT);
- append(SPACE);
- }
- append(NULL);
- }
-
- public void visit( JoinPredicate obj ) {
- addOptionComment(obj);
-
- if (obj.hasHint()) {
- append("(");//$NON-NLS-1$
- }
-
- // left clause
- FromClause leftClause = obj.getLeftClause();
- if (leftClause instanceof JoinPredicate && !((JoinPredicate)leftClause).hasHint()) {
- append("("); //$NON-NLS-1$
- visitNode(leftClause);
- append(")"); //$NON-NLS-1$
- } else {
- visitNode(leftClause);
- }
-
- // join type
- append(SPACE);
- visitNode(obj.getJoinType());
- append(SPACE);
-
- // right clause
- FromClause rightClause = obj.getRightClause();
- if (rightClause instanceof JoinPredicate && !((JoinPredicate)rightClause).hasHint()) {
- append("("); //$NON-NLS-1$
- visitNode(rightClause);
- append(")"); //$NON-NLS-1$
- } else {
- visitNode(rightClause);
- }
-
- // join criteria
- List joinCriteria = obj.getJoinCriteria();
- if (joinCriteria != null && joinCriteria.size() > 0) {
- append(SPACE);
- append(ON);
- append(SPACE);
- Iterator critIter = joinCriteria.iterator();
- while (critIter.hasNext()) {
- Criteria crit = (Criteria)critIter.next();
- if (crit instanceof PredicateCriteria || crit instanceof AtomicCriteria) {
- visitNode(crit);
- } else {
- append("("); //$NON-NLS-1$
- visitNode(crit);
- append(")"); //$NON-NLS-1$
- }
-
- if (critIter.hasNext()) {
- append(SPACE);
- append(AND);
- append(SPACE);
- }
- }
- }
-
- if (obj.hasHint()) {
- append(")"); //$NON-NLS-1$
- }
- addFromClasueDepOptions(obj);
- }
-
- private void addFromClasueDepOptions( FromClause obj ) {
- if (obj.isMakeDep()) {
- 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);
- append(END_HINT);
- append(SPACE);
- }
- }
-
- public void visit( JoinType obj ) {
- String[] output = null;
- if (obj.equals(JoinType.JOIN_INNER)) {
- output = new String[] {INNER, SPACE, JOIN};
- } else if (obj.equals(JoinType.JOIN_CROSS)) {
- output = new String[] {CROSS, SPACE, JOIN};
- } else if (obj.equals(JoinType.JOIN_LEFT_OUTER)) {
- output = new String[] {LEFT, SPACE, OUTER, SPACE, JOIN};
- } else if (obj.equals(JoinType.JOIN_RIGHT_OUTER)) {
- output = new String[] {RIGHT, SPACE, OUTER, SPACE, JOIN};
- } else if (obj.equals(JoinType.JOIN_FULL_OUTER)) {
- output = new String[] {FULL, SPACE, OUTER, SPACE, JOIN};
- } else if (obj.equals(JoinType.JOIN_UNION)) {
- output = new String[] {UNION, SPACE, JOIN};
- } else if (obj.equals(JoinType.JOIN_SEMI)) {
- output = new String[] {"SEMI", SPACE, JOIN}; //$NON-NLS-1$
- } else if (obj.equals(JoinType.JOIN_ANTI_SEMI)) {
- output = new String[] {"ANTI SEMI", SPACE, JOIN}; //$NON-NLS-1$
- } else {
- throw new AssertionError();
- }
- for (String part : output) {
- append(part);
- }
- }
-
- public void visit( MatchCriteria obj ) {
- visitNode(obj.getLeftExpression());
-
- append(SPACE);
- if (obj.isNegated()) {
- append(NOT);
- append(SPACE);
- }
- append(LIKE);
- append(SPACE);
-
- visitNode(obj.getRightExpression());
-
- if (obj.getEscapeChar() != MatchCriteria.NULL_ESCAPE_CHAR) {
- append(SPACE);
- append(ESCAPE);
- append(" '"); //$NON-NLS-1$
- append("" + obj.getEscapeChar()); //$NON-NLS-1$
- append("'"); //$NON-NLS-1$
- }
- }
-
- public void visit( NotCriteria obj ) {
- append(NOT);
- append(" ("); //$NON-NLS-1$
- visitNode(obj.getCriteria());
- append(")"); //$NON-NLS-1$
- }
-
- public void visit( Option obj ) {
- append(OPTION);
-
- Collection groups = obj.getDependentGroups();
- if (groups != null && groups.size() > 0) {
- append(" "); //$NON-NLS-1$
- append(MAKEDEP);
- append(" "); //$NON-NLS-1$
-
- Iterator iter = groups.iterator();
-
- while (iter.hasNext()) {
- outputDisplayName((String)iter.next());
-
- if (iter.hasNext()) {
- append(", ");//$NON-NLS-1$
- }
- }
- }
-
- groups = obj.getNotDependentGroups();
- if (groups != null && groups.size() > 0) {
- append(" "); //$NON-NLS-1$
- append(MAKENOTDEP);
- append(" "); //$NON-NLS-1$
-
- Iterator iter = groups.iterator();
-
- while (iter.hasNext()) {
- outputDisplayName((String)iter.next());
-
- if (iter.hasNext()) {
- append(", ");//$NON-NLS-1$
- }
- }
- }
-
- groups = obj.getNoCacheGroups();
- if (groups != null && groups.size() > 0) {
- append(" "); //$NON-NLS-1$
- append(NOCACHE);
- append(" "); //$NON-NLS-1$
-
- Iterator iter = groups.iterator();
-
- while (iter.hasNext()) {
- outputDisplayName((String)iter.next());
-
- if (iter.hasNext()) {
- append(", ");//$NON-NLS-1$
- }
- }
- } else if (obj.isNoCache()) {
- append(" "); //$NON-NLS-1$
- append(NOCACHE);
- }
-
- }
-
- public void visit( OrderBy obj ) {
- append(ORDER);
- append(SPACE);
- append(BY);
- append(SPACE);
- registerNodes(obj.getOrderByItems(), 0);
- }
-
- @Override
- public void visit( OrderByItem obj ) {
- SingleElementSymbol ses = obj.getSymbol();
- if (ses instanceof AliasSymbol) {
- AliasSymbol as = (AliasSymbol)ses;
- outputDisplayName(as.getOutputName());
- } else {
- visitNode(ses);
- }
- if (!obj.isAscending()) {
- append(SPACE);
- append(DESC);
- } // Don't print default "ASC"
- if (obj.getNullOrdering() != null) {
- append(SPACE);
- append(NonReserved.NULLS);
- append(SPACE);
- append(obj.getNullOrdering().name());
- }
- }
-
- public void visit( DynamicCommand obj ) {
- append(EXECUTE);
- append(SPACE);
- visitNode(obj.getSql());
-
- if (obj.isAsClauseSet()) {
- beginClause(1);
- append(AS);
- append(SPACE);
- for (int i = 0; i < obj.getAsColumns().size(); i++) {
- ElementSymbol symbol = (ElementSymbol)obj.getAsColumns().get(i);
- outputShortName(symbol);
- append(SPACE);
- append(DataTypeManager.getDataTypeName(symbol.getType()));
- if (i < obj.getAsColumns().size() - 1) {
- append(", "); //$NON-NLS-1$
- }
- }
- }
-
- if (obj.getIntoGroup() != null) {
- beginClause(1);
- append(INTO);
- append(SPACE);
- visitNode(obj.getIntoGroup());
- }
-
- if (obj.getUsing() != null && !obj.getUsing().isEmpty()) {
- beginClause(1);
- append(USING);
- append(SPACE);
- visitNode(obj.getUsing());
- }
-
- if (obj.getUpdatingModelCount() > 0) {
- beginClause(1);
- append(UPDATE);
- append(SPACE);
- if (obj.getUpdatingModelCount() > 1) {
- append("*"); //$NON-NLS-1$
- } else {
- append("1"); //$NON-NLS-1$
- }
- }
- }
-
- public void visit( SetClauseList obj ) {
- for (Iterator<SetClause> iterator = obj.getClauses().iterator(); iterator.hasNext();) {
- SetClause clause = iterator.next();
- visitNode(clause);
- if (iterator.hasNext()) {
- append(", "); //$NON-NLS-1$
- }
- }
- }
-
- public void visit( SetClause obj ) {
- ElementSymbol symbol = obj.getSymbol();
- outputShortName(symbol);
- append(" = "); //$NON-NLS-1$
- visitNode(obj.getValue());
- }
-
- @Override
- public void visit(WithQueryCommand obj) {
- visitNode(obj.getGroupSymbol());
- append(SPACE);
- if (obj.getColumns() != null && !obj.getColumns().isEmpty()) {
- append(Tokens.LPAREN);
- registerNodes(obj.getColumns(), 0);
- append(Tokens.RPAREN);
- append(SPACE);
- }
- append(AS);
- append(SPACE);
- append(Tokens.LPAREN);
- visitNode(obj.getCommand());
- append(Tokens.RPAREN);
- }
-
- public void visit( Query obj ) {
- addCacheHint(obj.getCacheHint());
- addWithClause(obj);
- visitNode(obj.getSelect());
-
- if (obj.getInto() != null) {
- beginClause(1);
- visitNode(obj.getInto());
- }
-
- if (obj.getFrom() != null) {
- beginClause(1);
- visitNode(obj.getFrom());
- }
-
- // Where clause
- if (obj.getCriteria() != null) {
- beginClause(1);
- visitCriteria(WHERE, obj.getCriteria());
- }
-
- // Group by clause
- if (obj.getGroupBy() != null) {
- beginClause(1);
- visitNode(obj.getGroupBy());
- }
-
- // Having clause
- if (obj.getHaving() != null) {
- beginClause(1);
- visitCriteria(HAVING, obj.getHaving());
- }
-
- // Order by clause
- if (obj.getOrderBy() != null) {
- beginClause(1);
- visitNode(obj.getOrderBy());
- }
-
- if (obj.getLimit() != null) {
- beginClause(1);
- visitNode(obj.getLimit());
- }
-
- // Option clause
- if (obj.getOption() != null) {
- beginClause(1);
- visitNode(obj.getOption());
- }
- }
-
- private void addWithClause(QueryCommand obj) {
- if (obj.getWith() != null) {
- append(WITH);
- append(SPACE);
- registerNodes(obj.getWith(), 0);
- beginClause(0);
- }
- }
-
- protected void visitCriteria( String keyWord,
- Criteria crit ) {
- append(keyWord);
- append(SPACE);
- visitNode(crit);
- }
-
- public void visit( SearchedCaseExpression obj ) {
- append(CASE);
- for (int i = 0; i < obj.getWhenCount(); i++) {
- append(SPACE);
- append(WHEN);
- append(SPACE);
- visitNode(obj.getWhenCriteria(i));
- append(SPACE);
- append(THEN);
- append(SPACE);
- visitNode(obj.getThenExpression(i));
- }
- append(SPACE);
- if (obj.getElseExpression() != null) {
- append(ELSE);
- append(SPACE);
- visitNode(obj.getElseExpression());
- append(SPACE);
- }
- append(END);
- }
-
- public void visit( Select obj ) {
- append(SELECT);
- if (obj.isDistinct()) {
- append(SPACE);
- append(DISTINCT);
- }
- beginClause(2);
-
- Iterator iter = obj.getSymbols().iterator();
- while (iter.hasNext()) {
- SelectSymbol symbol = (SelectSymbol)iter.next();
- visitNode(symbol);
- if (iter.hasNext()) {
- append(", "); //$NON-NLS-1$
- }
- }
- }
-
- public void visit( SetCriteria obj ) {
- // variable
- visitNode(obj.getExpression());
-
- // operator and beginning of list
- append(SPACE);
- if (obj.isNegated()) {
- append(NOT);
- append(SPACE);
- }
- append(IN);
- append(" ("); //$NON-NLS-1$
-
- // value list
- Collection vals = obj.getValues();
- int size = vals.size();
- if (size == 1) {
- Iterator iter = vals.iterator();
- Expression expr = (Expression)iter.next();
- visitNode(expr);
- } else if (size > 1) {
- Iterator iter = vals.iterator();
- Expression expr = (Expression)iter.next();
- visitNode(expr);
- while (iter.hasNext()) {
- expr = (Expression)iter.next();
- append(", "); //$NON-NLS-1$
- visitNode(expr);
- }
- }
- append(")"); //$NON-NLS-1$
- }
-
- public void visit( SetQuery obj ) {
- addCacheHint(obj.getCacheHint());
- addWithClause(obj);
- QueryCommand query = obj.getLeftQuery();
- appendSetQuery(obj, query, false);
-
- beginClause(0);
- append(obj.getOperation());
-
- if (obj.isAll()) {
- append(SPACE);
- append(ALL);
- }
- beginClause(0);
- query = obj.getRightQuery();
- appendSetQuery(obj, query, true);
-
- if (obj.getOrderBy() != null) {
- beginClause(0);
- visitNode(obj.getOrderBy());
- }
-
- if (obj.getLimit() != null) {
- beginClause(0);
- visitNode(obj.getLimit());
- }
-
- if (obj.getOption() != null) {
- beginClause(0);
- visitNode(obj.getOption());
- }
- }
-
- protected void appendSetQuery( SetQuery parent,
- QueryCommand obj,
- boolean right ) {
- if (right && ((obj instanceof SetQuery
- && ((parent.isAll() && !((SetQuery)obj).isAll()) || parent.getOperation() != ((SetQuery)obj).getOperation())) || obj.getLimit() != null || obj.getOrderBy() != null)) {
- append(Tokens.LPAREN);
- visitNode(obj);
- append(Tokens.RPAREN);
- } else {
- visitNode(obj);
- }
- }
-
- public void visit( StoredProcedure obj ) {
- addCacheHint(obj.getCacheHint());
- if (obj.isCalledWithReturn()) {
- for (SPParameter param : obj.getParameters()) {
- if (param.getParameterType() == SPParameter.RETURN_VALUE) {
- if (param.getExpression() == null) {
- append("?"); //$NON-NLS-1$
- } else {
- visitNode(param.getExpression());
- }
- }
- }
- append(SPACE);
- append(Tokens.EQ);
- append(SPACE);
- }
- // exec clause
- append(EXEC);
- append(SPACE);
- append(obj.getProcedureName());
- append("("); //$NON-NLS-1$
- boolean first = true;
- for (SPParameter param : obj.getParameters()) {
- if (param.isUsingDefault() || param.getParameterType() == SPParameter.RETURN_VALUE
- || param.getParameterType() == SPParameter.RESULT_SET || param.getExpression() == null) {
- continue;
- }
- if (first) {
- first = false;
- } else {
- append(", "); //$NON-NLS-1$
- }
- if (obj.displayNamedParameters()) {
- append(escapeSinglePart(ElementSymbol.getShortName(param.getParameterSymbol().getOutputName())));
- append(" => "); //$NON-NLS-1$
- }
-
- boolean addParens = !obj.displayNamedParameters() && param.getExpression() instanceof CompareCriteria;
- if (addParens) {
- append(Tokens.LPAREN);
- }
- visitNode(param.getExpression());
- if (addParens) {
- append(Tokens.RPAREN);
- }
- }
- append(")"); //$NON-NLS-1$
-
- // Option clause
- if (obj.getOption() != null) {
- beginClause(1);
- visitNode(obj.getOption());
- }
- }
-
- public void addCacheHint( CacheHint obj ) {
- if (obj == null) {
- return;
- }
- append(BEGIN_HINT);
- append(SPACE);
- append(CacheHint.CACHE);
- boolean addParens = false;
- if (obj.getPrefersMemory()) {
- append(Tokens.LPAREN);
- addParens = true;
- append(CacheHint.PREF_MEM);
- }
- if (obj.getTtl() != null) {
- if (!addParens) {
- append(Tokens.LPAREN);
- addParens = true;
- } else {
- append(SPACE);
- }
- append(CacheHint.TTL);
- append(obj.getTtl());
- }
- if (obj.isUpdatable()) {
- if (!addParens) {
- append(Tokens.LPAREN);
- addParens = true;
- } else {
- append(SPACE);
- }
- append(CacheHint.UPDATABLE);
- }
- if (obj.getScope() != null) {
- if (!addParens) {
- append(Tokens.LPAREN);
- addParens = true;
- } else {
- append(SPACE);
- }
- append(CacheHint.SCOPE);
- append(obj.getScope());
- }
- if (addParens) {
- append(Tokens.RPAREN);
- }
- append(SPACE);
- append(END_HINT);
- beginClause(0);
- }
-
- public void visit( SubqueryFromClause obj ) {
- addOptionComment(obj);
- if (obj.isTable()) {
- append(TABLE);
- }
- append("(");//$NON-NLS-1$
- visitNode(obj.getCommand());
- append(")");//$NON-NLS-1$
- append(" AS ");//$NON-NLS-1$
- append(obj.getOutputName());
- addFromClasueDepOptions(obj);
- }
-
- public void visit( SubquerySetCriteria obj ) {
- // variable
- visitNode(obj.getExpression());
-
- // operator and beginning of list
- append(SPACE);
- if (obj.isNegated()) {
- append(NOT);
- append(SPACE);
- }
- append(IN);
- addSubqueryHint(obj.getSubqueryHint());
- append(" ("); //$NON-NLS-1$
- visitNode(obj.getCommand());
- append(")"); //$NON-NLS-1$
- }
-
- public void visit( UnaryFromClause obj ) {
- addOptionComment(obj);
- visitNode(obj.getGroup());
- addFromClasueDepOptions(obj);
- }
-
- public void visit( Update obj ) {
- // Update clause
- append(UPDATE);
- append(SPACE);
- visitNode(obj.getGroup());
- beginClause(1);
- // Set clause
- append(SET);
- beginClause(2);
- visitNode(obj.getChangeList());
-
- // Where clause
- if (obj.getCriteria() != null) {
- beginClause(1);
- visitCriteria(WHERE, obj.getCriteria());
- }
-
- // Option clause
- if (obj.getOption() != null) {
- beginClause(1);
- visitNode(obj.getOption());
- }
- }
-
- public void visit( Into obj ) {
- append(INTO);
- append(SPACE);
- visitNode(obj.getGroup());
- }
-
- // ############ Visitor methods for symbol objects ####################
-
- public void visit( AggregateSymbol obj ) {
- append(obj.getAggregateFunction().name());
- append("("); //$NON-NLS-1$
-
- if (obj.isDistinct()) {
- append(DISTINCT);
- append(" "); //$NON-NLS-1$
- }
-
- if (obj.getExpression() == null) {
- append(Tokens.ALL_COLS);
- } else {
- visitNode(obj.getExpression());
- }
-
- if (obj.getOrderBy() != null) {
- append(SPACE);
- visitNode(obj.getOrderBy());
- }
- append(")"); //$NON-NLS-1$
- }
-
- public void visit( AliasSymbol obj ) {
- visitNode(obj.getSymbol());
- append(SPACE);
- append(AS);
- append(SPACE);
- append(escapeSinglePart(obj.getOutputName()));
- }
-
- public void visit( AllInGroupSymbol obj ) {
- append(obj.getName());
- }
-
- public void visit( AllSymbol obj ) {
- append(obj.getName());
- }
-
- public void visit( Constant obj ) {
- Class<?> type = obj.getType();
- String[] constantParts = null;
- if (obj.isMultiValued()) {
- constantParts = new String[] {"?"}; //$NON-NLS-1$
- } else if (obj.isNull()) {
- if (type.equals(DataTypeManager.DefaultDataClasses.BOOLEAN)) {
- constantParts = new String[] {UNKNOWN};
- } else {
- constantParts = new String[] {"null"}; //$NON-NLS-1$
- }
- } else {
- if (Number.class.isAssignableFrom(type)) {
- constantParts = new String[] {obj.getValue().toString()};
- } else if (type.equals(DataTypeManager.DefaultDataClasses.BOOLEAN)) {
- constantParts = new String[] {obj.getValue().equals(Boolean.TRUE) ? TRUE : FALSE};
- } else if (type.equals(DataTypeManager.DefaultDataClasses.TIMESTAMP)) {
- constantParts = new String[] {"{ts'", obj.getValue().toString(), "'}"}; //$NON-NLS-1$ //$NON-NLS-2$
- } else if (type.equals(DataTypeManager.DefaultDataClasses.TIME)) {
- constantParts = new String[] {"{t'", obj.getValue().toString(), "'}"}; //$NON-NLS-1$ //$NON-NLS-2$
- } else if (type.equals(DataTypeManager.DefaultDataClasses.DATE)) {
- constantParts = new String[] {"{d'", obj.getValue().toString(), "'}"}; //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (constantParts == null) {
- String strValue = obj.getValue().toString();
- strValue = escapeStringValue(strValue, "'"); //$NON-NLS-1$
- constantParts = new String[] {"'", strValue, "'"}; //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- for (String string : constantParts) {
- append(string);
- }
- }
-
- /**
- * Take a string literal and escape it as necessary. By default, this converts ' to ''.
- *
- * @param str String literal value (unquoted), never null
- * @return Escaped string literal value
- */
- static String escapeStringValue( String str,
- String tick ) {
- return StringUtil.replaceAll(str, tick, tick + tick);
- }
-
- public void visit( ElementSymbol obj ) {
- if (obj.getDisplayMode().equals(ElementSymbol.DisplayMode.SHORT_OUTPUT_NAME)) {
- outputShortName(obj);
- return;
- }
- String name = obj.getOutputName();
- if (obj.getDisplayMode().equals(ElementSymbol.DisplayMode.FULLY_QUALIFIED)) {
- name = obj.getName();
- }
- outputDisplayName(name);
- }
-
- private void outputShortName( ElementSymbol obj ) {
- outputDisplayName(SingleElementSymbol.getShortName(obj.getOutputName()));
- }
-
- private void outputDisplayName( String name ) {
- String[] pathParts = name.split("\\."); //$NON-NLS-1$
- for (int i = 0; i < pathParts.length; i++) {
- if (i > 0) {
- append(ElementSymbol.SEPARATOR);
- }
- append(escapeSinglePart(pathParts[i]));
- }
- }
-
- public void visit( ExpressionSymbol obj ) {
- visitNode(obj.getExpression());
- }
-
- public void visit( Function obj ) {
- String name = obj.getName();
- Expression[] args = obj.getArgs();
- if (obj.isImplicit()) {
- // Hide this function, which is implicit
- visitNode(args[0]);
-
- } else if (name.equalsIgnoreCase(CONVERT) || name.equalsIgnoreCase(CAST)) {
- append(name);
- append("("); //$NON-NLS-1$
-
- if (args != null && args.length > 0) {
- visitNode(args[0]);
-
- if (name.equalsIgnoreCase(CONVERT)) {
- append(", "); //$NON-NLS-1$
- } else {
- append(" "); //$NON-NLS-1$
- append(AS);
- append(" "); //$NON-NLS-1$
- }
-
- if (args.length < 2 || args[1] == null || !(args[1] instanceof Constant)) {
- append(UNDEFINED);
- } else {
- append(((Constant)args[1]).getValue());
- }
- }
- append(")"); //$NON-NLS-1$
-
- } else if (name.equals("+") || name.equals("-") || name.equals("*") || name.equals("/") || name.equals("||")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- append("("); //$NON-NLS-1$
-
- if (args != null) {
- for (int i = 0; i < args.length; i++) {
- visitNode(args[i]);
- if (i < (args.length - 1)) {
- append(SPACE);
- append(name);
- append(SPACE);
- }
- }
- }
- append(")"); //$NON-NLS-1$
-
- } else if (name.equalsIgnoreCase(NonReserved.TIMESTAMPADD) || name.equalsIgnoreCase(NonReserved.TIMESTAMPDIFF)) {
- append(name);
- append("("); //$NON-NLS-1$
-
- if (args != null && args.length > 0) {
- append(((Constant)args[0]).getValue());
- registerNodes(args, 1);
- }
- append(")"); //$NON-NLS-1$
-
- } else if (name.equalsIgnoreCase(SourceSystemFunctions.XMLPI)) {
- append(name);
- append("(NAME "); //$NON-NLS-1$
- outputDisplayName((String)((Constant)args[0]).getValue());
- registerNodes(args, 1);
- append(")"); //$NON-NLS-1$
- } else {
- append(name);
- append("("); //$NON-NLS-1$
- registerNodes(args, 0);
- append(")"); //$NON-NLS-1$
- }
- }
-
- private void registerNodes( LanguageObject[] objects,
- int begin ) {
- registerNodes(Arrays.asList(objects), begin);
- }
-
- private void registerNodes( List<? extends LanguageObject> objects,
- int begin ) {
- for (int i = begin; i < objects.size(); i++) {
- if (i > 0) {
- append(", "); //$NON-NLS-1$
- }
- visitNode(objects.get(i));
- }
- }
-
- public void visit( GroupSymbol obj ) {
- String alias = null;
- String fullGroup = obj.getOutputName();
- if (obj.getOutputDefinition() != null) {
- alias = obj.getOutputName();
- fullGroup = obj.getOutputDefinition();
- }
-
- outputDisplayName(fullGroup);
-
- if (alias != null) {
- append(SPACE);
- append(AS);
- append(SPACE);
- append(escapeSinglePart(alias));
- }
- }
-
- public void visit( Reference obj ) {
- if (!obj.isPositional() && obj.getExpression() != null) {
- visitNode(obj.getExpression());
- } else {
- append("?"); //$NON-NLS-1$
- }
- }
-
- // ############ Visitor methods for storedprocedure language objects ####################
-
- public void visit( Block obj ) {
- List statements = obj.getStatements();
- // Add first clause
- append(BEGIN);
- append("\n"); //$NON-NLS-1$
- Iterator stmtIter = statements.iterator();
- while (stmtIter.hasNext()) {
- // Add each statement
- addTabs(1);
- visitNode((Statement)stmtIter.next());
- append("\n"); //$NON-NLS-1$
- }
- addTabs(0);
- append(END);
- }
-
- protected void addTabs( int level ) {
- }
-
- public void visit( CommandStatement obj ) {
- visitNode(obj.getCommand());
- append(";"); //$NON-NLS-1$
- }
-
- public void visit( CreateUpdateProcedureCommand obj ) {
- append(CREATE);
- append(SPACE);
- if (!obj.isUpdateProcedure()) {
- append(VIRTUAL);
- append(SPACE);
- }
- append(PROCEDURE);
- append("\n"); //$NON-NLS-1$
- addTabs(0);
- visitNode(obj.getBlock());
- }
-
- public void visit( DeclareStatement obj ) {
- append(DECLARE);
- append(SPACE);
- append(obj.getVariableType());
- append(SPACE);
- createAssignment(obj);
- }
-
- /**
- * @param obj
- * @param parts
- */
- private void createAssignment( AssignmentStatement obj ) {
- visitNode(obj.getVariable());
- if (obj.getExpression() != null) {
- append(" = "); //$NON-NLS-1$
- visitNode(obj.getExpression());
- }
- append(";"); //$NON-NLS-1$
- }
-
- public void visit( IfStatement obj ) {
- append(IF);
- append("("); //$NON-NLS-1$
- visitNode(obj.getCondition());
- append(")\n"); //$NON-NLS-1$
- addTabs(0);
- visitNode(obj.getIfBlock());
- if (obj.hasElseBlock()) {
- append("\n"); //$NON-NLS-1$
- addTabs(0);
- append(ELSE);
- append("\n"); //$NON-NLS-1$
- addTabs(0);
- visitNode(obj.getElseBlock());
- }
- }
-
- public void visit( AssignmentStatement obj ) {
- createAssignment(obj);
- }
-
- public void visit( HasCriteria obj ) {
- append(HAS);
- append(SPACE);
- visitNode(obj.getSelector());
- }
-
- public void visit( TranslateCriteria obj ) {
- append(TRANSLATE);
- append(SPACE);
- visitNode(obj.getSelector());
-
- if (obj.hasTranslations()) {
- append(SPACE);
- append(WITH);
- append(SPACE);
- append("("); //$NON-NLS-1$
- Iterator critIter = obj.getTranslations().iterator();
-
- while (critIter.hasNext()) {
- visitNode((Criteria)critIter.next());
- if (critIter.hasNext()) {
- append(", "); //$NON-NLS-1$
- }
- if (!critIter.hasNext()) {
- append(")"); //$NON-NLS-1$
- }
- }
- }
- }
-
- public void visit( CriteriaSelector obj ) {
- int selectorType = obj.getSelectorType();
-
- switch (selectorType) {
- case CriteriaSelector.COMPARE_EQ:
- append("= "); //$NON-NLS-1$
- break;
- case CriteriaSelector.COMPARE_GE:
- append(">= "); //$NON-NLS-1$
- break;
- case CriteriaSelector.COMPARE_GT:
- append("> "); //$NON-NLS-1$
- break;
- case CriteriaSelector.COMPARE_LE:
- append("<= "); //$NON-NLS-1$
- break;
- case CriteriaSelector.COMPARE_LT:
- append("< "); //$NON-NLS-1$
- break;
- case CriteriaSelector.COMPARE_NE:
- append("<> "); //$NON-NLS-1$
- break;
- case CriteriaSelector.IN:
- append(IN);
- append(SPACE);
- break;
- case CriteriaSelector.IS_NULL:
- append(IS);
- append(SPACE);
- append(NULL);
- append(SPACE);
- break;
- case CriteriaSelector.LIKE:
- append(LIKE);
- append(SPACE);
- break;
- case CriteriaSelector.BETWEEN:
- append(BETWEEN);
- append(SPACE);
- break;
- }
-
- append(CRITERIA);
- if (obj.hasElements()) {
- append(SPACE);
- append(ON);
- append(SPACE);
- append("("); //$NON-NLS-1$
-
- Iterator elmtIter = obj.getElements().iterator();
- while (elmtIter.hasNext()) {
- visitNode((ElementSymbol)elmtIter.next());
- if (elmtIter.hasNext()) {
- append(", "); //$NON-NLS-1$
- }
- }
- append(")"); //$NON-NLS-1$
- }
- }
-
- public void visit( RaiseErrorStatement obj ) {
- append(ERROR);
- append(SPACE);
- visitNode(obj.getExpression());
- append(";"); //$NON-NLS-1$
- }
-
- public void visit( BreakStatement obj ) {
- append(BREAK);
- append(";"); //$NON-NLS-1$
- }
-
- public void visit( ContinueStatement obj ) {
- append(CONTINUE);
- append(";"); //$NON-NLS-1$
- }
-
- public void visit( LoopStatement obj ) {
- append(LOOP);
- append(" "); //$NON-NLS-1$
- append(ON);
- append(" ("); //$NON-NLS-1$
- visitNode(obj.getCommand());
- append(") "); //$NON-NLS-1$
- append(AS);
- append(" "); //$NON-NLS-1$
- append(obj.getCursorName());
- append("\n"); //$NON-NLS-1$
- addTabs(0);
- visitNode(obj.getBlock());
- }
-
- public void visit( WhileStatement obj ) {
- append(WHILE);
- append("("); //$NON-NLS-1$
- visitNode(obj.getCondition());
- append(")\n"); //$NON-NLS-1$
- addTabs(0);
- visitNode(obj.getBlock());
- }
-
- public void visit( ExistsCriteria obj ) {
- if (obj.isNegated()) {
- append(NOT);
- append(SPACE);
- }
- append(EXISTS);
- addSubqueryHint(obj.getSubqueryHint());
- append(" ("); //$NON-NLS-1$
- visitNode(obj.getCommand());
- append(")"); //$NON-NLS-1$
- }
-
- public void addSubqueryHint(SubqueryHint hint) {
- if (hint.isNoUnnest()) {
- append(SPACE);
- append(BEGIN_HINT);
- append(SPACE);
- append(SubqueryHint.NOUNNEST);
- append(SPACE);
- append(END_HINT);
- } else if (hint.isMergeJoin()) {
- append(SPACE);
- append(BEGIN_HINT);
- append(SPACE);
- append(SubqueryHint.MJ);
- append(SPACE);
- append(END_HINT);
- }
- }
-
- public void visit( SubqueryCompareCriteria obj ) {
- Expression leftExpression = obj.getLeftExpression();
- visitNode(leftExpression);
-
- String operator = obj.getOperatorAsString();
- String quantifier = obj.getPredicateQuantifierAsString();
-
- // operator and beginning of list
- append(SPACE);
- append(operator);
- append(SPACE);
- append(quantifier);
- append("("); //$NON-NLS-1$
- visitNode(obj.getCommand());
- append(")"); //$NON-NLS-1$
- }
-
- public void visit( ScalarSubquery obj ) {
- // operator and beginning of list
- append("("); //$NON-NLS-1$
- visitNode(obj.getCommand());
- append(")"); //$NON-NLS-1$
- }
-
- @Override
- public void visit( XMLAttributes obj ) {
- append(XMLATTRIBUTES);
- append("("); //$NON-NLS-1$
- registerNodes(obj.getArgs(), 0);
- append(")"); //$NON-NLS-1$
- }
-
- @Override
- public void visit( XMLElement obj ) {
- append(XMLELEMENT);
- append("(NAME "); //$NON-NLS-1$
- outputDisplayName(obj.getName());
- if (obj.getNamespaces() != null) {
- append(", "); //$NON-NLS-1$
- visitNode(obj.getNamespaces());
- }
- if (obj.getAttributes() != null) {
- append(", "); //$NON-NLS-1$
- visitNode(obj.getAttributes());
- }
- if (!obj.getContent().isEmpty()) {
- append(", "); //$NON-NLS-1$
- }
- registerNodes(obj.getContent(), 0);
- append(")"); //$NON-NLS-1$
- }
-
- @Override
- public void visit( XMLForest obj ) {
- append(XMLFOREST);
- append("("); //$NON-NLS-1$
- if (obj.getNamespaces() != null) {
- visitNode(obj.getNamespaces());
- append(", "); //$NON-NLS-1$
- }
- registerNodes(obj.getArgs(), 0);
- append(")"); //$NON-NLS-1$
- }
-
- @Override
- public void visit( TextLine obj ) {
- append(FOR);
- append(SPACE);
- registerNodes(obj.getExpressions(), 0);
-
- if (obj.getDelimiter() != null) {
- append(SPACE);
- append(NonReserved.DELIMITER);
- append(SPACE);
- visitNode(new Constant(obj.getDelimiter()));
- }
- if (obj.getQuote() != null) {
- append(SPACE);
- append(NonReserved.QUOTE);
- append(SPACE);
- visitNode(new Constant(obj.getQuote()));
- }
- if (obj.isIncludeHeader()) {
- append(SPACE);
- append(NonReserved.HEADER);
- }
- if (obj.getEncoding() != null) {
- append(SPACE);
- append(NonReserved.ENCODING);
- append(SPACE);
- outputDisplayName(obj.getEncoding());
- }
- }
-
- @Override
- public void visit( XMLNamespaces obj ) {
- append(XMLNAMESPACES);
- append("("); //$NON-NLS-1$
- for (Iterator<NamespaceItem> items = obj.getNamespaceItems().iterator(); items.hasNext();) {
- NamespaceItem item = items.next();
- if (item.getPrefix() == null) {
- if (item.getUri() == null) {
- append("NO DEFAULT"); //$NON-NLS-1$
- } else {
- append("DEFAULT "); //$NON-NLS-1$
- visitNode(new Constant(item.getUri()));
- }
- } else {
- visitNode(new Constant(item.getUri()));
- append(" AS "); //$NON-NLS-1$
- outputDisplayName(item.getPrefix());
- }
- if (items.hasNext()) {
- append(", "); //$NON-NLS-1$
- }
- }
- append(")"); //$NON-NLS-1$
- }
-
- public void visit( Limit obj ) {
- append(LIMIT);
- if (obj.getOffset() != null) {
- append(SPACE);
- visitNode(obj.getOffset());
- append(","); //$NON-NLS-1$
- }
- append(SPACE);
- visitNode(obj.getRowLimit());
- }
-
- @Override
- public void visit( TextTable obj ) {
- append("TEXTTABLE("); //$NON-NLS-1$
- visitNode(obj.getFile());
- append(SPACE);
- append(NonReserved.COLUMNS);
-
- for (Iterator<TextColumn> cols = obj.getColumns().iterator(); cols.hasNext();) {
- TextColumn col = cols.next();
- append(SPACE);
- outputDisplayName(col.getName());
- append(SPACE);
- append(col.getType());
- if (col.getWidth() != null) {
- append(SPACE);
- append(NonReserved.WIDTH);
- append(SPACE);
- append(col.getWidth());
- }
- if (cols.hasNext()) {
- append(","); //$NON-NLS-1$
- }
- }
- if (obj.getDelimiter() != null) {
- append(SPACE);
- append(NonReserved.DELIMITER);
- append(SPACE);
- visitNode(new Constant(obj.getDelimiter()));
- }
- if (obj.getQuote() != null) {
- append(SPACE);
- if (obj.isEscape()) {
- append(ESCAPE);
- } else {
- append(NonReserved.QUOTE);
- }
- append(SPACE);
- visitNode(new Constant(obj.getQuote()));
- }
- if (obj.getHeader() != null) {
- append(SPACE);
- append(NonReserved.HEADER);
- if (1 != obj.getHeader()) {
- append(SPACE);
- append(obj.getHeader());
- }
- }
- if (obj.getSkip() != null) {
- append(SPACE);
- append("SKIP"); //$NON-NLS-1$
- append(SPACE);
- append(obj.getSkip());
- }
- append(")");//$NON-NLS-1$
- append(SPACE);
- append(AS);
- append(SPACE);
- outputDisplayName(obj.getName());
- }
-
- @Override
- public void visit( XMLTable obj ) {
- append("XMLTABLE("); //$NON-NLS-1$
- if (obj.getNamespaces() != null) {
- visitNode(obj.getNamespaces());
- append(","); //$NON-NLS-1$
- append(SPACE);
- }
- visitNode(new Constant(obj.getXquery()));
- if (!obj.getPassing().isEmpty()) {
- append(SPACE);
- append(NonReserved.PASSING);
- append(SPACE);
- registerNodes(obj.getPassing(), 0);
- }
- if (!obj.getColumns().isEmpty()) {
- append(SPACE);
- append(NonReserved.COLUMNS);
- for (Iterator<XMLColumn> cols = obj.getColumns().iterator(); cols.hasNext();) {
- XMLColumn col = cols.next();
- append(SPACE);
- outputDisplayName(col.getName());
- append(SPACE);
- if (col.isOrdinal()) {
- append(FOR);
- append(SPACE);
- append(NonReserved.ORDINALITY);
- } else {
- append(col.getType());
- if (col.getDefaultExpression() != null) {
- append(SPACE);
- append(DEFAULT);
- append(SPACE);
- visitNode(col.getDefaultExpression());
- }
- if (col.getPath() != null) {
- append(SPACE);
- append(NonReserved.PATH);
- append(SPACE);
- visitNode(new Constant(col.getPath()));
- }
- }
- if (cols.hasNext()) {
- append(","); //$NON-NLS-1$
- }
- }
- }
- append(")");//$NON-NLS-1$
- append(SPACE);
- append(AS);
- append(SPACE);
- outputDisplayName(obj.getName());
- }
-
- @Override
- public void visit( XMLQuery obj ) {
- append("XMLQUERY("); //$NON-NLS-1$
- if (obj.getNamespaces() != null) {
- visitNode(obj.getNamespaces());
- append(","); //$NON-NLS-1$
- append(SPACE);
- }
- visitNode(new Constant(obj.getXquery()));
- if (!obj.getPassing().isEmpty()) {
- append(SPACE);
- append(NonReserved.PASSING);
- append(SPACE);
- registerNodes(obj.getPassing(), 0);
- }
- if (obj.getEmptyOnEmpty() != null) {
- append(SPACE);
- if (obj.getEmptyOnEmpty()) {
- append(NonReserved.EMPTY);
- } else {
- append(NULL);
- }
- append(SPACE);
- append(ON);
- append(SPACE);
- append(NonReserved.EMPTY);
- }
- append(")");//$NON-NLS-1$
- }
-
- @Override
- public void visit( DerivedColumn obj ) {
- visitNode(obj.getExpression());
- if (obj.getAlias() != null) {
- append(SPACE);
- append(AS);
- append(SPACE);
- outputDisplayName(obj.getAlias());
- }
- }
-
- @Override
- public void visit( XMLSerialize obj ) {
- append(XMLSERIALIZE);
- append(Tokens.LPAREN);
- if (obj.isDocument() != null) {
- if (obj.isDocument()) {
- append(NonReserved.DOCUMENT);
- } else {
- append(NonReserved.CONTENT);
- }
- append(SPACE);
- }
- visitNode(obj.getExpression());
- if (obj.getTypeString() != null) {
- append(SPACE);
- append(AS);
- append(SPACE);
- append(obj.getTypeString());
- }
- append(Tokens.RPAREN);
- }
-
- @Override
- public void visit( QueryString obj ) {
- append(NonReserved.QUERYSTRING);
- append("("); //$NON-NLS-1$
- visitNode(obj.getPath());
- if (!obj.getArgs().isEmpty()) {
- append(","); //$NON-NLS-1$
- append(SPACE);
- registerNodes(obj.getArgs(), 0);
- }
- append(")"); //$NON-NLS-1$
- }
-
- @Override
- public void visit( XMLParse obj ) {
- append(XMLPARSE);
- append(Tokens.LPAREN);
- if (obj.isDocument()) {
- append(NonReserved.DOCUMENT);
- } else {
- append(NonReserved.CONTENT);
- }
- append(SPACE);
- visitNode(obj.getExpression());
- if (obj.isWellFormed()) {
- append(SPACE);
- append(NonReserved.WELLFORMED);
- }
- append(Tokens.RPAREN);
- }
-
- @Override
- public void visit( ExpressionCriteria obj ) {
- visitNode(obj.getExpression());
- }
-
- @Override
- public void visit(TriggerAction obj) {
- append(FOR);
- append(SPACE);
- append(EACH);
- append(SPACE);
- append(ROW);
- append("\n"); //$NON-NLS-1$
- addTabs(0);
- visitNode(obj.getBlock());
- }
-
- @Override
- public void visit(ArrayTable obj) {
- append("ARRAYTABLE("); //$NON-NLS-1$
- visitNode(obj.getArrayValue());
- append(SPACE);
- append(NonReserved.COLUMNS);
-
- for (Iterator<ProjectedColumn> cols = obj.getColumns().iterator(); cols.hasNext();) {
- ProjectedColumn col = cols.next();
- append(SPACE);
- outputDisplayName(col.getName());
- append(SPACE);
- append(col.getType());
- if (cols.hasNext()) {
- append(","); //$NON-NLS-1$
- }
- }
-
- append(")");//$NON-NLS-1$
- append(SPACE);
- append(AS);
- append(SPACE);
- outputDisplayName(obj.getName());
- }
-
- @Override
- public void visit(AlterProcedure alterProcedure) {
- append(ALTER);
- append(SPACE);
- append(PROCEDURE);
- append(SPACE);
- append(alterProcedure.getTarget());
- beginClause(1);
- append(AS);
- addCacheHint(alterProcedure.getCacheHint());
- append(alterProcedure.getDefinition().getBlock());
- }
-
- @Override
- public void visit(AlterTrigger alterTrigger) {
- if (alterTrigger.isCreate()) {
- append(CREATE);
- } else {
- append(ALTER);
- }
- append(SPACE);
- append(TRIGGER);
- append(SPACE);
- append(ON);
- append(SPACE);
- append(alterTrigger.getTarget());
- beginClause(0);
- append(NonReserved.INSTEAD);
- append(SPACE);
- append(OF);
- append(SPACE);
- append(alterTrigger.getEvent());
- if (alterTrigger.getDefinition() != null) {
- beginClause(0);
- append(AS);
- append("\n"); //$NON-NLS-1$
- addTabs(0);
- append(alterTrigger.getDefinition());
- } else {
- append(SPACE);
- append(alterTrigger.getEnabled()?NonReserved.ENABLED:NonReserved.DISABLED);
- }
- }
-
- @Override
- public void visit(AlterView alterView) {
- append(ALTER);
- append(SPACE);
- append(NonReserved.VIEW);
- append(SPACE);
- append(alterView.getTarget());
- beginClause(0);
- append(AS);
- append("\n"); //$NON-NLS-1$
- addTabs(0);
- append(alterView.getDefinition());
- }
-
- public static String escapeSinglePart( String part ) {
- if (isReservedWord(part)) {
- return ID_ESCAPE_CHAR + part + ID_ESCAPE_CHAR;
- }
- boolean escape = true;
- char start = part.charAt(0);
- if (start == '#' || start == '@' || StringUtil.isLetter(start)) {
- escape = false;
- for (int i = 1; !escape && i < part.length(); i++) {
- char c = part.charAt(i);
- escape = !StringUtil.isLetterOrDigit(c) && c != '_';
- }
- }
- if (escape) {
- return ID_ESCAPE_CHAR + escapeStringValue(part, "\"") + ID_ESCAPE_CHAR; //$NON-NLS-1$
- }
- return part;
- }
-
- /**
- * Check whether a string is considered a reserved word or not. Subclasses may override to change definition of reserved word.
- *
- * @param string String to check
- * @return True if reserved word
- */
- static boolean isReservedWord( String string ) {
- if (string == null) {
- return false;
- }
- return SQLConstants.isReservedWord(string);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,2062 @@
+/*
+ * 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.visitor;
+
+import static org.teiid.language.SQLConstants.Reserved.*;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.StringUtil;
+import org.teiid.language.SQLConstants;
+import org.teiid.language.SQLConstants.NonReserved;
+import org.teiid.language.SQLConstants.Tokens;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.BaseColumn.NullType;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.lang.AlterProcedure;
+import org.teiid.query.sql.lang.AlterTrigger;
+import org.teiid.query.sql.lang.AlterView;
+import org.teiid.query.sql.lang.ArrayTable;
+import org.teiid.query.sql.lang.AtomicCriteria;
+import org.teiid.query.sql.lang.BetweenCriteria;
+import org.teiid.query.sql.lang.CacheHint;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Create;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.DependentSetCriteria;
+import org.teiid.query.sql.lang.Drop;
+import org.teiid.query.sql.lang.DynamicCommand;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.ExpressionCriteria;
+import org.teiid.query.sql.lang.From;
+import org.teiid.query.sql.lang.FromClause;
+import org.teiid.query.sql.lang.GroupBy;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.Into;
+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.Option;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.OrderByItem;
+import org.teiid.query.sql.lang.PredicateCriteria;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.SetClause;
+import org.teiid.query.sql.lang.SetClauseList;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.SubqueryCompareCriteria;
+import org.teiid.query.sql.lang.SubqueryFromClause;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.lang.TextTable;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.lang.WithQueryCommand;
+import org.teiid.query.sql.lang.XMLTable;
+import org.teiid.query.sql.lang.ExistsCriteria.SubqueryHint;
+import org.teiid.query.sql.lang.TableFunctionReference.ProjectedColumn;
+import org.teiid.query.sql.lang.TextTable.TextColumn;
+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.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;
+import org.teiid.query.sql.proc.HasCriteria;
+import org.teiid.query.sql.proc.IfStatement;
+import org.teiid.query.sql.proc.LoopStatement;
+import org.teiid.query.sql.proc.RaiseErrorStatement;
+import org.teiid.query.sql.proc.Statement;
+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.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;
+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;
+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.SelectSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.symbol.TextLine;
+import org.teiid.query.sql.symbol.XMLAttributes;
+import org.teiid.query.sql.symbol.XMLElement;
+import org.teiid.query.sql.symbol.XMLForest;
+import org.teiid.query.sql.symbol.XMLNamespaces;
+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.XMLNamespaces.NamespaceItem;
+import org.teiid.translator.SourceSystemFunctions;
+
+/**
+ * <p>
+ * The SQLStringVisitor will visit a set of language objects and return the corresponding SQL string representation.
+ * </p>
+ */
+public class SQLStringVisitor extends LanguageVisitor {
+
+ public static final String UNDEFINED = "<undefined>"; //$NON-NLS-1$
+ private static final String SPACE = " "; //$NON-NLS-1$
+ private static final String BEGIN_HINT = "/*+"; //$NON-NLS-1$
+ private static final String END_HINT = "*/"; //$NON-NLS-1$
+ private static final char ID_ESCAPE_CHAR = '\"';
+ protected StringBuilder parts = new StringBuilder();
+
+ /**
+ * Helper to quickly get the parser string for an object using the visitor.
+ *
+ * @param obj Language object
+ * @return String SQL String for obj
+ */
+ public static final String getSQLString( LanguageObject obj ) {
+ if (obj == null) {
+ return UNDEFINED;
+ }
+ SQLStringVisitor visitor = new SQLStringVisitor();
+ obj.acceptVisitor(visitor);
+ return visitor.getSQLString();
+ }
+
+ /**
+ * Retrieve completed string from the visitor.
+ *
+ * @return Complete SQL string for the visited nodes
+ */
+ public String getSQLString() {
+ return this.parts.toString();
+ }
+
+ protected void visitNode( LanguageObject obj ) {
+ if (obj == null) {
+ append(UNDEFINED);
+ return;
+ }
+ obj.acceptVisitor(this);
+ }
+
+ protected void append( Object value ) {
+ this.parts.append(value);
+ }
+
+ protected void beginClause( @SuppressWarnings("unused") int level ) {
+ append(SPACE);
+ }
+
+ // ############ Visitor methods for language objects ####################
+
+ public void visit( BetweenCriteria obj ) {
+ visitNode(obj.getExpression());
+ append(SPACE);
+
+ if (obj.isNegated()) {
+ append(NOT);
+ append(SPACE);
+ }
+ append(BETWEEN);
+ append(SPACE);
+ visitNode(obj.getLowerExpression());
+
+ append(SPACE);
+ append(AND);
+ append(SPACE);
+ visitNode(obj.getUpperExpression());
+ }
+
+ public void visit( CaseExpression obj ) {
+ append(CASE);
+ append(SPACE);
+ visitNode(obj.getExpression());
+ append(SPACE);
+
+ for (int i = 0; i < obj.getWhenCount(); i++) {
+ append(WHEN);
+ append(SPACE);
+ visitNode(obj.getWhenExpression(i));
+ append(SPACE);
+ append(THEN);
+ append(SPACE);
+ visitNode(obj.getThenExpression(i));
+ append(SPACE);
+ }
+
+ if (obj.getElseExpression() != null) {
+ append(ELSE);
+ append(SPACE);
+ visitNode(obj.getElseExpression());
+ append(SPACE);
+ }
+ append(END);
+ }
+
+ public void visit( CompareCriteria obj ) {
+ Expression leftExpression = obj.getLeftExpression();
+ visitNode(leftExpression);
+ append(SPACE);
+ append(obj.getOperatorAsString());
+ append(SPACE);
+ Expression rightExpression = obj.getRightExpression();
+ visitNode(rightExpression);
+ }
+
+ public void visit( CompoundCriteria obj ) {
+ // Get operator string
+ int operator = obj.getOperator();
+ String operatorStr = ""; //$NON-NLS-1$
+ if (operator == CompoundCriteria.AND) {
+ operatorStr = AND;
+ } else if (operator == CompoundCriteria.OR) {
+ operatorStr = OR;
+ }
+
+ // Get criteria
+ List<Criteria> subCriteria = obj.getCriteria();
+
+ // Build parts
+ if (subCriteria.size() == 1) {
+ // Special case - should really never happen, but we are tolerant
+ Criteria firstChild = subCriteria.get(0);
+ visitNode(firstChild);
+ } else {
+ // Add first criteria
+ Iterator<Criteria> iter = subCriteria.iterator();
+
+ while (iter.hasNext()) {
+ // Add criteria
+ Criteria crit = iter.next();
+ append(Tokens.LPAREN);
+ visitNode(crit);
+ append(Tokens.RPAREN);
+
+ if (iter.hasNext()) {
+ // Add connector
+ append(SPACE);
+ append(operatorStr);
+ append(SPACE);
+ }
+ }
+ }
+ }
+
+ public void visit( Delete obj ) {
+ // add delete clause
+ append(DELETE);
+ append(SPACE);
+ // add from clause
+ append(FROM);
+ append(SPACE);
+ visitNode(obj.getGroup());
+
+ // add where clause
+ if (obj.getCriteria() != null) {
+ beginClause(0);
+ visitCriteria(WHERE, obj.getCriteria());
+ }
+
+ // Option clause
+ if (obj.getOption() != null) {
+ beginClause(0);
+ visitNode(obj.getOption());
+ }
+ }
+
+ public void visit( DependentSetCriteria obj ) {
+ visitNode(obj.getExpression());
+
+ // operator and beginning of list
+ append(SPACE);
+ if (obj.isNegated()) {
+ append(NOT);
+ append(SPACE);
+ }
+ append(IN);
+ append(" (<dependent values>)"); //$NON-NLS-1$
+ }
+
+ public void visit( From obj ) {
+ append(FROM);
+ beginClause(1);
+ registerNodes(obj.getClauses(), 0);
+ }
+
+ public void visit( GroupBy obj ) {
+ append(GROUP);
+ append(SPACE);
+ append(BY);
+ append(SPACE);
+ registerNodes(obj.getSymbols(), 0);
+ }
+
+ public void visit( Insert obj ) {
+ append(INSERT);
+ append(SPACE);
+ append(INTO);
+ append(SPACE);
+ visitNode(obj.getGroup());
+
+ if (!obj.getVariables().isEmpty()) {
+ beginClause(2);
+
+ // Columns clause
+ List vars = obj.getVariables();
+ if (vars != null) {
+ append("("); //$NON-NLS-1$
+ registerNodes(vars, 0);
+ append(")"); //$NON-NLS-1$
+ }
+ }
+ beginClause(1);
+ if (obj.getQueryExpression() != null) {
+ visitNode(obj.getQueryExpression());
+ } else if (obj.getTupleSource() != null) {
+ append(VALUES);
+ append(" (...)"); //$NON-NLS-1$
+ } else if (obj.getValues() != null) {
+ append(VALUES);
+ beginClause(2);
+ append("("); //$NON-NLS-1$
+ registerNodes(obj.getValues(), 0);
+ append(")"); //$NON-NLS-1$
+ }
+
+ // Option clause
+ if (obj.getOption() != null) {
+ beginClause(1);
+ visitNode(obj.getOption());
+ }
+ }
+
+ public void visit( Create obj ) {
+ append(CREATE);
+ append(SPACE);
+ append(LOCAL);
+ append(SPACE);
+ append(TEMPORARY);
+ append(SPACE);
+ append(TABLE);
+ append(SPACE);
+ visitNode(obj.getTable());
+ append(SPACE);
+
+ // Columns clause
+ List<Column> columns = obj.getColumns();
+ append("("); //$NON-NLS-1$
+ Iterator<Column> iter = columns.iterator();
+ while (iter.hasNext()) {
+ Column element = iter.next();
+ outputDisplayName(element.getName());
+ append(SPACE);
+ if (element.isAutoIncremented()) {
+ append(NonReserved.SERIAL);
+ } else {
+ append(element.getRuntimeType());
+ if (element.getNullType() == NullType.No_Nulls) {
+ append(NOT);
+ append(SPACE);
+ append(NULL);
+ }
+ }
+ if (iter.hasNext()) {
+ append(", "); //$NON-NLS-1$
+ }
+ }
+ if (!obj.getPrimaryKey().isEmpty()) {
+ append(", "); //$NON-NLS-1$
+ append(PRIMARY);
+ append(" "); //$NON-NLS-1$
+ append(NonReserved.KEY);
+ append(Tokens.LPAREN);
+ Iterator<ElementSymbol> pkiter = obj.getPrimaryKey().iterator();
+ while (pkiter.hasNext()) {
+ outputShortName(pkiter.next());
+ if (pkiter.hasNext()) {
+ append(", "); //$NON-NLS-1$
+ }
+ }
+ append(Tokens.RPAREN);
+ }
+ append(")"); //$NON-NLS-1$
+ }
+
+ public void visit( Drop obj ) {
+ append(DROP);
+ append(SPACE);
+ append(TABLE);
+ append(SPACE);
+ visitNode(obj.getTable());
+ }
+
+ public void visit( IsNullCriteria obj ) {
+ Expression expr = obj.getExpression();
+ visitNode(expr);
+ append(SPACE);
+ append(IS);
+ append(SPACE);
+ if (obj.isNegated()) {
+ append(NOT);
+ append(SPACE);
+ }
+ append(NULL);
+ }
+
+ public void visit( JoinPredicate obj ) {
+ addHintComment(obj);
+
+ if (obj.hasHint()) {
+ append("(");//$NON-NLS-1$
+ }
+
+ // left clause
+ FromClause leftClause = obj.getLeftClause();
+ if (leftClause instanceof JoinPredicate && !((JoinPredicate)leftClause).hasHint()) {
+ append("("); //$NON-NLS-1$
+ visitNode(leftClause);
+ append(")"); //$NON-NLS-1$
+ } else {
+ visitNode(leftClause);
+ }
+
+ // join type
+ append(SPACE);
+ visitNode(obj.getJoinType());
+ append(SPACE);
+
+ // right clause
+ FromClause rightClause = obj.getRightClause();
+ if (rightClause instanceof JoinPredicate && !((JoinPredicate)rightClause).hasHint()) {
+ append("("); //$NON-NLS-1$
+ visitNode(rightClause);
+ append(")"); //$NON-NLS-1$
+ } else {
+ visitNode(rightClause);
+ }
+
+ // join criteria
+ List joinCriteria = obj.getJoinCriteria();
+ if (joinCriteria != null && joinCriteria.size() > 0) {
+ append(SPACE);
+ append(ON);
+ append(SPACE);
+ Iterator critIter = joinCriteria.iterator();
+ while (critIter.hasNext()) {
+ Criteria crit = (Criteria)critIter.next();
+ if (crit instanceof PredicateCriteria || crit instanceof AtomicCriteria) {
+ visitNode(crit);
+ } else {
+ append("("); //$NON-NLS-1$
+ visitNode(crit);
+ append(")"); //$NON-NLS-1$
+ }
+
+ if (critIter.hasNext()) {
+ append(SPACE);
+ append(AND);
+ append(SPACE);
+ }
+ }
+ }
+
+ if (obj.hasHint()) {
+ append(")"); //$NON-NLS-1$
+ }
+ }
+
+ private void addHintComment( FromClause obj ) {
+ if (obj.hasHint()) {
+ append(BEGIN_HINT);
+ 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 ) {
+ String[] output = null;
+ if (obj.equals(JoinType.JOIN_INNER)) {
+ output = new String[] {INNER, SPACE, JOIN};
+ } else if (obj.equals(JoinType.JOIN_CROSS)) {
+ output = new String[] {CROSS, SPACE, JOIN};
+ } else if (obj.equals(JoinType.JOIN_LEFT_OUTER)) {
+ output = new String[] {LEFT, SPACE, OUTER, SPACE, JOIN};
+ } else if (obj.equals(JoinType.JOIN_RIGHT_OUTER)) {
+ output = new String[] {RIGHT, SPACE, OUTER, SPACE, JOIN};
+ } else if (obj.equals(JoinType.JOIN_FULL_OUTER)) {
+ output = new String[] {FULL, SPACE, OUTER, SPACE, JOIN};
+ } else if (obj.equals(JoinType.JOIN_UNION)) {
+ output = new String[] {UNION, SPACE, JOIN};
+ } else if (obj.equals(JoinType.JOIN_SEMI)) {
+ output = new String[] {"SEMI", SPACE, JOIN}; //$NON-NLS-1$
+ } else if (obj.equals(JoinType.JOIN_ANTI_SEMI)) {
+ output = new String[] {"ANTI SEMI", SPACE, JOIN}; //$NON-NLS-1$
+ } else {
+ throw new AssertionError();
+ }
+ for (String part : output) {
+ append(part);
+ }
+ }
+
+ public void visit( MatchCriteria obj ) {
+ visitNode(obj.getLeftExpression());
+
+ append(SPACE);
+ if (obj.isNegated()) {
+ append(NOT);
+ append(SPACE);
+ }
+ append(LIKE);
+ append(SPACE);
+
+ visitNode(obj.getRightExpression());
+
+ if (obj.getEscapeChar() != MatchCriteria.NULL_ESCAPE_CHAR) {
+ append(SPACE);
+ append(ESCAPE);
+ append(" '"); //$NON-NLS-1$
+ append("" + obj.getEscapeChar()); //$NON-NLS-1$
+ append("'"); //$NON-NLS-1$
+ }
+ }
+
+ public void visit( NotCriteria obj ) {
+ append(NOT);
+ append(" ("); //$NON-NLS-1$
+ visitNode(obj.getCriteria());
+ append(")"); //$NON-NLS-1$
+ }
+
+ public void visit( Option obj ) {
+ append(OPTION);
+
+ Collection groups = obj.getDependentGroups();
+ if (groups != null && groups.size() > 0) {
+ append(" "); //$NON-NLS-1$
+ append(MAKEDEP);
+ append(" "); //$NON-NLS-1$
+
+ Iterator iter = groups.iterator();
+
+ while (iter.hasNext()) {
+ outputDisplayName((String)iter.next());
+
+ if (iter.hasNext()) {
+ append(", ");//$NON-NLS-1$
+ }
+ }
+ }
+
+ groups = obj.getNotDependentGroups();
+ if (groups != null && groups.size() > 0) {
+ append(" "); //$NON-NLS-1$
+ append(MAKENOTDEP);
+ append(" "); //$NON-NLS-1$
+
+ Iterator iter = groups.iterator();
+
+ while (iter.hasNext()) {
+ outputDisplayName((String)iter.next());
+
+ if (iter.hasNext()) {
+ append(", ");//$NON-NLS-1$
+ }
+ }
+ }
+
+ groups = obj.getNoCacheGroups();
+ if (groups != null && groups.size() > 0) {
+ append(" "); //$NON-NLS-1$
+ append(NOCACHE);
+ append(" "); //$NON-NLS-1$
+
+ Iterator iter = groups.iterator();
+
+ while (iter.hasNext()) {
+ outputDisplayName((String)iter.next());
+
+ if (iter.hasNext()) {
+ append(", ");//$NON-NLS-1$
+ }
+ }
+ } else if (obj.isNoCache()) {
+ append(" "); //$NON-NLS-1$
+ append(NOCACHE);
+ }
+
+ }
+
+ public void visit( OrderBy obj ) {
+ append(ORDER);
+ append(SPACE);
+ append(BY);
+ append(SPACE);
+ registerNodes(obj.getOrderByItems(), 0);
+ }
+
+ @Override
+ public void visit( OrderByItem obj ) {
+ SingleElementSymbol ses = obj.getSymbol();
+ if (ses instanceof AliasSymbol) {
+ AliasSymbol as = (AliasSymbol)ses;
+ outputDisplayName(as.getOutputName());
+ } else {
+ visitNode(ses);
+ }
+ if (!obj.isAscending()) {
+ append(SPACE);
+ append(DESC);
+ } // Don't print default "ASC"
+ if (obj.getNullOrdering() != null) {
+ append(SPACE);
+ append(NonReserved.NULLS);
+ append(SPACE);
+ append(obj.getNullOrdering().name());
+ }
+ }
+
+ public void visit( DynamicCommand obj ) {
+ append(EXECUTE);
+ append(SPACE);
+ visitNode(obj.getSql());
+
+ if (obj.isAsClauseSet()) {
+ beginClause(1);
+ append(AS);
+ append(SPACE);
+ for (int i = 0; i < obj.getAsColumns().size(); i++) {
+ ElementSymbol symbol = (ElementSymbol)obj.getAsColumns().get(i);
+ outputShortName(symbol);
+ append(SPACE);
+ append(DataTypeManager.getDataTypeName(symbol.getType()));
+ if (i < obj.getAsColumns().size() - 1) {
+ append(", "); //$NON-NLS-1$
+ }
+ }
+ }
+
+ if (obj.getIntoGroup() != null) {
+ beginClause(1);
+ append(INTO);
+ append(SPACE);
+ visitNode(obj.getIntoGroup());
+ }
+
+ if (obj.getUsing() != null && !obj.getUsing().isEmpty()) {
+ beginClause(1);
+ append(USING);
+ append(SPACE);
+ visitNode(obj.getUsing());
+ }
+
+ if (obj.getUpdatingModelCount() > 0) {
+ beginClause(1);
+ append(UPDATE);
+ append(SPACE);
+ if (obj.getUpdatingModelCount() > 1) {
+ append("*"); //$NON-NLS-1$
+ } else {
+ append("1"); //$NON-NLS-1$
+ }
+ }
+ }
+
+ public void visit( SetClauseList obj ) {
+ for (Iterator<SetClause> iterator = obj.getClauses().iterator(); iterator.hasNext();) {
+ SetClause clause = iterator.next();
+ visitNode(clause);
+ if (iterator.hasNext()) {
+ append(", "); //$NON-NLS-1$
+ }
+ }
+ }
+
+ public void visit( SetClause obj ) {
+ ElementSymbol symbol = obj.getSymbol();
+ outputShortName(symbol);
+ append(" = "); //$NON-NLS-1$
+ visitNode(obj.getValue());
+ }
+
+ @Override
+ public void visit(WithQueryCommand obj) {
+ visitNode(obj.getGroupSymbol());
+ append(SPACE);
+ if (obj.getColumns() != null && !obj.getColumns().isEmpty()) {
+ append(Tokens.LPAREN);
+ registerNodes(obj.getColumns(), 0);
+ append(Tokens.RPAREN);
+ append(SPACE);
+ }
+ append(AS);
+ append(SPACE);
+ append(Tokens.LPAREN);
+ visitNode(obj.getCommand());
+ append(Tokens.RPAREN);
+ }
+
+ public void visit( Query obj ) {
+ addCacheHint(obj.getCacheHint());
+ addWithClause(obj);
+ visitNode(obj.getSelect());
+
+ if (obj.getInto() != null) {
+ beginClause(1);
+ visitNode(obj.getInto());
+ }
+
+ if (obj.getFrom() != null) {
+ beginClause(1);
+ visitNode(obj.getFrom());
+ }
+
+ // Where clause
+ if (obj.getCriteria() != null) {
+ beginClause(1);
+ visitCriteria(WHERE, obj.getCriteria());
+ }
+
+ // Group by clause
+ if (obj.getGroupBy() != null) {
+ beginClause(1);
+ visitNode(obj.getGroupBy());
+ }
+
+ // Having clause
+ if (obj.getHaving() != null) {
+ beginClause(1);
+ visitCriteria(HAVING, obj.getHaving());
+ }
+
+ // Order by clause
+ if (obj.getOrderBy() != null) {
+ beginClause(1);
+ visitNode(obj.getOrderBy());
+ }
+
+ if (obj.getLimit() != null) {
+ beginClause(1);
+ visitNode(obj.getLimit());
+ }
+
+ // Option clause
+ if (obj.getOption() != null) {
+ beginClause(1);
+ visitNode(obj.getOption());
+ }
+ }
+
+ private void addWithClause(QueryCommand obj) {
+ if (obj.getWith() != null) {
+ append(WITH);
+ append(SPACE);
+ registerNodes(obj.getWith(), 0);
+ beginClause(0);
+ }
+ }
+
+ protected void visitCriteria( String keyWord,
+ Criteria crit ) {
+ append(keyWord);
+ append(SPACE);
+ visitNode(crit);
+ }
+
+ public void visit( SearchedCaseExpression obj ) {
+ append(CASE);
+ for (int i = 0; i < obj.getWhenCount(); i++) {
+ append(SPACE);
+ append(WHEN);
+ append(SPACE);
+ visitNode(obj.getWhenCriteria(i));
+ append(SPACE);
+ append(THEN);
+ append(SPACE);
+ visitNode(obj.getThenExpression(i));
+ }
+ append(SPACE);
+ if (obj.getElseExpression() != null) {
+ append(ELSE);
+ append(SPACE);
+ visitNode(obj.getElseExpression());
+ append(SPACE);
+ }
+ append(END);
+ }
+
+ public void visit( Select obj ) {
+ append(SELECT);
+ if (obj.isDistinct()) {
+ append(SPACE);
+ append(DISTINCT);
+ }
+ beginClause(2);
+
+ Iterator iter = obj.getSymbols().iterator();
+ while (iter.hasNext()) {
+ SelectSymbol symbol = (SelectSymbol)iter.next();
+ visitNode(symbol);
+ if (iter.hasNext()) {
+ append(", "); //$NON-NLS-1$
+ }
+ }
+ }
+
+ public void visit( SetCriteria obj ) {
+ // variable
+ visitNode(obj.getExpression());
+
+ // operator and beginning of list
+ append(SPACE);
+ if (obj.isNegated()) {
+ append(NOT);
+ append(SPACE);
+ }
+ append(IN);
+ append(" ("); //$NON-NLS-1$
+
+ // value list
+ Collection vals = obj.getValues();
+ int size = vals.size();
+ if (size == 1) {
+ Iterator iter = vals.iterator();
+ Expression expr = (Expression)iter.next();
+ visitNode(expr);
+ } else if (size > 1) {
+ Iterator iter = vals.iterator();
+ Expression expr = (Expression)iter.next();
+ visitNode(expr);
+ while (iter.hasNext()) {
+ expr = (Expression)iter.next();
+ append(", "); //$NON-NLS-1$
+ visitNode(expr);
+ }
+ }
+ append(")"); //$NON-NLS-1$
+ }
+
+ public void visit( SetQuery obj ) {
+ addCacheHint(obj.getCacheHint());
+ addWithClause(obj);
+ QueryCommand query = obj.getLeftQuery();
+ appendSetQuery(obj, query, false);
+
+ beginClause(0);
+ append(obj.getOperation());
+
+ if (obj.isAll()) {
+ append(SPACE);
+ append(ALL);
+ }
+ beginClause(0);
+ query = obj.getRightQuery();
+ appendSetQuery(obj, query, true);
+
+ if (obj.getOrderBy() != null) {
+ beginClause(0);
+ visitNode(obj.getOrderBy());
+ }
+
+ if (obj.getLimit() != null) {
+ beginClause(0);
+ visitNode(obj.getLimit());
+ }
+
+ if (obj.getOption() != null) {
+ beginClause(0);
+ visitNode(obj.getOption());
+ }
+ }
+
+ protected void appendSetQuery( SetQuery parent,
+ QueryCommand obj,
+ boolean right ) {
+ if (right && ((obj instanceof SetQuery
+ && ((parent.isAll() && !((SetQuery)obj).isAll()) || parent.getOperation() != ((SetQuery)obj).getOperation())) || obj.getLimit() != null || obj.getOrderBy() != null)) {
+ append(Tokens.LPAREN);
+ visitNode(obj);
+ append(Tokens.RPAREN);
+ } else {
+ visitNode(obj);
+ }
+ }
+
+ public void visit( StoredProcedure obj ) {
+ addCacheHint(obj.getCacheHint());
+ if (obj.isCalledWithReturn()) {
+ for (SPParameter param : obj.getParameters()) {
+ if (param.getParameterType() == SPParameter.RETURN_VALUE) {
+ if (param.getExpression() == null) {
+ append("?"); //$NON-NLS-1$
+ } else {
+ visitNode(param.getExpression());
+ }
+ }
+ }
+ append(SPACE);
+ append(Tokens.EQ);
+ append(SPACE);
+ }
+ // exec clause
+ append(EXEC);
+ append(SPACE);
+ append(obj.getProcedureName());
+ append("("); //$NON-NLS-1$
+ boolean first = true;
+ for (SPParameter param : obj.getParameters()) {
+ if (param.isUsingDefault() || param.getParameterType() == SPParameter.RETURN_VALUE
+ || param.getParameterType() == SPParameter.RESULT_SET || param.getExpression() == null) {
+ continue;
+ }
+ if (first) {
+ first = false;
+ } else {
+ append(", "); //$NON-NLS-1$
+ }
+ if (obj.displayNamedParameters()) {
+ append(escapeSinglePart(ElementSymbol.getShortName(param.getParameterSymbol().getOutputName())));
+ append(" => "); //$NON-NLS-1$
+ }
+
+ boolean addParens = !obj.displayNamedParameters() && param.getExpression() instanceof CompareCriteria;
+ if (addParens) {
+ append(Tokens.LPAREN);
+ }
+ visitNode(param.getExpression());
+ if (addParens) {
+ append(Tokens.RPAREN);
+ }
+ }
+ append(")"); //$NON-NLS-1$
+
+ // Option clause
+ if (obj.getOption() != null) {
+ beginClause(1);
+ visitNode(obj.getOption());
+ }
+ }
+
+ public void addCacheHint( CacheHint obj ) {
+ if (obj == null) {
+ return;
+ }
+ append(BEGIN_HINT);
+ append(SPACE);
+ append(CacheHint.CACHE);
+ boolean addParens = false;
+ if (obj.getPrefersMemory()) {
+ append(Tokens.LPAREN);
+ addParens = true;
+ append(CacheHint.PREF_MEM);
+ }
+ if (obj.getTtl() != null) {
+ if (!addParens) {
+ append(Tokens.LPAREN);
+ addParens = true;
+ } else {
+ append(SPACE);
+ }
+ append(CacheHint.TTL);
+ append(obj.getTtl());
+ }
+ if (obj.isUpdatable()) {
+ if (!addParens) {
+ append(Tokens.LPAREN);
+ addParens = true;
+ } else {
+ append(SPACE);
+ }
+ append(CacheHint.UPDATABLE);
+ }
+ if (obj.getScope() != null) {
+ if (!addParens) {
+ append(Tokens.LPAREN);
+ addParens = true;
+ } else {
+ append(SPACE);
+ }
+ append(CacheHint.SCOPE);
+ append(obj.getScope());
+ }
+ if (addParens) {
+ append(Tokens.RPAREN);
+ }
+ append(SPACE);
+ append(END_HINT);
+ beginClause(0);
+ }
+
+ public void visit( SubqueryFromClause obj ) {
+ addHintComment(obj);
+ if (obj.isTable()) {
+ append(TABLE);
+ }
+ append("(");//$NON-NLS-1$
+ visitNode(obj.getCommand());
+ append(")");//$NON-NLS-1$
+ append(" AS ");//$NON-NLS-1$
+ append(obj.getOutputName());
+ }
+
+ public void visit( SubquerySetCriteria obj ) {
+ // variable
+ visitNode(obj.getExpression());
+
+ // operator and beginning of list
+ append(SPACE);
+ if (obj.isNegated()) {
+ append(NOT);
+ append(SPACE);
+ }
+ append(IN);
+ addSubqueryHint(obj.getSubqueryHint());
+ append(" ("); //$NON-NLS-1$
+ visitNode(obj.getCommand());
+ append(")"); //$NON-NLS-1$
+ }
+
+ public void visit( UnaryFromClause obj ) {
+ addHintComment(obj);
+ visitNode(obj.getGroup());
+ }
+
+ public void visit( Update obj ) {
+ // Update clause
+ append(UPDATE);
+ append(SPACE);
+ visitNode(obj.getGroup());
+ beginClause(1);
+ // Set clause
+ append(SET);
+ beginClause(2);
+ visitNode(obj.getChangeList());
+
+ // Where clause
+ if (obj.getCriteria() != null) {
+ beginClause(1);
+ visitCriteria(WHERE, obj.getCriteria());
+ }
+
+ // Option clause
+ if (obj.getOption() != null) {
+ beginClause(1);
+ visitNode(obj.getOption());
+ }
+ }
+
+ public void visit( Into obj ) {
+ append(INTO);
+ append(SPACE);
+ visitNode(obj.getGroup());
+ }
+
+ // ############ Visitor methods for symbol objects ####################
+
+ public void visit( AggregateSymbol obj ) {
+ append(obj.getAggregateFunction().name());
+ append("("); //$NON-NLS-1$
+
+ if (obj.isDistinct()) {
+ append(DISTINCT);
+ append(" "); //$NON-NLS-1$
+ }
+
+ if (obj.getExpression() == null) {
+ append(Tokens.ALL_COLS);
+ } else {
+ visitNode(obj.getExpression());
+ }
+
+ if (obj.getOrderBy() != null) {
+ append(SPACE);
+ visitNode(obj.getOrderBy());
+ }
+ append(")"); //$NON-NLS-1$
+ }
+
+ public void visit( AliasSymbol obj ) {
+ visitNode(obj.getSymbol());
+ append(SPACE);
+ append(AS);
+ append(SPACE);
+ append(escapeSinglePart(obj.getOutputName()));
+ }
+
+ public void visit( AllInGroupSymbol obj ) {
+ append(obj.getName());
+ }
+
+ public void visit( AllSymbol obj ) {
+ append(obj.getName());
+ }
+
+ public void visit( Constant obj ) {
+ Class<?> type = obj.getType();
+ String[] constantParts = null;
+ if (obj.isMultiValued()) {
+ constantParts = new String[] {"?"}; //$NON-NLS-1$
+ } else if (obj.isNull()) {
+ if (type.equals(DataTypeManager.DefaultDataClasses.BOOLEAN)) {
+ constantParts = new String[] {UNKNOWN};
+ } else {
+ constantParts = new String[] {"null"}; //$NON-NLS-1$
+ }
+ } else {
+ if (Number.class.isAssignableFrom(type)) {
+ constantParts = new String[] {obj.getValue().toString()};
+ } else if (type.equals(DataTypeManager.DefaultDataClasses.BOOLEAN)) {
+ constantParts = new String[] {obj.getValue().equals(Boolean.TRUE) ? TRUE : FALSE};
+ } else if (type.equals(DataTypeManager.DefaultDataClasses.TIMESTAMP)) {
+ constantParts = new String[] {"{ts'", obj.getValue().toString(), "'}"}; //$NON-NLS-1$ //$NON-NLS-2$
+ } else if (type.equals(DataTypeManager.DefaultDataClasses.TIME)) {
+ constantParts = new String[] {"{t'", obj.getValue().toString(), "'}"}; //$NON-NLS-1$ //$NON-NLS-2$
+ } else if (type.equals(DataTypeManager.DefaultDataClasses.DATE)) {
+ constantParts = new String[] {"{d'", obj.getValue().toString(), "'}"}; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (constantParts == null) {
+ String strValue = obj.getValue().toString();
+ strValue = escapeStringValue(strValue, "'"); //$NON-NLS-1$
+ constantParts = new String[] {"'", strValue, "'"}; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ for (String string : constantParts) {
+ append(string);
+ }
+ }
+
+ /**
+ * Take a string literal and escape it as necessary. By default, this converts ' to ''.
+ *
+ * @param str String literal value (unquoted), never null
+ * @return Escaped string literal value
+ */
+ static String escapeStringValue( String str,
+ String tick ) {
+ return StringUtil.replaceAll(str, tick, tick + tick);
+ }
+
+ public void visit( ElementSymbol obj ) {
+ if (obj.getDisplayMode().equals(ElementSymbol.DisplayMode.SHORT_OUTPUT_NAME)) {
+ outputShortName(obj);
+ return;
+ }
+ String name = obj.getOutputName();
+ if (obj.getDisplayMode().equals(ElementSymbol.DisplayMode.FULLY_QUALIFIED)) {
+ name = obj.getName();
+ }
+ outputDisplayName(name);
+ }
+
+ private void outputShortName( ElementSymbol obj ) {
+ outputDisplayName(SingleElementSymbol.getShortName(obj.getOutputName()));
+ }
+
+ private void outputDisplayName( String name ) {
+ String[] pathParts = name.split("\\."); //$NON-NLS-1$
+ for (int i = 0; i < pathParts.length; i++) {
+ if (i > 0) {
+ append(ElementSymbol.SEPARATOR);
+ }
+ append(escapeSinglePart(pathParts[i]));
+ }
+ }
+
+ public void visit( ExpressionSymbol obj ) {
+ visitNode(obj.getExpression());
+ }
+
+ public void visit( Function obj ) {
+ String name = obj.getName();
+ Expression[] args = obj.getArgs();
+ if (obj.isImplicit()) {
+ // Hide this function, which is implicit
+ visitNode(args[0]);
+
+ } else if (name.equalsIgnoreCase(CONVERT) || name.equalsIgnoreCase(CAST)) {
+ append(name);
+ append("("); //$NON-NLS-1$
+
+ if (args != null && args.length > 0) {
+ visitNode(args[0]);
+
+ if (name.equalsIgnoreCase(CONVERT)) {
+ append(", "); //$NON-NLS-1$
+ } else {
+ append(" "); //$NON-NLS-1$
+ append(AS);
+ append(" "); //$NON-NLS-1$
+ }
+
+ if (args.length < 2 || args[1] == null || !(args[1] instanceof Constant)) {
+ append(UNDEFINED);
+ } else {
+ append(((Constant)args[1]).getValue());
+ }
+ }
+ append(")"); //$NON-NLS-1$
+
+ } else if (name.equals("+") || name.equals("-") || name.equals("*") || name.equals("/") || name.equals("||")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ append("("); //$NON-NLS-1$
+
+ if (args != null) {
+ for (int i = 0; i < args.length; i++) {
+ visitNode(args[i]);
+ if (i < (args.length - 1)) {
+ append(SPACE);
+ append(name);
+ append(SPACE);
+ }
+ }
+ }
+ append(")"); //$NON-NLS-1$
+
+ } else if (name.equalsIgnoreCase(NonReserved.TIMESTAMPADD) || name.equalsIgnoreCase(NonReserved.TIMESTAMPDIFF)) {
+ append(name);
+ append("("); //$NON-NLS-1$
+
+ if (args != null && args.length > 0) {
+ append(((Constant)args[0]).getValue());
+ registerNodes(args, 1);
+ }
+ append(")"); //$NON-NLS-1$
+
+ } else if (name.equalsIgnoreCase(SourceSystemFunctions.XMLPI)) {
+ append(name);
+ append("(NAME "); //$NON-NLS-1$
+ outputDisplayName((String)((Constant)args[0]).getValue());
+ registerNodes(args, 1);
+ append(")"); //$NON-NLS-1$
+ } else {
+ append(name);
+ append("("); //$NON-NLS-1$
+ registerNodes(args, 0);
+ append(")"); //$NON-NLS-1$
+ }
+ }
+
+ private void registerNodes( LanguageObject[] objects,
+ int begin ) {
+ registerNodes(Arrays.asList(objects), begin);
+ }
+
+ private void registerNodes( List<? extends LanguageObject> objects,
+ int begin ) {
+ for (int i = begin; i < objects.size(); i++) {
+ if (i > 0) {
+ append(", "); //$NON-NLS-1$
+ }
+ visitNode(objects.get(i));
+ }
+ }
+
+ public void visit( GroupSymbol obj ) {
+ String alias = null;
+ String fullGroup = obj.getOutputName();
+ if (obj.getOutputDefinition() != null) {
+ alias = obj.getOutputName();
+ fullGroup = obj.getOutputDefinition();
+ }
+
+ outputDisplayName(fullGroup);
+
+ if (alias != null) {
+ append(SPACE);
+ append(AS);
+ append(SPACE);
+ append(escapeSinglePart(alias));
+ }
+ }
+
+ public void visit( Reference obj ) {
+ if (!obj.isPositional() && obj.getExpression() != null) {
+ visitNode(obj.getExpression());
+ } else {
+ append("?"); //$NON-NLS-1$
+ }
+ }
+
+ // ############ Visitor methods for storedprocedure language objects ####################
+
+ public void visit( Block obj ) {
+ List statements = obj.getStatements();
+ // Add first clause
+ append(BEGIN);
+ append("\n"); //$NON-NLS-1$
+ Iterator stmtIter = statements.iterator();
+ while (stmtIter.hasNext()) {
+ // Add each statement
+ addTabs(1);
+ visitNode((Statement)stmtIter.next());
+ append("\n"); //$NON-NLS-1$
+ }
+ addTabs(0);
+ append(END);
+ }
+
+ protected void addTabs( int level ) {
+ }
+
+ public void visit( CommandStatement obj ) {
+ visitNode(obj.getCommand());
+ append(";"); //$NON-NLS-1$
+ }
+
+ public void visit( CreateUpdateProcedureCommand obj ) {
+ append(CREATE);
+ append(SPACE);
+ if (!obj.isUpdateProcedure()) {
+ append(VIRTUAL);
+ append(SPACE);
+ }
+ append(PROCEDURE);
+ append("\n"); //$NON-NLS-1$
+ addTabs(0);
+ visitNode(obj.getBlock());
+ }
+
+ public void visit( DeclareStatement obj ) {
+ append(DECLARE);
+ append(SPACE);
+ append(obj.getVariableType());
+ append(SPACE);
+ createAssignment(obj);
+ }
+
+ /**
+ * @param obj
+ * @param parts
+ */
+ private void createAssignment( AssignmentStatement obj ) {
+ visitNode(obj.getVariable());
+ if (obj.getExpression() != null) {
+ append(" = "); //$NON-NLS-1$
+ visitNode(obj.getExpression());
+ }
+ append(";"); //$NON-NLS-1$
+ }
+
+ public void visit( IfStatement obj ) {
+ append(IF);
+ append("("); //$NON-NLS-1$
+ visitNode(obj.getCondition());
+ append(")\n"); //$NON-NLS-1$
+ addTabs(0);
+ visitNode(obj.getIfBlock());
+ if (obj.hasElseBlock()) {
+ append("\n"); //$NON-NLS-1$
+ addTabs(0);
+ append(ELSE);
+ append("\n"); //$NON-NLS-1$
+ addTabs(0);
+ visitNode(obj.getElseBlock());
+ }
+ }
+
+ public void visit( AssignmentStatement obj ) {
+ createAssignment(obj);
+ }
+
+ public void visit( HasCriteria obj ) {
+ append(HAS);
+ append(SPACE);
+ visitNode(obj.getSelector());
+ }
+
+ public void visit( TranslateCriteria obj ) {
+ append(TRANSLATE);
+ append(SPACE);
+ visitNode(obj.getSelector());
+
+ if (obj.hasTranslations()) {
+ append(SPACE);
+ append(WITH);
+ append(SPACE);
+ append("("); //$NON-NLS-1$
+ Iterator critIter = obj.getTranslations().iterator();
+
+ while (critIter.hasNext()) {
+ visitNode((Criteria)critIter.next());
+ if (critIter.hasNext()) {
+ append(", "); //$NON-NLS-1$
+ }
+ if (!critIter.hasNext()) {
+ append(")"); //$NON-NLS-1$
+ }
+ }
+ }
+ }
+
+ public void visit( CriteriaSelector obj ) {
+ int selectorType = obj.getSelectorType();
+
+ switch (selectorType) {
+ case CriteriaSelector.COMPARE_EQ:
+ append("= "); //$NON-NLS-1$
+ break;
+ case CriteriaSelector.COMPARE_GE:
+ append(">= "); //$NON-NLS-1$
+ break;
+ case CriteriaSelector.COMPARE_GT:
+ append("> "); //$NON-NLS-1$
+ break;
+ case CriteriaSelector.COMPARE_LE:
+ append("<= "); //$NON-NLS-1$
+ break;
+ case CriteriaSelector.COMPARE_LT:
+ append("< "); //$NON-NLS-1$
+ break;
+ case CriteriaSelector.COMPARE_NE:
+ append("<> "); //$NON-NLS-1$
+ break;
+ case CriteriaSelector.IN:
+ append(IN);
+ append(SPACE);
+ break;
+ case CriteriaSelector.IS_NULL:
+ append(IS);
+ append(SPACE);
+ append(NULL);
+ append(SPACE);
+ break;
+ case CriteriaSelector.LIKE:
+ append(LIKE);
+ append(SPACE);
+ break;
+ case CriteriaSelector.BETWEEN:
+ append(BETWEEN);
+ append(SPACE);
+ break;
+ }
+
+ append(CRITERIA);
+ if (obj.hasElements()) {
+ append(SPACE);
+ append(ON);
+ append(SPACE);
+ append("("); //$NON-NLS-1$
+
+ Iterator elmtIter = obj.getElements().iterator();
+ while (elmtIter.hasNext()) {
+ visitNode((ElementSymbol)elmtIter.next());
+ if (elmtIter.hasNext()) {
+ append(", "); //$NON-NLS-1$
+ }
+ }
+ append(")"); //$NON-NLS-1$
+ }
+ }
+
+ public void visit( RaiseErrorStatement obj ) {
+ append(ERROR);
+ append(SPACE);
+ visitNode(obj.getExpression());
+ append(";"); //$NON-NLS-1$
+ }
+
+ public void visit( BreakStatement obj ) {
+ append(BREAK);
+ append(";"); //$NON-NLS-1$
+ }
+
+ public void visit( ContinueStatement obj ) {
+ append(CONTINUE);
+ append(";"); //$NON-NLS-1$
+ }
+
+ public void visit( LoopStatement obj ) {
+ append(LOOP);
+ append(" "); //$NON-NLS-1$
+ append(ON);
+ append(" ("); //$NON-NLS-1$
+ visitNode(obj.getCommand());
+ append(") "); //$NON-NLS-1$
+ append(AS);
+ append(" "); //$NON-NLS-1$
+ append(obj.getCursorName());
+ append("\n"); //$NON-NLS-1$
+ addTabs(0);
+ visitNode(obj.getBlock());
+ }
+
+ public void visit( WhileStatement obj ) {
+ append(WHILE);
+ append("("); //$NON-NLS-1$
+ visitNode(obj.getCondition());
+ append(")\n"); //$NON-NLS-1$
+ addTabs(0);
+ visitNode(obj.getBlock());
+ }
+
+ public void visit( ExistsCriteria obj ) {
+ if (obj.isNegated()) {
+ append(NOT);
+ append(SPACE);
+ }
+ append(EXISTS);
+ addSubqueryHint(obj.getSubqueryHint());
+ append(" ("); //$NON-NLS-1$
+ visitNode(obj.getCommand());
+ append(")"); //$NON-NLS-1$
+ }
+
+ public void addSubqueryHint(SubqueryHint hint) {
+ if (hint.isNoUnnest()) {
+ append(SPACE);
+ append(BEGIN_HINT);
+ append(SPACE);
+ 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);
+ append(SPACE);
+ append(SubqueryHint.MJ);
+ append(SPACE);
+ append(END_HINT);
+ }
+ }
+
+ public void visit( SubqueryCompareCriteria obj ) {
+ Expression leftExpression = obj.getLeftExpression();
+ visitNode(leftExpression);
+
+ String operator = obj.getOperatorAsString();
+ String quantifier = obj.getPredicateQuantifierAsString();
+
+ // operator and beginning of list
+ append(SPACE);
+ append(operator);
+ append(SPACE);
+ append(quantifier);
+ append("("); //$NON-NLS-1$
+ visitNode(obj.getCommand());
+ append(")"); //$NON-NLS-1$
+ }
+
+ public void visit( ScalarSubquery obj ) {
+ // operator and beginning of list
+ append("("); //$NON-NLS-1$
+ visitNode(obj.getCommand());
+ append(")"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void visit( XMLAttributes obj ) {
+ append(XMLATTRIBUTES);
+ append("("); //$NON-NLS-1$
+ registerNodes(obj.getArgs(), 0);
+ append(")"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void visit( XMLElement obj ) {
+ append(XMLELEMENT);
+ append("(NAME "); //$NON-NLS-1$
+ outputDisplayName(obj.getName());
+ if (obj.getNamespaces() != null) {
+ append(", "); //$NON-NLS-1$
+ visitNode(obj.getNamespaces());
+ }
+ if (obj.getAttributes() != null) {
+ append(", "); //$NON-NLS-1$
+ visitNode(obj.getAttributes());
+ }
+ if (!obj.getContent().isEmpty()) {
+ append(", "); //$NON-NLS-1$
+ }
+ registerNodes(obj.getContent(), 0);
+ append(")"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void visit( XMLForest obj ) {
+ append(XMLFOREST);
+ append("("); //$NON-NLS-1$
+ if (obj.getNamespaces() != null) {
+ visitNode(obj.getNamespaces());
+ append(", "); //$NON-NLS-1$
+ }
+ registerNodes(obj.getArgs(), 0);
+ append(")"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void visit( TextLine obj ) {
+ append(FOR);
+ append(SPACE);
+ registerNodes(obj.getExpressions(), 0);
+
+ if (obj.getDelimiter() != null) {
+ append(SPACE);
+ append(NonReserved.DELIMITER);
+ append(SPACE);
+ visitNode(new Constant(obj.getDelimiter()));
+ }
+ if (obj.getQuote() != null) {
+ append(SPACE);
+ append(NonReserved.QUOTE);
+ append(SPACE);
+ visitNode(new Constant(obj.getQuote()));
+ }
+ if (obj.isIncludeHeader()) {
+ append(SPACE);
+ append(NonReserved.HEADER);
+ }
+ if (obj.getEncoding() != null) {
+ append(SPACE);
+ append(NonReserved.ENCODING);
+ append(SPACE);
+ outputDisplayName(obj.getEncoding());
+ }
+ }
+
+ @Override
+ public void visit( XMLNamespaces obj ) {
+ append(XMLNAMESPACES);
+ append("("); //$NON-NLS-1$
+ for (Iterator<NamespaceItem> items = obj.getNamespaceItems().iterator(); items.hasNext();) {
+ NamespaceItem item = items.next();
+ if (item.getPrefix() == null) {
+ if (item.getUri() == null) {
+ append("NO DEFAULT"); //$NON-NLS-1$
+ } else {
+ append("DEFAULT "); //$NON-NLS-1$
+ visitNode(new Constant(item.getUri()));
+ }
+ } else {
+ visitNode(new Constant(item.getUri()));
+ append(" AS "); //$NON-NLS-1$
+ outputDisplayName(item.getPrefix());
+ }
+ if (items.hasNext()) {
+ append(", "); //$NON-NLS-1$
+ }
+ }
+ append(")"); //$NON-NLS-1$
+ }
+
+ public void visit( Limit obj ) {
+ append(LIMIT);
+ if (obj.getOffset() != null) {
+ append(SPACE);
+ visitNode(obj.getOffset());
+ append(","); //$NON-NLS-1$
+ }
+ append(SPACE);
+ visitNode(obj.getRowLimit());
+ }
+
+ @Override
+ public void visit( TextTable obj ) {
+ addHintComment(obj);
+ append("TEXTTABLE("); //$NON-NLS-1$
+ visitNode(obj.getFile());
+ append(SPACE);
+ append(NonReserved.COLUMNS);
+
+ for (Iterator<TextColumn> cols = obj.getColumns().iterator(); cols.hasNext();) {
+ TextColumn col = cols.next();
+ append(SPACE);
+ outputDisplayName(col.getName());
+ append(SPACE);
+ append(col.getType());
+ if (col.getWidth() != null) {
+ append(SPACE);
+ append(NonReserved.WIDTH);
+ append(SPACE);
+ append(col.getWidth());
+ }
+ if (cols.hasNext()) {
+ append(","); //$NON-NLS-1$
+ }
+ }
+ if (obj.getDelimiter() != null) {
+ append(SPACE);
+ append(NonReserved.DELIMITER);
+ append(SPACE);
+ visitNode(new Constant(obj.getDelimiter()));
+ }
+ if (obj.getQuote() != null) {
+ append(SPACE);
+ if (obj.isEscape()) {
+ append(ESCAPE);
+ } else {
+ append(NonReserved.QUOTE);
+ }
+ append(SPACE);
+ visitNode(new Constant(obj.getQuote()));
+ }
+ if (obj.getHeader() != null) {
+ append(SPACE);
+ append(NonReserved.HEADER);
+ if (1 != obj.getHeader()) {
+ append(SPACE);
+ append(obj.getHeader());
+ }
+ }
+ if (obj.getSkip() != null) {
+ append(SPACE);
+ append("SKIP"); //$NON-NLS-1$
+ append(SPACE);
+ append(obj.getSkip());
+ }
+ append(")");//$NON-NLS-1$
+ append(SPACE);
+ append(AS);
+ append(SPACE);
+ outputDisplayName(obj.getName());
+ }
+
+ @Override
+ public void visit( XMLTable obj ) {
+ addHintComment(obj);
+ append("XMLTABLE("); //$NON-NLS-1$
+ if (obj.getNamespaces() != null) {
+ visitNode(obj.getNamespaces());
+ append(","); //$NON-NLS-1$
+ append(SPACE);
+ }
+ visitNode(new Constant(obj.getXquery()));
+ if (!obj.getPassing().isEmpty()) {
+ append(SPACE);
+ append(NonReserved.PASSING);
+ append(SPACE);
+ registerNodes(obj.getPassing(), 0);
+ }
+ if (!obj.getColumns().isEmpty()) {
+ append(SPACE);
+ append(NonReserved.COLUMNS);
+ for (Iterator<XMLColumn> cols = obj.getColumns().iterator(); cols.hasNext();) {
+ XMLColumn col = cols.next();
+ append(SPACE);
+ outputDisplayName(col.getName());
+ append(SPACE);
+ if (col.isOrdinal()) {
+ append(FOR);
+ append(SPACE);
+ append(NonReserved.ORDINALITY);
+ } else {
+ append(col.getType());
+ if (col.getDefaultExpression() != null) {
+ append(SPACE);
+ append(DEFAULT);
+ append(SPACE);
+ visitNode(col.getDefaultExpression());
+ }
+ if (col.getPath() != null) {
+ append(SPACE);
+ append(NonReserved.PATH);
+ append(SPACE);
+ visitNode(new Constant(col.getPath()));
+ }
+ }
+ if (cols.hasNext()) {
+ append(","); //$NON-NLS-1$
+ }
+ }
+ }
+ append(")");//$NON-NLS-1$
+ append(SPACE);
+ append(AS);
+ append(SPACE);
+ outputDisplayName(obj.getName());
+ }
+
+ @Override
+ public void visit( XMLQuery obj ) {
+ append("XMLQUERY("); //$NON-NLS-1$
+ if (obj.getNamespaces() != null) {
+ visitNode(obj.getNamespaces());
+ append(","); //$NON-NLS-1$
+ append(SPACE);
+ }
+ visitNode(new Constant(obj.getXquery()));
+ if (!obj.getPassing().isEmpty()) {
+ append(SPACE);
+ append(NonReserved.PASSING);
+ append(SPACE);
+ registerNodes(obj.getPassing(), 0);
+ }
+ if (obj.getEmptyOnEmpty() != null) {
+ append(SPACE);
+ if (obj.getEmptyOnEmpty()) {
+ append(NonReserved.EMPTY);
+ } else {
+ append(NULL);
+ }
+ append(SPACE);
+ append(ON);
+ append(SPACE);
+ append(NonReserved.EMPTY);
+ }
+ append(")");//$NON-NLS-1$
+ }
+
+ @Override
+ public void visit( DerivedColumn obj ) {
+ visitNode(obj.getExpression());
+ if (obj.getAlias() != null) {
+ append(SPACE);
+ append(AS);
+ append(SPACE);
+ outputDisplayName(obj.getAlias());
+ }
+ }
+
+ @Override
+ public void visit( XMLSerialize obj ) {
+ append(XMLSERIALIZE);
+ append(Tokens.LPAREN);
+ if (obj.isDocument() != null) {
+ if (obj.isDocument()) {
+ append(NonReserved.DOCUMENT);
+ } else {
+ append(NonReserved.CONTENT);
+ }
+ append(SPACE);
+ }
+ visitNode(obj.getExpression());
+ if (obj.getTypeString() != null) {
+ append(SPACE);
+ append(AS);
+ append(SPACE);
+ append(obj.getTypeString());
+ }
+ append(Tokens.RPAREN);
+ }
+
+ @Override
+ public void visit( QueryString obj ) {
+ append(NonReserved.QUERYSTRING);
+ append("("); //$NON-NLS-1$
+ visitNode(obj.getPath());
+ if (!obj.getArgs().isEmpty()) {
+ append(","); //$NON-NLS-1$
+ append(SPACE);
+ registerNodes(obj.getArgs(), 0);
+ }
+ append(")"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void visit( XMLParse obj ) {
+ append(XMLPARSE);
+ append(Tokens.LPAREN);
+ if (obj.isDocument()) {
+ append(NonReserved.DOCUMENT);
+ } else {
+ append(NonReserved.CONTENT);
+ }
+ append(SPACE);
+ visitNode(obj.getExpression());
+ if (obj.isWellFormed()) {
+ append(SPACE);
+ append(NonReserved.WELLFORMED);
+ }
+ append(Tokens.RPAREN);
+ }
+
+ @Override
+ public void visit( ExpressionCriteria obj ) {
+ visitNode(obj.getExpression());
+ }
+
+ @Override
+ public void visit(TriggerAction obj) {
+ append(FOR);
+ append(SPACE);
+ append(EACH);
+ append(SPACE);
+ append(ROW);
+ append("\n"); //$NON-NLS-1$
+ addTabs(0);
+ visitNode(obj.getBlock());
+ }
+
+ @Override
+ public void visit(ArrayTable obj) {
+ addHintComment(obj);
+ append("ARRAYTABLE("); //$NON-NLS-1$
+ visitNode(obj.getArrayValue());
+ append(SPACE);
+ append(NonReserved.COLUMNS);
+
+ for (Iterator<ProjectedColumn> cols = obj.getColumns().iterator(); cols.hasNext();) {
+ ProjectedColumn col = cols.next();
+ append(SPACE);
+ outputDisplayName(col.getName());
+ append(SPACE);
+ append(col.getType());
+ if (cols.hasNext()) {
+ append(","); //$NON-NLS-1$
+ }
+ }
+
+ append(")");//$NON-NLS-1$
+ append(SPACE);
+ append(AS);
+ append(SPACE);
+ outputDisplayName(obj.getName());
+ }
+
+ @Override
+ public void visit(AlterProcedure alterProcedure) {
+ append(ALTER);
+ append(SPACE);
+ append(PROCEDURE);
+ append(SPACE);
+ append(alterProcedure.getTarget());
+ beginClause(1);
+ append(AS);
+ addCacheHint(alterProcedure.getCacheHint());
+ append(alterProcedure.getDefinition().getBlock());
+ }
+
+ @Override
+ public void visit(AlterTrigger alterTrigger) {
+ if (alterTrigger.isCreate()) {
+ append(CREATE);
+ } else {
+ append(ALTER);
+ }
+ append(SPACE);
+ append(TRIGGER);
+ append(SPACE);
+ append(ON);
+ append(SPACE);
+ append(alterTrigger.getTarget());
+ beginClause(0);
+ append(NonReserved.INSTEAD);
+ append(SPACE);
+ append(OF);
+ append(SPACE);
+ append(alterTrigger.getEvent());
+ if (alterTrigger.getDefinition() != null) {
+ beginClause(0);
+ append(AS);
+ append("\n"); //$NON-NLS-1$
+ addTabs(0);
+ append(alterTrigger.getDefinition());
+ } else {
+ append(SPACE);
+ append(alterTrigger.getEnabled()?NonReserved.ENABLED:NonReserved.DISABLED);
+ }
+ }
+
+ @Override
+ public void visit(AlterView alterView) {
+ append(ALTER);
+ append(SPACE);
+ append(NonReserved.VIEW);
+ append(SPACE);
+ append(alterView.getTarget());
+ beginClause(0);
+ append(AS);
+ append("\n"); //$NON-NLS-1$
+ addTabs(0);
+ append(alterView.getDefinition());
+ }
+
+ public static String escapeSinglePart( String part ) {
+ if (isReservedWord(part)) {
+ return ID_ESCAPE_CHAR + part + ID_ESCAPE_CHAR;
+ }
+ boolean escape = true;
+ char start = part.charAt(0);
+ if (start == '#' || start == '@' || StringUtil.isLetter(start)) {
+ escape = false;
+ for (int i = 1; !escape && i < part.length(); i++) {
+ char c = part.charAt(i);
+ escape = !StringUtil.isLetterOrDigit(c) && c != '_';
+ }
+ }
+ if (escape) {
+ return ID_ESCAPE_CHAR + escapeStringValue(part, "\"") + ID_ESCAPE_CHAR; //$NON-NLS-1$
+ }
+ return part;
+ }
+
+ /**
+ * Check whether a string is considered a reserved word or not. Subclasses may override to change definition of reserved word.
+ *
+ * @param string String to check
+ * @return True if reserved word
+ */
+ static boolean isReservedWord( String string ) {
+ if (string == null) {
+ return false;
+ }
+ return SQLConstants.isReservedWord(string);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,643 +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.tempdata;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.Executor;
-import java.util.concurrent.FutureTask;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryProcessingException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.cache.Cache;
-import org.teiid.cache.CacheConfiguration;
-import org.teiid.cache.CacheFactory;
-import org.teiid.cache.CacheConfiguration.Policy;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.TupleBuffer;
-import org.teiid.common.buffer.TupleSource;
-import org.teiid.core.CoreConstants;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.HashCodeUtil;
-import org.teiid.core.util.StringUtil;
-import org.teiid.dqp.internal.process.CachedResults;
-import org.teiid.dqp.internal.process.SessionAwareCache;
-import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
-import org.teiid.events.EventDistributor;
-import org.teiid.language.SQLConstants.Reserved;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.metadata.MetadataRepository;
-import org.teiid.metadata.FunctionMethod.Determinism;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.eval.Evaluator;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataID;
-import org.teiid.query.optimizer.relational.RelationalPlanner;
-import org.teiid.query.parser.ParseInfo;
-import org.teiid.query.processor.BatchCollector;
-import org.teiid.query.processor.CollectionTupleSource;
-import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.processor.QueryProcessor;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.sql.lang.CacheHint;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.Create;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.Drop;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.Option;
-import org.teiid.query.sql.lang.ProcedureContainer;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.navigator.PostOrderNavigator;
-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.GroupSymbol;
-import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
-import org.teiid.query.tempdata.TempTableStore.MatState;
-import org.teiid.query.tempdata.TempTableStore.MatTableInfo;
-import org.teiid.query.util.CommandContext;
-import org.teiid.vdb.runtime.VDBKey;
-
-/**
- * This proxy ProcessorDataManager is used to handle temporary tables.
- *
- * This isn't handled as a connector because of the temporary metadata and
- * the create/drop handling (which doesn't have push down support)
- */
-public class TempTableDataManager implements ProcessorDataManager {
-
- private static final String REFRESHMATVIEWROW = ".refreshmatviewrow"; //$NON-NLS-1$
- private static final String REFRESHMATVIEW = ".refreshmatview"; //$NON-NLS-1$
- private static final String CODE_PREFIX = "#CODE_"; //$NON-NLS-1$
-
- private ProcessorDataManager processorDataManager;
- private BufferManager bufferManager;
- private SessionAwareCache<CachedResults> cache;
- private Executor executor;
-
- private static class MatTableKey implements Serializable {
- private static final long serialVersionUID = 5481692896572663992L;
- String name;
- VDBKey vdb;
-
- @Override
- public int hashCode() {
- return HashCodeUtil.hashCode(name.hashCode(), vdb);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (!(obj instanceof MatTableKey)) {
- return false;
- }
- MatTableKey other = (MatTableKey)obj;
- return this.name.equals(other.name) && this.vdb.equals(other.vdb);
- }
- }
-
- private static class MatTableEntry implements Serializable {
- private static final long serialVersionUID = 8559613701442751579L;
- long lastUpdate = System.currentTimeMillis();
- boolean valid;
- }
-
- private Cache<MatTableKey, MatTableEntry> tables;
- private SessionAwareCache<CachedResults> distributedCache;
- private EventDistributor eventDistributor;
-
- public TempTableDataManager(ProcessorDataManager processorDataManager, BufferManager bufferManager,
- Executor executor, SessionAwareCache<CachedResults> cache, SessionAwareCache<CachedResults> distibutedCache, CacheFactory cacheFactory){
- this.processorDataManager = processorDataManager;
- this.bufferManager = bufferManager;
- this.executor = executor;
- this.cache = cache;
- this.distributedCache = distibutedCache;
- if (distibutedCache != null) {
- CacheConfiguration cc = new CacheConfiguration(Policy.LRU, -1, -1, "MaterializationUpdates"); //$NON-NLS-1$
- tables = cacheFactory.get(cc.getLocation(), cc);
- }
- }
-
- public void setEventDistributor(EventDistributor eventDistributor) {
- this.eventDistributor = eventDistributor;
- }
-
- public TupleSource registerRequest(
- CommandContext context,
- Command command,
- String modelName,
- String connectorBindingId, int nodeID, int limit)
- throws TeiidComponentException, TeiidProcessingException {
-
- TempTableStore tempTableStore = context.getTempTableStore();
- if(tempTableStore != null) {
- TupleSource result = registerRequest(context, modelName, command);
- if (result != null) {
- return result;
- }
- }
- return this.processorDataManager.registerRequest(context, command, modelName, connectorBindingId, nodeID, limit);
- }
-
- TupleSource registerRequest(CommandContext context, String modelName, Command command) throws TeiidComponentException, TeiidProcessingException {
- TempTableStore contextStore = context.getTempTableStore();
- if (command instanceof Query) {
- Query query = (Query)command;
- return registerQuery(context, contextStore, query);
- }
- if (command instanceof ProcedureContainer) {
- if (command instanceof StoredProcedure) {
- StoredProcedure proc = (StoredProcedure)command;
- if (CoreConstants.SYSTEM_ADMIN_MODEL.equals(modelName)) {
- TupleSource result = handleSystemProcedures(context, proc);
- if (result != null) {
- return result;
- }
- } else if (proc.getGroup().isGlobalTable()) {
- return handleCachedProcedure(context, proc);
- }
- return null; //it's not a stored procedure we want to handle
- }
-
- GroupSymbol group = ((ProcedureContainer)command).getGroup();
- if (!group.isTempGroupSymbol()) {
- return null;
- }
- final String groupKey = group.getNonCorrelationName().toUpperCase();
- final TempTable table = contextStore.getOrCreateTempTable(groupKey, command, bufferManager, false);
- if (command instanceof Insert) {
- Insert insert = (Insert)command;
- TupleSource ts = insert.getTupleSource();
- if (ts == null) {
- List<Object> values = new ArrayList<Object>(insert.getValues().size());
- for (Expression expr : (List<Expression>)insert.getValues()) {
- values.add(Evaluator.evaluate(expr));
- }
- ts = new CollectionTupleSource(Arrays.asList(values).iterator());
- }
- return table.insert(ts, insert.getVariables());
- }
- if (command instanceof Update) {
- final Update update = (Update)command;
- final Criteria crit = update.getCriteria();
- return table.update(crit, update.getChangeList());
- }
- if (command instanceof Delete) {
- final Delete delete = (Delete)command;
- final Criteria crit = delete.getCriteria();
- if (crit == null) {
- //because we are non-transactional, just use a truncate
- int rows = table.truncate();
- return CollectionTupleSource.createUpdateCountTupleSource(rows);
- }
- return table.delete(crit);
- }
- }
- if (command instanceof Create) {
- Create create = (Create)command;
- String tempTableName = create.getTable().getCanonicalName();
- if (contextStore.hasTempTable(tempTableName)) {
- throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableStore.table_exist_error", tempTableName));//$NON-NLS-1$
- }
- contextStore.addTempTable(tempTableName, create, bufferManager, true);
- return CollectionTupleSource.createUpdateCountTupleSource(0);
- }
- if (command instanceof Drop) {
- String tempTableName = ((Drop)command).getTable().getCanonicalName();
- contextStore.removeTempTableByName(tempTableName);
- return CollectionTupleSource.createUpdateCountTupleSource(0);
- }
- return null;
- }
-
- private TupleSource handleCachedProcedure(CommandContext context,
- StoredProcedure proc) throws TeiidComponentException,
- QueryMetadataException, TeiidProcessingException {
- String fullName = context.getMetadata().getFullName(proc.getProcedureID());
- LogManager.logDetail(LogConstants.CTX_DQP, "processing cached procedure request for", fullName); //$NON-NLS-1$
- LinkedList<Object> vals = new LinkedList<Object>();
- for (SPParameter param : proc.getInputParameters()) {
- vals.add(((Constant)param.getExpression()).getValue());
- }
- //collapse the hash to single byte for the key to restrict the possible results to 256
- int hash = vals.hashCode();
- hash |= (hash >>> 16);
- hash |= (hash >>> 8);
- hash &= 0x000000ff;
- CacheID cid = new CacheID(new ParseInfo(), fullName + hash, context.getVdbName(),
- context.getVdbVersion(), context.getConnectionID(), context.getUserName());
- cid.setParameters(vals);
- CachedResults results = cache.get(cid);
- if (results != null) {
- TupleBuffer buffer = results.getResults();
- return buffer.createIndexedTupleSource();
- }
- //construct a query with a no cache hint
- //note that it's safe to use the stringified form of the parameters because
- //it's not possible to use xml/clob/blob/object
- CacheHint hint = proc.getCacheHint();
- proc.setCacheHint(null);
- Option option = new Option();
- option.setNoCache(true);
- option.addNoCacheGroup(fullName);
- proc.setOption(option);
- Determinism determinismLevel = context.resetDeterminismLevel();
- QueryProcessor qp = context.getQueryProcessorFactory().createQueryProcessor(proc.toString(), fullName.toUpperCase(), context);
- qp.setNonBlocking(true);
- qp.getContext().setDataObjects(null);
- BatchCollector bc = qp.createBatchCollector();
- TupleBuffer tb = bc.collectTuples();
- CachedResults cr = new CachedResults();
- cr.setResults(tb, qp.getProcessorPlan());
- cr.setHint(hint);
- if (hint != null && hint.getDeterminism() != null) {
- LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Cache hint modified the query determinism from ",determinismLevel, " to ", hint.getDeterminism() }); //$NON-NLS-1$ //$NON-NLS-2$
- determinismLevel = hint.getDeterminism();
- }
- cache.put(cid, determinismLevel, cr, hint != null?hint.getTtl():null);
- context.setDeterminismLevel(determinismLevel);
- return tb.createIndexedTupleSource();
- }
-
- private TupleSource handleSystemProcedures(CommandContext context, StoredProcedure proc)
- throws TeiidComponentException, QueryMetadataException,
- QueryProcessingException, QueryResolverException,
- QueryValidatorException, TeiidProcessingException,
- ExpressionEvaluationException {
- QueryMetadataInterface metadata = context.getMetadata();
- TempTableStore globalStore = context.getGlobalTableStore();
- if (StringUtil.endsWithIgnoreCase(proc.getProcedureCallableName(), REFRESHMATVIEW)) {
- Object groupID = validateMatView(metadata, proc);
- 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());
- if (invalidate) {
- touchTable(context, matTableName, false);
- }
- MatState oldState = info.setState(MatState.NEEDS_LOADING, invalidate?Boolean.FALSE:null, null);
- if (oldState == MatState.LOADING) {
- return CollectionTupleSource.createUpdateCountTupleSource(-1);
- }
- GroupSymbol matTable = new GroupSymbol(matTableName);
- matTable.setMetadataID(matTableId);
- int rowCount = loadGlobalTable(context, matTable, matTableName, globalStore, info, null);
- return CollectionTupleSource.createUpdateCountTupleSource(rowCount);
- } else if (StringUtil.endsWithIgnoreCase(proc.getProcedureCallableName(), REFRESHMATVIEWROW)) {
- Object groupID = validateMatView(metadata, proc);
- Object pk = metadata.getPrimaryKey(groupID);
- String matViewName = metadata.getFullName(groupID);
- if (pk == null) {
- throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.row_refresh_pk", matViewName)); //$NON-NLS-1$
- }
- List<?> ids = metadata.getElementIDsInKey(pk);
- if (ids.size() > 1) {
- throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.row_refresh_composite", matViewName)); //$NON-NLS-1$
- }
- String matTableName = RelationalPlanner.MAT_PREFIX+matViewName.toUpperCase();
- MatTableInfo info = globalStore.getMatTableInfo(matTableName);
- if (!info.isValid()) {
- return CollectionTupleSource.createUpdateCountTupleSource(-1);
- }
- TempTable tempTable = globalStore.getOrCreateTempTable(matTableName, new Query(), bufferManager, false);
- if (!tempTable.isUpdatable()) {
- throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.row_refresh_updatable", matViewName)); //$NON-NLS-1$
- }
- Constant key = (Constant)proc.getParameter(2).getExpression();
- LogManager.logInfo(LogConstants.CTX_MATVIEWS, QueryPlugin.Util.getString("TempTableDataManager.row_refresh", matViewName, key)); //$NON-NLS-1$
- String queryString = Reserved.SELECT + " * " + Reserved.FROM + ' ' + matViewName + ' ' + Reserved.WHERE + ' ' + //$NON-NLS-1$
- metadata.getFullName(ids.iterator().next()) + " = ?" + ' ' + Reserved.OPTION + ' ' + Reserved.NOCACHE; //$NON-NLS-1$
- QueryProcessor qp = context.getQueryProcessorFactory().createQueryProcessor(queryString, matViewName.toUpperCase(), context, key.getValue());
- qp.setNonBlocking(true);
- qp.getContext().setDataObjects(null);
- TupleSource ts = new BatchCollector.BatchProducerTupleSource(qp);
- List<?> tuple = ts.nextTuple();
- boolean delete = false;
- if (tuple == null) {
- delete = true;
- tuple = Arrays.asList(key.getValue());
- }
- List<?> result = updateMatViewRow(globalStore, matTableName, tuple, delete);
- if (result != null && eventDistributor != null) {
- this.eventDistributor.updateMatViewRow(context.getVdbName(), context.getVdbVersion(), metadata.getName(metadata.getModelID(groupID)), metadata.getName(groupID), tuple, delete);
- }
- return CollectionTupleSource.createUpdateCountTupleSource(result != null ? 1 : 0);
- }
- return null;
- }
-
- public List<?> updateMatViewRow(TempTableStore globalStore,
- String matTableName, List<?> tuple, boolean delete)
- throws QueryProcessingException, TeiidComponentException {
- TempTable tempTable = globalStore.getOrCreateTempTable(matTableName, new Query(), bufferManager, false);
- return tempTable.updateTuple(tuple, delete);
- }
-
- private Object validateMatView(QueryMetadataInterface metadata,
- StoredProcedure proc) throws TeiidComponentException,
- TeiidProcessingException {
- String name = (String)((Constant)proc.getParameter(1).getExpression()).getValue();
- try {
- Object groupID = metadata.getGroupID(name);
- if (!metadata.hasMaterialization(groupID) || metadata.getMaterialization(groupID) != null) {
- throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.not_implicit_matview", name)); //$NON-NLS-1$
- }
- return groupID;
- } catch (QueryMetadataException e) {
- throw new TeiidProcessingException(e);
- }
- }
-
- private TupleSource registerQuery(final CommandContext context,
- TempTableStore contextStore, Query query)
- throws TeiidComponentException, QueryMetadataException,
- TeiidProcessingException, ExpressionEvaluationException,
- QueryProcessingException {
- final GroupSymbol group = query.getFrom().getGroups().get(0);
- if (!group.isTempGroupSymbol()) {
- return null;
- }
- final String tableName = group.getNonCorrelationName().toUpperCase();
- boolean remapColumns = !tableName.equalsIgnoreCase(group.getName());
- TempTable table = null;
- if (group.isGlobalTable()) {
- final TempTableStore globalStore = context.getGlobalTableStore();
- final MatTableInfo info = globalStore.getMatTableInfo(tableName);
- Long loadTime = null;
- if (this.distributedCache != null) {
- MatTableKey key = new MatTableKey();
- key.name = tableName;
- key.vdb = new VDBKey(context.getVdbName(), context.getVdbVersion());
-
- MatTableEntry entry = this.tables.get(key);
- boolean firstload = !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);
- loadTime = entry.lastUpdate;
- }
- }
- boolean load = info.shouldLoad();
- if (load) {
- if (!info.isValid()) {
- //blocking load
- loadGlobalTable(context, group, tableName, globalStore, info, loadTime);
- } else {
- loadAsynch(context, group, tableName, globalStore, info, loadTime);
- }
- }
- table = globalStore.getOrCreateTempTable(tableName, query, bufferManager, false);
- context.accessedDataObject(group.getMetadataID());
- } else {
- table = contextStore.getOrCreateTempTable(tableName, query, bufferManager, true);
- if (context.getDataObjects() != null) {
- Object id = RelationalPlanner.getTrackableGroup(group, context.getMetadata());
- if (id != null) {
- context.accessedDataObject(group.getMetadataID());
- }
- }
- }
- if (remapColumns) {
- //convert to the actual table symbols (this is typically handled by the languagebridgefactory
- ExpressionMappingVisitor emv = new ExpressionMappingVisitor(null) {
- @Override
- public Expression replaceExpression(Expression element) {
- if (element instanceof ElementSymbol) {
- ElementSymbol es = (ElementSymbol)element;
- es.getGroupSymbol().setName(tableName);
- es.getGroupSymbol().setDefinition(null);
- }
- return element;
- }
- };
- PostOrderNavigator.doVisit(query, emv);
- }
- return table.createTupleSource(query.getProjectedSymbols(), query.getCriteria(), query.getOrderBy());
- }
-
- private void loadAsynch(final CommandContext context,
- final GroupSymbol group, final String tableName,
- 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);
- }
- };
- FutureTask<Integer> task = new FutureTask<Integer>(toCall);
- executor.execute(task);
- }
-
- private int loadGlobalTable(CommandContext context,
- GroupSymbol group, final String tableName,
- TempTableStore globalStore, MatTableInfo info, Long loadTime)
- throws TeiidComponentException, TeiidProcessingException {
- LogManager.logInfo(LogConstants.CTX_MATVIEWS, QueryPlugin.Util.getString("TempTableDataManager.loading", tableName)); //$NON-NLS-1$
- QueryMetadataInterface metadata = context.getMetadata();
- Create create = new Create();
- create.setTable(group);
- List<ElementSymbol> allColumns = ResolverUtil.resolveElementsInGroup(group, metadata);
- create.setElementSymbolsAsColumns(allColumns);
- Object pk = metadata.getPrimaryKey(group.getMetadataID());
- if (pk != null) {
- List<ElementSymbol> pkColumns = resolveIndex(metadata, allColumns, pk);
- create.getPrimaryKey().addAll(pkColumns);
- }
- TempTable table = globalStore.addTempTable(tableName, create, bufferManager, false);
- table.setUpdatable(false);
- CacheHint hint = table.getCacheHint();
- boolean updatable = false;
- if (hint != null) {
- table.setPreferMemory(hint.getPrefersMemory());
- if (hint.getTtl() != null) {
- info.setTtl(hint.getTtl());
- }
- if (pk != null) {
- updatable = hint.isUpdatable();
- }
- }
- int rowCount = -1;
- try {
- String fullName = metadata.getFullName(group.getMetadataID());
- TupleSource ts = null;
- CacheID cid = null;
- if (distributedCache != null) {
- cid = new CacheID(new ParseInfo(), fullName, context.getVdbName(),
- context.getVdbVersion(), context.getConnectionID(), context.getUserName());
- CachedResults cr = this.distributedCache.get(cid);
- if (cr != null) {
- ts = cr.getResults().createIndexedTupleSource();
- }
- }
-
- List<ElementSymbol> variables = table.getColumns();
-
- if (ts == null) {
- variables = allColumns;
- //TODO: coordinate a distributed load
- //TODO: order by primary key nulls first - then have an insert ordered optimization
- String transformation = metadata.getVirtualPlan(group.getMetadataID()).getQuery();
- QueryProcessor qp = context.getQueryProcessorFactory().createQueryProcessor(transformation, fullName, context);
- qp.setNonBlocking(true);
- qp.getContext().setDataObjects(null);
- if (distributedCache != null) {
- CachedResults cr = new CachedResults();
- BatchCollector bc = qp.createBatchCollector();
- TupleBuffer tb = bc.collectTuples();
- cr.setResults(tb, qp.getProcessorPlan());
- touchTable(context, fullName, true);
- this.distributedCache.put(cid, Determinism.VDB_DETERMINISTIC, cr, info.getTtl());
- ts = tb.createIndexedTupleSource();
- } else {
- ts = new BatchCollector.BatchProducerTupleSource(qp);
- }
- }
-
- //TODO: if this insert fails, it's unnecessary to do the undo processing
- table.insert(ts, variables);
- table.getTree().compact();
- rowCount = table.getRowCount();
- //TODO: could pre-process indexes to remove overlap
- for (Object index : metadata.getIndexesInGroup(group.getMetadataID())) {
- List<ElementSymbol> columns = resolveIndex(metadata, allColumns, index);
- table.addIndex(columns, false);
- }
- for (Object key : metadata.getUniqueKeysInGroup(group.getMetadataID())) {
- List<ElementSymbol> columns = resolveIndex(metadata, allColumns, key);
- table.addIndex(columns, true);
- }
- table.setUpdatable(updatable);
- } catch (TeiidComponentException e) {
- LogManager.logError(LogConstants.CTX_MATVIEWS, e, QueryPlugin.Util.getString("TempTableDataManager.failed_load", tableName)); //$NON-NLS-1$
- throw e;
- } catch (TeiidProcessingException e) {
- LogManager.logError(LogConstants.CTX_MATVIEWS, e, QueryPlugin.Util.getString("TempTableDataManager.failed_load", tableName)); //$NON-NLS-1$
- throw e;
- } finally {
- if (rowCount == -1) {
- info.setState(MatState.FAILED_LOAD, null, null);
- } else {
- globalStore.swapTempTable(tableName, table);
- info.setState(MatState.LOADED, true, loadTime);
- 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) {
- MatTableKey key = new MatTableKey();
- key.name = fullName;
- key.vdb = new VDBKey(context.getVdbName(), context.getVdbVersion());
- MatTableEntry matTableEntry = new MatTableEntry();
- matTableEntry.valid = valid;
- tables.put(key, matTableEntry, null);
- }
-
- /**
- * Return a list of ElementSymbols for the given index/key object
- */
- private List<ElementSymbol> resolveIndex(QueryMetadataInterface metadata,
- List<ElementSymbol> allColumns, Object pk)
- throws TeiidComponentException, QueryMetadataException {
- Collection<?> pkIds = metadata.getElementIDsInKey(pk);
- List<ElementSymbol> pkColumns = new ArrayList<ElementSymbol>(pkIds.size());
- for (Object col : pkIds) {
- pkColumns.add(allColumns.get(metadata.getPosition(col)-1));
- }
- return pkColumns;
- }
-
- public Object lookupCodeValue(CommandContext context, String codeTableName,
- String returnElementName, String keyElementName, Object keyValue)
- throws BlockedException, TeiidComponentException,
- TeiidProcessingException {
- String matTableName = CODE_PREFIX + (codeTableName + ElementSymbol.SEPARATOR + keyElementName + ElementSymbol.SEPARATOR + returnElementName).toUpperCase();
-
- ElementSymbol keyElement = new ElementSymbol(matTableName + ElementSymbol.SEPARATOR + keyElementName);
- ElementSymbol returnElement = new ElementSymbol(matTableName + ElementSymbol.SEPARATOR + returnElementName);
-
- QueryMetadataInterface metadata = context.getMetadata();
-
- keyElement.setType(DataTypeManager.getDataTypeClass(metadata.getElementType(metadata.getElementID(codeTableName + ElementSymbol.SEPARATOR + keyElementName))));
- returnElement.setType(DataTypeManager.getDataTypeClass(metadata.getElementType(metadata.getElementID(codeTableName + ElementSymbol.SEPARATOR + returnElementName))));
-
- TempMetadataID id = context.getGlobalTableStore().getMetadataStore().getTempGroupID(matTableName);
- if (id == null) {
- id = context.getGlobalTableStore().getMetadataStore().addTempGroup(matTableName, Arrays.asList(keyElement, returnElement), false, true);
- String queryString = Reserved.SELECT + ' ' + keyElementName + " ," + returnElementName + ' ' + Reserved.FROM + ' ' + codeTableName; //$NON-NLS-1$
- id.setQueryNode(new QueryNode(queryString));
- id.setPrimaryKey(id.getElements().subList(0, 1));
- CacheHint hint = new CacheHint(true, null);
- id.setCacheHint(hint);
- }
- Query query = RelationalPlanner.createMatViewQuery(id, matTableName, Arrays.asList(returnElement), true);
- query.setCriteria(new CompareCriteria(keyElement, CompareCriteria.EQ, new Constant(keyValue)));
-
- TupleSource ts = registerQuery(context, context.getTempTableStore(), query);
- List<?> row = ts.nextTuple();
- Object result = null;
- if (row != null) {
- result = row.get(0);
- }
- ts.closeSource();
- return result;
- }
-
- @Override
- public EventDistributor getEventDistributor() {
- return this.eventDistributor;
- }
-
- @Override
- public MetadataRepository getMetadataRepository() {
- return this.processorDataManager.getMetadataRepository();
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,644 @@
+/*
+ * 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.tempdata;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Executor;
+import java.util.concurrent.FutureTask;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryProcessingException;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.cache.Cache;
+import org.teiid.cache.CacheConfiguration;
+import org.teiid.cache.CacheFactory;
+import org.teiid.cache.CacheConfiguration.Policy;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.common.buffer.TupleSource;
+import org.teiid.core.CoreConstants;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.HashCodeUtil;
+import org.teiid.core.util.StringUtil;
+import org.teiid.dqp.internal.process.CachedResults;
+import org.teiid.dqp.internal.process.SessionAwareCache;
+import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
+import org.teiid.events.EventDistributor;
+import org.teiid.language.SQLConstants.Reserved;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.MetadataRepository;
+import org.teiid.metadata.FunctionMethod.Determinism;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.eval.Evaluator;
+import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataID;
+import org.teiid.query.optimizer.relational.RelationalPlanner;
+import org.teiid.query.parser.ParseInfo;
+import org.teiid.query.processor.BatchCollector;
+import org.teiid.query.processor.CollectionTupleSource;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.processor.QueryProcessor;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.sql.lang.CacheHint;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.Create;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.Drop;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.Option;
+import org.teiid.query.sql.lang.ProcedureContainer;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.navigator.PostOrderNavigator;
+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.GroupSymbol;
+import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
+import org.teiid.query.tempdata.TempTableStore.MatState;
+import org.teiid.query.tempdata.TempTableStore.MatTableInfo;
+import org.teiid.query.util.CommandContext;
+import org.teiid.vdb.runtime.VDBKey;
+
+/**
+ * This proxy ProcessorDataManager is used to handle temporary tables.
+ *
+ * This isn't handled as a connector because of the temporary metadata and
+ * the create/drop handling (which doesn't have push down support)
+ */
+public class TempTableDataManager implements ProcessorDataManager {
+
+ private static final String REFRESHMATVIEWROW = ".refreshmatviewrow"; //$NON-NLS-1$
+ private static final String REFRESHMATVIEW = ".refreshmatview"; //$NON-NLS-1$
+ private static final String CODE_PREFIX = "#CODE_"; //$NON-NLS-1$
+
+ private ProcessorDataManager processorDataManager;
+ private BufferManager bufferManager;
+ private SessionAwareCache<CachedResults> cache;
+ private Executor executor;
+
+ private static class MatTableKey implements Serializable {
+ private static final long serialVersionUID = 5481692896572663992L;
+ String name;
+ VDBKey vdb;
+
+ @Override
+ public int hashCode() {
+ return HashCodeUtil.hashCode(name.hashCode(), vdb);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (!(obj instanceof MatTableKey)) {
+ return false;
+ }
+ MatTableKey other = (MatTableKey)obj;
+ return this.name.equals(other.name) && this.vdb.equals(other.vdb);
+ }
+ }
+
+ private static class MatTableEntry implements Serializable {
+ private static final long serialVersionUID = 8559613701442751579L;
+ long lastUpdate = System.currentTimeMillis();
+ boolean valid;
+ }
+
+ private Cache<MatTableKey, MatTableEntry> tables;
+ private SessionAwareCache<CachedResults> distributedCache;
+ private EventDistributor eventDistributor;
+
+ public TempTableDataManager(ProcessorDataManager processorDataManager, BufferManager bufferManager,
+ Executor executor, SessionAwareCache<CachedResults> cache, SessionAwareCache<CachedResults> distibutedCache, CacheFactory cacheFactory){
+ this.processorDataManager = processorDataManager;
+ this.bufferManager = bufferManager;
+ this.executor = executor;
+ this.cache = cache;
+ this.distributedCache = distibutedCache;
+ if (distibutedCache != null) {
+ CacheConfiguration cc = new CacheConfiguration(Policy.LRU, -1, -1, "MaterializationUpdates"); //$NON-NLS-1$
+ tables = cacheFactory.get(cc.getLocation(), cc);
+ }
+ }
+
+ public void setEventDistributor(EventDistributor eventDistributor) {
+ this.eventDistributor = eventDistributor;
+ }
+
+ public TupleSource registerRequest(
+ CommandContext context,
+ Command command,
+ String modelName,
+ String connectorBindingId, int nodeID, int limit)
+ throws TeiidComponentException, TeiidProcessingException {
+
+ TempTableStore tempTableStore = context.getTempTableStore();
+ if(tempTableStore != null) {
+ TupleSource result = registerRequest(context, modelName, command);
+ if (result != null) {
+ return result;
+ }
+ }
+ return this.processorDataManager.registerRequest(context, command, modelName, connectorBindingId, nodeID, limit);
+ }
+
+ TupleSource registerRequest(CommandContext context, String modelName, Command command) throws TeiidComponentException, TeiidProcessingException {
+ TempTableStore contextStore = context.getTempTableStore();
+ if (command instanceof Query) {
+ Query query = (Query)command;
+ return registerQuery(context, contextStore, query);
+ }
+ if (command instanceof ProcedureContainer) {
+ if (command instanceof StoredProcedure) {
+ StoredProcedure proc = (StoredProcedure)command;
+ if (CoreConstants.SYSTEM_ADMIN_MODEL.equals(modelName)) {
+ TupleSource result = handleSystemProcedures(context, proc);
+ if (result != null) {
+ return result;
+ }
+ } else if (proc.getGroup().isGlobalTable()) {
+ return handleCachedProcedure(context, proc);
+ }
+ return null; //it's not a stored procedure we want to handle
+ }
+
+ GroupSymbol group = ((ProcedureContainer)command).getGroup();
+ if (!group.isTempGroupSymbol()) {
+ return null;
+ }
+ final String groupKey = group.getNonCorrelationName().toUpperCase();
+ final TempTable table = contextStore.getOrCreateTempTable(groupKey, command, bufferManager, false);
+ if (command instanceof Insert) {
+ Insert insert = (Insert)command;
+ TupleSource ts = insert.getTupleSource();
+ if (ts == null) {
+ List<Object> values = new ArrayList<Object>(insert.getValues().size());
+ for (Expression expr : (List<Expression>)insert.getValues()) {
+ values.add(Evaluator.evaluate(expr));
+ }
+ ts = new CollectionTupleSource(Arrays.asList(values).iterator());
+ }
+ return table.insert(ts, insert.getVariables());
+ }
+ if (command instanceof Update) {
+ final Update update = (Update)command;
+ final Criteria crit = update.getCriteria();
+ return table.update(crit, update.getChangeList());
+ }
+ if (command instanceof Delete) {
+ final Delete delete = (Delete)command;
+ final Criteria crit = delete.getCriteria();
+ if (crit == null) {
+ //because we are non-transactional, just use a truncate
+ int rows = table.truncate();
+ return CollectionTupleSource.createUpdateCountTupleSource(rows);
+ }
+ return table.delete(crit);
+ }
+ }
+ if (command instanceof Create) {
+ Create create = (Create)command;
+ String tempTableName = create.getTable().getCanonicalName();
+ if (contextStore.hasTempTable(tempTableName)) {
+ throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableStore.table_exist_error", tempTableName));//$NON-NLS-1$
+ }
+ contextStore.addTempTable(tempTableName, create, bufferManager, true);
+ return CollectionTupleSource.createUpdateCountTupleSource(0);
+ }
+ if (command instanceof Drop) {
+ String tempTableName = ((Drop)command).getTable().getCanonicalName();
+ contextStore.removeTempTableByName(tempTableName);
+ return CollectionTupleSource.createUpdateCountTupleSource(0);
+ }
+ return null;
+ }
+
+ private TupleSource handleCachedProcedure(CommandContext context,
+ StoredProcedure proc) throws TeiidComponentException,
+ QueryMetadataException, TeiidProcessingException {
+ String fullName = context.getMetadata().getFullName(proc.getProcedureID());
+ LogManager.logDetail(LogConstants.CTX_DQP, "processing cached procedure request for", fullName); //$NON-NLS-1$
+ LinkedList<Object> vals = new LinkedList<Object>();
+ for (SPParameter param : proc.getInputParameters()) {
+ vals.add(((Constant)param.getExpression()).getValue());
+ }
+ //collapse the hash to single byte for the key to restrict the possible results to 256
+ int hash = vals.hashCode();
+ hash |= (hash >>> 16);
+ hash |= (hash >>> 8);
+ hash &= 0x000000ff;
+ CacheID cid = new CacheID(new ParseInfo(), fullName + hash, context.getVdbName(),
+ context.getVdbVersion(), context.getConnectionID(), context.getUserName());
+ cid.setParameters(vals);
+ CachedResults results = cache.get(cid);
+ if (results != null) {
+ TupleBuffer buffer = results.getResults();
+ return buffer.createIndexedTupleSource();
+ }
+ //construct a query with a no cache hint
+ //note that it's safe to use the stringified form of the parameters because
+ //it's not possible to use xml/clob/blob/object
+ CacheHint hint = proc.getCacheHint();
+ proc.setCacheHint(null);
+ Option option = new Option();
+ option.setNoCache(true);
+ option.addNoCacheGroup(fullName);
+ proc.setOption(option);
+ Determinism determinismLevel = context.resetDeterminismLevel();
+ QueryProcessor qp = context.getQueryProcessorFactory().createQueryProcessor(proc.toString(), fullName.toUpperCase(), context);
+ qp.setNonBlocking(true);
+ qp.getContext().setDataObjects(null);
+ BatchCollector bc = qp.createBatchCollector();
+ TupleBuffer tb = bc.collectTuples();
+ CachedResults cr = new CachedResults();
+ cr.setResults(tb, qp.getProcessorPlan());
+ cr.setHint(hint);
+ if (hint != null && hint.getDeterminism() != null) {
+ LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Cache hint modified the query determinism from ",determinismLevel, " to ", hint.getDeterminism() }); //$NON-NLS-1$ //$NON-NLS-2$
+ determinismLevel = hint.getDeterminism();
+ }
+ cache.put(cid, determinismLevel, cr, hint != null?hint.getTtl():null);
+ context.setDeterminismLevel(determinismLevel);
+ return tb.createIndexedTupleSource();
+ }
+
+ private TupleSource handleSystemProcedures(CommandContext context, StoredProcedure proc)
+ throws TeiidComponentException, QueryMetadataException,
+ QueryProcessingException, QueryResolverException,
+ QueryValidatorException, TeiidProcessingException,
+ ExpressionEvaluationException {
+ QueryMetadataInterface metadata = context.getMetadata();
+ TempTableStore globalStore = context.getGlobalTableStore();
+ if (StringUtil.endsWithIgnoreCase(proc.getProcedureCallableName(), REFRESHMATVIEW)) {
+ Object groupID = validateMatView(metadata, proc);
+ 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());
+ if (invalidate) {
+ touchTable(context, matTableName, false);
+ }
+ MatState oldState = info.setState(MatState.NEEDS_LOADING, invalidate?Boolean.FALSE:null, null);
+ if (oldState == MatState.LOADING) {
+ return CollectionTupleSource.createUpdateCountTupleSource(-1);
+ }
+ GroupSymbol matTable = new GroupSymbol(matTableName);
+ matTable.setMetadataID(matTableId);
+ int rowCount = loadGlobalTable(context, matTable, matTableName, globalStore, info, null);
+ return CollectionTupleSource.createUpdateCountTupleSource(rowCount);
+ } else if (StringUtil.endsWithIgnoreCase(proc.getProcedureCallableName(), REFRESHMATVIEWROW)) {
+ Object groupID = validateMatView(metadata, proc);
+ Object pk = metadata.getPrimaryKey(groupID);
+ String matViewName = metadata.getFullName(groupID);
+ if (pk == null) {
+ throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.row_refresh_pk", matViewName)); //$NON-NLS-1$
+ }
+ List<?> ids = metadata.getElementIDsInKey(pk);
+ if (ids.size() > 1) {
+ throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.row_refresh_composite", matViewName)); //$NON-NLS-1$
+ }
+ String matTableName = RelationalPlanner.MAT_PREFIX+matViewName.toUpperCase();
+ MatTableInfo info = globalStore.getMatTableInfo(matTableName);
+ if (!info.isValid()) {
+ return CollectionTupleSource.createUpdateCountTupleSource(-1);
+ }
+ TempTable tempTable = globalStore.getOrCreateTempTable(matTableName, new Query(), bufferManager, false);
+ if (!tempTable.isUpdatable()) {
+ throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.row_refresh_updatable", matViewName)); //$NON-NLS-1$
+ }
+ Constant key = (Constant)proc.getParameter(2).getExpression();
+ LogManager.logInfo(LogConstants.CTX_MATVIEWS, QueryPlugin.Util.getString("TempTableDataManager.row_refresh", matViewName, key)); //$NON-NLS-1$
+ String queryString = Reserved.SELECT + " * " + Reserved.FROM + ' ' + matViewName + ' ' + Reserved.WHERE + ' ' + //$NON-NLS-1$
+ metadata.getFullName(ids.iterator().next()) + " = ?" + ' ' + Reserved.OPTION + ' ' + Reserved.NOCACHE; //$NON-NLS-1$
+ QueryProcessor qp = context.getQueryProcessorFactory().createQueryProcessor(queryString, matViewName.toUpperCase(), context, key.getValue());
+ qp.setNonBlocking(true);
+ qp.getContext().setDataObjects(null);
+ TupleSource ts = new BatchCollector.BatchProducerTupleSource(qp);
+ List<?> tuple = ts.nextTuple();
+ boolean delete = false;
+ if (tuple == null) {
+ delete = true;
+ tuple = Arrays.asList(key.getValue());
+ }
+ 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);
+ }
+ return null;
+ }
+
+ public List<?> updateMatViewRow(TempTableStore globalStore,
+ String matTableName, List<?> tuple, boolean delete)
+ throws QueryProcessingException, TeiidComponentException {
+ TempTable tempTable = globalStore.getOrCreateTempTable(matTableName, new Query(), bufferManager, false);
+ return tempTable.updateTuple(tuple, delete);
+ }
+
+ private Object validateMatView(QueryMetadataInterface metadata,
+ StoredProcedure proc) throws TeiidComponentException,
+ TeiidProcessingException {
+ String name = (String)((Constant)proc.getParameter(1).getExpression()).getValue();
+ try {
+ Object groupID = metadata.getGroupID(name);
+ if (!metadata.hasMaterialization(groupID) || metadata.getMaterialization(groupID) != null) {
+ throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.not_implicit_matview", name)); //$NON-NLS-1$
+ }
+ return groupID;
+ } catch (QueryMetadataException e) {
+ throw new TeiidProcessingException(e);
+ }
+ }
+
+ private TupleSource registerQuery(final CommandContext context,
+ TempTableStore contextStore, Query query)
+ throws TeiidComponentException, QueryMetadataException,
+ TeiidProcessingException, ExpressionEvaluationException,
+ QueryProcessingException {
+ final GroupSymbol group = query.getFrom().getGroups().get(0);
+ if (!group.isTempGroupSymbol()) {
+ return null;
+ }
+ final String tableName = group.getNonCorrelationName().toUpperCase();
+ boolean remapColumns = !tableName.equalsIgnoreCase(group.getName());
+ TempTable table = null;
+ if (group.isGlobalTable()) {
+ final TempTableStore globalStore = context.getGlobalTableStore();
+ final MatTableInfo info = globalStore.getMatTableInfo(tableName);
+ Long loadTime = null;
+ if (this.distributedCache != null) {
+ MatTableKey key = new MatTableKey();
+ key.name = tableName;
+ key.vdb = new VDBKey(context.getVdbName(), context.getVdbVersion());
+
+ MatTableEntry entry = this.tables.get(key);
+ boolean firstload = !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);
+ loadTime = entry.lastUpdate;
+ }
+ }
+ boolean load = info.shouldLoad();
+ if (load) {
+ if (!info.isValid()) {
+ //blocking load
+ loadGlobalTable(context, group, tableName, globalStore, info, loadTime);
+ } else {
+ loadAsynch(context, group, tableName, globalStore, info, loadTime);
+ }
+ }
+ table = globalStore.getOrCreateTempTable(tableName, query, bufferManager, false);
+ context.accessedDataObject(group.getMetadataID());
+ } else {
+ table = contextStore.getOrCreateTempTable(tableName, query, bufferManager, true);
+ if (context.getDataObjects() != null) {
+ Object id = RelationalPlanner.getTrackableGroup(group, context.getMetadata());
+ if (id != null) {
+ context.accessedDataObject(group.getMetadataID());
+ }
+ }
+ }
+ if (remapColumns) {
+ //convert to the actual table symbols (this is typically handled by the languagebridgefactory
+ ExpressionMappingVisitor emv = new ExpressionMappingVisitor(null) {
+ @Override
+ public Expression replaceExpression(Expression element) {
+ if (element instanceof ElementSymbol) {
+ ElementSymbol es = (ElementSymbol)element;
+ es.getGroupSymbol().setName(tableName);
+ es.getGroupSymbol().setDefinition(null);
+ }
+ return element;
+ }
+ };
+ PostOrderNavigator.doVisit(query, emv);
+ }
+ return table.createTupleSource(query.getProjectedSymbols(), query.getCriteria(), query.getOrderBy());
+ }
+
+ private void loadAsynch(final CommandContext context,
+ final GroupSymbol group, final String tableName,
+ 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);
+ }
+ };
+ FutureTask<Integer> task = new FutureTask<Integer>(toCall);
+ executor.execute(task);
+ }
+
+ private int loadGlobalTable(CommandContext context,
+ GroupSymbol group, final String tableName,
+ TempTableStore globalStore, MatTableInfo info, Long loadTime)
+ throws TeiidComponentException, TeiidProcessingException {
+ LogManager.logInfo(LogConstants.CTX_MATVIEWS, QueryPlugin.Util.getString("TempTableDataManager.loading", tableName)); //$NON-NLS-1$
+ QueryMetadataInterface metadata = context.getMetadata();
+ Create create = new Create();
+ create.setTable(group);
+ List<ElementSymbol> allColumns = ResolverUtil.resolveElementsInGroup(group, metadata);
+ create.setElementSymbolsAsColumns(allColumns);
+ Object pk = metadata.getPrimaryKey(group.getMetadataID());
+ if (pk != null) {
+ List<ElementSymbol> pkColumns = resolveIndex(metadata, allColumns, pk);
+ create.getPrimaryKey().addAll(pkColumns);
+ }
+ TempTable table = globalStore.addTempTable(tableName, create, bufferManager, false);
+ table.setUpdatable(false);
+ CacheHint hint = table.getCacheHint();
+ boolean updatable = false;
+ if (hint != null) {
+ table.setPreferMemory(hint.getPrefersMemory());
+ if (hint.getTtl() != null) {
+ info.setTtl(hint.getTtl());
+ }
+ if (pk != null) {
+ updatable = hint.isUpdatable();
+ }
+ }
+ int rowCount = -1;
+ try {
+ String fullName = metadata.getFullName(group.getMetadataID());
+ TupleSource ts = null;
+ CacheID cid = null;
+ if (distributedCache != null) {
+ cid = new CacheID(new ParseInfo(), fullName, context.getVdbName(),
+ context.getVdbVersion(), context.getConnectionID(), context.getUserName());
+ CachedResults cr = this.distributedCache.get(cid);
+ if (cr != null) {
+ ts = cr.getResults().createIndexedTupleSource();
+ }
+ }
+
+ List<ElementSymbol> variables = table.getColumns();
+
+ if (ts == null) {
+ variables = allColumns;
+ //TODO: coordinate a distributed load
+ //TODO: order by primary key nulls first - then have an insert ordered optimization
+ String transformation = metadata.getVirtualPlan(group.getMetadataID()).getQuery();
+ QueryProcessor qp = context.getQueryProcessorFactory().createQueryProcessor(transformation, fullName, context);
+ qp.setNonBlocking(true);
+ qp.getContext().setDataObjects(null);
+ if (distributedCache != null) {
+ CachedResults cr = new CachedResults();
+ BatchCollector bc = qp.createBatchCollector();
+ TupleBuffer tb = bc.collectTuples();
+ cr.setResults(tb, qp.getProcessorPlan());
+ touchTable(context, fullName, true);
+ this.distributedCache.put(cid, Determinism.VDB_DETERMINISTIC, cr, info.getTtl());
+ ts = tb.createIndexedTupleSource();
+ } else {
+ ts = new BatchCollector.BatchProducerTupleSource(qp);
+ }
+ }
+
+ //TODO: if this insert fails, it's unnecessary to do the undo processing
+ table.insert(ts, variables);
+ table.getTree().compact();
+ rowCount = table.getRowCount();
+ //TODO: could pre-process indexes to remove overlap
+ for (Object index : metadata.getIndexesInGroup(group.getMetadataID())) {
+ List<ElementSymbol> columns = resolveIndex(metadata, allColumns, index);
+ table.addIndex(columns, false);
+ }
+ for (Object key : metadata.getUniqueKeysInGroup(group.getMetadataID())) {
+ List<ElementSymbol> columns = resolveIndex(metadata, allColumns, key);
+ table.addIndex(columns, true);
+ }
+ table.setUpdatable(updatable);
+ } catch (TeiidComponentException e) {
+ LogManager.logError(LogConstants.CTX_MATVIEWS, e, QueryPlugin.Util.getString("TempTableDataManager.failed_load", tableName)); //$NON-NLS-1$
+ throw e;
+ } catch (TeiidProcessingException e) {
+ LogManager.logError(LogConstants.CTX_MATVIEWS, e, QueryPlugin.Util.getString("TempTableDataManager.failed_load", tableName)); //$NON-NLS-1$
+ throw e;
+ } finally {
+ if (rowCount == -1) {
+ info.setState(MatState.FAILED_LOAD, null, null);
+ } else {
+ globalStore.swapTempTable(tableName, table);
+ info.setState(MatState.LOADED, true, loadTime);
+ 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) {
+ MatTableKey key = new MatTableKey();
+ key.name = fullName;
+ key.vdb = new VDBKey(context.getVdbName(), context.getVdbVersion());
+ MatTableEntry matTableEntry = new MatTableEntry();
+ matTableEntry.valid = valid;
+ tables.put(key, matTableEntry, null);
+ }
+
+ /**
+ * Return a list of ElementSymbols for the given index/key object
+ */
+ private List<ElementSymbol> resolveIndex(QueryMetadataInterface metadata,
+ List<ElementSymbol> allColumns, Object pk)
+ throws TeiidComponentException, QueryMetadataException {
+ Collection<?> pkIds = metadata.getElementIDsInKey(pk);
+ List<ElementSymbol> pkColumns = new ArrayList<ElementSymbol>(pkIds.size());
+ for (Object col : pkIds) {
+ pkColumns.add(allColumns.get(metadata.getPosition(col)-1));
+ }
+ return pkColumns;
+ }
+
+ public Object lookupCodeValue(CommandContext context, String codeTableName,
+ String returnElementName, String keyElementName, Object keyValue)
+ throws BlockedException, TeiidComponentException,
+ TeiidProcessingException {
+ String matTableName = CODE_PREFIX + (codeTableName + ElementSymbol.SEPARATOR + keyElementName + ElementSymbol.SEPARATOR + returnElementName).toUpperCase();
+
+ ElementSymbol keyElement = new ElementSymbol(matTableName + ElementSymbol.SEPARATOR + keyElementName);
+ ElementSymbol returnElement = new ElementSymbol(matTableName + ElementSymbol.SEPARATOR + returnElementName);
+
+ QueryMetadataInterface metadata = context.getMetadata();
+
+ keyElement.setType(DataTypeManager.getDataTypeClass(metadata.getElementType(metadata.getElementID(codeTableName + ElementSymbol.SEPARATOR + keyElementName))));
+ returnElement.setType(DataTypeManager.getDataTypeClass(metadata.getElementType(metadata.getElementID(codeTableName + ElementSymbol.SEPARATOR + returnElementName))));
+
+ TempMetadataID id = context.getGlobalTableStore().getMetadataStore().getTempGroupID(matTableName);
+ if (id == null) {
+ id = context.getGlobalTableStore().getMetadataStore().addTempGroup(matTableName, Arrays.asList(keyElement, returnElement), false, true);
+ String queryString = Reserved.SELECT + ' ' + keyElementName + " ," + returnElementName + ' ' + Reserved.FROM + ' ' + codeTableName; //$NON-NLS-1$
+ id.setQueryNode(new QueryNode(queryString));
+ id.setPrimaryKey(id.getElements().subList(0, 1));
+ CacheHint hint = new CacheHint(true, null);
+ id.setCacheHint(hint);
+ }
+ Query query = RelationalPlanner.createMatViewQuery(id, matTableName, Arrays.asList(returnElement), true);
+ query.setCriteria(new CompareCriteria(keyElement, CompareCriteria.EQ, new Constant(keyValue)));
+
+ TupleSource ts = registerQuery(context, context.getTempTableStore(), query);
+ List<?> row = ts.nextTuple();
+ Object result = null;
+ if (row != null) {
+ result = row.get(0);
+ }
+ ts.closeSource();
+ return result;
+ }
+
+ @Override
+ public EventDistributor getEventDistributor() {
+ return this.eventDistributor;
+ }
+
+ @Override
+ public MetadataRepository getMetadataRepository() {
+ return this.processorDataManager.getMetadataRepository();
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/util/CommandContext.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,570 +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.util;
-
-import java.io.Serializable;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.Properties;
-import java.util.Random;
-import java.util.Set;
-import java.util.TimeZone;
-
-import javax.security.auth.Subject;
-
-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.PreparedPlan;
-import org.teiid.dqp.internal.process.SessionAwareCache;
-import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
-import org.teiid.metadata.FunctionMethod.Determinism;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.eval.SecurityFunctionEvaluator;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.relational.PlanToProcessConverter;
-import org.teiid.query.parser.ParseInfo;
-import org.teiid.query.processor.QueryProcessor;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.util.VariableContext;
-import org.teiid.query.tempdata.TempTableStore;
-
-/**
- * Defines the context that a command is processing in. For example, this defines
- * who is processing the command and why. Also, this class (or subclasses) provide
- * a means to pass context-specific information between users of the query processor
- * framework.
- */
-public class CommandContext implements Cloneable, org.teiid.CommandContext {
-
- private static class GlobalState {
- /** Uniquely identify the command being processed */
- private Object processorID;
-
- /** Identify a group of related commands, which typically get cleaned up together */
- private String connectionID;
-
- private int processorBatchSize = BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE;
-
- private int connectorBatchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
-
- private String userName;
-
- private Serializable commandPayload;
-
- private String vdbName = ""; //$NON-NLS-1$
-
- private int vdbVersion;
-
- private Properties environmentProperties;
-
- /** Indicate whether statistics should be collected for relational node processing*/
- private boolean collectNodeStatistics;
-
- private Random random = null;
-
- private SecurityFunctionEvaluator securityFunctionEvaluator;
-
- private TimeZone timezone = TimeZone.getDefault();
-
- private PlanToProcessConverter planToProcessConverter;
-
- private QueryProcessor.ProcessorFactory queryProcessorFactory;
-
- private Determinism determinismLevel = Determinism.DETERMINISTIC;
-
- private Set<String> groups;
-
- private long timeSliceEnd = Long.MAX_VALUE;
-
- private long timeoutEnd = Long.MAX_VALUE;
-
- private QueryMetadataInterface metadata;
-
- private boolean validateXML;
-
- private BufferManager bufferManager;
-
- private TempTableStore globalTables;
-
- private SessionAwareCache<PreparedPlan> planCache;
-
- private boolean resultSetCacheEnabled = true;
-
- private int userRequestSourceConcurrency;
- private Subject subject;
- private HashSet<Object> dataObjects;
- }
-
- private GlobalState globalState = new GlobalState();
-
- private VariableContext variableContext = new VariableContext();
- private TempTableStore tempTableStore;
- private LinkedList<String> recursionStack;
- private boolean nonBlocking;
- private HashSet<Object> planningObjects;
- private HashSet<Object> dataObjects = this.globalState.dataObjects;
-
- /**
- * Construct a new context.
- */
- public CommandContext(Object processorID, String connectionID, String userName,
- Serializable commandPayload, String vdbName, int vdbVersion, Properties envProperties, boolean collectNodeStatistics) {
- setProcessorID(processorID);
- setConnectionID(connectionID);
- setUserName(userName);
- setCommandPayload(commandPayload);
- setVdbName(vdbName);
- setVdbVersion(vdbVersion);
- setEnvironmentProperties(envProperties);
- setCollectNodeStatistics(collectNodeStatistics);
- }
-
- /**
- * Construct a new context.
- */
- public CommandContext(Object processorID, String connectionID, String userName,
- String vdbName, int vdbVersion) {
-
- this(processorID, connectionID, userName, null, vdbName,
- vdbVersion, null, false);
-
- }
-
- public CommandContext() {
- }
-
- private CommandContext(GlobalState state) {
- this.globalState = state;
- this.dataObjects = this.globalState.dataObjects;
- }
-
- public Determinism getDeterminismLevel() {
- return globalState.determinismLevel;
- }
-
- public Determinism resetDeterminismLevel() {
- Determinism result = globalState.determinismLevel;
- globalState.determinismLevel = Determinism.DETERMINISTIC;
- return result;
- }
-
- public void setDeterminismLevel(Determinism level) {
- if (globalState.determinismLevel == null || level.compareTo(globalState.determinismLevel) < 0) {
- globalState.determinismLevel = level;
- }
- }
-
- /**
- * @return
- */
- public Object getProcessorID() {
- return globalState.processorID;
- }
-
- /**
- * @param object
- */
- public void setProcessorID(Object object) {
- ArgCheck.isNotNull(object);
- globalState.processorID = object;
- }
-
- public CommandContext clone() {
- CommandContext clone = new CommandContext(this.globalState);
- clone.variableContext = this.variableContext;
- clone.tempTableStore = this.tempTableStore;
- if (this.recursionStack != null) {
- clone.recursionStack = new LinkedList<String>(this.recursionStack);
- }
- clone.setNonBlocking(this.nonBlocking);
- return clone;
- }
-
- public String toString() {
- return "CommandContext: " + globalState.processorID; //$NON-NLS-1$
- }
-
- /**
- * @return String
- */
- public String getConnectionID() {
- return globalState.connectionID;
- }
-
- /**
- * @return String
- */
- public String getUserName() {
- return globalState.userName;
- }
-
- /**
- * @return String
- */
- public String getVdbName() {
- return globalState.vdbName;
- }
-
- /**
- * @return String
- */
- public int getVdbVersion() {
- return globalState.vdbVersion;
- }
-
- /**
- * Sets the connectionID.
- * @param connectionID The connectionID to set
- */
- public void setConnectionID(String connectionID) {
- this.globalState.connectionID = connectionID;
- }
-
- /**
- * Sets the userName.
- * @param userName The userName to set
- */
- public void setUserName(String userName) {
- this.globalState.userName = userName;
- }
-
- /**
- * Sets the vdbName.
- * @param vdbName The vdbName to set
- */
- public void setVdbName(String vdbName) {
- this.globalState.vdbName = vdbName;
- }
-
- /**
- * Sets the vdbVersion.
- * @param vdbVersion The vdbVersion to set
- */
- public void setVdbVersion(int vdbVersion) {
- this.globalState.vdbVersion = vdbVersion;
- }
-
- public Properties getEnvironmentProperties() {
- return globalState.environmentProperties;
- }
-
- public void setEnvironmentProperties(Properties properties) {
- globalState.environmentProperties = properties;
- }
-
- public Serializable getCommandPayload() {
- return this.globalState.commandPayload;
- }
- public void setCommandPayload(Serializable commandPayload) {
- this.globalState.commandPayload = commandPayload;
- }
-
- /**
- * @param collectNodeStatistics The collectNodeStatistics to set.
- * @since 4.2
- */
- public void setCollectNodeStatistics(boolean collectNodeStatistics) {
- this.globalState.collectNodeStatistics = collectNodeStatistics;
- }
-
- public boolean getCollectNodeStatistics() {
- return this.globalState.collectNodeStatistics;
- }
-
- public int getConnectorBatchSize() {
- return this.globalState.connectorBatchSize;
- }
-
- public void setConnectorBatchSize(int connectorBatchSize) {
- this.globalState.connectorBatchSize = connectorBatchSize;
- }
-
-
- public int getProcessorBatchSize() {
- return this.globalState.processorBatchSize;
- }
-
-
- public void setProcessorBatchSize(int processorBatchSize) {
- this.globalState.processorBatchSize = processorBatchSize;
- }
-
- public double getNextRand() {
- if (globalState.random == null) {
- globalState.random = new Random();
- }
- return globalState.random.nextDouble();
- }
-
- public double getNextRand(long seed) {
- if (globalState.random == null) {
- globalState.random = new Random();
- }
- globalState.random.setSeed(seed);
- return globalState.random.nextDouble();
- }
-
- void setRandom(Random random) {
- this.globalState.random = random;
- }
-
- public void pushCall(String value) throws QueryProcessingException {
- if (recursionStack == null) {
- recursionStack = new LinkedList<String>();
- } else if (recursionStack.contains(value)) {
- throw new QueryProcessingException(QueryPlugin.Util.getString("ExecDynamicSqlInstruction.3", value)); //$NON-NLS-1$
- }
-
- recursionStack.push(value);
- }
-
- public int getCallStackDepth() {
- if (this.recursionStack == null) {
- return 0;
- }
- return this.recursionStack.size();
- }
-
- public void popCall() {
- if (recursionStack != null) {
- recursionStack.pop();
- }
- }
-
- /**
- * @return Returns the securityFunctionEvaluator.
- */
- public SecurityFunctionEvaluator getSecurityFunctionEvaluator() {
- return this.globalState.securityFunctionEvaluator;
- }
-
- /**
- * @param securityFunctionEvaluator The securityFunctionEvaluator to set.
- */
- public void setSecurityFunctionEvaluator(SecurityFunctionEvaluator securityFunctionEvaluator) {
- this.globalState.securityFunctionEvaluator = securityFunctionEvaluator;
- }
-
- public TempTableStore getTempTableStore() {
- return tempTableStore;
- }
-
- public void setTempTableStore(TempTableStore tempTableStore) {
- this.tempTableStore = tempTableStore;
- }
-
- public TimeZone getServerTimeZone() {
- return globalState.timezone;
- }
-
- public void setPlanToProcessConverter(PlanToProcessConverter planToProcessConverter) {
- this.globalState.planToProcessConverter = planToProcessConverter;
- }
-
- public PlanToProcessConverter getPlanToProcessConverter() {
- return globalState.planToProcessConverter;
- }
-
- public QueryProcessor.ProcessorFactory getQueryProcessorFactory() {
- return this.globalState.queryProcessorFactory;
- }
-
- public void setQueryProcessorFactory(QueryProcessor.ProcessorFactory queryProcessorFactory) {
- this.globalState.queryProcessorFactory = queryProcessorFactory;
- }
-
- public VariableContext getVariableContext() {
- return variableContext;
- }
-
- public void setVariableContext(VariableContext variableContext) {
- this.variableContext = variableContext;
- }
-
- public void pushVariableContext(VariableContext toPush) {
- toPush.setParentContext(this.variableContext);
- this.variableContext = toPush;
- }
-
- public Object getFromContext(Expression expression) throws TeiidComponentException {
- if (variableContext == null || !(expression instanceof ElementSymbol)) {
- throw new TeiidComponentException("ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", expression, "No value was available")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- Object value = variableContext.getValue((ElementSymbol)expression);
- if (value == null && !variableContext.containsVariable((ElementSymbol)expression)) {
- throw new TeiidComponentException("ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", expression, "No value was available")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return value;
- }
-
- public Set<String> getGroups() {
- return globalState.groups;
- }
-
- public void setGroups(Set<String> groups) {
- this.globalState.groups = groups;
- }
-
- public long getTimeSliceEnd() {
- return globalState.timeSliceEnd;
- }
-
- public long getTimeoutEnd() {
- return globalState.timeoutEnd;
- }
-
- public void setTimeSliceEnd(long timeSliceEnd) {
- globalState.timeSliceEnd = timeSliceEnd;
- }
-
- public void setTimeoutEnd(long timeoutEnd) {
- globalState.timeoutEnd = timeoutEnd;
- }
-
- public void setMetadata(QueryMetadataInterface metadata) {
- globalState.metadata = metadata;
- }
-
- public QueryMetadataInterface getMetadata() {
- return globalState.metadata;
- }
-
- public void setValidateXML(boolean validateXML) {
- globalState.validateXML = validateXML;
- }
-
- public boolean validateXML() {
- return globalState.validateXML;
- }
-
- public BufferManager getBufferManager() {
- return globalState.bufferManager;
- }
-
- public void setBufferManager(BufferManager bm) {
- globalState.bufferManager = bm;
- }
-
- public TempTableStore getGlobalTableStore() {
- return globalState.globalTables;
- }
-
- public void setGlobalTableStore(TempTableStore tempTableStore) {
- globalState.globalTables = tempTableStore;
- }
-
- public boolean isNonBlocking() {
- return nonBlocking;
- }
-
- public void setNonBlocking(boolean nonBlocking) {
- this.nonBlocking = nonBlocking;
- }
-
- public void setPreparedPlanCache(SessionAwareCache<PreparedPlan> cache) {
- this.globalState.planCache = cache;
- }
-
- public PreparedPlan getPlan(String key) {
- if (this.globalState.planCache == null) {
- return null;
- }
- CacheID id = new CacheID(new ParseInfo(), key, getVdbName(), getVdbVersion(), getConnectionID(), getUserName());
- PreparedPlan pp = this.globalState.planCache.get(id);
- if (pp != null) {
- if (id.getSessionId() != null) {
- setDeterminismLevel(Determinism.USER_DETERMINISTIC);
- } else if (id.getUserName() != null) {
- setDeterminismLevel(Determinism.SESSION_DETERMINISTIC);
- }
- return pp;
- }
- return null;
- }
-
- public void putPlan(String key, PreparedPlan plan, Determinism determinismLevel) {
- if (this.globalState.planCache == null) {
- return;
- }
- CacheID id = new CacheID(new ParseInfo(), key, getVdbName(), getVdbVersion(), getConnectionID(), getUserName());
- this.globalState.planCache.put(id, determinismLevel, plan, null);
- }
-
- public boolean isResultSetCacheEnabled() {
- return globalState.resultSetCacheEnabled;
- }
-
- public void setResultSetCacheEnabled(boolean resultSetCacheEnabled) {
- this.globalState.resultSetCacheEnabled = resultSetCacheEnabled;
- }
-
- public int getUserRequestSourceConcurrency() {
- return this.globalState.userRequestSourceConcurrency;
- }
-
- public void setUserRequestSourceConcurrency(int userRequestSourceConcurrency) {
- this.globalState.userRequestSourceConcurrency = userRequestSourceConcurrency;
- }
-
- @Override
- public Subject getSubject() {
- return this.globalState.subject;
- }
-
- public void setSubject(Subject subject) {
- this.globalState.subject = subject;
- }
-
- public void accessedPlanningObject(Object id) {
- if (this.planningObjects == null) {
- this.planningObjects = new HashSet<Object>();
- }
- this.planningObjects.add(id);
- }
-
- public Set<Object> getPlanningObjects() {
- if (this.planningObjects == null) {
- return Collections.emptySet();
- }
- return planningObjects;
- }
-
- public void accessedDataObject(Object id) {
- if (this.dataObjects != null) {
- this.dataObjects.add(id);
- }
- }
-
- public Set<Object> getDataObjects() {
- return dataObjects;
- }
-
- public void setDataObjects(HashSet<Object> dataObjectsAccessed) {
- this.dataObjects = dataObjectsAccessed;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java (from rev 3218, trunk/engine/src/main/java/org/teiid/query/util/CommandContext.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,594 @@
+/*
+ * 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.util;
+
+import java.io.Serializable;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.Properties;
+import java.util.Random;
+import java.util.Set;
+import java.util.TimeZone;
+
+import javax.security.auth.Subject;
+
+import org.teiid.adminapi.Session;
+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.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.metadata.FunctionMethod.Determinism;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.eval.SecurityFunctionEvaluator;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.relational.PlanToProcessConverter;
+import org.teiid.query.parser.ParseInfo;
+import org.teiid.query.processor.QueryProcessor;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.util.VariableContext;
+import org.teiid.query.tempdata.TempTableStore;
+
+/**
+ * Defines the context that a command is processing in. For example, this defines
+ * who is processing the command and why. Also, this class (or subclasses) provide
+ * a means to pass context-specific information between users of the query processor
+ * framework.
+ */
+public class CommandContext implements Cloneable, org.teiid.CommandContext {
+
+ private static class GlobalState {
+ /** Uniquely identify the command being processed */
+ private Object processorID;
+
+ /** Identify a group of related commands, which typically get cleaned up together */
+ private String connectionID;
+
+ private int processorBatchSize = BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE;
+
+ private int connectorBatchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
+
+ private String userName;
+
+ private Serializable commandPayload;
+
+ private String vdbName = ""; //$NON-NLS-1$
+
+ private int vdbVersion;
+
+ private Properties environmentProperties;
+
+ /** Indicate whether statistics should be collected for relational node processing*/
+ private boolean collectNodeStatistics;
+
+ private Random random = null;
+
+ private SecurityFunctionEvaluator securityFunctionEvaluator;
+
+ private TimeZone timezone = TimeZone.getDefault();
+
+ private PlanToProcessConverter planToProcessConverter;
+
+ private QueryProcessor.ProcessorFactory queryProcessorFactory;
+
+ private Determinism determinismLevel = Determinism.DETERMINISTIC;
+
+ private Set<String> groups;
+
+ private long timeSliceEnd = Long.MAX_VALUE;
+
+ private long timeoutEnd = Long.MAX_VALUE;
+
+ private QueryMetadataInterface metadata;
+
+ private boolean validateXML;
+
+ private BufferManager bufferManager;
+
+ private TempTableStore globalTables;
+
+ private SessionAwareCache<PreparedPlan> planCache;
+
+ private boolean resultSetCacheEnabled = true;
+
+ private int userRequestSourceConcurrency;
+ private Subject subject;
+ private HashSet<Object> dataObjects;
+
+ public Session session;
+
+ public RequestID requestId;
+ }
+
+ private GlobalState globalState = new GlobalState();
+
+ private VariableContext variableContext = new VariableContext();
+ private TempTableStore tempTableStore;
+ private LinkedList<String> recursionStack;
+ private boolean nonBlocking;
+ private HashSet<Object> planningObjects;
+ private HashSet<Object> dataObjects = this.globalState.dataObjects;
+
+ /**
+ * Construct a new context.
+ */
+ public CommandContext(Object processorID, String connectionID, String userName,
+ Serializable commandPayload, String vdbName, int vdbVersion, Properties envProperties, boolean collectNodeStatistics) {
+ setProcessorID(processorID);
+ setConnectionID(connectionID);
+ setUserName(userName);
+ setCommandPayload(commandPayload);
+ setVdbName(vdbName);
+ setVdbVersion(vdbVersion);
+ setEnvironmentProperties(envProperties);
+ setCollectNodeStatistics(collectNodeStatistics);
+ }
+
+ /**
+ * Construct a new context.
+ */
+ public CommandContext(Object processorID, String connectionID, String userName,
+ String vdbName, int vdbVersion) {
+
+ this(processorID, connectionID, userName, null, vdbName,
+ vdbVersion, null, false);
+
+ }
+
+ public CommandContext() {
+ }
+
+ private CommandContext(GlobalState state) {
+ this.globalState = state;
+ this.dataObjects = this.globalState.dataObjects;
+ }
+
+ public Determinism getDeterminismLevel() {
+ return globalState.determinismLevel;
+ }
+
+ public Determinism resetDeterminismLevel() {
+ Determinism result = globalState.determinismLevel;
+ globalState.determinismLevel = Determinism.DETERMINISTIC;
+ return result;
+ }
+
+ public void setDeterminismLevel(Determinism level) {
+ if (globalState.determinismLevel == null || level.compareTo(globalState.determinismLevel) < 0) {
+ globalState.determinismLevel = level;
+ }
+ }
+
+ /**
+ * @return
+ */
+ public Object getProcessorID() {
+ return globalState.processorID;
+ }
+
+ /**
+ * @param object
+ */
+ public void setProcessorID(Object object) {
+ ArgCheck.isNotNull(object);
+ globalState.processorID = object;
+ }
+
+ public CommandContext clone() {
+ CommandContext clone = new CommandContext(this.globalState);
+ clone.variableContext = this.variableContext;
+ clone.tempTableStore = this.tempTableStore;
+ if (this.recursionStack != null) {
+ clone.recursionStack = new LinkedList<String>(this.recursionStack);
+ }
+ clone.setNonBlocking(this.nonBlocking);
+ return clone;
+ }
+
+ public String toString() {
+ return "CommandContext: " + globalState.processorID; //$NON-NLS-1$
+ }
+
+ /**
+ * @return String
+ */
+ public String getConnectionID() {
+ return globalState.connectionID;
+ }
+
+ /**
+ * @return String
+ */
+ public String getUserName() {
+ return globalState.userName;
+ }
+
+ /**
+ * @return String
+ */
+ public String getVdbName() {
+ return globalState.vdbName;
+ }
+
+ /**
+ * @return String
+ */
+ public int getVdbVersion() {
+ return globalState.vdbVersion;
+ }
+
+ /**
+ * Sets the connectionID.
+ * @param connectionID The connectionID to set
+ */
+ public void setConnectionID(String connectionID) {
+ this.globalState.connectionID = connectionID;
+ }
+
+ /**
+ * Sets the userName.
+ * @param userName The userName to set
+ */
+ public void setUserName(String userName) {
+ this.globalState.userName = userName;
+ }
+
+ /**
+ * Sets the vdbName.
+ * @param vdbName The vdbName to set
+ */
+ public void setVdbName(String vdbName) {
+ this.globalState.vdbName = vdbName;
+ }
+
+ /**
+ * Sets the vdbVersion.
+ * @param vdbVersion The vdbVersion to set
+ */
+ public void setVdbVersion(int vdbVersion) {
+ this.globalState.vdbVersion = vdbVersion;
+ }
+
+ public Properties getEnvironmentProperties() {
+ return globalState.environmentProperties;
+ }
+
+ public void setEnvironmentProperties(Properties properties) {
+ globalState.environmentProperties = properties;
+ }
+
+ public Serializable getCommandPayload() {
+ return this.globalState.commandPayload;
+ }
+ public void setCommandPayload(Serializable commandPayload) {
+ this.globalState.commandPayload = commandPayload;
+ }
+
+ /**
+ * @param collectNodeStatistics The collectNodeStatistics to set.
+ * @since 4.2
+ */
+ public void setCollectNodeStatistics(boolean collectNodeStatistics) {
+ this.globalState.collectNodeStatistics = collectNodeStatistics;
+ }
+
+ public boolean getCollectNodeStatistics() {
+ return this.globalState.collectNodeStatistics;
+ }
+
+ public int getConnectorBatchSize() {
+ return this.globalState.connectorBatchSize;
+ }
+
+ public void setConnectorBatchSize(int connectorBatchSize) {
+ this.globalState.connectorBatchSize = connectorBatchSize;
+ }
+
+
+ public int getProcessorBatchSize() {
+ return this.globalState.processorBatchSize;
+ }
+
+
+ public void setProcessorBatchSize(int processorBatchSize) {
+ this.globalState.processorBatchSize = processorBatchSize;
+ }
+
+ public double getNextRand() {
+ if (globalState.random == null) {
+ globalState.random = new Random();
+ }
+ return globalState.random.nextDouble();
+ }
+
+ public double getNextRand(long seed) {
+ if (globalState.random == null) {
+ globalState.random = new Random();
+ }
+ globalState.random.setSeed(seed);
+ return globalState.random.nextDouble();
+ }
+
+ void setRandom(Random random) {
+ this.globalState.random = random;
+ }
+
+ public void pushCall(String value) throws QueryProcessingException {
+ if (recursionStack == null) {
+ recursionStack = new LinkedList<String>();
+ } else if (recursionStack.contains(value)) {
+ throw new QueryProcessingException(QueryPlugin.Util.getString("ExecDynamicSqlInstruction.3", value)); //$NON-NLS-1$
+ }
+
+ recursionStack.push(value);
+ }
+
+ public int getCallStackDepth() {
+ if (this.recursionStack == null) {
+ return 0;
+ }
+ return this.recursionStack.size();
+ }
+
+ public void popCall() {
+ if (recursionStack != null) {
+ recursionStack.pop();
+ }
+ }
+
+ /**
+ * @return Returns the securityFunctionEvaluator.
+ */
+ public SecurityFunctionEvaluator getSecurityFunctionEvaluator() {
+ return this.globalState.securityFunctionEvaluator;
+ }
+
+ /**
+ * @param securityFunctionEvaluator The securityFunctionEvaluator to set.
+ */
+ public void setSecurityFunctionEvaluator(SecurityFunctionEvaluator securityFunctionEvaluator) {
+ this.globalState.securityFunctionEvaluator = securityFunctionEvaluator;
+ }
+
+ public TempTableStore getTempTableStore() {
+ return tempTableStore;
+ }
+
+ public void setTempTableStore(TempTableStore tempTableStore) {
+ this.tempTableStore = tempTableStore;
+ }
+
+ public TimeZone getServerTimeZone() {
+ return globalState.timezone;
+ }
+
+ public void setPlanToProcessConverter(PlanToProcessConverter planToProcessConverter) {
+ this.globalState.planToProcessConverter = planToProcessConverter;
+ }
+
+ public PlanToProcessConverter getPlanToProcessConverter() {
+ return globalState.planToProcessConverter;
+ }
+
+ public QueryProcessor.ProcessorFactory getQueryProcessorFactory() {
+ return this.globalState.queryProcessorFactory;
+ }
+
+ public void setQueryProcessorFactory(QueryProcessor.ProcessorFactory queryProcessorFactory) {
+ this.globalState.queryProcessorFactory = queryProcessorFactory;
+ }
+
+ public VariableContext getVariableContext() {
+ return variableContext;
+ }
+
+ public void setVariableContext(VariableContext variableContext) {
+ this.variableContext = variableContext;
+ }
+
+ public void pushVariableContext(VariableContext toPush) {
+ toPush.setParentContext(this.variableContext);
+ this.variableContext = toPush;
+ }
+
+ public Object getFromContext(Expression expression) throws TeiidComponentException {
+ if (variableContext == null || !(expression instanceof ElementSymbol)) {
+ throw new TeiidComponentException("ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", expression, "No value was available")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ Object value = variableContext.getValue((ElementSymbol)expression);
+ if (value == null && !variableContext.containsVariable((ElementSymbol)expression)) {
+ throw new TeiidComponentException("ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", expression, "No value was available")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ return value;
+ }
+
+ public Set<String> getGroups() {
+ return globalState.groups;
+ }
+
+ public void setGroups(Set<String> groups) {
+ this.globalState.groups = groups;
+ }
+
+ public long getTimeSliceEnd() {
+ return globalState.timeSliceEnd;
+ }
+
+ public long getTimeoutEnd() {
+ return globalState.timeoutEnd;
+ }
+
+ public void setTimeSliceEnd(long timeSliceEnd) {
+ globalState.timeSliceEnd = timeSliceEnd;
+ }
+
+ public void setTimeoutEnd(long timeoutEnd) {
+ globalState.timeoutEnd = timeoutEnd;
+ }
+
+ public void setMetadata(QueryMetadataInterface metadata) {
+ globalState.metadata = metadata;
+ }
+
+ public QueryMetadataInterface getMetadata() {
+ return globalState.metadata;
+ }
+
+ public void setValidateXML(boolean validateXML) {
+ globalState.validateXML = validateXML;
+ }
+
+ public boolean validateXML() {
+ return globalState.validateXML;
+ }
+
+ public BufferManager getBufferManager() {
+ return globalState.bufferManager;
+ }
+
+ public void setBufferManager(BufferManager bm) {
+ globalState.bufferManager = bm;
+ }
+
+ public TempTableStore getGlobalTableStore() {
+ return globalState.globalTables;
+ }
+
+ public void setGlobalTableStore(TempTableStore tempTableStore) {
+ globalState.globalTables = tempTableStore;
+ }
+
+ public boolean isNonBlocking() {
+ return nonBlocking;
+ }
+
+ public void setNonBlocking(boolean nonBlocking) {
+ this.nonBlocking = nonBlocking;
+ }
+
+ public void setPreparedPlanCache(SessionAwareCache<PreparedPlan> cache) {
+ this.globalState.planCache = cache;
+ }
+
+ public PreparedPlan getPlan(String key) {
+ if (this.globalState.planCache == null) {
+ return null;
+ }
+ CacheID id = new CacheID(new ParseInfo(), key, getVdbName(), getVdbVersion(), getConnectionID(), getUserName());
+ PreparedPlan pp = this.globalState.planCache.get(id);
+ if (pp != null) {
+ if (id.getSessionId() != null) {
+ setDeterminismLevel(Determinism.USER_DETERMINISTIC);
+ } else if (id.getUserName() != null) {
+ setDeterminismLevel(Determinism.SESSION_DETERMINISTIC);
+ }
+ return pp;
+ }
+ return null;
+ }
+
+ public void putPlan(String key, PreparedPlan plan, Determinism determinismLevel) {
+ if (this.globalState.planCache == null) {
+ return;
+ }
+ CacheID id = new CacheID(new ParseInfo(), key, getVdbName(), getVdbVersion(), getConnectionID(), getUserName());
+ this.globalState.planCache.put(id, determinismLevel, plan, null);
+ }
+
+ public boolean isResultSetCacheEnabled() {
+ return globalState.resultSetCacheEnabled;
+ }
+
+ public void setResultSetCacheEnabled(boolean resultSetCacheEnabled) {
+ this.globalState.resultSetCacheEnabled = resultSetCacheEnabled;
+ }
+
+ public int getUserRequestSourceConcurrency() {
+ return this.globalState.userRequestSourceConcurrency;
+ }
+
+ public void setUserRequestSourceConcurrency(int userRequestSourceConcurrency) {
+ this.globalState.userRequestSourceConcurrency = userRequestSourceConcurrency;
+ }
+
+ @Override
+ public Subject getSubject() {
+ return this.globalState.subject;
+ }
+
+ public void setSubject(Subject subject) {
+ this.globalState.subject = subject;
+ }
+
+ public void accessedPlanningObject(Object id) {
+ if (this.planningObjects == null) {
+ this.planningObjects = new HashSet<Object>();
+ }
+ this.planningObjects.add(id);
+ }
+
+ public Set<Object> getPlanningObjects() {
+ if (this.planningObjects == null) {
+ return Collections.emptySet();
+ }
+ return planningObjects;
+ }
+
+ public void accessedDataObject(Object id) {
+ if (this.dataObjects != null) {
+ this.dataObjects.add(id);
+ }
+ }
+
+ public Set<Object> getDataObjects() {
+ return dataObjects;
+ }
+
+ public void setDataObjects(HashSet<Object> dataObjectsAccessed) {
+ 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;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/security/Credentials.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/security/Credentials.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/security/Credentials.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,47 +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.security;
-
-import java.io.Serializable;
-
-public class Credentials implements Serializable {
-
- private char[] credentials = null;
-
- /**
- * Construct a new PasswordCredentials
- * @param credentials the password.
- */
- public Credentials(char[] credentials) {
- this.credentials = credentials;
- }
-
- /**
- * Get the Credentials as a char[].
- * @returns The Credentials in a char[].
- */
- public char[] getCredentialsAsCharArray() {
- return this.credentials;
- }
-
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/security/Credentials.java (from rev 3218, trunk/engine/src/main/java/org/teiid/security/Credentials.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/security/Credentials.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/java/org/teiid/security/Credentials.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,49 @@
+/*
+ * 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.security;
+
+import java.io.Serializable;
+
+public class Credentials implements Serializable {
+
+ private static final long serialVersionUID = 7453114713211221240L;
+
+ private char[] credentials = null;
+
+ /**
+ * Construct a new PasswordCredentials
+ * @param credentials the password.
+ */
+ public Credentials(char[] credentials) {
+ this.credentials = credentials;
+ }
+
+ /**
+ * Get the Credentials as a char[].
+ * @returns The Credentials in a char[].
+ */
+ public char[] getCredentialsAsCharArray() {
+ return this.credentials;
+ }
+
+}
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/resources/org/teiid/query/i18n.properties
===================================================================
--- trunk/engine/src/main/resources/org/teiid/query/i18n.properties 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/resources/org/teiid/query/i18n.properties 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,919 +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.
-#
-
-# Error messages for query (015) project to address internationalization
-# Format:
-#
-
-# function (001)
-ERR.015.001.0002 = Cannot find implementation for known function {0}
-ERR.015.001.0003 = Error while evaluating function {0}
-ERR.015.001.0004 = Unable to access function implementation for [{0}]
-ERR.015.001.0005 = ERROR loading system functions: {0}
-ERR.015.001.0017 = Left count is invalid: {0}
-ERR.015.001.0025 = Pad length must be > 0.
-ERR.015.001.0027 = Pad string for lpad/rpad must have length greater than 0.
-ERR.015.001.0031 = Source and destination character lists must be the same length.
-ERR.015.001.0033 = Error converting [{0}] of type {1} to type {2}
-ERR.015.001.0035 = The context function may only be used in XML queries.
-ERR.015.001.0035a = The rowlimit and rowlimitexception functions may only be used in XML queries.
-ERR.015.001.0042 = Illegal argument for formating: {0}
-ERR.015.001.0043 = Parse Exception occurs for executing: {0} {1}
-ERR.015.001.0044 = Function metadata source is of invalid type: {0}
-ERR.015.001.0046 = The function "{0}" will not be added because a function with the same name and signature already exists.
-ERR.015.001.0047 = Unexpected exception while loading "{1}.{2}" for UDF "{0}"
-FunctionTree.not_void = UDF "{0}" method "{1}" must not return void.
-FunctionTree.not_public = UDF "{0}" method "{1}" must be public.
-FunctionTree.not_static = UDF "{0}" method "{1}" must be static.
-FunctionTree.no_class = Could not load UDF "{0}", since its invocation class "{1}" could not be found.
-FunctionTree.no_method = UDF "{0}" could not loaded, since no method on class "{1}" with name "{2}" has a matching type signature.
-ERR.015.001.0048 = Unable to represent average value from {0} / {1}
-ERR.015.001.0050 = Unable to compute aggregate function {0} on data of type {1}
-ERR.015.001.0052 = {0} must be non-null.
-ERR.015.001.0053 = Method parameter must be non-null.
-ERR.015.001.0054 = Type is unknown: {0}
-ERR.015.001.0055 = {0} exceeds maximum length of {1}
-ERR.015.001.0056 = {0} has invalid first character: {1}
-ERR.015.001.0057 = {0} has invalid character: {1}
-ERR.015.001.0058 = {0} cannot end with a ''.''
-ERR.015.001.0061 = <start> value of {0} is invalid, which should never be less than zero or bigger than the length of original string {1}
-ERR.015.001.0062 = <length> value of {0} is invalid, which should never less be than zero.
-ERR.015.001.0063 = Input String is an empty string but start value or/and length value is bigger than zero.
-ERR.015.001.0066 = Unknown type signature for evaluating function of: {0} ({1})
-ERR.015.001.0069 = Unknown type signature for evaluating function of: {0} ({1})
-
-# mapping (002)
-ERR.015.002.0009 = Search direction arg ''{0}'' is not one of the search constants defined in MappingNodeConstants.
-ERR.015.002.0010 = Value for property ''{0}'' is null.
-ERR.015.002.0011 = Invalid type: {0}
-
-
-# parser (005)
-QueryParser.emptysql=Parser cannot parse an empty sql statement.
-QueryParser.parsingError=Parsing error: {0}
-QueryParser.nullSqlCrit=Parser cannot parse a null sql criteria.
-QueryParser.lexicalError= Lexical error: {0}
-QueryParser.nullSqlExpr= Parser cannot parse a null sql expression.
-QueryParser.xqueryCompilation= Direct usage of XQuery is no longer supported, use XMLQUERY instead.
-
-# processor (006)
-ERR.015.006.0010= Unknown criteria type: {0}
-ERR.015.006.0011= Unable to evaluate {0} expression of {1}
-ERR.015.006.0012= Unknown compare criteria operator: {0}
-ERR.015.006.0014= Failed to create regular expression from match pattern: {0}. {1}
-ERR.015.006.0015= Unable to evaluate expression of {0}
-ERR.015.006.0016= Unknown expression type: {0}
-ERR.015.006.0033= Unable to evaluate {0}: {1}
-ERR.015.006.0055= Unable to evaluate LOOKUP function.
-ERR.015.006.0057= Unknown subquery comparison predicate quantifier: {0}
-ERR.015.006.0058= The command of this scalar subquery returned more than one value: {0}
-
-# resolver (008)
-ERR.015.008.0003= Only one XML document may be specified in the FROM clause of a query.
-ERR.015.008.0007= Incorrect number of parameters specified on the stored procedure {2} - expected {0} but got {1}
-ERR.015.008.0009= {1} is not allowed on the view {0}: a procedure must be defined to handle the {1}.
-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}
-ERR.015.008.0025= Binding reference cannot be a function: {0}
-ERR.015.008.0026= Expression ''{0}'' has a parameter with non-determinable type information. The use of an explicit convert may be necessary.
-ERR.015.008.0027= The expressions in this criteria are being compared but are of differing types ({0} and {1}) and no implicit conversion is available: {2}
-ERR.015.008.0029= This criteria must have string or CLOB expressions on each side: {0}
-ERR.015.008.0030= Type cannot be null for expression: {0}
-ERR.015.008.0031= This criteria must have values only of the same type as the left expression: {0}
-ERR.015.008.0032= There must be exactly one projected symbol of the subquery: {0}
-ERR.015.008.0033= The left expression must have a type convertible to the type of the subquery projected symbol: {0}
-ERR.015.008.0035= Type was null for {0} in function {1}
-ERR.015.008.0036= The function ''{0}'' has more than one possible signature.
-ERR.015.008.0037= The conversion from {0} to {1} is not allowed.
-ERR.015.008.0039= The function ''{0}'' is an unknown form. Check that the function name and number of arguments is correct.
-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.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.
-ERR.015.008.0049= Bindings must be specified
-ERR.015.008.0051= Symbol {0} is specified with an unknown group context
-ERR.015.008.0053= Element "{0}" is ambiguous, it exists in two or more groups.
-ERR.015.008.0054= Element "{0}" is not defined by any relevant group.
-ERR.015.008.0055= Group specified is ambiguous, resubmit the query by fully qualifying the group name
-ambiguous_procedure= Procedure ''{0}'' is ambiguous, use the fully qualified name instead
-ERR.015.008.0056= Group does not exist
-ERR.015.008.0061= Unable to resolve stored procedure {0} the datatype for the parameter {1} is not specified.
-ERR.015.008.0062= Unable to resolve return element referred to by LOOKUP function: {0}
-ERR.015.008.0063= The first three arguments for the LOOKUP function must be specified as constants.
-ERR.015.008.0065= Group {0} is not allowed in LOOKUP function.
-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
-
-# sql (010)
-ERR.015.010.0001= Invalid compare operator: {0}
-ERR.015.010.0002= Invalid logical operator: {0}
-ERR.015.010.0003= Cannot set null collection of elements on GroupBy
-ERR.015.010.0006= Invalid parameter type [{0}] must be IN, OUT, INOUT, RETURN_VALUE, RESULT_SET
-ERR.015.010.0009= No columns exist.
-ERR.015.010.0010= Invalid column index: {0}
-ERR.015.010.0011= Parameter cannot be null
-ERR.015.010.0014= Constant type should never be null
-ERR.015.010.0015= Unknown constant type: {0}
-ERR.015.010.0016= A group symbol may not resolve to a null metadata ID.
-ERR.015.010.0017= The name of a symbol may not be null.
-ERR.015.010.0018= Inconsistent number of elements in transformation projected symbols and virtual group.
-ERR.015.010.0021= Elements cannot be null
-ERR.015.010.0022= Functions cannot be null
-ERR.015.010.0023= Groups cannot be null
-ERR.015.010.0029= Cannot create AliasSymbol wrapping AliasSymbol
-ERR.015.010.0031= Illegal variable name ''{1}''. Variable names can only be prefixed with the special group name ''{0}''.
-ERR.015.010.0032= Variable {0} was previously declared.
-ERR.015.010.0035= The <expression> cannot be null in CASE <expression>
-ERR.015.010.0036= There must be at least one WHEN expression and one THEN expression. The number of WHEN and THEN expressions must be equal.
-ERR.015.010.0037= The WHEN part of the CASE expression must contain an expression.
-ERR.015.010.0038= The THEN part of the CASE expression must contain an expression
-ERR.015.010.0039= The WHEN part of the searched CASE expression must contain a criteria.
-
-# util (011)
-
-# validator (012)
-ERR.015.012.0001 = The updatable view query must be simple (containing a FROM clause and not using SELECT INTO) or a UNION ALL of simple queries.
-ERR.015.012.0002 = The updatable view query has a WITH clause, pass-through processing will not be used for UPDATE/DELETE operations.
-ERR.015.012.0003 = The updatable view query projects a column from a non-updatable group {0}.
-ERR.015.012.0004 = The updatable view query has a non key preserving group {0}, which cannot be targeted by INSERT/UPDATE/DELETE operations.
-ERR.015.012.0005 = The updatable view has no valid target for UPDATEs.
-ERR.015.012.0006 = The updatable view query must not use aggregates or grouping.
-ERR.015.012.0007 = The updatable view query has a non-updatable expression {0} for view column {1}.
-ERR.015.012.0008 = The updatable view query cannot use SELECT DISTINCT.
-ERR.015.012.0009 = The updatable view query has a FROM clause that is not a single table, pass-through processing will not be used for UPDATE/DELETE operations.
-ERR.015.012.0010 = The updatable view query does not project the column {0}, which is required to make {1} a target of INSERT operations.
-ERR.015.012.0011 = There must be exactly one projected symbol in the subcommand of an IN clause.
-ERR.015.012.0012 = An AssignmentStatement cannot change the value of a {0} or {1} variable.
-ERR.015.012.0013 = The query defining an updatable virtual group cannot use LIMIT.
-ERR.015.012.0014 = The non-simple query defining an updatable view does not have a valid key preserving delete target.
-ERR.015.012.0015 = The query defining an updatable view has no valid target for INSERTs.
-ERR.015.012.0016 = Variable {0} not assigned any value in this procedure.
-ERR.015.012.0017 = Variables declared the procedure''s DeclareStatement cannot be one of the special variables: {0}, {1} and {2}.
-ERR.015.012.0018 = Inherent INSERT is not possible on a view defined by a non-partitioned UNION.
-ERR.015.012.0019 = Translate/HasCriteria cannot be used in a non-update procedure.
-ERR.015.012.0021 = Element being translated in the WITH clause not among the elements on the ON clause of the TranslateCriteria.
-ERR.015.012.0022 = Unable to translate criteria on the update command against the virtual group, the element {0} is mapped to an aggregate symbol in the virtual group''s query transform, and cannot be translated.
-ERR.015.012.0023 = Unable to translate criteria on the update command against the virtual group, the element {0} is mapped to an expression whose elements are not present on the command in the procedure using the translated criteria.
-ERR.015.012.0024 = The following data elements are not supported in the SELECT clause: {0}.
-ERR.015.012.0025 = Command must project at least one symbol
-ERR.015.012.0026 = Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used in SELECT DISTINCT, ORDER BY, GROUP BY, KEYS, or non-all set queries: [{0}]
-ERR.015.012.0027 = Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used in comparison: {0}.
-ValidationVisitor.expression_requires_name = Non-column expressions require a name in XMLATTRIBUTES, XMLFOREST, QUERYSTRING, or TEXTAGG with HEADER
-ValidationVisitor.invalid_lookup_key=Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used as LOOKUP key columns: {0}.
-ValidationVisitor.limit_not_valid_for_xml=The limit clause cannot be used on an XML document query.
-ValidationVisitor.union_insert = Select into is not allowed under a set operation: {0}.
-ValidationVisitor.multisource_insert = A multi-source table, {0}, cannot be used in an INSERT with query expression or SELECT INTO statement.
-ValidationVisitor.invalid_encoding = Invalid encoding: {0}.
-ValidationVisitor.nonUpdatable = The specified change set {0} against an inherently updatable view does not map to a key preserving group.
-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.
-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
-ERR.015.012.0032 = Queries against XML documents can not have a HAVING clause
-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.0039 = Nested aggregate expressions are not allowed: {0}
-ERR.015.012.0041 = The aggregate function {0} cannot be used with non-numeric expressions: {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.
-AggregateValidationVisitor.invalid_distinct=The enhanced numeric aggregate functions STDDEV_POP, STDDEV_SAMP, VAR_POP, VAR_SAMP cannot have DISTINCT specified.
-ERR.015.012.0052 = The element [{0}] is in an INSERT but does not support updates.
-ERR.015.012.0053 = Element in the group {0}, for which value is not specified in the insert command is neither nullable nor has a default value: {1}
-ERR.015.012.0054 = Column variables do not reference columns on group "{0}": {1}
-ERR.015.012.0055 = Element {0} does not allow nulls.
-ERR.015.012.0059 = Left side of update expression must be an element that supports update: {0}
-ERR.015.012.0060 = Element {0} does not allow nulls.
-ERR.015.012.0061 = Views using update procedures must have update values that are constant expressions. The expression ''{0}'' cannot be evaluated to a constant.
-ERR.015.012.0062 = Elements cannot appear more than once in a SET or USING clause. The following elements are duplicated: {0}
-ERR.015.012.0063 = Multiple failures occurred during validation:
-ERR.015.012.0064 = Validation succeeded
-ERR.015.012.0065 = Nested Loop can not use the same cursor name as that of its parent.
-ERR.015.012.0067 = No scalar subqueries are allowed in the SELECT with no FROM clause.
-ERR.015.012.0069 = INTO clause can not be used in XML query.
-
-# optimizer (004)
-ERR.015.004.0007= Can''t convert plan node of type {0}
-ERR.015.004.0009= Error finding connectorBindingID for command
-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.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.
-ERR.015.004.0037= No mapping node found named, ''{0}', in use of ''context''
-ERR.015.004.0046= The XML document element(s) {0} are not mapped to data and cannot be used in the criteria \"{1}\".
-ERR.015.004.0054= Could not parse query transformation for {0}: {1}
-ERR.015.004.0068= Context functions within the same conjunct refer to different contexts: {0}
-
-# processor (006)
-ERR.015.006.0001= XMLPlan toString couldn''t print entire Program.
-ERR.015.006.0034= Unexpected symbol type while updating tuple: {0}
-ERR.015.006.0037= Tuple source does not exist: {0}
-ERR.015.006.0039= Instructed to abort processing when recursion limit reached.
-ERR.015.006.0042= No xml schema to validate document against
-ERR.015.006.0048= Fatal Error: {0}
-ERR.015.006.0049= Error: {0}
-ERR.015.006.0051= Invalid direction for MoveDocInstruction: {0}
-ERR.015.006.0054= Instructed to abort processing as default of choice.
-
-# rewriter (009)
-ERR.015.009.0001= Error evaluating criteria: {0}
-ERR.015.009.0002= Error translating criteria on the user''s command, the criteria translated to {0} is not valid
-ERR.015.009.0003= Error simplifying mathematical expression: {0}
-
-
-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.Unknown_agg_func=Unknown aggregate function: {0}
-SQLParser.Invalid_func=Invalid function name: [{0}]
-SQLParser.Integer_parse=Unable to parse integer literal: {0}
-SQLParser.Float_parse=Unable to parse floating point literal: {0}
-SQLParser.Invalid_id=Invalid metadata ID format: [{0}]
-SQLParser.Invalid_alias=Invalid alias format: [{0}]
-SQLParser.Invalid_short_name=Invalid simple identifier format: [{0}]
-SQLParser.Invalid_char={0} value must be a single character: [{1}].
-SQLParser.expected_non_reserved=Expected non-reserved word {0}, but was {1}.
-SystemSource.array_length_desc=Get the length of the given array value
-SystemSource.array_param1=Array
-SystemSource.array_length_result=The array length
-SystemSource.array_get_desc=Get the object value at the given array index
-SystemSource.array_get_param2=Array index
-SystemSource.array_get_result=The object value
-SystemSource.Add_desc=Converts escape sequences in the given string to their actual characters.
-SystemSource.unescape_param1=String to be unescaped
-SystemSource.unescape_result=Unescaped string
-SystemSource.Add_desc=Add two numbers
-SystemSource.Add_result_desc=Left operand + right operand
-SystemSource.Subtract_desc=Subtract two numbers
-SystemSource.Subtract_result_desc=Left operand - right operand
-SystemSource.Multiply_desc=Multiply two numbers
-SystemSource.Multiply_result_desc=Left operand * right operand
-SystemSource.Divide_desc=Divide two numbers
-SystemSource.Divide_result_desc=Left operand / right operand
-SystemSource.Ceiling_desc=Ceiling of number
-SystemSource.Exp_desc=e^number
-SystemSource.Floor_desc=Floor of number
-SystemSource.Log_desc=Log (base e) of number
-SystemSource.Log10_desc=Log (base 10) of number
-SystemSource.Acos_desc=Arccosine of number
-SystemSource.Asin_desc=Arcsine of number
-SystemSource.Atan_desc=Arctan of number
-SystemSource.Atan2_desc=Arctan of number1 / number2
-SystemSource.Cos_desc=Cosine of number
-SystemSource.Cot_desc=Cotangent of number
-SystemSource.Degrees_desc=Convert from radians to degrees
-SystemSource.Pi_desc=Constant value for pi
-SystemSource.Radians_desc=Convert from degrees to radians
-SystemSource.Sin_desc=Sine of number
-SystemSource.Tan_desc=Tangent of number
-SystemSource.Bitand_desc=Bitwise AND of two integers
-SystemSource.Bitand_result_desc=integer1 AND integer2
-SystemSource.Bitor_desc=Bitwise inclusive OR of two integers
-SystemSource.Bitor_result_desc=integer1 OR integer2
-SystemSource.Bitxor_desc=Bitwise exclusive OR (XOR) of two integers
-SystemSource.Bitxor_result_desc=integer1 XOR integer2
-SystemSource.Bitnot_desc=Bitwise inversion (NOT) of a 32-bit integer. Equivalent to XOR(integer, 0xFFFFFFFF)
-SystemSource.Bitnot_result_desc=32-bit inverted integer
-SystemSource.Curdate_desc=Current date
-SystemSource.Curtime_desc=Current time
-SystemSource.Now_desc=Current timestamp
-SystemSource.Dayname_result_d_desc=Day name for date
-SystemSource.Dayname_result_ts_desc=Day name for timestamp
-SystemSource.Dayofmonth_result_d_desc=Day of month for date (1 = 1st)
-SystemSource.Dayofmonth_result_ts_desc=Day of month for timestamp (1 = 1st)
-SystemSource.Dayofweek_result_d_desc=Day of week for date (1 = Sunday)
-SystemSource.Dayofweek_result_ts_desc=Day of week for timestamp (1 = Sunday)
-SystemSource.Dayofyear_result_d_desc=Day of year for date (1 = Jan 1st)
-SystemSource.Dayofyear_result_ts_desc=Day of year for timestamp (1 = Jan 1st)
-SystemSource.Month_result_d_desc=Month for date (1 = January)
-SystemSource.Month_result_ts_desc=Month for timestamp (1 = January)
-SystemSource.Monthname_result_d_desc=Month name for date
-SystemSource.Monthname_result_ts_desc=Month name for timestamp
-SystemSource.Week_result_d_desc=Week of year for date
-SystemSource.Week_result_ts_desc=Week of year for timestamp
-SystemSource.Year_result_d_desc=Year for date
-SystemSource.Year_result_ts_desc=Year for timestamp
-SystemSource.Hour_result_t_desc=Hour for time
-SystemSource.Hour_result_ts_desc=Hour for timestamp
-SystemSource.Minute_result_t_desc=Minute for time
-SystemSource.Minute_result_ts_desc=Minute for timestamp
-SystemSource.Second_result_t_desc=Second for time
-SystemSource.Second_result_ts_desc=Second for timestamp
-SystemSource.Quarter_result_d_desc=Quarter for date (1=Jan/Feb/Mar)
-SystemSource.Quarter_result_ts_desc=Quarter for timestamp (1=Jan/Feb/Mar)
-SystemSource.Length_result=Length of string
-SystemSource.Ucase_result=Upper case of string
-SystemSource.Lcase_result=Lower case of string
-SystemSource.Lower_result=Lower case of string
-SystemSource.Upper_result=Upper case of string
-SystemSource.UcaseClob_result=Upper case of clob
-SystemSource.LcaseClob_result=Lower case of clob
-SystemSource.LowerClob_result=Lower case of clob
-SystemSource.UpperClob_result=Upper case of clob
-SystemSource.Left_result=Left trimmed string
-SystemSource.Right_result=Right trimmed string
-SystemSource.Formattime_desc=Convert to string
-SystemSource.Formattime_result_desc=Converted time
-SystemSource.Formatdate_desc=Convert to string
-SystemSource.Formatdate_result_desc=Converted date
-SystemSource.Formattimestamp_desc=Convert to string
-SystemSource.Formattimestamp_result_desc=Converted timestamp
-SystemSource.Parsetime_desc=Convert string to time
-SystemSource.Parsetime_result_desc=Time converted
-SystemSource.Parsedate_desc=Convert string to date
-SystemSource.Parsedate_result_desc=Date converted
-SystemSource.Parsetimestamp_desc=Convert string to timestamp
-SystemSource.Parsetimestamp_result_desc=Timestamp converted
-SystemSource.Formatinteger_desc=Convert to Integer
-SystemSource.Formatinteger_result_desc=Integer formatted
-SystemSource.Formatlong_desc=Convert to Long
-SystemSource.Formatlong_result_desc=Long formatted
-SystemSource.Formatdouble_desc=Convert to Double
-SystemSource.Formatdouble_result_desc=Double formatted
-SystemSource.Formatfloat_desc=Convert to Float
-SystemSource.Formatfloat_result_desc=Float formatted
-SystemSource.Formatbiginteger_desc=Convert to Big integer
-SystemSource.Formatbiginteger_result_desc=Big integer formatted
-SystemSource.Formatbigdecimal_desc=Convert to Big decimal
-SystemSource.Formatbigdecimal_result_desc=Big decimal formatted
-SystemSource.Parseinteger_desc=Parse to Integer
-SystemSource.Parseinteger_result_desc=Integer parsed
-SystemSource.Parselong_desc=Parse to Long
-SystemSource.Parselong_result_desc=Long parsed
-SystemSource.Parsedouble_desc=Parse to Double
-SystemSource.Parsedouble_result_desc=Double parsed
-SystemSource.Parsefloat_desc=Parse to Float
-SystemSource.Parsefloat_result_desc=Float parsed
-SystemSource.Parsebiginteger_desc=Parse to Biginteger
-SystemSource.Parsebiginteger_result_desc=Biginteger parsed
-SystemSource.Parsebigdecimal_desc=parse to Bigdecimal
-SystemSource.Parsebigdecimal_result_desc=Bigdecimal parsed
-SystemSource.Arith_left_op=Left operand
-SystemSource.Arith_right_op=Right operand
-SystemSource.Abs_desc=Absolute value of number
-SystemSource.Abs_arg=Number
-SystemSource.Abs_result_desc=Absolute value of number
-SystemSource.Rand_desc=Random Number
-SystemSource.Rand_arg=Number
-SystemSource.Rand_result_desc=Generated Random Number
-SystemSource.uuid_desc=UUID
-SystemSource.uuid_result_desc=type 4 UUID
-SystemSource.Double_arg2=Number
-SystemSource.Atan_arg1=Number parameter1
-SystemSource.Atan_arg2=Number parameter2
-SystemSource.Mod_desc=Modulus of two numbers
-SystemSource.Mod_result_desc=Left operand mod right operand
-SystemSource.Power_desc=Raise base to power
-SystemSource.Power_arg1=Base
-SystemSource.Power_arg2=Power
-SystemSource.Power_result_desc=Base ^ Power
-SystemSource.Round_desc=Round number to specified places
-SystemSource.Round_arg1=Numbers
-SystemSource.Round_arg2=Places
-SystemSource.Round_result_desc=Number rounded to specified places
-SystemSource.Sign_desc=Sign of number: 1 if number>0, 0 if number==0, -1 if number<0
-SystemSource.Sign_arg1=Number
-SystemSource.Sign_result_desc=Sign of number
-SystemSource.Sqrt_desc=Square root of number
-SystemSource.Sqrt_arg1=Number
-SystemSource.Sqrt_result_desc=Square root of number
-SystemSource.Timestampadd_d_desc=Add count number of interval type to date
-SystemSource.Timestampadd_d_arg1=Interval type
-SystemSource.Timestampadd_d_arg2=Count number
-SystemSource.Timestampadd_d_arg3=Date type
-SystemSource.Timestampadd_d_result_desc=Returned modified date
-SystemSource.Timestampadd_t_desc=Add count number of interval type to time
-SystemSource.Timestampadd_t_arg1=Interval type
-SystemSource.Timestampadd_t_arg2=Count number
-SystemSource.Timestampadd_t_arg3=Time type
-SystemSource.Timestampadd_t_result_desc=Returned modified time
-SystemSource.Timestampadd_ts_desc=Add count number of interval type to timestamp
-SystemSource.Timestampadd_ts_arg1=Interval type
-SystemSource.Timestampadd_ts_arg2=Count number
-SystemSource.Timestampadd_ts_arg3=Timestamp type
-SystemSource.Timestampadd_ts_result=Returned modified timestamp
-SystemSource.Timestampdiff_ts_desc=Calculate estimated number of intervals between start and end timestamp
-SystemSource.Timestampdiff_ts_arg1=Interval type
-SystemSource.Timestampdiff_ts_arg2=Start timestamp
-SystemSource.Timestampdiff_ts_arg3=End timestamp
-SystemSource.Timestampdiff_ts_result_desc=Returns estimated number of intervals between start and end timestamp
-SystemSource.TimestampCreate_desc=Create timestamp from a date and a time
-SystemSource.TimestampCreate_arg1=Date
-SystemSource.TimestampCreate_arg2=Time
-SystemSource.TimestampCreate_result_desc=Timestamp built from date and time
-SystemSource.Stringfunc_arg1=String
-SystemSource.Clobfunc_arg1=Clob
-SystemSource.Concat_desc=Concatenate left and right strings
-SystemSource.Concat_arg1=Left string
-SystemSource.Concat_arg2=Right string
-SystemSource.Concat_result_desc=Concatenated strings
-SystemSource.Concatop_desc=Concatenate left and right strings
-SystemSource.Concatop_arg1=Left string
-SystemSource.Concatop_arg2=Right string
-SystemSource.Concatop_result_desc=Concatenated strings
-SystemSource.Substring_desc=Substring of string, starting at index, of length
-SystemSource.Substring_arg1=String
-SystemSource.Substring_arg2=Starting index
-SystemSource.Substring_arg3=Length of substring
-SystemSource.Substring_result=Substring
-SystemSource.Susbstring2_desc=Substring of string, starting at index, to end of string
-SystemSource.Substring2_arg1=String
-SystemSource.Substring2_arg2=Starting index
-SystemSource.Substring2_result=Substring
-SystemSource.Left_desc=First length characters of string
-SystemSource.Left_arg1=String
-SystemSource.Left_arg2=Length of substring
-SystemSource.Left2_result=First length characters of string
-SystemSource.Right_desc=Last length characters of string
-SystemSource.Right_arg1=String
-SystemSource.Right_arg2=Length of substring
-SystemSource.Right2_result=Last length characters of string
-SystemSource.Locate_desc=Find index of substring in string starting at index
-SystemSource.Locate_arg1=Substring to find
-SystemSource.Locate_arg2=String
-SystemSource.Locate_arg3=Starting index
-SystemSource.Locate_result=Index of substring or -1 if not found
-SystemSource.Locate2_desc=Find index of substring in string
-SystemSource.Locate2_arg1=Substring to find
-SystemSource.Locate2_arg2=String
-SystemSource.Locate2_result=Index of substring or -1 if not found
-SystemSource.Replace_desc=Replace any substring in string with replacement
-SystemSource.Replace_arg1=String
-SystemSource.Replace_arg2=Substring to match
-SystemSource.Replace_arg3=Replacement string
-SystemSource.Replace_result=String with replacements
-SystemSource.Repeat_desc=Repeat string with count times
-SystemSource.Repeat_arg1=String
-SystemSource.Repeat_arg2=Count times to repeat
-SystemSource.Repeat_result=String repeated with count times
-SystemSource.Space_desc=Repeat space count times
-SystemSource.Space_arg1=Number of times to repeat
-SystemSource.Space_result=Space repeated count times
-SystemSource.Insert_desc=Insert string2 into string1 by deleting length characters at start and inserting string2
-SystemSource.Insert_arg1=Initial string
-SystemSource.Insert_arg2=Starting position
-SystemSource.Insert_arg3=Number of characters to delete at start
-SystemSource.Insert_arg4=String to insert
-SystemSource.Insert_result=Inserted string
-SystemSource.Ascii_desc=Takes a character and returns the ASCII or unicode integer representation
-SystemSource.Ascii_arg1=String
-SystemSource.Ascii_result=Character value
-SystemSource.Ascii2_desc=Takes a character and returns the ASCII or unicode integer representation
-SystemSource.Ascii2_arg1=Character
-SystemSource.Ascii2_result=Character value
-SystemSource.Chr_desc=Takes a unicode or ASCII value and returns the character representation
-SystemSource.Chr_arg1=Code value
-SystemSource.Chr_result=Character representation
-SystemSource.Char_desc=Takes a unicode or ASCII value and returns the character representation
-SystemSource.Char_arg1=Code value
-SystemSource.Char_result=Character representation
-SystemSource.Initcap_desc=Capitalizes each word (each letter after whitespace)
-SystemSource.Initcap_arg1=Input string
-SystemSource.Initcap_result=Result string
-SystemSource.Lpad_desc=Pad the input string on the left to length
-SystemSource.Lpad_arg1=String
-SystemSource.Lpad_arg2=Padded length
-SystemSource.Lpad_result=Padded string
-SystemSource.Lpad3_desc=Pad the input string on the left to length with pad character
-SystemSource.Lpad3_arg1=String
-SystemSource.Lpad3_arg2=Padded length
-SystemSource.Lpad3_arg3=Pad character
-SystemSource.Lpad3_result=Padded string
-SystemSource.Rpad1_desc=Pad the input string on the right to length
-SystemSource.Rpad1_arg1=String
-SystemSource.Rpad1_arg2=Padded length
-SystemSource.Rpad1_result=Padded string
-SystemSource.Rpad3_desc=Pad the input string on the right to length with pad character
-SystemSource.Rpad3_arg1=String
-SystemSource.Rpad3_arg2=Padded length
-SystemSource.Rpad3_arg3=Pad character
-SystemSource.Rpad3_result=Padded string
-SystemSource.Translate_desc=Translate the input string by converting characters in the source string to characters in the destination string
-SystemSource.Translate_arg1=String
-SystemSource.Translate_arg2=Source string
-SystemSource.Translate_arg3=Destination string
-SystemSource.Translate_result=Translated string
-SystemSource.Convert_arg1=Source value
-SystemSource.Convert_arg2=Target type
-SystemSource.Convert_result=Converted value
-SystemSource.Context_desc=Evaluate XML expression in the context of a different mapping level
-SystemSource.Context_arg1=XML context tag
-SystemSource.Context_arg2=XML element
-SystemSource.Context_result=Expression in higher context
-SystemSource.Rowlimit_desc=Limit the number of rows from an XML mapping class
-SystemSource.RowlimitException_desc=Limit the number of rows from an XML mapping class, throw Exception if passed
-SystemSource.Rowlimit_arg1=XML tag in the scope of a mapping class
-SystemSource.Rowlimit_result=Number of rows to be limited to
-SystemSource.Decode1_desc=Map the input value to a comma-separated list of allowed output values
-SystemSource.Decode1_arg1=Input column for decode
-SystemSource.Decode1_arg2=The comma delimited String that represents the mapping between input column value and output values.
-SystemSource.Decode1_result=The decoded value from the decode string.
-SystemSource.Decode2_desc=Map the input value to a delimiter-separated list of allowed output values
-SystemSource.Decode2_arg1=Input column for decode
-SystemSource.Decode2_arg2=The comma delimited String that represents the mapping between input column value and output values.
-SystemSource.Decode2_arg3=Decode String delimiter character(s)
-SystemSource.Decode2_result=The decoded value from the decode string.
-SystemSource.Lookup_desc=Look up a value in a cached code table
-SystemSource.Lookup_arg1=Full group name of code table
-SystemSource.Lookup_arg2=Short name of return element in code table
-SystemSource.Lookup_arg3=Short name of key element in code table
-SystemSource.Lookup_arg4=Key value to lookup
-SystemSource.Lookup_result=Return value for key as specified in code table
-SystemSource.User_desc=Get current user name
-SystemSource.User_result=Return user name
-SystemSource.current_database_desc=Get current database name
-current_database_result=Returns the catalog name
-SystemSource.Env_desc=Get the value of an environment variable
-SystemSource.Env_varname=Name of the environment variable
-SystemSource.Env_result=Return the string value of the environment variable
-SystemSource.Nvl_desc=Specifies a value to use instead if the input value is null
-SystemSource.Nvl_arg1=Value to check
-SystemSource.Nvl_arg2=Returned if value is null
-SystemSource.Nvl_result=Value or valueIfNull if value is null
-SystemSource.Ifnull_desc=Specifies a value to use instead if the input value is null
-SystemSource.Ifnull_arg1=Value to check
-SystemSource.Ifnull_arg2=Returned if value is null
-SystemSource.Ifnull_result=Value or valueIfNull if value is null
-SystemSource.Formattime_arg1=Time input
-SystemSource.Formattime_arg2=Time format
-SystemSource.Formatdate_arg1=Date input
-SystemSource.Formatdate_arg2=Date format
-SystemSource.Formattimestamp_arg1=Timestamp input
-SystemSource.Formattimestamp_arg2=Timestamp format
-SystemSource.Parsetime_arg1=String input
-SystemSource.Parsetime_arg2=Time format
-SystemSource.Parsedate_arg1=String input
-SystemSource.Parsedate_arg2=Date format
-SystemSource.Parsetimestamp_arg1=String input
-SystemSource.Parsetimestamp_arg2=Timestamp format
-SystemSource.Formatnumber_arg1=String input
-SystemSource.Formatnumber_arg2=Number format
-SystemSource.Parsenumber_arg1=String input
-SystemSource.Parsenumber_arg2=Parse format
-SystemSource.Bitfunc_arg1=Integer parameter
-SystemSource.Bitfunc2_arg1=First integer
-SystemSource.Bitfunc2_arg2=Second integer
-SystemSource.Convert_desc=Convert from {0} to target type
-SystemSource.xpathvalue_description=Retrieve the first match content for an XPath statement
-SystemSource.xpath_param1=Source document
-SystemSource.xpath_param2=XPath expression
-SystemSource.xpathvalue_result=Single result
-SystemSource.xsltransform_description=Transform the document with the given stylesheet.
-SystemSource.xsltransform_param1=Source document
-SystemSource.xsltransform_param2=XSL stylesheet
-SystemSource.xsltransform_result=Clob result
-SystemSource.xmlconcat_description=Concat XML types.
-SystemSource.xmlconcat_param1=First element
-SystemSource.xmlcomment_description=Create an XML comment.
-SystemSource.xmlconcat_param1=String comment
-SystemSource.xmlconcat_result=XML result
-SystemSource.xmlpi_description=Create an XML processing instruction.
-SystemSource.xmlpi_param1=Target
-SystemSource.xmlpi_param2=Content
-SystemSource.xmlpi_result=XML result
-SystemSource.jsonToXml_description=Create an XML document representing the given JSON.
-SystemSource.jsonToXml_param1=Root element name
-SystemSource.jsonToXml_param2=JSON
-SystemSource.jsonToXml_result=XML result
-SystemSource.modifyTimeZone_description=Modify the time zone of this timestamp by adding or subtracting time
-SystemSource.modifyTimeZone_param1=Timestamp
-SystemSource.modifyTimeZone_param2=Starting time zone
-SystemSource.modifyTimeZone_param3=Ending time zone
-SystemSource.modifyTimeZone_result=Original timestamp with time added or subtracted to give the equivalent time in a different time zone
-SystemSource.CommandPayload_desc0=Retrieve the command payload as a string
-SystemSource.CommandPayload_desc1=Retrieve a property from the command payload, passed as a Properties object
-SystemSource.CommandPayload_result=The property value from the command payload
-SystemSource.CommandPayload_property=The property name
-SystemSource.hasRole_description=Determine if the caller has the given role
-SystemSource.hasRole_param1=Role type
-SystemSource.hasRole_param2=Role name
-SystemSource.hasRole_result=whether the caller is in the given role
-SystemSource.from_unixtime_description=Return the Unix timestamp (in seconds) as a Timestamp value
-SystemSource.from_unixtime_param1=Unix timestamp (in seconds)
-SystemSource.from_unixtime_result=Timestamp value
-SystemSource.nullif_description=Equivalent to case when (param1 = param2) then null else param1
-SystemSource.nullif_param1=First parameter
-SystemSource.nullif_result=null if the parameters are equivalent else param1
-SystemSource.coalesce_description=Returns the first non-null parameter
-SystemSource.coalesce_param1=parameter
-SystemSource.coalesce_result=The first non-null parameter
-SystemSource.encode_desc=Converts a Blob to the appropriate chars
-SystemSource.encode_arg1=Blob
-SystemSource.encode_arg2=char representation Clob
-SystemSource.encode_result=Clob char rep
-SystemSource.decode_desc=Converts a Clob to the appropriate bytes
-SystemSource.decode_arg1=Clob
-SystemSource.decode_arg2=The encoding
-SystemSource.decode_result=byte representation Blob
-SystemSource.session_id_desc=Returns the session id of the currently logged in user
-SystemSource.session_id_result=Returns the session id of the currently logged in user
-TempMetadataAdapter.Element_____{0}_____not_found._1=Element ''{0}'' not found.
-TempMetadataAdapter.Group_____{0}_____not_found._1=Group ''{0}'' not found.
-ExpressionEvaluator.Must_push=Function {0} is marked in the function metadata as a function that must be evaluated at the source.
-ExpressionEvaluator.Eval_failed=Unable to evaluate {0}: {1}
-XMLSerialize.resolvingError=XMLSerialize is valid only for XML expressions: {0}
-Evaluator.xmlserialize=XMLSerialize: data exception - not an xml document
-Evaluator.xmlquery=Error evaluating XMLQuery: {0}
-ExecResolver.Param_convert_fail=Unable to convert procedural parameter of type {0} to expected type {1}
-ExecResolver.return_expected=Procedure {0} does not have a return value.
-ExecResolver.out_type_mismatch=OUT/RETURN parameter {0} with type {1} cannot be converted to {2}
-DynamicCommandResolver.SQL_String=Expected dynamic command sql to be of type STRING instead of type {0}.
-UnionQueryResolver.type_conversion=The Expression {0} used in a nested UNION ORDER BY clause cannot be implicitly converted from type {1} to type {2}.
-ValidationVisitor.select_into_no_implicit_conversion=There is no implicit conversion between the source element type ({0}) and the target element type ({1}) at position {2} of the query: {3}
-ValidationVisitor.excpet_intersect_all=EXCEPT ALL and INTERSECT ALL are currently unsupported
-ValidationVisitor.element_updates_not_allowed=Metadata does not allow updates on the element: {0}
-ValidationVisitor.invalid_batch_command=Only INSERT, UPDATE, DELETE, and SELECT ... INTO statements are allowed within a batch.
-ValidationVisitor.badoffset2=The row offset in the LIMIT clause must be >= 0
-ValidationVisitor.badlimit2=The row limit in the LIMIT clause must be >= 0
-ValidationVisitor.invalid_scalar_group_reference=Cannot reference a scalar group as a table: {0}
-ValidationVisitor.select_into_wrong_elements=Wrong number of elements being SELECTed INTO the target table. Expected {0} elements, but was {1}.
-SimpleQueryResolver.Query_was_redirected_to_Mat_table=The query against {0} was redirected to the materialization table {1}.
-SimpleQueryResolver.ambiguous_all_in_group=The symbol {0} refers to more than one group defined in the FROM clause.
-SimpleQueryResolver.Proc_Relational_Name_conflict=Cannot access procedure {0} using table semantics since the parameter and result set column names are not all unique.
-SimpleQueryResolver.duplicate_with=Duplicate WITH clause item name {0}
-SimpleQueryResolver.mismatched_with_columns=The number of WITH clause columns for item {0} do not match the query expression
-QueryResolver.invalid_xpath=Invalid xpath value: {0}
-QueryResolver.wrong_view_symbols=The definition for {0} does not have the correct number of projected symbols. Expected {1}, but was {2}.
-QueryResolver.wrong_view_symbol_type=The definition for {0} has the wrong type for column {1}. Expected {2}, but was {3}.
-ResolveVariablesVisitor.reserved_word_for_temporary_used=Cursor names cannot begin with "#" as that indicates the name of a temporary table: {0}.
-SimpleQueryResolver.materialized_table_not_used=The query against {0} did not use materialization table {1} due to the use of OPTION NOCACHE.
-SimpleQueryResolver.cache_hint_used=Loading materialized view {1} for view {0} using cache hint {2}.
-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.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
-ValidationVisitor.The_context_function_cannot_be_used_in_a_non-XML_command=The ''context'' function cannot be used in a non-XML command
-ValidationVisitor.0=The ''rowlimit'' and ''rowlimitexception'' functions cannot be nested within other functions.
-ValidationVisitor.1=The ''rowlimit'' and ''rowlimitexception'' functions operand must be a constant nonnegative integer.
-ValidationVisitor.2=The ''rowlimit'' and ''rowlimitexception'' functions arg must be an XML node symbol
-ValidationVisitor.3=''Rowlimit'' and ''rowlimitexception'' functions can only be used within a compare criteria which is entirely a single conjunct.
-ValidationVisitor.Context_function_nested=Context functions cannot be nested
-ERR.015.004.0036= First argument in ''context'' must be the name of a node in the XML document model. Found Object {0} of Class {1}
-ExecResolver.invalid_named_params=Invalid param name(s): {0}. Name(s) of params without explicit values: {1}
-ExecResolver.duplicate_named_params=Duplicate named param ''{0}''
-ResolverUtil.required_param=Required parameter ''{0}'' has no value was set or is an invalid parameter.
-ResolverUtil.duplicateName=Cannot create group ''{0}'' with multiple columns named ''{1}''
-ResolverUtil.error_converting_value_type=Exception converting value {0} of type {1} to expected type {2}
-ResolverUtil.setquery_order_expression=ORDER BY expression ''{0}'' cannot be used with a set query.
-ResolverUtil.invalid_unrelated=Unrelated order by column {0} cannot be used in a SET query, with SELECT DISTINCT, or GROUP BY
-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.
-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.
-ValidationVisitor.text_table_width=Fixed width text tables should not have DELIMITER, QUOTE, ESCAPE, or HEADER specified.
-ValidationVisitor.text_table_negative=Text table WIDTH, HEADER, or SKIP values must not be negative.
-ValidationVisitor.text_table_delimiter=Text DELIMITER cannot be the same as the QUOTE or ESCAPE characters.
-ValidationVisitor.text_table_newline=Text DELIMITER, QUOTE, and ESCAPE characters cannot be the new line character.
-ValidationVisitor.xml_namespaces=At most only one NO DEFAULT or DEFAULT namespace may be specified.
-ValidationVisitor.xml_namespaces_reserved=The namespaces xmlns and xml are reserved.
-ValidationVisitor.xml_namespaces_null_uri=The null uri, or empty string, is not allowed as the uri value.
-ValidationVisitor.xml_attributes_reserved=The namespace xmlns is reserved.
-ValidationVisitor.xml_content_type=The expression "{0}" is of OBJECT or BLOB type, which cannot be used as an XML or TEXT content value.
-ValidationVisitor.xml_invalid_qname=The qname "{0}" is invalid.
-ValidationVisitor.context_item_type=XMLTABLE or XMLQUERY PASSING context item must be an XML value.
-ValidationVisitor.passing_requires_name=XMLTABLE or XMLQUERY PASSING clause can only contain at most 1 unnamed item.
-ValidationVisitor.duplicate_passing=XMLTABLE or XMLQUERY PASSING clause duplicate item name "{0}".
-ValidationVisitor.one_ordinal=Only one FOR ORDINALITY column is allowed for an XMLTABLE.
-ValidationVisitor.invalid_default=XMLTABLE DEFAULT expression is invalid: "{0}"
-ValidationVisitor.context_required=The XQuery requires a context item, but none exists in the PASSING clause.
-ValidationVisitor.xmlparse_type=XMLPARSE expects a STRING, CLOB, or BLOB value.
-ValidationVisitor.invalid_encoding=Encoding {0} is not valid.
-ValidationVisitor.subquery_insert=SELECT INTO should not be used in a subquery.
-UpdateProcedureResolver.only_variables=Variable "{0}" is read only and cannot be assigned a value.
-MappingLoader.unknown_node_type=Unknown Node Type "{0}" being loaded by the XML mapping document.
-MappingLoader.invalid_criteria_node=Invalid criteria node found; A criteria node must have criteria specified or it must be a default node.
-WrongTypeChild=Wrong type of child node is being added.
-NoCriteria=Failed to add the node, because Criteria nodes must have "criteria" value set on them, or they need to be the default node.
-root_cannotbe_null=Root node assigned to a document can be null.
-invalid_recurive_node= Found recursive node {0} without recursive root node.
-SaxonXQueryExpression.bad_xquery=Failed to evaluate XQuery expression; Please check the query and correct errors in syntax or usage.
-SaxonXQueryExpression.compile_failed=Could not compile XQuery; Please check the query for syntax or usage errors.
-SaxonXQueryExpression.invalid_path=Column "{0}" has an invalid path expression: {1}
-SaxonXQueryExpression.bad_context=Error building Source for context item.
-MappingLoader.invalidName=Null or blank name found in the Mapping Document, Must have valid name. Re-build the VDB
-MatchCriteria.invalid_escape=Invalid escape sequence "{0}" with escape character "{1}"
-QueryUtil.wrong_number_of_values=The number of bound values ''{0}'' does not match the number of parameters ''{1}'' in the prepared statement.
-QueryUtil.Error_executing_conversion_function_to_convert_value=Error converting parameter number {0} with value "{1}" to expected type {2}.
-InsertResolver.cant_convert_query_type=Cannot convert insert query expression projected symbol ''{0}'' of type {1} to insert column ''{2}'' of type {3}
-SetClause.resolvingError=Cannot set symbol ''{1}'' with expected type {2} to expression ''{0}''
-NewCalculateCostUtil.badCost=Unexpected format encountered for max or min value
-
-WorkerPool.Max_thread=Reached maximum thread count "{0}" for worker pool "{1}" with a queue size high of "{2}". Queued work waited {3} ms prior to executing. To avoid queuing of work you may consider increasing "RuntimeEngineDeployer.maxThreads" or decreasing the "RuntimeEngineDeployer.maxActivePlans" in the "teiid-jboss-beans.xml" file.
-WorkerPool.uncaughtException=Uncaught exception processing work
-
-
-TempTable.duplicate_key=Duplicate key
-TempTable.not_null=Null value is not allowed for column {0}
-ValidationVisitor.group_in_both_dep=Table specified in both dependent and independent queries '{0}'
-XMLQuery.resolvingError=Failed to resolve the query '{0}'
-SQLParser.non_position_constant=Invalid order by at {0}
-
-
-QueryRewriter.infinite_while=Infinite loop detected, procedure will not be executed.
-
-BatchedUpdatePlanner.unrecognized_command=The batch contained an unrecognized command: {0}
-ProcedurePlanner.bad_stmt=Error while planning update procedure, unknown statement type encountered: {0}
-RulePushSelectCriteria.Error_getting_modelID=Error getting modelID
-XMLPlanner.no_uri=Cannot find namespace URI for namespace {0} of element {1}
-
-XMLPlanner.The_XML_document_element_{0}_is_not_mapped_to_data_and_cannot_be_used_in_the_ORDER_BY_clause__{1}_1=The XML document element {0} is not mapped to data and cannot be used in the ORDER BY clause: {1}
-XMLPlanner.The_rowlimit_parameter_{0}_is_not_in_the_scope_of_any_mapping_class=The ''rowlimit'' or ''rowlimitexception'' function parameter ''{0}'' is not an XML node within the scope of any mapping class.
-XMLPlanner.Criteria_{0}_contains_conflicting_row_limits=The criteria ''{0}'' contains conflicting row limits for an XML mapping class.
-AccessNode.rewrite_failed=Failed to rewrite the command: {0}
-BatchedUpdateNode.unexpected_end_of_batch=Unexpectedly reached the end of the batched update counts at {0}, expected {1}.
-row_limit_passed=The row limit {0} has been exceeded for XML mapping class {1}.
-AddNodeInstruction.element__1=element
-AddNodeInstruction.Unable_to_add_xml_{0}_{1},_namespace_{2},_namespace_declarations_{3}_3=Unable to add xml {0} {1}, namespace {2}, namespace declarations {3}
-QueryProcessor.request_cancelled=The request {0} has been cancelled.
-VariableSubstitutionVisitor.Input_vars_should_have_same_changing_state=INPUT variables used in the expression should all have same CHANGING state: {0}
-
-ExecDynamicSqlInstruction.0=Evaluated dynamic SQL expression value was null.
-ExecDynamicSqlInstruction.3=There is a recursive invocation of group ''{0}''. Please correct the SQL.
-ExecDynamicSqlInstruction.4=The dynamic sql string contains an incorrect number of elements.
-ExecDynamicSqlInstruction.6=The datatype ''{0}'' for element ''{1}'' in the dynamic SQL cannot be implicitly converted to ''{2}''.
-ExecDynamicSqlInstruction.couldnt_execute=Couldn''t execute the dynamic SQL command "{0}" with the SQL statement "{1}" due to: {2}
-
-RulePlanJoins.cantSatisfy=Join region with unsatisfied access patterns cannot be satisfied by the join criteria, Access patterns: {0}
-TempTableStore.table_exist_error=Temporary table "{0}" already exists.
-TempTableStore.table_doesnt_exist_error=Temporary table "{0}" does not exist.
-
-XMLQueryPlanner.cannot_plan=Cannot create a query for MappingClass with user criteria {0}
-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}
-CriteriaPlanner.invalid_element=Element {0} is not a valid data node
-results_not_found=Results for the mapping class {0} are not found;
-RulePlanProcedures.no_values=No valid criteria specified for procedure parameter {0}
-ProcedurePlan.nonNullableParam=The procedure parameter {0} is not nullable, but is set to null.
-
-FileStoreageManager.error_creating=Error creating {0}
-FileStoreageManager.error_reading=Error reading {0}
-FileStoreageManager.no_directory=No directory specified for the file storage manager.
-FileStoreageManager.not_a_directory={0} is not a valid storage manager directory.
-FileStoreageManager.space_exhausted=Max buffer space of {0} bytes has been exceed. The current operation will be aborted.
-
-TextTableNode.no_value=No value found for column {0} in the row ending on text line {1} in {2}.
-TextTableNode.conversion_error=Could not convert value for column {0} in the row ending on text line {1} in {2}.
-TextTableNode.header_missing=HEADER entry missing for column name {0} in {1}.
-TextTableNode.unclosed=Text parse error: Unclosed qualifier at end of text in {0}.
-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}.
-
-XMLTableNode.error=Error evaluating XQuery row context for XMLTable: {0}
-XMLTableNode.path_error=Error evaluating XMLTable column path expression for column: {0}
-XMLTableName.multi_value=Unexpected multi-valued result was returned for XMLTable column "{0}". Path expressions for non-XML type columns should return at most a single result.
-
-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.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.
-TempTableDataManager.row_refresh_updatable=Materialized view {0} cannot have a row refreshed because it's cache hint did not specify \"updatable\".
-TempTableDataManager.row_refresh=Refreshing row {1} for materialized view {0}.
-CriteriaPlanner.no_context=No root node found.
-
-BasicInterceptor.ProcessTree_for__4=ProcessTree for
-
-
-ConnectorManager.not_in_valid_state=Connector is not in OPEN state
-
-ConnectorManagerImpl.Initializing_connector=Initializing connector {0}
-Cancel_request_failed=AtomicRequest {0} failed to cancel.
-
-ConnectorWorker.MaxResultRowsExceed=The number of result rows has exceeded the maximum result rows "{0}"
-ConnectorWorker.zero_size_non_last_batch=Connector returned a 0 row non-last batch: {0}.
-ConnectorWorker.process_failed=Connector worker process failed for atomic-request={0}
-ConnectorWorker.ConnectorWorker_result_set_unexpected_columns=Could not process stored procedure results for {0}. Expected {1} result set columns, but was {2}. Please update your models to allow for stored procedure results batching.
-
-
-DataTierManager.could_not_obtain_connector_binding=Could not obtain connection factory for model {0} in VDB name= {1}, version {2}
-DataTierManagerImpl.max_value_length=Property value length exceeds max of {0}.
-DataTierManagerImpl.unknown_uuid=Could not find a metadata record with uuid {0}.
-
-DQPCore.Unable_to_load_metadata_for_VDB_name__{0},_version__{1}=Unable to load metadata for VDB name= {0}, version= {1}
-DQPCore.Unknown_query_metadata_exception_while_registering_query__{0}.=Unknown query metadata exception while registering query: {0}.
-DQPCore.Clearing_prepared_plan_cache=Clearing prepared plan cache
-DQPCore.Clearing_prepared_plan_cache_for_vdb=Clearing prepared plan cache for vdb {0}.{1}
-DQPCore.clearing_resultset_cache=Clearing the resultset cache for vdb {0}.{1}
-DQPCore.The_request_has_been_closed.=The request {0} has been closed.
-DQPCore.The_atomic_request_has_been_cancelled=The atomic request {0} has been canceled.
-DQPCore.failed_to_cancel=Failed to Cancel request, as request already finished processing
-DQPCore.invalid_max_active_plan=The maxActivePlan {0} setting should never be greater than the max processing threads {1}.
-
-ProcessWorker.failed_rollback=Failed to properly rollback autowrap transaction properly
-ProcessWorker.error=Unexpected exception for request {0}
-ProcessWorker.processing_error=Processing exception ''{0}'' for request {1}. Exception type {2} thrown from {3}. Enable more detailed logging to see the entire stacktrace.
-
-
-# #query (018.005)
-ERR.018.005.0095 = User <{0}> is not entitled to action <{1}> for 1 or more of the groups/elements/procedures.
-
-# services (003)
-
-Request.Invalid_character_in_query=Bind variables (represented as "?") were found but are allowed only in prepared or callable statements.
-Request.no_result_set=The query does not return a result set.
-Request.result_set=The query does not return an update count.
-
-ProcessWorker.wrongdata=Wrong type of data found or no data found; expecting streamable object from the buffer manager.
-ProcessWorker.LobError=An error occurred during streaming of Lob Chunks to Client.
-
-TransactionServer.existing_transaction=Client thread already involved in a transaction. Transaction nesting is not supported. The current transaction must be completed first.
-TransactionServer.no_transaction=No transaction found for client {0}.
-TransactionServer.concurrent_transaction=Concurrent enlistment in global transaction {0} is not supported.
-TransactionServer.no_global_transaction=Expected an existing global transaction {0} but there was none for client {1}
-TransactionServer.unknown_flags=Unknown flags
-TransactionServer.no_global_transaction=No global transaction found for {0}.
-TransactionServer.wrong_transaction=Client is not currently enlisted in transaction {0}.
-TransactionServer.resume_failed=Cannot resume, transaction {0} was not suspended by client {1}.
-TransactionServer.existing_global_transaction=Global transaction {0} already exists.
-TransactionServer.suspended_exist=Suspended work still exists on transaction {0}.
-
-TransformationMetadata.does_not_exist._1=does not exist.
-TransformationMetadata.Error_trying_to_read_virtual_document_{0},_with_body__n{1}_1=Error trying to read virtual document {0}, with body \n{1}
-TransformationMetadata.Unknown_support_constant___12=Unknown support constant:
-TransformationMetadata.QueryPlan_could_not_be_found_for_physical_group__6=QueryPlan could not be found for physical group
-TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__8=InsertPlan could not be found for physical group
-TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__10=InsertPlan could not be found for physical group
-TransformationMetadata.DeletePlan_could_not_be_found_for_physical_group__12=DeletePlan could not be found for physical group
-TransformationMetadata.Error_trying_to_read_schemas_for_the_document/table____1=Error trying to read schemas for the document/table :
-TransformationMetadata.Invalid_type=Invalid type: {0}.
-TransformationMetadata.does_not_exist._1=does not exist.
-TransformationMetadata.0={0} ambiguous, more than one entity matching the same name
-TransformationMetadata.Error_trying_to_read_virtual_document_{0},_with_body__n{1}_1=Error trying to read virtual document {0}, with body \n{1}
-TransformationMetadata.Unknown_support_constant___12=Unknown support constant:
-TransformationMetadata.QueryPlan_could_not_be_found_for_physical_group__6=QueryPlan could not be found for physical group
-TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__8=InsertPlan could not be found for physical group
-TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__10=InsertPlan could not be found for physical group
-TransformationMetadata.DeletePlan_could_not_be_found_for_physical_group__12=DeletePlan could not be found for physical group
-TransformationMetadata.Error_trying_to_read_schemas_for_the_document/table____1=Error trying to read schemas for the document/table :
-TransformationMetadata.Invalid_type=Invalid type: {0}.
-
-CachedFinder.no_connector_found=No connector with jndi-name {0} found for Model {1} with source name {2}
-translator_not_found=Translator {0} not accessible.
-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
-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.
-
-RelationalPlanner.nonpushdown_command=Source UPDATE or DELETE command "{0}" contains non-pushdown constructs and no compensating action can be taken as the table lacks a unique key or the source does not support equality predicates.
-
-Translate.error=Cannot translate criteria "{0}", it is not matched by selector "{1}"
-
-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.array_index=Array index out of range: {0}
-ArrayTableNode.conversion_error=Could not convert value for column: {0}
-
-AlterResolver.not_a_view={0} is not a valid view.
-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
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/main/resources/org/teiid/query/i18n.properties (from rev 3218, trunk/engine/src/main/resources/org/teiid/query/i18n.properties)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/main/resources/org/teiid/query/i18n.properties (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/main/resources/org/teiid/query/i18n.properties 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,923 @@
+#
+# 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.
+#
+
+# Error messages for query (015) project to address internationalization
+# Format:
+#
+
+# function (001)
+ERR.015.001.0002 = Cannot find implementation for known function {0}
+ERR.015.001.0003 = Error while evaluating function {0}
+ERR.015.001.0004 = Unable to access function implementation for [{0}]
+ERR.015.001.0005 = ERROR loading system functions: {0}
+ERR.015.001.0017 = Left count is invalid: {0}
+ERR.015.001.0025 = Pad length must be > 0.
+ERR.015.001.0027 = Pad string for lpad/rpad must have length greater than 0.
+ERR.015.001.0031 = Source and destination character lists must be the same length.
+ERR.015.001.0033 = Error converting [{0}] of type {1} to type {2}
+ERR.015.001.0035 = The context function may only be used in XML queries.
+ERR.015.001.0035a = The rowlimit and rowlimitexception functions may only be used in XML queries.
+ERR.015.001.0042 = Illegal argument for formating: {0}
+ERR.015.001.0043 = Parse Exception occurs for executing: {0} {1}
+ERR.015.001.0044 = Function metadata source is of invalid type: {0}
+ERR.015.001.0046 = The function "{0}" will not be added because a function with the same name and signature already exists.
+ERR.015.001.0047 = Unexpected exception while loading "{1}.{2}" for UDF "{0}"
+FunctionTree.not_void = UDF "{0}" method "{1}" must not return void.
+FunctionTree.not_public = UDF "{0}" method "{1}" must be public.
+FunctionTree.not_static = UDF "{0}" method "{1}" must be static.
+FunctionTree.no_class = Could not load UDF "{0}", since its invocation class "{1}" could not be found.
+FunctionTree.no_method = UDF "{0}" could not loaded, since no method on class "{1}" with name "{2}" has a matching type signature.
+ERR.015.001.0048 = Unable to represent average value from {0} / {1}
+ERR.015.001.0050 = Unable to compute aggregate function {0} on data of type {1}
+ERR.015.001.0052 = {0} must be non-null.
+ERR.015.001.0053 = Method parameter must be non-null.
+ERR.015.001.0054 = Type is unknown: {0}
+ERR.015.001.0055 = {0} exceeds maximum length of {1}
+ERR.015.001.0056 = {0} has invalid first character: {1}
+ERR.015.001.0057 = {0} has invalid character: {1}
+ERR.015.001.0058 = {0} cannot end with a ''.''
+ERR.015.001.0061 = <start> value of {0} is invalid, which should never be less than zero or bigger than the length of original string {1}
+ERR.015.001.0062 = <length> value of {0} is invalid, which should never less be than zero.
+ERR.015.001.0063 = Input String is an empty string but start value or/and length value is bigger than zero.
+ERR.015.001.0066 = Unknown type signature for evaluating function of: {0} ({1})
+ERR.015.001.0069 = Unknown type signature for evaluating function of: {0} ({1})
+
+# mapping (002)
+ERR.015.002.0009 = Search direction arg ''{0}'' is not one of the search constants defined in MappingNodeConstants.
+ERR.015.002.0010 = Value for property ''{0}'' is null.
+ERR.015.002.0011 = Invalid type: {0}
+
+
+# parser (005)
+QueryParser.emptysql=Parser cannot parse an empty sql statement.
+QueryParser.parsingError=Parsing error: {0}
+QueryParser.nullSqlCrit=Parser cannot parse a null sql criteria.
+QueryParser.lexicalError= Lexical error: {0}
+QueryParser.nullSqlExpr= Parser cannot parse a null sql expression.
+QueryParser.xqueryCompilation= Direct usage of XQuery is no longer supported, use XMLQUERY instead.
+
+# processor (006)
+ERR.015.006.0010= Unknown criteria type: {0}
+ERR.015.006.0011= Unable to evaluate {0} expression of {1}
+ERR.015.006.0012= Unknown compare criteria operator: {0}
+ERR.015.006.0014= Failed to create regular expression from match pattern: {0}. {1}
+ERR.015.006.0015= Unable to evaluate expression of {0}
+ERR.015.006.0016= Unknown expression type: {0}
+ERR.015.006.0033= Unable to evaluate {0}: {1}
+ERR.015.006.0055= Unable to evaluate LOOKUP function.
+ERR.015.006.0057= Unknown subquery comparison predicate quantifier: {0}
+ERR.015.006.0058= The command of this scalar subquery returned more than one value: {0}
+
+# resolver (008)
+ERR.015.008.0003= Only one XML document may be specified in the FROM clause of a query.
+ERR.015.008.0007= Incorrect number of parameters specified on the stored procedure {2} - expected {0} but got {1}
+ERR.015.008.0009= {1} is not allowed on the view {0}: a procedure must be defined to handle the {1}.
+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}
+ERR.015.008.0025= Binding reference cannot be a function: {0}
+ERR.015.008.0026= Expression ''{0}'' has a parameter with non-determinable type information. The use of an explicit convert may be necessary.
+ERR.015.008.0027= The expressions in this criteria are being compared but are of differing types ({0} and {1}) and no implicit conversion is available: {2}
+ERR.015.008.0029= This criteria must have string or CLOB expressions on each side: {0}
+ERR.015.008.0030= Type cannot be null for expression: {0}
+ERR.015.008.0031= This criteria must have values only of the same type as the left expression: {0}
+ERR.015.008.0032= There must be exactly one projected symbol of the subquery: {0}
+ERR.015.008.0033= The left expression must have a type convertible to the type of the subquery projected symbol: {0}
+ERR.015.008.0035= Type was null for {0} in function {1}
+ERR.015.008.0036= The function ''{0}'' has more than one possible signature.
+ERR.015.008.0037= The conversion from {0} to {1} is not allowed.
+ERR.015.008.0039= The function ''{0}'' is an unknown form. Check that the function name and number of arguments is correct.
+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.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.
+ERR.015.008.0049= Bindings must be specified
+ERR.015.008.0051= Symbol {0} is specified with an unknown group context
+ERR.015.008.0053= Element "{0}" is ambiguous, it exists in two or more groups.
+ERR.015.008.0054= Element "{0}" is not defined by any relevant group.
+ERR.015.008.0055= Group specified is ambiguous, resubmit the query by fully qualifying the group name
+ambiguous_procedure= Procedure ''{0}'' is ambiguous, use the fully qualified name instead
+ERR.015.008.0056= Group does not exist
+ERR.015.008.0061= Unable to resolve stored procedure {0} the datatype for the parameter {1} is not specified.
+ERR.015.008.0062= Unable to resolve return element referred to by LOOKUP function: {0}
+ERR.015.008.0063= The first three arguments for the LOOKUP function must be specified as constants.
+ERR.015.008.0065= Group {0} is not allowed in LOOKUP function.
+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}
+ERR.015.010.0002= Invalid logical operator: {0}
+ERR.015.010.0003= Cannot set null collection of elements on GroupBy
+ERR.015.010.0006= Invalid parameter type [{0}] must be IN, OUT, INOUT, RETURN_VALUE, RESULT_SET
+ERR.015.010.0009= No columns exist.
+ERR.015.010.0010= Invalid column index: {0}
+ERR.015.010.0011= Parameter cannot be null
+ERR.015.010.0014= Constant type should never be null
+ERR.015.010.0015= Unknown constant type: {0}
+ERR.015.010.0016= A group symbol may not resolve to a null metadata ID.
+ERR.015.010.0017= The name of a symbol may not be null.
+ERR.015.010.0018= Inconsistent number of elements in transformation projected symbols and virtual group.
+ERR.015.010.0021= Elements cannot be null
+ERR.015.010.0022= Functions cannot be null
+ERR.015.010.0023= Groups cannot be null
+ERR.015.010.0029= Cannot create AliasSymbol wrapping AliasSymbol
+ERR.015.010.0031= Illegal variable name ''{1}''. Variable names can only be prefixed with the special group name ''{0}''.
+ERR.015.010.0032= Variable {0} was previously declared.
+ERR.015.010.0035= The <expression> cannot be null in CASE <expression>
+ERR.015.010.0036= There must be at least one WHEN expression and one THEN expression. The number of WHEN and THEN expressions must be equal.
+ERR.015.010.0037= The WHEN part of the CASE expression must contain an expression.
+ERR.015.010.0038= The THEN part of the CASE expression must contain an expression
+ERR.015.010.0039= The WHEN part of the searched CASE expression must contain a criteria.
+
+# util (011)
+
+# validator (012)
+ERR.015.012.0001 = The updatable view query must be simple (containing a FROM clause and not using SELECT INTO) or a UNION ALL of simple queries.
+ERR.015.012.0002 = The updatable view query has a WITH clause, pass-through processing will not be used for UPDATE/DELETE operations.
+ERR.015.012.0003 = The updatable view query projects a column from a non-updatable group {0}.
+ERR.015.012.0004 = The updatable view query has a non key preserving group {0}, which cannot be targeted by INSERT/UPDATE/DELETE operations.
+ERR.015.012.0005 = The updatable view has no valid target for UPDATEs.
+ERR.015.012.0006 = The updatable view query must not use aggregates or grouping.
+ERR.015.012.0007 = The updatable view query has a non-updatable expression {0} for view column {1}.
+ERR.015.012.0008 = The updatable view query cannot use SELECT DISTINCT.
+ERR.015.012.0009 = The updatable view query has a FROM clause that is not a single table, pass-through processing will not be used for UPDATE/DELETE operations.
+ERR.015.012.0010 = The updatable view query does not project the column {0}, which is required to make {1} a target of INSERT operations.
+ERR.015.012.0011 = There must be exactly one projected symbol in the subcommand of an IN clause.
+ERR.015.012.0012 = An AssignmentStatement cannot change the value of a {0} or {1} variable.
+ERR.015.012.0013 = The query defining an updatable virtual group cannot use LIMIT.
+ERR.015.012.0014 = The non-simple query defining an updatable view does not have a valid key preserving delete target.
+ERR.015.012.0015 = The query defining an updatable view has no valid target for INSERTs.
+ERR.015.012.0016 = Variable {0} not assigned any value in this procedure.
+ERR.015.012.0017 = Variables declared the procedure''s DeclareStatement cannot be one of the special variables: {0}, {1} and {2}.
+ERR.015.012.0018 = Inherent INSERT is not possible on a view defined by a non-partitioned UNION.
+ERR.015.012.0019 = Translate/HasCriteria cannot be used in a non-update procedure.
+ERR.015.012.0021 = Element being translated in the WITH clause not among the elements on the ON clause of the TranslateCriteria.
+ERR.015.012.0022 = Unable to translate criteria on the update command against the virtual group, the element {0} is mapped to an aggregate symbol in the virtual group''s query transform, and cannot be translated.
+ERR.015.012.0023 = Unable to translate criteria on the update command against the virtual group, the element {0} is mapped to an expression whose elements are not present on the command in the procedure using the translated criteria.
+ERR.015.012.0024 = The following data elements are not supported in the SELECT clause: {0}.
+ERR.015.012.0025 = Command must project at least one symbol
+ERR.015.012.0026 = Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used in SELECT DISTINCT, ORDER BY, GROUP BY, KEYS, or non-all set queries: [{0}]
+ERR.015.012.0027 = Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used in comparison: {0}.
+ValidationVisitor.expression_requires_name = Non-column expressions require a name in XMLATTRIBUTES, XMLFOREST, QUERYSTRING, or TEXTAGG with HEADER
+ValidationVisitor.invalid_lookup_key=Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used as LOOKUP key columns: {0}.
+ValidationVisitor.limit_not_valid_for_xml=The limit clause cannot be used on an XML document query.
+ValidationVisitor.union_insert = Select into is not allowed under a set operation: {0}.
+ValidationVisitor.multisource_insert = A multi-source table, {0}, cannot be used in an INSERT with query expression or SELECT INTO statement.
+ValidationVisitor.invalid_encoding = Invalid encoding: {0}.
+ValidationVisitor.nonUpdatable = The specified change set {0} against an inherently updatable view does not map to a key preserving group.
+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.
+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
+ERR.015.012.0032 = Queries against XML documents can not have a HAVING clause
+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.0039 = Nested aggregate expressions are not allowed: {0}
+ERR.015.012.0041 = The aggregate function {0} cannot be used with non-numeric expressions: {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.
+AggregateValidationVisitor.invalid_distinct=The enhanced numeric aggregate functions STDDEV_POP, STDDEV_SAMP, VAR_POP, VAR_SAMP cannot have DISTINCT specified.
+ERR.015.012.0052 = The element [{0}] is in an INSERT but does not support updates.
+ERR.015.012.0053 = Element in the group {0}, for which value is not specified in the insert command is neither nullable nor has a default value: {1}
+ERR.015.012.0054 = Column variables do not reference columns on group "{0}": {1}
+ERR.015.012.0055 = Element {0} does not allow nulls.
+ERR.015.012.0059 = Left side of update expression must be an element that supports update: {0}
+ERR.015.012.0060 = Element {0} does not allow nulls.
+ERR.015.012.0061 = Views using update procedures must have update values that are constant expressions. The expression ''{0}'' cannot be evaluated to a constant.
+ERR.015.012.0062 = Elements cannot appear more than once in a SET or USING clause. The following elements are duplicated: {0}
+ERR.015.012.0063 = Multiple failures occurred during validation:
+ERR.015.012.0064 = Validation succeeded
+ERR.015.012.0065 = Nested Loop can not use the same cursor name as that of its parent.
+ERR.015.012.0067 = No scalar subqueries are allowed in the SELECT with no FROM clause.
+ERR.015.012.0069 = INTO clause can not be used in XML query.
+
+# optimizer (004)
+ERR.015.004.0007= Can''t convert plan node of type {0}
+ERR.015.004.0009= Error finding connectorBindingID for command
+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.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.
+ERR.015.004.0037= No mapping node found named, ''{0}', in use of ''context''
+ERR.015.004.0046= The XML document element(s) {0} are not mapped to data and cannot be used in the criteria \"{1}\".
+ERR.015.004.0054= Could not parse query transformation for {0}: {1}
+ERR.015.004.0068= Context functions within the same conjunct refer to different contexts: {0}
+
+# processor (006)
+ERR.015.006.0001= XMLPlan toString couldn''t print entire Program.
+ERR.015.006.0034= Unexpected symbol type while updating tuple: {0}
+ERR.015.006.0037= Tuple source does not exist: {0}
+ERR.015.006.0039= Instructed to abort processing when recursion limit reached.
+ERR.015.006.0042= No xml schema to validate document against
+ERR.015.006.0048= Fatal Error: {0}
+ERR.015.006.0049= Error: {0}
+ERR.015.006.0051= Invalid direction for MoveDocInstruction: {0}
+ERR.015.006.0054= Instructed to abort processing as default of choice.
+
+# rewriter (009)
+ERR.015.009.0001= Error evaluating criteria: {0}
+ERR.015.009.0002= Error translating criteria on the user''s command, the criteria translated to {0} is not valid
+ERR.015.009.0003= Error simplifying mathematical expression: {0}
+
+
+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.Unknown_agg_func=Unknown aggregate function: {0}
+SQLParser.Invalid_func=Invalid function name: [{0}]
+SQLParser.Integer_parse=Unable to parse integer literal: {0}
+SQLParser.Float_parse=Unable to parse floating point literal: {0}
+SQLParser.Invalid_id=Invalid metadata ID format: [{0}]
+SQLParser.Invalid_alias=Invalid alias format: [{0}]
+SQLParser.Invalid_short_name=Invalid simple identifier format: [{0}]
+SQLParser.Invalid_char={0} value must be a single character: [{1}].
+SQLParser.expected_non_reserved=Expected non-reserved word {0}, but was {1}.
+SystemSource.array_length_desc=Get the length of the given array value
+SystemSource.array_param1=Array
+SystemSource.array_length_result=The array length
+SystemSource.array_get_desc=Get the object value at the given array index
+SystemSource.array_get_param2=Array index
+SystemSource.array_get_result=The object value
+SystemSource.Add_desc=Converts escape sequences in the given string to their actual characters.
+SystemSource.unescape_param1=String to be unescaped
+SystemSource.unescape_result=Unescaped string
+SystemSource.Add_desc=Add two numbers
+SystemSource.Add_result_desc=Left operand + right operand
+SystemSource.Subtract_desc=Subtract two numbers
+SystemSource.Subtract_result_desc=Left operand - right operand
+SystemSource.Multiply_desc=Multiply two numbers
+SystemSource.Multiply_result_desc=Left operand * right operand
+SystemSource.Divide_desc=Divide two numbers
+SystemSource.Divide_result_desc=Left operand / right operand
+SystemSource.Ceiling_desc=Ceiling of number
+SystemSource.Exp_desc=e^number
+SystemSource.Floor_desc=Floor of number
+SystemSource.Log_desc=Log (base e) of number
+SystemSource.Log10_desc=Log (base 10) of number
+SystemSource.Acos_desc=Arccosine of number
+SystemSource.Asin_desc=Arcsine of number
+SystemSource.Atan_desc=Arctan of number
+SystemSource.Atan2_desc=Arctan of number1 / number2
+SystemSource.Cos_desc=Cosine of number
+SystemSource.Cot_desc=Cotangent of number
+SystemSource.Degrees_desc=Convert from radians to degrees
+SystemSource.Pi_desc=Constant value for pi
+SystemSource.Radians_desc=Convert from degrees to radians
+SystemSource.Sin_desc=Sine of number
+SystemSource.Tan_desc=Tangent of number
+SystemSource.Bitand_desc=Bitwise AND of two integers
+SystemSource.Bitand_result_desc=integer1 AND integer2
+SystemSource.Bitor_desc=Bitwise inclusive OR of two integers
+SystemSource.Bitor_result_desc=integer1 OR integer2
+SystemSource.Bitxor_desc=Bitwise exclusive OR (XOR) of two integers
+SystemSource.Bitxor_result_desc=integer1 XOR integer2
+SystemSource.Bitnot_desc=Bitwise inversion (NOT) of a 32-bit integer. Equivalent to XOR(integer, 0xFFFFFFFF)
+SystemSource.Bitnot_result_desc=32-bit inverted integer
+SystemSource.Curdate_desc=Current date
+SystemSource.Curtime_desc=Current time
+SystemSource.Now_desc=Current timestamp
+SystemSource.Dayname_result_d_desc=Day name for date
+SystemSource.Dayname_result_ts_desc=Day name for timestamp
+SystemSource.Dayofmonth_result_d_desc=Day of month for date (1 = 1st)
+SystemSource.Dayofmonth_result_ts_desc=Day of month for timestamp (1 = 1st)
+SystemSource.Dayofweek_result_d_desc=Day of week for date (1 = Sunday)
+SystemSource.Dayofweek_result_ts_desc=Day of week for timestamp (1 = Sunday)
+SystemSource.Dayofyear_result_d_desc=Day of year for date (1 = Jan 1st)
+SystemSource.Dayofyear_result_ts_desc=Day of year for timestamp (1 = Jan 1st)
+SystemSource.Month_result_d_desc=Month for date (1 = January)
+SystemSource.Month_result_ts_desc=Month for timestamp (1 = January)
+SystemSource.Monthname_result_d_desc=Month name for date
+SystemSource.Monthname_result_ts_desc=Month name for timestamp
+SystemSource.Week_result_d_desc=Week of year for date
+SystemSource.Week_result_ts_desc=Week of year for timestamp
+SystemSource.Year_result_d_desc=Year for date
+SystemSource.Year_result_ts_desc=Year for timestamp
+SystemSource.Hour_result_t_desc=Hour for time
+SystemSource.Hour_result_ts_desc=Hour for timestamp
+SystemSource.Minute_result_t_desc=Minute for time
+SystemSource.Minute_result_ts_desc=Minute for timestamp
+SystemSource.Second_result_t_desc=Second for time
+SystemSource.Second_result_ts_desc=Second for timestamp
+SystemSource.Quarter_result_d_desc=Quarter for date (1=Jan/Feb/Mar)
+SystemSource.Quarter_result_ts_desc=Quarter for timestamp (1=Jan/Feb/Mar)
+SystemSource.Length_result=Length of string
+SystemSource.Ucase_result=Upper case of string
+SystemSource.Lcase_result=Lower case of string
+SystemSource.Lower_result=Lower case of string
+SystemSource.Upper_result=Upper case of string
+SystemSource.UcaseClob_result=Upper case of clob
+SystemSource.LcaseClob_result=Lower case of clob
+SystemSource.LowerClob_result=Lower case of clob
+SystemSource.UpperClob_result=Upper case of clob
+SystemSource.Left_result=Left trimmed string
+SystemSource.Right_result=Right trimmed string
+SystemSource.Formattime_desc=Convert to string
+SystemSource.Formattime_result_desc=Converted time
+SystemSource.Formatdate_desc=Convert to string
+SystemSource.Formatdate_result_desc=Converted date
+SystemSource.Formattimestamp_desc=Convert to string
+SystemSource.Formattimestamp_result_desc=Converted timestamp
+SystemSource.Parsetime_desc=Convert string to time
+SystemSource.Parsetime_result_desc=Time converted
+SystemSource.Parsedate_desc=Convert string to date
+SystemSource.Parsedate_result_desc=Date converted
+SystemSource.Parsetimestamp_desc=Convert string to timestamp
+SystemSource.Parsetimestamp_result_desc=Timestamp converted
+SystemSource.Formatinteger_desc=Convert to Integer
+SystemSource.Formatinteger_result_desc=Integer formatted
+SystemSource.Formatlong_desc=Convert to Long
+SystemSource.Formatlong_result_desc=Long formatted
+SystemSource.Formatdouble_desc=Convert to Double
+SystemSource.Formatdouble_result_desc=Double formatted
+SystemSource.Formatfloat_desc=Convert to Float
+SystemSource.Formatfloat_result_desc=Float formatted
+SystemSource.Formatbiginteger_desc=Convert to Big integer
+SystemSource.Formatbiginteger_result_desc=Big integer formatted
+SystemSource.Formatbigdecimal_desc=Convert to Big decimal
+SystemSource.Formatbigdecimal_result_desc=Big decimal formatted
+SystemSource.Parseinteger_desc=Parse to Integer
+SystemSource.Parseinteger_result_desc=Integer parsed
+SystemSource.Parselong_desc=Parse to Long
+SystemSource.Parselong_result_desc=Long parsed
+SystemSource.Parsedouble_desc=Parse to Double
+SystemSource.Parsedouble_result_desc=Double parsed
+SystemSource.Parsefloat_desc=Parse to Float
+SystemSource.Parsefloat_result_desc=Float parsed
+SystemSource.Parsebiginteger_desc=Parse to Biginteger
+SystemSource.Parsebiginteger_result_desc=Biginteger parsed
+SystemSource.Parsebigdecimal_desc=parse to Bigdecimal
+SystemSource.Parsebigdecimal_result_desc=Bigdecimal parsed
+SystemSource.Arith_left_op=Left operand
+SystemSource.Arith_right_op=Right operand
+SystemSource.Abs_desc=Absolute value of number
+SystemSource.Abs_arg=Number
+SystemSource.Abs_result_desc=Absolute value of number
+SystemSource.Rand_desc=Random Number
+SystemSource.Rand_arg=Number
+SystemSource.Rand_result_desc=Generated Random Number
+SystemSource.uuid_desc=UUID
+SystemSource.uuid_result_desc=type 4 UUID
+SystemSource.Double_arg2=Number
+SystemSource.Atan_arg1=Number parameter1
+SystemSource.Atan_arg2=Number parameter2
+SystemSource.Mod_desc=Modulus of two numbers
+SystemSource.Mod_result_desc=Left operand mod right operand
+SystemSource.Power_desc=Raise base to power
+SystemSource.Power_arg1=Base
+SystemSource.Power_arg2=Power
+SystemSource.Power_result_desc=Base ^ Power
+SystemSource.Round_desc=Round number to specified places
+SystemSource.Round_arg1=Numbers
+SystemSource.Round_arg2=Places
+SystemSource.Round_result_desc=Number rounded to specified places
+SystemSource.Sign_desc=Sign of number: 1 if number>0, 0 if number==0, -1 if number<0
+SystemSource.Sign_arg1=Number
+SystemSource.Sign_result_desc=Sign of number
+SystemSource.Sqrt_desc=Square root of number
+SystemSource.Sqrt_arg1=Number
+SystemSource.Sqrt_result_desc=Square root of number
+SystemSource.Timestampadd_d_desc=Add count number of interval type to date
+SystemSource.Timestampadd_d_arg1=Interval type
+SystemSource.Timestampadd_d_arg2=Count number
+SystemSource.Timestampadd_d_arg3=Date type
+SystemSource.Timestampadd_d_result_desc=Returned modified date
+SystemSource.Timestampadd_t_desc=Add count number of interval type to time
+SystemSource.Timestampadd_t_arg1=Interval type
+SystemSource.Timestampadd_t_arg2=Count number
+SystemSource.Timestampadd_t_arg3=Time type
+SystemSource.Timestampadd_t_result_desc=Returned modified time
+SystemSource.Timestampadd_ts_desc=Add count number of interval type to timestamp
+SystemSource.Timestampadd_ts_arg1=Interval type
+SystemSource.Timestampadd_ts_arg2=Count number
+SystemSource.Timestampadd_ts_arg3=Timestamp type
+SystemSource.Timestampadd_ts_result=Returned modified timestamp
+SystemSource.Timestampdiff_ts_desc=Calculate estimated number of intervals between start and end timestamp
+SystemSource.Timestampdiff_ts_arg1=Interval type
+SystemSource.Timestampdiff_ts_arg2=Start timestamp
+SystemSource.Timestampdiff_ts_arg3=End timestamp
+SystemSource.Timestampdiff_ts_result_desc=Returns estimated number of intervals between start and end timestamp
+SystemSource.TimestampCreate_desc=Create timestamp from a date and a time
+SystemSource.TimestampCreate_arg1=Date
+SystemSource.TimestampCreate_arg2=Time
+SystemSource.TimestampCreate_result_desc=Timestamp built from date and time
+SystemSource.Stringfunc_arg1=String
+SystemSource.Clobfunc_arg1=Clob
+SystemSource.Concat_desc=Concatenate left and right strings
+SystemSource.Concat_arg1=Left string
+SystemSource.Concat_arg2=Right string
+SystemSource.Concat_result_desc=Concatenated strings
+SystemSource.Concatop_desc=Concatenate left and right strings
+SystemSource.Concatop_arg1=Left string
+SystemSource.Concatop_arg2=Right string
+SystemSource.Concatop_result_desc=Concatenated strings
+SystemSource.Substring_desc=Substring of string, starting at index, of length
+SystemSource.Substring_arg1=String
+SystemSource.Substring_arg2=Starting index
+SystemSource.Substring_arg3=Length of substring
+SystemSource.Substring_result=Substring
+SystemSource.Susbstring2_desc=Substring of string, starting at index, to end of string
+SystemSource.Substring2_arg1=String
+SystemSource.Substring2_arg2=Starting index
+SystemSource.Substring2_result=Substring
+SystemSource.Left_desc=First length characters of string
+SystemSource.Left_arg1=String
+SystemSource.Left_arg2=Length of substring
+SystemSource.Left2_result=First length characters of string
+SystemSource.Right_desc=Last length characters of string
+SystemSource.Right_arg1=String
+SystemSource.Right_arg2=Length of substring
+SystemSource.Right2_result=Last length characters of string
+SystemSource.Locate_desc=Find index of substring in string starting at index
+SystemSource.Locate_arg1=Substring to find
+SystemSource.Locate_arg2=String
+SystemSource.Locate_arg3=Starting index
+SystemSource.Locate_result=Index of substring or -1 if not found
+SystemSource.Locate2_desc=Find index of substring in string
+SystemSource.Locate2_arg1=Substring to find
+SystemSource.Locate2_arg2=String
+SystemSource.Locate2_result=Index of substring or -1 if not found
+SystemSource.Replace_desc=Replace any substring in string with replacement
+SystemSource.Replace_arg1=String
+SystemSource.Replace_arg2=Substring to match
+SystemSource.Replace_arg3=Replacement string
+SystemSource.Replace_result=String with replacements
+SystemSource.Repeat_desc=Repeat string with count times
+SystemSource.Repeat_arg1=String
+SystemSource.Repeat_arg2=Count times to repeat
+SystemSource.Repeat_result=String repeated with count times
+SystemSource.Space_desc=Repeat space count times
+SystemSource.Space_arg1=Number of times to repeat
+SystemSource.Space_result=Space repeated count times
+SystemSource.Insert_desc=Insert string2 into string1 by deleting length characters at start and inserting string2
+SystemSource.Insert_arg1=Initial string
+SystemSource.Insert_arg2=Starting position
+SystemSource.Insert_arg3=Number of characters to delete at start
+SystemSource.Insert_arg4=String to insert
+SystemSource.Insert_result=Inserted string
+SystemSource.Ascii_desc=Takes a character and returns the ASCII or unicode integer representation
+SystemSource.Ascii_arg1=String
+SystemSource.Ascii_result=Character value
+SystemSource.Ascii2_desc=Takes a character and returns the ASCII or unicode integer representation
+SystemSource.Ascii2_arg1=Character
+SystemSource.Ascii2_result=Character value
+SystemSource.Chr_desc=Takes a unicode or ASCII value and returns the character representation
+SystemSource.Chr_arg1=Code value
+SystemSource.Chr_result=Character representation
+SystemSource.Char_desc=Takes a unicode or ASCII value and returns the character representation
+SystemSource.Char_arg1=Code value
+SystemSource.Char_result=Character representation
+SystemSource.Initcap_desc=Capitalizes each word (each letter after whitespace)
+SystemSource.Initcap_arg1=Input string
+SystemSource.Initcap_result=Result string
+SystemSource.Lpad_desc=Pad the input string on the left to length
+SystemSource.Lpad_arg1=String
+SystemSource.Lpad_arg2=Padded length
+SystemSource.Lpad_result=Padded string
+SystemSource.Lpad3_desc=Pad the input string on the left to length with pad character
+SystemSource.Lpad3_arg1=String
+SystemSource.Lpad3_arg2=Padded length
+SystemSource.Lpad3_arg3=Pad character
+SystemSource.Lpad3_result=Padded string
+SystemSource.Rpad1_desc=Pad the input string on the right to length
+SystemSource.Rpad1_arg1=String
+SystemSource.Rpad1_arg2=Padded length
+SystemSource.Rpad1_result=Padded string
+SystemSource.Rpad3_desc=Pad the input string on the right to length with pad character
+SystemSource.Rpad3_arg1=String
+SystemSource.Rpad3_arg2=Padded length
+SystemSource.Rpad3_arg3=Pad character
+SystemSource.Rpad3_result=Padded string
+SystemSource.Translate_desc=Translate the input string by converting characters in the source string to characters in the destination string
+SystemSource.Translate_arg1=String
+SystemSource.Translate_arg2=Source string
+SystemSource.Translate_arg3=Destination string
+SystemSource.Translate_result=Translated string
+SystemSource.Convert_arg1=Source value
+SystemSource.Convert_arg2=Target type
+SystemSource.Convert_result=Converted value
+SystemSource.Context_desc=Evaluate XML expression in the context of a different mapping level
+SystemSource.Context_arg1=XML context tag
+SystemSource.Context_arg2=XML element
+SystemSource.Context_result=Expression in higher context
+SystemSource.Rowlimit_desc=Limit the number of rows from an XML mapping class
+SystemSource.RowlimitException_desc=Limit the number of rows from an XML mapping class, throw Exception if passed
+SystemSource.Rowlimit_arg1=XML tag in the scope of a mapping class
+SystemSource.Rowlimit_result=Number of rows to be limited to
+SystemSource.Decode1_desc=Map the input value to a comma-separated list of allowed output values
+SystemSource.Decode1_arg1=Input column for decode
+SystemSource.Decode1_arg2=The comma delimited String that represents the mapping between input column value and output values.
+SystemSource.Decode1_result=The decoded value from the decode string.
+SystemSource.Decode2_desc=Map the input value to a delimiter-separated list of allowed output values
+SystemSource.Decode2_arg1=Input column for decode
+SystemSource.Decode2_arg2=The comma delimited String that represents the mapping between input column value and output values.
+SystemSource.Decode2_arg3=Decode String delimiter character(s)
+SystemSource.Decode2_result=The decoded value from the decode string.
+SystemSource.Lookup_desc=Look up a value in a cached code table
+SystemSource.Lookup_arg1=Full group name of code table
+SystemSource.Lookup_arg2=Short name of return element in code table
+SystemSource.Lookup_arg3=Short name of key element in code table
+SystemSource.Lookup_arg4=Key value to lookup
+SystemSource.Lookup_result=Return value for key as specified in code table
+SystemSource.User_desc=Get current user name
+SystemSource.User_result=Return user name
+SystemSource.current_database_desc=Get current database name
+current_database_result=Returns the catalog name
+SystemSource.Env_desc=Get the value of an environment variable
+SystemSource.Env_varname=Name of the environment variable
+SystemSource.Env_result=Return the string value of the environment variable
+SystemSource.Nvl_desc=Specifies a value to use instead if the input value is null
+SystemSource.Nvl_arg1=Value to check
+SystemSource.Nvl_arg2=Returned if value is null
+SystemSource.Nvl_result=Value or valueIfNull if value is null
+SystemSource.Ifnull_desc=Specifies a value to use instead if the input value is null
+SystemSource.Ifnull_arg1=Value to check
+SystemSource.Ifnull_arg2=Returned if value is null
+SystemSource.Ifnull_result=Value or valueIfNull if value is null
+SystemSource.Formattime_arg1=Time input
+SystemSource.Formattime_arg2=Time format
+SystemSource.Formatdate_arg1=Date input
+SystemSource.Formatdate_arg2=Date format
+SystemSource.Formattimestamp_arg1=Timestamp input
+SystemSource.Formattimestamp_arg2=Timestamp format
+SystemSource.Parsetime_arg1=String input
+SystemSource.Parsetime_arg2=Time format
+SystemSource.Parsedate_arg1=String input
+SystemSource.Parsedate_arg2=Date format
+SystemSource.Parsetimestamp_arg1=String input
+SystemSource.Parsetimestamp_arg2=Timestamp format
+SystemSource.Formatnumber_arg1=String input
+SystemSource.Formatnumber_arg2=Number format
+SystemSource.Parsenumber_arg1=String input
+SystemSource.Parsenumber_arg2=Parse format
+SystemSource.Bitfunc_arg1=Integer parameter
+SystemSource.Bitfunc2_arg1=First integer
+SystemSource.Bitfunc2_arg2=Second integer
+SystemSource.Convert_desc=Convert from {0} to target type
+SystemSource.xpathvalue_description=Retrieve the first match content for an XPath statement
+SystemSource.xpath_param1=Source document
+SystemSource.xpath_param2=XPath expression
+SystemSource.xpathvalue_result=Single result
+SystemSource.xsltransform_description=Transform the document with the given stylesheet.
+SystemSource.xsltransform_param1=Source document
+SystemSource.xsltransform_param2=XSL stylesheet
+SystemSource.xsltransform_result=Clob result
+SystemSource.xmlconcat_description=Concat XML types.
+SystemSource.xmlconcat_param1=First element
+SystemSource.xmlcomment_description=Create an XML comment.
+SystemSource.xmlconcat_param1=String comment
+SystemSource.xmlconcat_result=XML result
+SystemSource.xmlpi_description=Create an XML processing instruction.
+SystemSource.xmlpi_param1=Target
+SystemSource.xmlpi_param2=Content
+SystemSource.xmlpi_result=XML result
+SystemSource.jsonToXml_description=Create an XML document representing the given JSON.
+SystemSource.jsonToXml_param1=Root element name
+SystemSource.jsonToXml_param2=JSON
+SystemSource.jsonToXml_result=XML result
+SystemSource.modifyTimeZone_description=Modify the time zone of this timestamp by adding or subtracting time
+SystemSource.modifyTimeZone_param1=Timestamp
+SystemSource.modifyTimeZone_param2=Starting time zone
+SystemSource.modifyTimeZone_param3=Ending time zone
+SystemSource.modifyTimeZone_result=Original timestamp with time added or subtracted to give the equivalent time in a different time zone
+SystemSource.CommandPayload_desc0=Retrieve the command payload as a string
+SystemSource.CommandPayload_desc1=Retrieve a property from the command payload, passed as a Properties object
+SystemSource.CommandPayload_result=The property value from the command payload
+SystemSource.CommandPayload_property=The property name
+SystemSource.hasRole_description=Determine if the caller has the given role
+SystemSource.hasRole_param1=Role type
+SystemSource.hasRole_param2=Role name
+SystemSource.hasRole_result=whether the caller is in the given role
+SystemSource.from_unixtime_description=Return the Unix timestamp (in seconds) as a Timestamp value
+SystemSource.from_unixtime_param1=Unix timestamp (in seconds)
+SystemSource.from_unixtime_result=Timestamp value
+SystemSource.nullif_description=Equivalent to case when (param1 = param2) then null else param1
+SystemSource.nullif_param1=First parameter
+SystemSource.nullif_result=null if the parameters are equivalent else param1
+SystemSource.coalesce_description=Returns the first non-null parameter
+SystemSource.coalesce_param1=parameter
+SystemSource.coalesce_result=The first non-null parameter
+SystemSource.encode_desc=Converts a Blob to the appropriate chars
+SystemSource.encode_arg1=Blob
+SystemSource.encode_arg2=char representation Clob
+SystemSource.encode_result=Clob char rep
+SystemSource.decode_desc=Converts a Clob to the appropriate bytes
+SystemSource.decode_arg1=Clob
+SystemSource.decode_arg2=The encoding
+SystemSource.decode_result=byte representation Blob
+SystemSource.session_id_desc=Returns the session id of the currently logged in user
+SystemSource.session_id_result=Returns the session id of the currently logged in user
+TempMetadataAdapter.Element_____{0}_____not_found._1=Element ''{0}'' not found.
+TempMetadataAdapter.Group_____{0}_____not_found._1=Group ''{0}'' not found.
+ExpressionEvaluator.Must_push=Function {0} is marked in the function metadata as a function that must be evaluated at the source.
+ExpressionEvaluator.Eval_failed=Unable to evaluate {0}: {1}
+XMLSerialize.resolvingError=XMLSerialize is valid only for XML expressions: {0}
+Evaluator.xmlserialize=XMLSerialize: data exception - not an xml document
+Evaluator.xmlquery=Error evaluating XMLQuery: {0}
+ExecResolver.Param_convert_fail=Unable to convert procedural parameter of type {0} to expected type {1}
+ExecResolver.return_expected=Procedure {0} does not have a return value.
+ExecResolver.out_type_mismatch=OUT/RETURN parameter {0} with type {1} cannot be converted to {2}
+DynamicCommandResolver.SQL_String=Expected dynamic command sql to be of type STRING instead of type {0}.
+UnionQueryResolver.type_conversion=The Expression {0} used in a nested UNION ORDER BY clause cannot be implicitly converted from type {1} to type {2}.
+ValidationVisitor.select_into_no_implicit_conversion=There is no implicit conversion between the source element type ({0}) and the target element type ({1}) at position {2} of the query: {3}
+ValidationVisitor.excpet_intersect_all=EXCEPT ALL and INTERSECT ALL are currently unsupported
+ValidationVisitor.element_updates_not_allowed=Metadata does not allow updates on the element: {0}
+ValidationVisitor.invalid_batch_command=Only INSERT, UPDATE, DELETE, and SELECT ... INTO statements are allowed within a batch.
+ValidationVisitor.badoffset2=The row offset in the LIMIT clause must be >= 0
+ValidationVisitor.badlimit2=The row limit in the LIMIT clause must be >= 0
+ValidationVisitor.invalid_scalar_group_reference=Cannot reference a scalar group as a table: {0}
+ValidationVisitor.select_into_wrong_elements=Wrong number of elements being SELECTed INTO the target table. Expected {0} elements, but was {1}.
+SimpleQueryResolver.Query_was_redirected_to_Mat_table=The query against {0} was redirected to the materialization table {1}.
+SimpleQueryResolver.ambiguous_all_in_group=The symbol {0} refers to more than one group defined in the FROM clause.
+SimpleQueryResolver.Proc_Relational_Name_conflict=Cannot access procedure {0} using table semantics since the parameter and result set column names are not all unique.
+SimpleQueryResolver.duplicate_with=Duplicate WITH clause item name {0}
+SimpleQueryResolver.mismatched_with_columns=The number of WITH clause columns for item {0} do not match the query expression
+QueryResolver.invalid_xpath=Invalid xpath value: {0}
+QueryResolver.wrong_view_symbols=The definition for {0} does not have the correct number of projected symbols. Expected {1}, but was {2}.
+QueryResolver.wrong_view_symbol_type=The definition for {0} has the wrong type for column {1}. Expected {2}, but was {3}.
+ResolveVariablesVisitor.reserved_word_for_temporary_used=Cursor names cannot begin with "#" as that indicates the name of a temporary table: {0}.
+SimpleQueryResolver.materialized_table_not_used=The query against {0} did not use materialization table {1} due to the use of OPTION NOCACHE.
+SimpleQueryResolver.cache_hint_used=Loading materialized view {1} for view {0} using cache hint {2}.
+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.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
+ValidationVisitor.The_context_function_cannot_be_used_in_a_non-XML_command=The ''context'' function cannot be used in a non-XML command
+ValidationVisitor.0=The ''rowlimit'' and ''rowlimitexception'' functions cannot be nested within other functions.
+ValidationVisitor.1=The ''rowlimit'' and ''rowlimitexception'' functions operand must be a constant nonnegative integer.
+ValidationVisitor.2=The ''rowlimit'' and ''rowlimitexception'' functions arg must be an XML node symbol
+ValidationVisitor.3=''Rowlimit'' and ''rowlimitexception'' functions can only be used within a compare criteria which is entirely a single conjunct.
+ValidationVisitor.Context_function_nested=Context functions cannot be nested
+ERR.015.004.0036= First argument in ''context'' must be the name of a node in the XML document model. Found Object {0} of Class {1}
+ExecResolver.invalid_named_params=Invalid param name(s): {0}. Name(s) of params without explicit values: {1}
+ExecResolver.duplicate_named_params=Duplicate named param ''{0}''
+ResolverUtil.required_param=Required parameter ''{0}'' has no value was set or is an invalid parameter.
+ResolverUtil.duplicateName=Cannot create group ''{0}'' with multiple columns named ''{1}''
+ResolverUtil.error_converting_value_type=Exception converting value {0} of type {1} to expected type {2}
+ResolverUtil.setquery_order_expression=ORDER BY expression ''{0}'' cannot be used with a set query.
+ResolverUtil.invalid_unrelated=Unrelated order by column {0} cannot be used in a SET query, with SELECT DISTINCT, or GROUP BY
+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}". 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.
+ValidationVisitor.text_table_width=Fixed width text tables should not have DELIMITER, QUOTE, ESCAPE, or HEADER specified.
+ValidationVisitor.text_table_negative=Text table WIDTH, HEADER, or SKIP values must not be negative.
+ValidationVisitor.text_table_delimiter=Text DELIMITER cannot be the same as the QUOTE or ESCAPE characters.
+ValidationVisitor.text_table_newline=Text DELIMITER, QUOTE, and ESCAPE characters cannot be the new line character.
+ValidationVisitor.xml_namespaces=At most only one NO DEFAULT or DEFAULT namespace may be specified.
+ValidationVisitor.xml_namespaces_reserved=The namespaces xmlns and xml are reserved.
+ValidationVisitor.xml_namespaces_null_uri=The null uri, or empty string, is not allowed as the uri value.
+ValidationVisitor.xml_attributes_reserved=The namespace xmlns is reserved.
+ValidationVisitor.xml_content_type=The expression "{0}" is of OBJECT or BLOB type, which cannot be used as an XML or TEXT content value.
+ValidationVisitor.xml_invalid_qname=The qname "{0}" is invalid.
+ValidationVisitor.context_item_type=XMLTABLE or XMLQUERY PASSING context item must be an XML value.
+ValidationVisitor.passing_requires_name=XMLTABLE or XMLQUERY PASSING clause can only contain at most 1 unnamed item.
+ValidationVisitor.duplicate_passing=XMLTABLE or XMLQUERY PASSING clause duplicate item name "{0}".
+ValidationVisitor.one_ordinal=Only one FOR ORDINALITY column is allowed for an XMLTABLE.
+ValidationVisitor.invalid_default=XMLTABLE DEFAULT expression is invalid: "{0}"
+ValidationVisitor.context_required=The XQuery requires a context item, but none exists in the PASSING clause.
+ValidationVisitor.xmlparse_type=XMLPARSE expects a STRING, CLOB, or BLOB value.
+ValidationVisitor.invalid_encoding=Encoding {0} is not valid.
+ValidationVisitor.subquery_insert=SELECT INTO should not be used in a subquery.
+UpdateProcedureResolver.only_variables=Variable "{0}" is read only and cannot be assigned a value.
+MappingLoader.unknown_node_type=Unknown Node Type "{0}" being loaded by the XML mapping document.
+MappingLoader.invalid_criteria_node=Invalid criteria node found; A criteria node must have criteria specified or it must be a default node.
+WrongTypeChild=Wrong type of child node is being added.
+NoCriteria=Failed to add the node, because Criteria nodes must have "criteria" value set on them, or they need to be the default node.
+root_cannotbe_null=Root node assigned to a document can be null.
+invalid_recurive_node= Found recursive node {0} without recursive root node.
+SaxonXQueryExpression.bad_xquery=Failed to evaluate XQuery expression; Please check the query and correct errors in syntax or usage.
+SaxonXQueryExpression.compile_failed=Could not compile XQuery; Please check the query for syntax or usage errors.
+SaxonXQueryExpression.invalid_path=Column "{0}" has an invalid path expression: {1}
+SaxonXQueryExpression.bad_context=Error building Source for context item.
+MappingLoader.invalidName=Null or blank name found in the Mapping Document, Must have valid name. Re-build the VDB
+MatchCriteria.invalid_escape=Invalid escape sequence "{0}" with escape character "{1}"
+QueryUtil.wrong_number_of_values=The number of bound values ''{0}'' does not match the number of parameters ''{1}'' in the prepared statement.
+QueryUtil.Error_executing_conversion_function_to_convert_value=Error converting parameter number {0} with value "{1}" to expected type {2}.
+InsertResolver.cant_convert_query_type=Cannot convert insert query expression projected symbol ''{0}'' of type {1} to insert column ''{2}'' of type {3}
+SetClause.resolvingError=Cannot set symbol ''{1}'' with expected type {2} to expression ''{0}''
+NewCalculateCostUtil.badCost=Unexpected format encountered for max or min value
+
+WorkerPool.Max_thread=Reached maximum thread count "{0}" for worker pool "{1}" with a queue size high of "{2}". Queued work waited {3} ms prior to executing. To avoid queuing of work you may consider increasing "RuntimeEngineDeployer.maxThreads" or decreasing the "RuntimeEngineDeployer.maxActivePlans" in the "teiid-jboss-beans.xml" file.
+WorkerPool.uncaughtException=Uncaught exception processing work
+
+
+TempTable.duplicate_key=Duplicate key
+TempTable.not_null=Null value is not allowed for column {0}
+ValidationVisitor.group_in_both_dep=Table specified in both dependent and independent queries '{0}'
+XMLQuery.resolvingError=Failed to resolve the query '{0}'
+SQLParser.non_position_constant=Invalid order by at {0}
+
+
+QueryRewriter.infinite_while=Infinite loop detected, procedure will not be executed.
+
+BatchedUpdatePlanner.unrecognized_command=The batch contained an unrecognized command: {0}
+ProcedurePlanner.bad_stmt=Error while planning update procedure, unknown statement type encountered: {0}
+RulePushSelectCriteria.Error_getting_modelID=Error getting modelID
+XMLPlanner.no_uri=Cannot find namespace URI for namespace {0} of element {1}
+
+XMLPlanner.The_XML_document_element_{0}_is_not_mapped_to_data_and_cannot_be_used_in_the_ORDER_BY_clause__{1}_1=The XML document element {0} is not mapped to data and cannot be used in the ORDER BY clause: {1}
+XMLPlanner.The_rowlimit_parameter_{0}_is_not_in_the_scope_of_any_mapping_class=The ''rowlimit'' or ''rowlimitexception'' function parameter ''{0}'' is not an XML node within the scope of any mapping class.
+XMLPlanner.Criteria_{0}_contains_conflicting_row_limits=The criteria ''{0}'' contains conflicting row limits for an XML mapping class.
+AccessNode.rewrite_failed=Failed to rewrite the command: {0}
+BatchedUpdateNode.unexpected_end_of_batch=Unexpectedly reached the end of the batched update counts at {0}, expected {1}.
+row_limit_passed=The row limit {0} has been exceeded for XML mapping class {1}.
+AddNodeInstruction.element__1=element
+AddNodeInstruction.Unable_to_add_xml_{0}_{1},_namespace_{2},_namespace_declarations_{3}_3=Unable to add xml {0} {1}, namespace {2}, namespace declarations {3}
+QueryProcessor.request_cancelled=The request {0} has been cancelled.
+VariableSubstitutionVisitor.Input_vars_should_have_same_changing_state=INPUT variables used in the expression should all have same CHANGING state: {0}
+
+ExecDynamicSqlInstruction.0=Evaluated dynamic SQL expression value was null.
+ExecDynamicSqlInstruction.3=There is a recursive invocation of group ''{0}''. Please correct the SQL.
+ExecDynamicSqlInstruction.4=The dynamic sql string contains an incorrect number of elements.
+ExecDynamicSqlInstruction.6=The datatype ''{0}'' for element ''{1}'' in the dynamic SQL cannot be implicitly converted to ''{2}''.
+ExecDynamicSqlInstruction.couldnt_execute=Couldn''t execute the dynamic SQL command "{0}" with the SQL statement "{1}" due to: {2}
+
+RulePlanJoins.cantSatisfy=Join region with unsatisfied access patterns cannot be satisfied by the join criteria, Access patterns: {0}
+TempTableStore.table_exist_error=Temporary table "{0}" already exists.
+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}
+CriteriaPlanner.invalid_element=Element {0} is not a valid data node
+results_not_found=Results for the mapping class {0} are not found;
+RulePlanProcedures.no_values=No valid criteria specified for procedure parameter {0}
+ProcedurePlan.nonNullableParam=The procedure parameter {0} is not nullable, but is set to null.
+
+FileStoreageManager.error_creating=Error creating {0}
+FileStoreageManager.error_reading=Error reading {0}
+FileStoreageManager.no_directory=No directory specified for the file storage manager.
+FileStoreageManager.not_a_directory={0} is not a valid storage manager directory.
+FileStoreageManager.space_exhausted=Max buffer space of {0} bytes has been exceed. The current operation will be aborted.
+
+TextTableNode.no_value=No value found for column {0} in the row ending on text line {1} in {2}.
+TextTableNode.conversion_error=Could not convert value for column {0} in the row ending on text line {1} in {2}.
+TextTableNode.header_missing=HEADER entry missing for column name {0} in {1}.
+TextTableNode.unclosed=Text parse error: Unclosed qualifier at end of text in {0}.
+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}.
+
+XMLTableNode.error=Error evaluating XQuery row context for XMLTable: {0}
+XMLTableNode.path_error=Error evaluating XMLTable column path expression for column: {0}
+XMLTableName.multi_value=Unexpected multi-valued result was returned for XMLTable column "{0}". Path expressions for non-XML type columns should return at most a single result.
+
+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.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.
+TempTableDataManager.row_refresh_updatable=Materialized view {0} cannot have a row refreshed because it's cache hint did not specify \"updatable\".
+TempTableDataManager.row_refresh=Refreshing row {1} for materialized view {0}.
+CriteriaPlanner.no_context=No root node found.
+
+BasicInterceptor.ProcessTree_for__4=ProcessTree for
+
+
+ConnectorManager.not_in_valid_state=Connector is not in OPEN state
+
+ConnectorManagerImpl.Initializing_connector=Initializing connector {0}
+Cancel_request_failed=AtomicRequest {0} failed to cancel.
+
+ConnectorWorker.MaxResultRowsExceed=The number of result rows has exceeded the maximum result rows "{0}"
+ConnectorWorker.zero_size_non_last_batch=Connector returned a 0 row non-last batch: {0}.
+ConnectorWorker.process_failed=Connector worker process failed for atomic-request={0}
+ConnectorWorker.ConnectorWorker_result_set_unexpected_columns=Could not process stored procedure results for {0}. Expected {1} result set columns, but was {2}. Please update your models to allow for stored procedure results batching.
+
+
+DataTierManager.could_not_obtain_connector_binding=Could not obtain connection factory for model {0} in VDB name= {1}, version {2}
+DataTierManagerImpl.max_value_length=Property value length exceeds max of {0}.
+DataTierManagerImpl.unknown_uuid=Could not find a metadata record with uuid {0}.
+
+DQPCore.Unable_to_load_metadata_for_VDB_name__{0},_version__{1}=Unable to load metadata for VDB name= {0}, version= {1}
+DQPCore.Unknown_query_metadata_exception_while_registering_query__{0}.=Unknown query metadata exception while registering query: {0}.
+DQPCore.Clearing_prepared_plan_cache=Clearing prepared plan cache
+DQPCore.Clearing_prepared_plan_cache_for_vdb=Clearing prepared plan cache for vdb {0}.{1}
+DQPCore.clearing_resultset_cache=Clearing the resultset cache for vdb {0}.{1}
+DQPCore.The_request_has_been_closed.=The request {0} has been closed.
+DQPCore.The_atomic_request_has_been_cancelled=The atomic request {0} has been canceled.
+DQPCore.failed_to_cancel=Failed to Cancel request, as request already finished processing
+DQPCore.invalid_max_active_plan=The maxActivePlan {0} setting should never be greater than the max processing threads {1}.
+
+ProcessWorker.failed_rollback=Failed to properly rollback autowrap transaction properly
+ProcessWorker.error=Unexpected exception for request {0}
+ProcessWorker.processing_error=Processing exception ''{0}'' for request {1}. Exception type {2} thrown from {3}. Enable more detailed logging to see the entire stacktrace.
+
+
+# #query (018.005)
+ERR.018.005.0095 = User <{0}> is not entitled to action <{1}> for 1 or more of the groups/elements/procedures.
+
+# services (003)
+
+Request.Invalid_character_in_query=Bind variables (represented as "?") were found but are allowed only in prepared or callable statements.
+Request.no_result_set=The query does not return a result set.
+Request.result_set=The query does not return an update count.
+
+ProcessWorker.wrongdata=Wrong type of data found or no data found; expecting streamable object from the buffer manager.
+ProcessWorker.LobError=An error occurred during streaming of Lob Chunks to Client.
+
+TransactionServer.existing_transaction=Client thread already involved in a transaction. Transaction nesting is not supported. The current transaction must be completed first.
+TransactionServer.no_transaction=No transaction found for client {0}.
+TransactionServer.concurrent_transaction=Concurrent enlistment in global transaction {0} is not supported.
+TransactionServer.no_global_transaction=Expected an existing global transaction {0} but there was none for client {1}
+TransactionServer.unknown_flags=Unknown flags
+TransactionServer.no_global_transaction=No global transaction found for {0}.
+TransactionServer.wrong_transaction=Client is not currently enlisted in transaction {0}.
+TransactionServer.resume_failed=Cannot resume, transaction {0} was not suspended by client {1}.
+TransactionServer.existing_global_transaction=Global transaction {0} already exists.
+TransactionServer.suspended_exist=Suspended work still exists on transaction {0}.
+
+TransformationMetadata.does_not_exist._1=does not exist.
+TransformationMetadata.Error_trying_to_read_virtual_document_{0},_with_body__n{1}_1=Error trying to read virtual document {0}, with body \n{1}
+TransformationMetadata.Unknown_support_constant___12=Unknown support constant:
+TransformationMetadata.QueryPlan_could_not_be_found_for_physical_group__6=QueryPlan could not be found for physical group
+TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__8=InsertPlan could not be found for physical group
+TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__10=InsertPlan could not be found for physical group
+TransformationMetadata.DeletePlan_could_not_be_found_for_physical_group__12=DeletePlan could not be found for physical group
+TransformationMetadata.Error_trying_to_read_schemas_for_the_document/table____1=Error trying to read schemas for the document/table :
+TransformationMetadata.Invalid_type=Invalid type: {0}.
+TransformationMetadata.does_not_exist._1=does not exist.
+TransformationMetadata.0={0} ambiguous, more than one entity matching the same name
+TransformationMetadata.Error_trying_to_read_virtual_document_{0},_with_body__n{1}_1=Error trying to read virtual document {0}, with body \n{1}
+TransformationMetadata.Unknown_support_constant___12=Unknown support constant:
+TransformationMetadata.QueryPlan_could_not_be_found_for_physical_group__6=QueryPlan could not be found for physical group
+TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__8=InsertPlan could not be found for physical group
+TransformationMetadata.InsertPlan_could_not_be_found_for_physical_group__10=InsertPlan could not be found for physical group
+TransformationMetadata.DeletePlan_could_not_be_found_for_physical_group__12=DeletePlan could not be found for physical group
+TransformationMetadata.Error_trying_to_read_schemas_for_the_document/table____1=Error trying to read schemas for the document/table :
+TransformationMetadata.Invalid_type=Invalid type: {0}.
+
+CachedFinder.no_connector_found=No connector with jndi-name {0} found for Model {1} with source name {2}
+translator_not_found=Translator {0} not accessible.
+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
+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.
+
+RelationalPlanner.nonpushdown_command=Source UPDATE or DELETE command "{0}" contains non-pushdown constructs and no compensating action can be taken as the table lacks a unique key or the source does not support equality predicates.
+
+Translate.error=Cannot translate criteria "{0}", it is not matched by selector "{1}"
+
+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.array_index=Array index out of range: {0}
+ArrayTableNode.conversion_error=Could not convert value for column: {0}
+
+AlterResolver.not_a_view={0} is not a valid view.
+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
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorWorkItem.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorWorkItem.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorWorkItem.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,186 +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.datamgr;
-
-import static junit.framework.Assert.*;
-
-import java.util.Arrays;
-import java.util.List;
-
-import javax.transaction.xa.Xid;
-
-import org.junit.Ignore;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.client.RequestMessage;
-import org.teiid.dqp.internal.datamgr.ConnectorManager;
-import org.teiid.dqp.internal.datamgr.ConnectorWorkItem;
-import org.teiid.dqp.internal.datamgr.LanguageBridgeFactory;
-import org.teiid.dqp.internal.datamgr.ProcedureBatchHandler;
-import org.teiid.dqp.internal.process.DQPWorkContext;
-import org.teiid.dqp.message.AtomicRequestMessage;
-import org.teiid.dqp.message.AtomicResultsMessage;
-import org.teiid.dqp.message.RequestID;
-import org.teiid.dqp.service.TransactionContext;
-import org.teiid.language.Call;
-import org.teiid.query.metadata.QueryMetadataInterface;
-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.StoredProcedure;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.translator.ProcedureExecution;
-import org.teiid.translator.TranslatorException;
-
-
-public class TestConnectorWorkItem {
-
- private static final QueryMetadataInterface EXAMPLE_BQT = FakeMetadataFactory.exampleBQTCached();
-
- private static Command helpGetCommand(String sql,
- QueryMetadataInterface metadata) throws Exception {
- Command command = QueryParser.getQueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(command, metadata);
- return command;
- }
-
- static AtomicRequestMessage createNewAtomicRequestMessage(int requestid, int nodeid) throws Exception {
- RequestMessage rm = new RequestMessage();
-
- DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(EXAMPLE_BQT, FakeMetadataFactory.exampleBQTVDB());
- workContext.getSession().setSessionId(String.valueOf(1));
- workContext.getSession().setUserName("foo"); //$NON-NLS-1$
-
- AtomicRequestMessage request = new AtomicRequestMessage(rm, workContext, nodeid);
- request.setCommand(helpGetCommand("SELECT BQT1.SmallA.INTKEY FROM BQT1.SmallA", EXAMPLE_BQT)); //$NON-NLS-1$
- request.setRequestID(new RequestID(requestid));
- request.setConnectorName("testing"); //$NON-NLS-1$
- request.setFetchSize(5);
- return request;
- }
-
- @Test public void testProcedureBatching() throws Exception {
- ProcedureExecution exec = new FakeProcedureExecution(2, 1);
-
- // this has two result set columns and 1 out parameter
- 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);
-
- ProcedureBatchHandler pbh = new ProcedureBatchHandler(proc, exec);
-
- assertEquals(total_columns, pbh.padRow(Arrays.asList(null, null)).size());
-
- List params = pbh.getParameterRow();
-
- assertEquals(total_columns, params.size());
- // check the parameter value
- assertEquals(Integer.valueOf(0), params.get(2));
-
- try {
- pbh.padRow(Arrays.asList(1));
- fail("Expected exception from resultset mismatch"); //$NON-NLS-1$
- } catch (TranslatorException err) {
- assertEquals(
- "Could not process stored procedure results for EXEC spTest8(1). Expected 2 result set columns, but was 1. Please update your models to allow for stored procedure results batching.", err.getMessage()); //$NON-NLS-1$
- }
- }
-
- @Test public void testUpdateExecution() throws Throwable {
- AtomicResultsMessage results = helpExecuteUpdate();
- assertEquals(Integer.valueOf(1), results.getResults()[0].get(0));
- }
-
- private AtomicResultsMessage helpExecuteUpdate() throws Exception,
- Throwable {
- Command command = helpGetCommand("update bqt1.smalla set stringkey = 1 where stringkey = 2", EXAMPLE_BQT); //$NON-NLS-1$
- AtomicRequestMessage arm = createNewAtomicRequestMessage(1, 1);
- arm.setCommand(command);
- ConnectorWorkItem synchConnectorWorkItem = new ConnectorWorkItem(arm, TestConnectorManager.getConnectorManager());
- return synchConnectorWorkItem.execute();
- }
-
- @Test public void testExecutionWarning() throws Throwable {
- AtomicResultsMessage results = helpExecuteUpdate();
- assertEquals(1, results.getWarnings().size());
- }
-
- @Ignore
- @Test public void testIsImmutablePropertySucceeds() throws Exception {
- /*
- * Setup:
- * 1. requestMsg.isTransactional() must be TRUE
- * 2. manager.isXa() must be FALSE ()
- * 3. command must NOT be a SELECT
- * 4. Then, set isImmutable to TRUE, we should SUCCEED
- */
- ConnectorManager cm = TestConnectorManager.getConnectorManager();
- ((FakeConnector)cm.getExecutionFactory()).setImmutable(true);
-
-
- // command must not be a SELECT
- Command command = helpGetCommand("update bqt1.smalla set stringkey = 1 where stringkey = 2", EXAMPLE_BQT); //$NON-NLS-1$
- AtomicRequestMessage requestMsg = createNewAtomicRequestMessage(1, 1);
- requestMsg.setCommand(command);
-
- // To make the AtomicRequestMessage transactional, construct your own
- requestMsg.setTransactionContext( new TransactionContext(){
- @Override
- public Xid getXid() {
- return Mockito.mock(Xid.class);
- }} );
-
- new ConnectorWorkItem(requestMsg, cm);
- }
-
- @Ignore
- @Test(expected=TranslatorException.class) public void testIsImmutablePropertyFails() throws Exception {
- /*
- * Setup:
- * 1. requestMsg.isTransactional() must be TRUE
- * 2. manager.isXa() must be FALSE ()
- * 3. command must NOT be a SELECT
- * 4. Then, set isImmutable to FALSE, and we should FAIL
- */
- ConnectorManager cm = TestConnectorManager.getConnectorManager();
- ((FakeConnector)cm.getExecutionFactory()).setImmutable(false);
-
-
- // command must not be a SELECT
- Command command = helpGetCommand("update bqt1.smalla set stringkey = 1 where stringkey = 2", EXAMPLE_BQT); //$NON-NLS-1$
- AtomicRequestMessage requestMsg = createNewAtomicRequestMessage(1, 1);
- requestMsg.setCommand(command);
-
- // To make the AtomicRequestMessage transactional, construct your own
- requestMsg.setTransactionContext( new TransactionContext(){
- @Override
- public Xid getXid() {
- return Mockito.mock(Xid.class);
- }} );
-
- new ConnectorWorkItem(requestMsg, cm);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorWorkItem.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorWorkItem.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorWorkItem.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorWorkItem.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,186 @@
+/*
+ * 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.datamgr;
+
+import static junit.framework.Assert.*;
+
+import java.util.Arrays;
+import java.util.List;
+
+import javax.transaction.xa.Xid;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.client.RequestMessage;
+import org.teiid.dqp.internal.datamgr.ConnectorManager;
+import org.teiid.dqp.internal.datamgr.ConnectorWorkItem;
+import org.teiid.dqp.internal.datamgr.LanguageBridgeFactory;
+import org.teiid.dqp.internal.datamgr.ProcedureBatchHandler;
+import org.teiid.dqp.internal.process.DQPWorkContext;
+import org.teiid.dqp.message.AtomicRequestMessage;
+import org.teiid.dqp.message.AtomicResultsMessage;
+import org.teiid.dqp.message.RequestID;
+import org.teiid.dqp.service.TransactionContext;
+import org.teiid.language.Call;
+import org.teiid.query.metadata.QueryMetadataInterface;
+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.StoredProcedure;
+import org.teiid.query.sql.symbol.Constant;
+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 = RealMetadataFactory.exampleBQTCached();
+
+ private static Command helpGetCommand(String sql,
+ QueryMetadataInterface metadata) throws Exception {
+ Command command = QueryParser.getQueryParser().parseCommand(sql);
+ QueryResolver.resolveCommand(command, metadata);
+ return command;
+ }
+
+ static AtomicRequestMessage createNewAtomicRequestMessage(int requestid, int nodeid) throws Exception {
+ RequestMessage rm = new RequestMessage();
+
+ DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(EXAMPLE_BQT, RealMetadataFactory.exampleBQTVDB());
+ workContext.getSession().setSessionId(String.valueOf(1));
+ workContext.getSession().setUserName("foo"); //$NON-NLS-1$
+
+ AtomicRequestMessage request = new AtomicRequestMessage(rm, workContext, nodeid);
+ request.setCommand(helpGetCommand("SELECT BQT1.SmallA.INTKEY FROM BQT1.SmallA", EXAMPLE_BQT)); //$NON-NLS-1$
+ request.setRequestID(new RequestID(requestid));
+ request.setConnectorName("testing"); //$NON-NLS-1$
+ request.setFetchSize(5);
+ return request;
+ }
+
+ @Test public void testProcedureBatching() throws Exception {
+ ProcedureExecution exec = new FakeProcedureExecution(2, 1);
+
+ // this has two result set columns and 1 out parameter
+ 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);
+
+ ProcedureBatchHandler pbh = new ProcedureBatchHandler(proc, exec);
+
+ assertEquals(total_columns, pbh.padRow(Arrays.asList(null, null)).size());
+
+ List params = pbh.getParameterRow();
+
+ assertEquals(total_columns, params.size());
+ // check the parameter value
+ assertEquals(Integer.valueOf(0), params.get(2));
+
+ try {
+ pbh.padRow(Arrays.asList(1));
+ fail("Expected exception from resultset mismatch"); //$NON-NLS-1$
+ } catch (TranslatorException err) {
+ assertEquals(
+ "Could not process stored procedure results for EXEC spTest8(1). Expected 2 result set columns, but was 1. Please update your models to allow for stored procedure results batching.", err.getMessage()); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testUpdateExecution() throws Throwable {
+ AtomicResultsMessage results = helpExecuteUpdate();
+ assertEquals(Integer.valueOf(1), results.getResults()[0].get(0));
+ }
+
+ private AtomicResultsMessage helpExecuteUpdate() throws Exception,
+ Throwable {
+ Command command = helpGetCommand("update bqt1.smalla set stringkey = 1 where stringkey = 2", EXAMPLE_BQT); //$NON-NLS-1$
+ AtomicRequestMessage arm = createNewAtomicRequestMessage(1, 1);
+ arm.setCommand(command);
+ ConnectorWorkItem synchConnectorWorkItem = new ConnectorWorkItem(arm, TestConnectorManager.getConnectorManager());
+ return synchConnectorWorkItem.execute();
+ }
+
+ @Test public void testExecutionWarning() throws Throwable {
+ AtomicResultsMessage results = helpExecuteUpdate();
+ assertEquals(1, results.getWarnings().size());
+ }
+
+ @Ignore
+ @Test public void testIsImmutablePropertySucceeds() throws Exception {
+ /*
+ * Setup:
+ * 1. requestMsg.isTransactional() must be TRUE
+ * 2. manager.isXa() must be FALSE ()
+ * 3. command must NOT be a SELECT
+ * 4. Then, set isImmutable to TRUE, we should SUCCEED
+ */
+ ConnectorManager cm = TestConnectorManager.getConnectorManager();
+ ((FakeConnector)cm.getExecutionFactory()).setImmutable(true);
+
+
+ // command must not be a SELECT
+ Command command = helpGetCommand("update bqt1.smalla set stringkey = 1 where stringkey = 2", EXAMPLE_BQT); //$NON-NLS-1$
+ AtomicRequestMessage requestMsg = createNewAtomicRequestMessage(1, 1);
+ requestMsg.setCommand(command);
+
+ // To make the AtomicRequestMessage transactional, construct your own
+ requestMsg.setTransactionContext( new TransactionContext(){
+ @Override
+ public Xid getXid() {
+ return Mockito.mock(Xid.class);
+ }} );
+
+ new ConnectorWorkItem(requestMsg, cm);
+ }
+
+ @Ignore
+ @Test(expected=TranslatorException.class) public void testIsImmutablePropertyFails() throws Exception {
+ /*
+ * Setup:
+ * 1. requestMsg.isTransactional() must be TRUE
+ * 2. manager.isXa() must be FALSE ()
+ * 3. command must NOT be a SELECT
+ * 4. Then, set isImmutable to FALSE, and we should FAIL
+ */
+ ConnectorManager cm = TestConnectorManager.getConnectorManager();
+ ((FakeConnector)cm.getExecutionFactory()).setImmutable(false);
+
+
+ // command must not be a SELECT
+ Command command = helpGetCommand("update bqt1.smalla set stringkey = 1 where stringkey = 2", EXAMPLE_BQT); //$NON-NLS-1$
+ AtomicRequestMessage requestMsg = createNewAtomicRequestMessage(1, 1);
+ requestMsg.setCommand(command);
+
+ // To make the AtomicRequestMessage transactional, construct your own
+ requestMsg.setTransactionContext( new TransactionContext(){
+ @Override
+ public Xid getXid() {
+ return Mockito.mock(Xid.class);
+ }} );
+
+ new ConnectorWorkItem(requestMsg, cm);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestElementImpl.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestElementImpl.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestElementImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,114 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.dqp.internal.datamgr;
-
-import junit.framework.TestCase;
-
-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 {
-
- /**
- * Constructor for TestElementImpl.
- * @param name
- */
- public TestElementImpl(String name) {
- super(name);
- }
-
- public static ElementSymbol helpExample(String groupName, String elementName) {
- 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;
-
- }
-
- public static ElementSymbol helpIntExample(String groupName, String elementName) {
- 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) {
- ElementSymbol symbol = new ElementSymbol(elementName);
- symbol.setGroupSymbol(TestGroupImpl.helpExample(groupName));
- symbol.setType(Integer.class);
- symbol.setMetadataID(metadataID);
- return symbol;
- }
-
- public static ColumnReference example(String groupName, String elementName) throws Exception {
- return TstLanguageBridgeFactory.factory.translate(helpExample(groupName, elementName));
- }
-
- public static ColumnReference example(String groupName, String elementName, Object metadataID) throws Exception {
- return TstLanguageBridgeFactory.factory.translate(helpExample(groupName, elementName, metadataID));
- }
-
- 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$
- }
-
- public void testGetGroup() throws Exception {
- Object metadataID = TstLanguageBridgeFactory.metadata.getElementID("pm1.g1.e1"); //$NON-NLS-1$
- assertNotNull(example("pm1.g1", "e1", metadataID).getTable()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testGetType() throws Exception {
- Object metadataID = TstLanguageBridgeFactory.metadata.getElementID("pm1.g1.e2"); //$NON-NLS-1$
- assertTrue(example("pm1.g1", "e2", metadataID).getType().equals(Integer.class)); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void helpTestEquals(ColumnReference e1, ColumnReference e2, boolean equal) {
- boolean actual = e1.equals(e2);
- boolean actual2 = e2.equals(e1);
-
- assertEquals("e1.equals(e2) != e2.equals(e1)", actual, actual2); //$NON-NLS-1$
- assertEquals("Did not get expected equal value", equal, actual); //$NON-NLS-1$
- }
-
- public NamedTable createGroup(String context, String definition) {
- return new NamedTable(context, definition, null);
- }
-
- public ColumnReference createElement(NamedTable group, String name) {
- return new ColumnReference(group, name, null, String.class);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestElementImpl.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestElementImpl.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestElementImpl.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestElementImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,104 @@
+/*
+ * 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.datamgr;
+
+import junit.framework.TestCase;
+
+import org.teiid.language.ColumnReference;
+import org.teiid.language.NamedTable;
+import org.teiid.query.sql.symbol.ElementSymbol;
+
+
+public class TestElementImpl extends TestCase {
+
+ /**
+ * Constructor for TestElementImpl.
+ * @param name
+ */
+ public TestElementImpl(String name) {
+ super(name);
+ }
+
+ public static ElementSymbol helpExample(String groupName, String elementName) {
+ ElementSymbol symbol = new ElementSymbol(elementName);
+ symbol.setType(String.class);
+ symbol.setGroupSymbol(TestGroupImpl.helpExample(groupName));
+ return symbol;
+
+ }
+
+ public static ElementSymbol helpIntExample(String groupName, String elementName) {
+ ElementSymbol symbol = new ElementSymbol(elementName);
+ symbol.setType(Integer.class);
+ symbol.setGroupSymbol(TestGroupImpl.helpExample(groupName));
+ return symbol;
+ }
+
+ public static ElementSymbol helpExample(String groupName, String elementName, Object metadataID) {
+ ElementSymbol symbol = new ElementSymbol(elementName);
+ symbol.setGroupSymbol(TestGroupImpl.helpExample(groupName));
+ symbol.setType(Integer.class);
+ symbol.setMetadataID(metadataID);
+ return symbol;
+ }
+
+ public static ColumnReference example(String groupName, String elementName) throws Exception {
+ return TstLanguageBridgeFactory.factory.translate(helpExample(groupName, elementName));
+ }
+
+ public static ColumnReference example(String groupName, String elementName, Object metadataID) throws Exception {
+ return TstLanguageBridgeFactory.factory.translate(helpExample(groupName, elementName, metadataID));
+ }
+
+ 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$
+ }
+
+ public void testGetGroup() throws Exception {
+ Object metadataID = TstLanguageBridgeFactory.metadata.getElementID("pm1.g1.e1"); //$NON-NLS-1$
+ assertNotNull(example("pm1.g1", "e1", metadataID).getTable()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ public void testGetType() throws Exception {
+ Object metadataID = TstLanguageBridgeFactory.metadata.getElementID("pm1.g1.e2"); //$NON-NLS-1$
+ assertTrue(example("pm1.g1", "e2", metadataID).getType().equals(Integer.class)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ public void helpTestEquals(ColumnReference e1, ColumnReference e2, boolean equal) {
+ boolean actual = e1.equals(e2);
+ boolean actual2 = e2.equals(e1);
+
+ assertEquals("e1.equals(e2) != e2.equals(e1)", actual, actual2); //$NON-NLS-1$
+ assertEquals("Did not get expected equal value", equal, actual); //$NON-NLS-1$
+ }
+
+ public NamedTable createGroup(String context, String definition) {
+ return new NamedTable(context, definition, null);
+ }
+
+ public ColumnReference createElement(NamedTable group, String name) {
+ return new ColumnReference(group, name, null, String.class);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestGroupImpl.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestGroupImpl.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestGroupImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.dqp.internal.datamgr;
-
-
-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 {
-
- /**
- * Constructor for TestGroupImpl.
- * @param name
- */
- public TestGroupImpl(String name) {
- super(name);
- }
-
- public static GroupSymbol helpExample(String groupName) {
- return helpExample(groupName, null);
- }
-
- 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);
- }
-
- public static GroupSymbol helpExample(String groupName, String definition, Object metadataID) {
- GroupSymbol symbol = new GroupSymbol(groupName, definition);
- symbol.setMetadataID(metadataID);
- return symbol;
- }
-
- public static NamedTable example(String groupName) throws Exception {
- return example(groupName, null);
- }
-
- public static NamedTable example(String groupName, String definition) throws Exception {
- return TstLanguageBridgeFactory.factory.translate(helpExample(groupName, definition));
- }
-
- public static NamedTable example(String groupName, String definition, Object metadataID) throws Exception {
- return TstLanguageBridgeFactory.factory.translate(helpExample(groupName, definition, metadataID));
- }
-
- public void testGetContext() throws Exception {
- Object metadataID = TstLanguageBridgeFactory.metadata.getGroupID("pm1.g1"); //$NON-NLS-1$
- assertEquals("x", example("x", "pm1.g1", metadataID).getCorrelationName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- public void testGetDefinition() throws Exception {
- Object metadataID = TstLanguageBridgeFactory.metadata.getGroupID("pm1.g1"); //$NON-NLS-1$
- assertEquals("g1", example("x", "pm1.g1", metadataID).getName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestGroupImpl.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestGroupImpl.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestGroupImpl.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestGroupImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,80 @@
+/*
+ * 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.datamgr;
+
+
+import junit.framework.TestCase;
+
+import org.teiid.language.NamedTable;
+import org.teiid.query.sql.symbol.GroupSymbol;
+
+
+public class TestGroupImpl extends TestCase {
+
+ /**
+ * Constructor for TestGroupImpl.
+ * @param name
+ */
+ public TestGroupImpl(String name) {
+ super(name);
+ }
+
+ public static GroupSymbol helpExample(String groupName) {
+ return helpExample(groupName, null);
+ }
+
+ public static GroupSymbol helpExample(String groupName, String definition) {
+ return helpExample(groupName, definition, null);
+ }
+
+ public static GroupSymbol helpExample(String groupName, String definition, Object metadataID) {
+ GroupSymbol symbol = new GroupSymbol(groupName, definition);
+ if (metadataID != null) {
+ symbol.setMetadataID(metadataID);
+ }
+ return symbol;
+ }
+
+ public static NamedTable example(String groupName) throws Exception {
+ return example(groupName, null);
+ }
+
+ public static NamedTable example(String groupName, String definition) throws Exception {
+ return TstLanguageBridgeFactory.factory.translate(helpExample(groupName, definition));
+ }
+
+ public static NamedTable example(String groupName, String definition, Object metadataID) throws Exception {
+ return TstLanguageBridgeFactory.factory.translate(helpExample(groupName, definition, metadataID));
+ }
+
+ public void testGetContext() throws Exception {
+ Object metadataID = TstLanguageBridgeFactory.metadata.getGroupID("pm1.g1"); //$NON-NLS-1$
+ assertEquals("x", example("x", "pm1.g1", metadataID).getCorrelationName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ public void testGetDefinition() throws Exception {
+ Object metadataID = TstLanguageBridgeFactory.metadata.getGroupID("pm1.g1"); //$NON-NLS-1$
+ assertEquals("g1", example("x", "pm1.g1", metadataID).getName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestInsertImpl.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestInsertImpl.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestInsertImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.dqp.internal.datamgr;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-
-import junit.framework.TestCase;
-
-import org.teiid.language.ColumnReference;
-import org.teiid.language.Expression;
-import org.teiid.language.ExpressionValueSource;
-import org.teiid.language.Insert;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.GroupSymbol;
-
-
-public class TestInsertImpl extends TestCase {
-
- /**
- * Constructor for TestInsertImpl.
- * @param name
- */
- public TestInsertImpl(String name) {
- super(name);
- }
-
- public static org.teiid.query.sql.lang.Insert helpExample(String groupName) {
- GroupSymbol group = TestGroupImpl.helpExample(groupName);
- ArrayList<ElementSymbol> elements = new ArrayList<ElementSymbol>();
- elements.add(TestElementImpl.helpExample(groupName, "e1")); //$NON-NLS-1$
- elements.add(TestElementImpl.helpExample(groupName, "e2")); //$NON-NLS-1$
- elements.add(TestElementImpl.helpExample(groupName, "e3")); //$NON-NLS-1$
- elements.add(TestElementImpl.helpExample(groupName, "e4")); //$NON-NLS-1$
-
- ArrayList<Constant> values = new ArrayList<Constant>();
- values.add(TestLiteralImpl.helpExample(1));
- values.add(TestLiteralImpl.helpExample(2));
- values.add(TestLiteralImpl.helpExample(3));
- values.add(TestLiteralImpl.helpExample(4));
-
- return new org.teiid.query.sql.lang.Insert(group,
- elements,
- values);
- }
-
- public static org.teiid.query.sql.lang.Insert helpExample2(String groupName) {
- GroupSymbol group = TestGroupImpl.helpExample(groupName);
- ArrayList elements = new ArrayList();
- elements.add(TestElementImpl.helpExample(groupName, "e1")); //$NON-NLS-1$
-
- ArrayList values = new ArrayList();
- values.add(TestSearchedCaseExpressionImpl.helpExample());
-
- return new org.teiid.query.sql.lang.Insert(group,
- elements,
- values);
- }
-
- public static Insert example(String groupName) throws Exception {
- return TstLanguageBridgeFactory.factory.translate(helpExample(groupName));
-
- }
- public static Insert example2(String groupName) throws Exception {
- return TstLanguageBridgeFactory.factory.translate(helpExample2(groupName));
-
- }
- public void testGetGroup() throws Exception {
- assertNotNull(example("a.b").getTable()); //$NON-NLS-1$
- }
-
- public void testGetElements() throws Exception {
- 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();
- assertTrue(sInsertSQL.substring(sInsertSQL.indexOf('(')).indexOf( '.') == -1 );
- }
-
- public void testGetValues() throws Exception {
- Insert insert = example("a.b"); //$NON-NLS-1$
- assertNotNull(insert.getValueSource());
- assertEquals(4, ((ExpressionValueSource)insert.getValueSource()).getValues().size());
- for (Iterator i = ((ExpressionValueSource)insert.getValueSource()).getValues().iterator(); i.hasNext();) {
- assertTrue(i.next() instanceof Expression);
- }
- }
-
- public void testExpressionsInInsert() throws Exception {
- Insert insert = example2("a.b"); //$NON-NLS-1$
- assertNotNull(insert.getColumns());
- assertEquals(1, insert.getColumns().size());
- for (Iterator i = insert.getColumns().iterator(); i.hasNext();) {
- assertTrue(i.next() instanceof ColumnReference);
- }
- assertNotNull(insert.getValueSource());
- assertEquals(1, ((ExpressionValueSource)insert.getValueSource()).getValues().size());
- for (Iterator i = ((ExpressionValueSource)insert.getValueSource()).getValues().iterator(); i.hasNext();) {
- assertTrue(i.next() instanceof Expression);
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestInsertImpl.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestInsertImpl.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestInsertImpl.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestInsertImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,126 @@
+/*
+ * 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.datamgr;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import junit.framework.TestCase;
+
+import org.teiid.language.ColumnReference;
+import org.teiid.language.Expression;
+import org.teiid.language.ExpressionValueSource;
+import org.teiid.language.Insert;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.GroupSymbol;
+
+
+public class TestInsertImpl extends TestCase {
+
+ /**
+ * Constructor for TestInsertImpl.
+ * @param name
+ */
+ public TestInsertImpl(String name) {
+ super(name);
+ }
+
+ public static org.teiid.query.sql.lang.Insert helpExample(String groupName) {
+ GroupSymbol group = TestGroupImpl.helpExample(groupName);
+ ArrayList<ElementSymbol> elements = new ArrayList<ElementSymbol>();
+ elements.add(TestElementImpl.helpExample(groupName, "e1")); //$NON-NLS-1$
+ elements.add(TestElementImpl.helpExample(groupName, "e2")); //$NON-NLS-1$
+ elements.add(TestElementImpl.helpExample(groupName, "e3")); //$NON-NLS-1$
+ elements.add(TestElementImpl.helpExample(groupName, "e4")); //$NON-NLS-1$
+
+ ArrayList<Constant> values = new ArrayList<Constant>();
+ values.add(TestLiteralImpl.helpExample(1));
+ values.add(TestLiteralImpl.helpExample(2));
+ values.add(TestLiteralImpl.helpExample(3));
+ values.add(TestLiteralImpl.helpExample(4));
+
+ return new org.teiid.query.sql.lang.Insert(group,
+ elements,
+ values);
+ }
+
+ public static org.teiid.query.sql.lang.Insert helpExample2(String groupName) {
+ GroupSymbol group = TestGroupImpl.helpExample(groupName);
+ ArrayList<ElementSymbol> elements = new ArrayList<ElementSymbol>();
+ elements.add(TestElementImpl.helpExample(groupName, "e1")); //$NON-NLS-1$
+
+ 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,
+ elements,
+ values);
+ }
+
+ public static Insert example(String groupName) throws Exception {
+ return TstLanguageBridgeFactory.factory.translate(helpExample(groupName));
+
+ }
+ public static Insert example2(String groupName) throws Exception {
+ return TstLanguageBridgeFactory.factory.translate(helpExample2(groupName));
+
+ }
+ public void testGetGroup() throws Exception {
+ assertNotNull(example("a.b").getTable()); //$NON-NLS-1$
+ }
+
+ public void testGetElements() throws Exception {
+ Insert insert = example("a.b"); //$NON-NLS-1$
+ assertNotNull(insert.getColumns());
+ assertEquals(4, insert.getColumns().size());
+
+ // verify that elements are not qualified by group
+ String sInsertSQL = insert.toString();
+ assertTrue(sInsertSQL.substring(sInsertSQL.indexOf('(')).indexOf( '.') == -1 );
+ }
+
+ public void testGetValues() throws Exception {
+ Insert insert = example("a.b"); //$NON-NLS-1$
+ assertNotNull(insert.getValueSource());
+ assertEquals(4, ((ExpressionValueSource)insert.getValueSource()).getValues().size());
+ for (Iterator i = ((ExpressionValueSource)insert.getValueSource()).getValues().iterator(); i.hasNext();) {
+ assertTrue(i.next() instanceof Expression);
+ }
+ }
+
+ public void testExpressionsInInsert() throws Exception {
+ Insert insert = example2("a.b"); //$NON-NLS-1$
+ assertNotNull(insert.getColumns());
+ assertEquals(1, insert.getColumns().size());
+ for (Iterator i = insert.getColumns().iterator(); i.hasNext();) {
+ assertTrue(i.next() instanceof ColumnReference);
+ }
+ assertNotNull(insert.getValueSource());
+ assertEquals(1, ((ExpressionValueSource)insert.getValueSource()).getValues().size());
+ for (Iterator i = ((ExpressionValueSource)insert.getValueSource()).getValues().iterator(); i.hasNext();) {
+ assertTrue(i.next() instanceof Expression);
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestMetadataFactory.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestMetadataFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestMetadataFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.dqp.internal.datamgr;
-
-import java.util.List;
-
-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 junit.framework.TestCase;
-
-
-public class TestMetadataFactory extends TestCase {
- private RuntimeMetadataImpl metadataFactory;
- private FakeMetadataObject pm1g1;
-
- public TestMetadataFactory(String name) {
- super(name);
- }
-
- 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$
- String[] mfPaths = metadataFactory.getVDBResourcePaths();
- assertEquals(expectedPaths.length, mfPaths.length);
- for (int i = 0; i < expectedPaths.length; i++) {
- assertEquals(expectedPaths[i], mfPaths[i]);
- }
- }
-
- public void testGetBinaryVDBResource() throws Exception {
- byte[] expectedBytes = "ResourceContents".getBytes(); //$NON-NLS-1$
- byte[] mfBytes = metadataFactory.getBinaryVDBResource(null);
- 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$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestMetadataFactory.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestMetadataFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestMetadataFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestMetadataFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,84 @@
+/*
+ * 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.datamgr;
+
+import static org.junit.Assert.*;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import org.jboss.virtual.VirtualFile;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.query.metadata.CompositeMetadataStore;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.metadata.TransformationMetadata.Resource;
+
+ at SuppressWarnings("nls")
+public class TestMetadataFactory {
+ private static final String MY_RESOURCE_PATH = "my/resource/path";
+ private RuntimeMetadataImpl metadataFactory;
+
+ @Before public void setUp() throws IOException{
+ 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>();
+ VirtualFile vf = Mockito.mock(VirtualFile.class);
+ Mockito.stub(vf.openStream()).toReturn(new ByteArrayInputStream("ResourceContents".getBytes()));
+ vdbEntries.put(MY_RESOURCE_PATH, new Resource(vf, true));
+ metadataFactory = new RuntimeMetadataImpl(new TransformationMetadata(vdbMetaData, store, vdbEntries, null, null));
+ }
+
+ @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++) {
+ assertEquals(expectedPaths[i], mfPaths[i]);
+ }
+ }
+
+ @Test public void testGetBinaryVDBResource() throws Exception {
+ byte[] expectedBytes = "ResourceContents".getBytes(); //$NON-NLS-1$
+ 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$
+ }
+ }
+
+ @Test public void testGetCharacterVDBResource() throws Exception {
+ assertEquals("ResourceContents", metadataFactory.getCharacterVDBResource(MY_RESOURCE_PATH)); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TstLanguageBridgeFactory.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/TstLanguageBridgeFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TstLanguageBridgeFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,37 +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.datamgr;
-
-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;
-
-
-public class TstLanguageBridgeFactory {
-
- public static final QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
- public static final RuntimeMetadataImpl metadataFactory = new RuntimeMetadataImpl(metadata);
- public static final LanguageBridgeFactory factory = new LanguageBridgeFactory(metadata);
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TstLanguageBridgeFactory.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/TstLanguageBridgeFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TstLanguageBridgeFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/datamgr/TstLanguageBridgeFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,37 @@
+/*
+ * 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.datamgr;
+
+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.RealMetadataFactory;
+
+
+public class TstLanguageBridgeFactory {
+
+ public static final QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ public static final RuntimeMetadataImpl metadataFactory = new RuntimeMetadataImpl(metadata);
+ public static final LanguageBridgeFactory factory = new LanguageBridgeFactory(metadata);
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,346 +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 static org.junit.Assert.*;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.junit.Ignore;
-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.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.validator.Validator;
-import org.teiid.query.validator.ValidatorFailure;
-import org.teiid.query.validator.ValidatorReport;
-
- at SuppressWarnings("nls")
-public class TestAuthorizationValidationVisitor {
-
- public static final String CONN_ID = "connID"; //$NON-NLS-1$
-
- PermissionMetaData addResource(PermissionType type, boolean flag, String resource) {
- PermissionMetaData p = new PermissionMetaData();
- p.setResourceName(resource);
- switch(type) {
- case CREATE:
- p.setAllowCreate(flag);
- break;
- case DELETE:
- p.setAllowDelete(flag);
- break;
- case READ:
- p.setAllowRead(flag);
- break;
- case UPDATE:
- p.setAllowUpdate(flag);
- break;
- case ALTER:
- p.setAllowAlter(flag);
- break;
- case EXECUTE:
- p.setAllowExecute(flag);
- break;
- }
- return p;
- }
- PermissionMetaData addResource(PermissionType type, String resource) {
- return addResource(type, true, resource);
- }
-
- private DataPolicyMetadata exampleAuthSvc1() {
- DataPolicyMetadata svc = new DataPolicyMetadata();
- svc.setName("test"); //$NON-NLS-1$
-
- // pm1.g1
- svc.addPermission(addResource(PermissionType.DELETE, "pm1.g1")); //$NON-NLS-1$
-
- svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.g1")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.g1.e1")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.READ, false, "pm1.g1.e2")); //$NON-NLS-1$
-
- svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e1")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e2")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e3")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e4")); //$NON-NLS-1$
-
- svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, false, "pm1.g1.e1")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1.e2")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1.e3")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1.e4")); //$NON-NLS-1$
-
-
- // pm1.g2
- svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, false, "pm1.g2.e1")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2.e2")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2.e3")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2.e4")); //$NON-NLS-1$
-
- svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, false, "pm1.g2.e1")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2.e2")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2.e3")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2.e4")); //$NON-NLS-1$
-
- // pm1.g4
- svc.addPermission(addResource(DataPolicy.PermissionType.DELETE, "pm1.g4")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.DELETE, "pm1.g4.e1")); //$NON-NLS-1$
- 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$
-
- return svc;
- }
-
- //allow by default
- private DataPolicyMetadata exampleAuthSvc2() {
- DataPolicyMetadata svc = new DataPolicyMetadata();
- svc.setName("test"); //$NON-NLS-1$
-
- svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.g2")); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm2.g1")); //$NON-NLS-1$
-
- // pm2.g2
- svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm2.g2.e1")); //$NON-NLS-1$
-
- // 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.setAllowCreateTemporaryTables(false);
- return svc;
- }
-
- private DataPolicyMetadata examplePolicyBQT() {
- DataPolicyMetadata svc = new DataPolicyMetadata();
- svc.setName("test"); //$NON-NLS-1$
- svc.addPermission(addResource(DataPolicy.PermissionType.ALTER, "VQT.SmallA_2589")); //$NON-NLS-1$
- return svc;
- }
-
- private void helpTest(DataPolicyMetadata policy, String sql, QueryMetadataInterface metadata, String[] expectedInaccesible, VDBMetaData vdb) throws QueryParserException, QueryResolverException, TeiidComponentException {
- QueryParser parser = QueryParser.getQueryParser();
- Command command = parser.parseCommand(sql);
- QueryResolver.resolveCommand(command, metadata);
-
- vdb.addAttchment(QueryMetadataInterface.class, metadata);
-
- 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);
- ValidatorReport report = Validator.validate(command, metadata, visitor);
- if(report.hasItems()) {
- ValidatorFailure firstFailure = report.getItems().iterator().next();
-
- // strings
- Set<String> expected = new HashSet<String>(Arrays.asList(expectedInaccesible));
- // elements
- Set<String> actual = new HashSet<String>();
- for (LanguageObject obj : firstFailure.getInvalidObjects()) {
- if (obj instanceof ElementSymbol) {
- actual.add(((ElementSymbol)obj).getName());
- } else {
- actual.add(obj.toString());
- }
- }
- assertEquals(expected, actual);
- } else if(expectedInaccesible.length > 0) {
- fail("Expected inaccessible objects, but got none."); //$NON-NLS-1$
- }
- }
-
- @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$
- //explicitly denied
- helpTest(exampleAuthSvc2(), "create local temporary table x (y string)", FakeMetadataFactory.example1Cached(), new String[] {"x"}, FakeMetadataFactory.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$
- }
-
- @Test public void testEverythingAccessible() throws Exception {
- helpTest(exampleAuthSvc1(), "SELECT e1 FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @Test public void testUpdate() throws Exception {
- helpTest(exampleAuthSvc1(), "UPDATE pm1.g1 SET e2 = 5", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @Test public void testDelete() throws Exception {
- helpTest(exampleAuthSvc1(), "DELETE FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.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$
- }
-
- @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$
- }
-
- @Test public void testProc() throws Exception {
- helpTest(exampleAuthSvc1(), "EXEC pm1.sq1()", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @Test public void testTempTableSelectInto() throws Exception {
- helpTest(exampleAuthSvc1(), "SELECT e1 INTO #temp FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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 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$
- }
-
- 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$
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,353 @@
+/*
+ * 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.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+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.metadata.QueryMetadataInterface;
+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.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;
+
+ at SuppressWarnings("nls")
+public class TestAuthorizationValidationVisitor {
+
+ public static final String CONN_ID = "connID"; //$NON-NLS-1$
+ private static CommandContext context = new CommandContext();
+
+ @BeforeClass public static void oneTimeSetup() {
+ context.setSession(new SessionMetadata());
+ }
+
+ PermissionMetaData addResource(PermissionType type, boolean flag, String resource) {
+ PermissionMetaData p = new PermissionMetaData();
+ p.setResourceName(resource);
+ switch(type) {
+ case CREATE:
+ p.setAllowCreate(flag);
+ break;
+ case DELETE:
+ p.setAllowDelete(flag);
+ break;
+ case READ:
+ p.setAllowRead(flag);
+ break;
+ case UPDATE:
+ p.setAllowUpdate(flag);
+ break;
+ case ALTER:
+ p.setAllowAlter(flag);
+ break;
+ case EXECUTE:
+ p.setAllowExecute(flag);
+ break;
+ }
+ return p;
+ }
+ PermissionMetaData addResource(PermissionType type, String resource) {
+ return addResource(type, true, resource);
+ }
+
+ private DataPolicyMetadata exampleAuthSvc1() {
+ DataPolicyMetadata svc = new DataPolicyMetadata();
+ svc.setName("test"); //$NON-NLS-1$
+
+ // pm1.g1
+ svc.addPermission(addResource(PermissionType.DELETE, "pm1.g1")); //$NON-NLS-1$
+
+ svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.g1")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.g1.e1")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.READ, false, "pm1.g1.e2")); //$NON-NLS-1$
+
+ svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e1")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e2")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e3")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e4")); //$NON-NLS-1$
+
+ svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, false, "pm1.g1.e1")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1.e2")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1.e3")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1.e4")); //$NON-NLS-1$
+
+
+ // pm1.g2
+ svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, false, "pm1.g2.e1")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2.e2")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2.e3")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2.e4")); //$NON-NLS-1$
+
+ svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, false, "pm1.g2.e1")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2.e2")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2.e3")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2.e4")); //$NON-NLS-1$
+
+ // pm1.g4
+ svc.addPermission(addResource(DataPolicy.PermissionType.DELETE, "pm1.g4")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.DELETE, "pm1.g4.e1")); //$NON-NLS-1$
+ 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, "pm1.xyz")); //$NON-NLS-1$
+
+ return svc;
+ }
+
+ //allow by default
+ private DataPolicyMetadata exampleAuthSvc2() {
+ DataPolicyMetadata svc = new DataPolicyMetadata();
+ svc.setName("test"); //$NON-NLS-1$
+
+ svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.g2")); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm2.g1")); //$NON-NLS-1$
+
+ // pm2.g2
+ svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm2.g2.e1")); //$NON-NLS-1$
+
+ // 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;
+ }
+
+ private DataPolicyMetadata examplePolicyBQT() {
+ DataPolicyMetadata svc = new DataPolicyMetadata();
+ svc.setName("test"); //$NON-NLS-1$
+ svc.addPermission(addResource(DataPolicy.PermissionType.ALTER, "VQT.SmallA_2589")); //$NON-NLS-1$
+ return svc;
+ }
+
+ private void helpTest(DataPolicyMetadata policy, String sql, QueryMetadataInterface metadata, String[] expectedInaccesible, VDBMetaData vdb) throws QueryParserException, QueryResolverException, TeiidComponentException {
+ QueryParser parser = QueryParser.getQueryParser();
+ Command command = parser.parseCommand(sql);
+ QueryResolver.resolveCommand(command, metadata);
+
+ vdb.addAttchment(QueryMetadataInterface.class, metadata);
+
+ HashMap<String, DataPolicy> policies = new HashMap<String, DataPolicy>();
+ policies.put(policy.getName(), policy);
+
+ AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(policies, context); //$NON-NLS-1$
+ visitor.setAllowFunctionCallsByDefault(false);
+ ValidatorReport report = Validator.validate(command, metadata, visitor);
+ if(report.hasItems()) {
+ ValidatorFailure firstFailure = report.getItems().iterator().next();
+
+ // strings
+ Set<String> expected = new HashSet<String>(Arrays.asList(expectedInaccesible));
+ // elements
+ Set<String> actual = new HashSet<String>();
+ for (LanguageObject obj : firstFailure.getInvalidObjects()) {
+ if (obj instanceof ElementSymbol) {
+ actual.add(((ElementSymbol)obj).getName());
+ } else {
+ actual.add(obj.toString());
+ }
+ }
+ assertEquals(expected, actual);
+ } else if(expectedInaccesible.length > 0) {
+ fail("Expected inaccessible objects, but got none."); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testTemp() throws Exception {
+ //allowed by default
+ 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)", RealMetadataFactory.example1Cached(), new String[] {"x"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
+ }
+
+ @Test public void testFunction() throws Exception {
+ 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", 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", 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", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
+ }
+
+ @Test public void testInaccesibleElement() throws Exception {
+ 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')", 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", 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)", 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)", 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", 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'", 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)", 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'", 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", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
+ }
+
+ @Test public void testDeleteCriteriaInaccesibleForRead() throws Exception {
+ 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", 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()", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
+ }
+
+ @Test public void testProcInaccesible() throws Exception {
+ 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", 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", RealMetadataFactory.example1Cached(), new String[] {"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", RealMetadataFactory.example1Cached(), new String[] {"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", 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", RealMetadataFactory.example1Cached(), new String[] {"pm1.g1.e2"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testTempTableInsert() throws Exception {
+ 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", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLInAccessible() throws Exception {
+ 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"}, 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"}, 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 = RealMetadataFactory.example1VDB();
+ vdb.getModel("pm1").setVisible(visible); //$NON-NLS-1$
+ AuthorizationValidationVisitor mvvv = new AuthorizationValidationVisitor(new HashMap<String, DataPolicy>(), context); //$NON-NLS-1$
+ String sql = "select lookup('pm1.g1', 'e1', 'e2', 1)"; //$NON-NLS-1$
+ Command command = QueryParser.getQueryParser().parseCommand(sql);
+ Request.validateWithVisitor(mvvv, RealMetadataFactory.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$
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCachedResults.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestCachedResults.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCachedResults.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,111 +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 static org.junit.Assert.*;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.cache.Cache;
-import org.teiid.cache.DefaultCache;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.TupleBuffer;
-import org.teiid.common.buffer.TestTupleBuffer.FakeBatchManager;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.UnitTestUtil;
-import org.teiid.dqp.service.FakeBufferService;
-import org.teiid.metadata.Table;
-import org.teiid.query.processor.FakeProcessorPlan;
-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;
-
- at SuppressWarnings({"nls", "unchecked"})
-public class TestCachedResults {
-
- @Test
- public void testCaching() throws Exception {
- FakeBufferService fbs = new FakeBufferService();
-
- ElementSymbol x = new ElementSymbol("x"); //$NON-NLS-1$
- x.setType(DataTypeManager.DefaultDataClasses.INTEGER);
- List<ElementSymbol> schema = Arrays.asList(x);
- TupleBuffer tb = new TupleBuffer(new FakeBatchManager(), "x", schema, null, 4); //$NON-NLS-1$
- tb.setForwardOnly(false);
-
- tb.addTuple(Arrays.asList(1));
- tb.addTuple(Arrays.asList(2));
- tb.addTuple(Arrays.asList(3));
- tb.addTuple(Arrays.asList(4));
- tb.addTuple(Arrays.asList(5));
- tb.addTuple(Arrays.asList(6));
- tb.addTuple(Arrays.asList(7));
- tb.addTuple(Arrays.asList(8));
- tb.addTuple(Arrays.asList(9));
- tb.addTuple(Arrays.asList(10));
-
- tb.close();
-
- BufferManager bm = fbs.getBufferManager();
- CachedResults results = new CachedResults();
- ProcessorPlan plan = new FakeProcessorPlan(0);
- CommandContext cc = new CommandContext();
- Table t = RealMetadataFactory.exampleBQT().getGroupID("bqt1.smalla");
- cc.accessedDataObject(t);
- plan.setContext(cc);
- results.setResults(tb, plan);
- results.setCommand(new Query());
- Cache cache = new DefaultCache("dummy"); //$NON-NLS-1$
- long ts = results.getAccessInfo().getCreationTime();
- // simulate the jboss-cache remote transport, where the batches are remotely looked up
- // in cache
- for (int row=1; row<=tb.getRowCount();row+=4) {
- cache.put(results.getId()+","+row, tb.getBatch(row), null); //$NON-NLS-1$
- }
-
- results.prepare(cache, bm);
-
- CachedResults cachedResults = UnitTestUtil.helpSerialize(results);
-
- FakeMetadataFactory.buildWorkContext(RealMetadataFactory.exampleBQT());
-
- cachedResults.restore(cache, bm);
-
- // since restored, simulate a async cache flush
- cache.clear();
-
- TupleBuffer cachedTb = cachedResults.getResults();
-
- assertTrue(cachedTb.isFinal());
- assertEquals(tb.getRowCount(), cachedTb.getRowCount());
- assertEquals(tb.getBatchSize(), cachedTb.getBatchSize());
-
- assertArrayEquals(tb.getBatch(1).getAllTuples(), cachedTb.getBatch(1).getAllTuples());
- assertArrayEquals(tb.getBatch(9).getAllTuples(), cachedTb.getBatch(9).getAllTuples());
- assertTrue(ts - cachedResults.getAccessInfo().getCreationTime() <= 5000);
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCachedResults.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestCachedResults.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCachedResults.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCachedResults.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,110 @@
+/*
+ * 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.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.cache.Cache;
+import org.teiid.cache.DefaultCache;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.common.buffer.TestTupleBuffer.FakeBatchManager;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.UnitTestUtil;
+import org.teiid.dqp.service.FakeBufferService;
+import org.teiid.metadata.Table;
+import org.teiid.query.processor.FakeProcessorPlan;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+ at SuppressWarnings({"nls", "unchecked"})
+public class TestCachedResults {
+
+ @Test
+ public void testCaching() throws Exception {
+ FakeBufferService fbs = new FakeBufferService();
+
+ ElementSymbol x = new ElementSymbol("x"); //$NON-NLS-1$
+ x.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+ List<ElementSymbol> schema = Arrays.asList(x);
+ TupleBuffer tb = new TupleBuffer(new FakeBatchManager(), "x", schema, null, 4); //$NON-NLS-1$
+ tb.setForwardOnly(false);
+
+ tb.addTuple(Arrays.asList(1));
+ tb.addTuple(Arrays.asList(2));
+ tb.addTuple(Arrays.asList(3));
+ tb.addTuple(Arrays.asList(4));
+ tb.addTuple(Arrays.asList(5));
+ tb.addTuple(Arrays.asList(6));
+ tb.addTuple(Arrays.asList(7));
+ tb.addTuple(Arrays.asList(8));
+ tb.addTuple(Arrays.asList(9));
+ tb.addTuple(Arrays.asList(10));
+
+ tb.close();
+
+ BufferManager bm = fbs.getBufferManager();
+ CachedResults results = new CachedResults();
+ ProcessorPlan plan = new FakeProcessorPlan(0);
+ CommandContext cc = new CommandContext();
+ Table t = RealMetadataFactory.exampleBQT().getGroupID("bqt1.smalla");
+ cc.accessedDataObject(t);
+ plan.setContext(cc);
+ results.setResults(tb, plan);
+ results.setCommand(new Query());
+ Cache cache = new DefaultCache("dummy"); //$NON-NLS-1$
+ long ts = results.getAccessInfo().getCreationTime();
+ // simulate the jboss-cache remote transport, where the batches are remotely looked up
+ // in cache
+ for (int row=1; row<=tb.getRowCount();row+=4) {
+ cache.put(results.getId()+","+row, tb.getBatch(row), null); //$NON-NLS-1$
+ }
+
+ results.prepare(cache, bm);
+
+ CachedResults cachedResults = UnitTestUtil.helpSerialize(results);
+
+ RealMetadataFactory.buildWorkContext(RealMetadataFactory.exampleBQT());
+
+ cachedResults.restore(cache, bm);
+
+ // since restored, simulate a async cache flush
+ cache.clear();
+
+ TupleBuffer cachedTb = cachedResults.getResults();
+
+ assertTrue(cachedTb.isFinal());
+ assertEquals(tb.getRowCount(), cachedTb.getRowCount());
+ assertEquals(tb.getBatchSize(), cachedTb.getBatchSize());
+
+ assertArrayEquals(tb.getBatch(1).getAllTuples(), cachedTb.getBatch(1).getAllTuples());
+ assertArrayEquals(tb.getBatch(9).getAllTuples(), cachedTb.getBatch(9).getAllTuples());
+ assertTrue(ts - cachedResults.getAccessInfo().getCreationTime() <= 5000);
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,123 +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 static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.query.processor.HardcodedDataManager;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
- at SuppressWarnings("nls")
-public class TestCallableStatement {
-
- @Test public void testMissingInput() throws Exception {
- String sql = "{? = call pm4.spTest9()}"; //$NON-NLS-1$
-
- try {
- TestPreparedStatement.helpTestProcessing(sql, Collections.EMPTY_LIST, null, new HardcodedDataManager(), FakeMetadataFactory.exampleBQTCached(), true, FakeMetadataFactory.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$
- }
- }
-
- @Test public void testReturnParameter() throws Exception {
- String sql = "{? = call pm4.spTest9(?)}"; //$NON-NLS-1$
-
- List values = new ArrayList();
- values.add(1);
-
- List[] expected = new List[1];
- expected[0] = Arrays.asList(1);
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData("? = EXEC pm4.spTest9(1)", expected);
-
- TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, FakeMetadataFactory.exampleBQTCached(), true, FakeMetadataFactory.exampleBQTVDB());
- }
-
- /**
- * same result as above, but the return parameter is not specified
- * TODO: it would be best if the return parameter were not actually returned here, since it wasn't specified in the initial sql
- */
- @Test public void testNoReturnParameter() throws Exception {
- String sql = "{call pm4.spTest9(?)}"; //$NON-NLS-1$
-
- List values = new ArrayList();
- values.add(1);
-
- List[] expected = new List[1];
- expected[0] = Arrays.asList(1);
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData("EXEC pm4.spTest9(1)", expected);
-
- TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, FakeMetadataFactory.exampleBQTCached(), true, FakeMetadataFactory.exampleBQTVDB());
- }
-
- @Test public void testOutParameter() throws Exception {
- String sql = "{call pm2.spTest8(?, ?)}"; //$NON-NLS-1$
-
- List values = new ArrayList();
- values.add(2);
-
- List[] expected = new List[1];
- expected[0] = Arrays.asList(null, null, 1);
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData("EXEC pm2.spTest8(2)", expected);
-
- TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, FakeMetadataFactory.exampleBQTCached(), true, FakeMetadataFactory.exampleBQTVDB());
- }
-
- @Test(expected=QueryResolverException.class) public void testInvalidReturn() throws Exception {
- String sql = "{? = call pm2.spTest8(?, ?)}"; //$NON-NLS-1$
-
- List values = Arrays.asList(2);
-
- List[] expected = new List[0];
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
- TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, FakeMetadataFactory.exampleBQTCached(), true, FakeMetadataFactory.exampleBQTVDB());
- }
-
- @Test public void testInputExpression() throws Exception {
- String sql = "{call pm2.spTest8(1, ?)}"; //$NON-NLS-1$
-
- List[] expected = new List[1];
- expected[0] = Arrays.asList(null, null, 0);
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData("EXEC pm2.spTest8(1)", expected);
-
- TestPreparedStatement.helpTestProcessing(sql, null, expected, dataManager, FakeMetadataFactory.exampleBQTCached(), true, FakeMetadataFactory.exampleBQTVDB());
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,123 @@
+/*
+ * 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.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.query.processor.HardcodedDataManager;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+ at SuppressWarnings("nls")
+public class TestCallableStatement {
+
+ @Test public void testMissingInput() throws Exception {
+ String sql = "{? = call pm4.spTest9()}"; //$NON-NLS-1$
+
+ try {
+ 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$
+ }
+ }
+
+ @Test public void testReturnParameter() throws Exception {
+ String sql = "{? = call pm4.spTest9(?)}"; //$NON-NLS-1$
+
+ List values = new ArrayList();
+ values.add(1);
+
+ List[] expected = new List[1];
+ expected[0] = Arrays.asList(1);
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("? = EXEC pm4.spTest9(1)", expected);
+
+ TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, RealMetadataFactory.exampleBQTCached(), true, RealMetadataFactory.exampleBQTVDB());
+ }
+
+ /**
+ * same result as above, but the return parameter is not specified
+ * TODO: it would be best if the return parameter were not actually returned here, since it wasn't specified in the initial sql
+ */
+ @Test public void testNoReturnParameter() throws Exception {
+ String sql = "{call pm4.spTest9(?)}"; //$NON-NLS-1$
+
+ List values = new ArrayList();
+ values.add(1);
+
+ List[] expected = new List[1];
+ expected[0] = Arrays.asList(1);
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("EXEC pm4.spTest9(1)", expected);
+
+ TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, RealMetadataFactory.exampleBQTCached(), true, RealMetadataFactory.exampleBQTVDB());
+ }
+
+ @Test public void testOutParameter() throws Exception {
+ String sql = "{call pm2.spTest8(?, ?)}"; //$NON-NLS-1$
+
+ List values = new ArrayList();
+ values.add(2);
+
+ List[] expected = new List[1];
+ expected[0] = Arrays.asList(null, null, 1);
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("EXEC pm2.spTest8(2)", expected);
+
+ TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, RealMetadataFactory.exampleBQTCached(), true, RealMetadataFactory.exampleBQTVDB());
+ }
+
+ @Test(expected=QueryResolverException.class) public void testInvalidReturn() throws Exception {
+ String sql = "{? = call pm2.spTest8(?, ?)}"; //$NON-NLS-1$
+
+ List values = Arrays.asList(2);
+
+ List[] expected = new List[0];
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, RealMetadataFactory.exampleBQTCached(), true, RealMetadataFactory.exampleBQTVDB());
+ }
+
+ @Test public void testInputExpression() throws Exception {
+ String sql = "{call pm2.spTest8(1, ?)}"; //$NON-NLS-1$
+
+ List[] expected = new List[1];
+ expected[0] = Arrays.asList(null, null, 0);
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("EXEC pm2.spTest8(1)", expected);
+
+ TestPreparedStatement.helpTestProcessing(sql, null, expected, dataManager, RealMetadataFactory.exampleBQTCached(), true, RealMetadataFactory.exampleBQTVDB());
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,102 +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 java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import org.mockito.Mockito;
-import org.teiid.adminapi.impl.ModelMetaData;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.core.types.DataTypeManager;
-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;
-
-
-/**
- */
-public class TestConnectorCapabilitiesFinder extends TestCase {
-
- /**
- * Constructor for TestConnectorCapabilitiesFinder.
- * @param name
- */
- public TestConnectorCapabilitiesFinder(String name) {
- super(name);
- }
-
- public void testFind() throws Exception {
- String modelName = "model"; //$NON-NLS-1$
- String functionName = "fakeFunction"; //$NON-NLS-1$
-
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setFunctionSupport("fakeFunction", true); //$NON-NLS-1$
-
- ArrayList<String> bindings = new ArrayList<String>();
- bindings.add(modelName);
-
- VDBMetaData vdb = Mockito.mock(VDBMetaData.class);
- ModelMetaData model = Mockito.mock(ModelMetaData.class);
- Mockito.stub(vdb.getModel(modelName)).toReturn(model);
- Mockito.stub(model.getSourceNames()).toReturn(bindings);
-
- BasicSourceCapabilities basicSourceCapabilities = new BasicSourceCapabilities();
- basicSourceCapabilities.setFunctionSupport(functionName, true);
-
- ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
- ConnectorManager cm = Mockito.mock(ConnectorManager.class);
- Mockito.stub(cm.getCapabilities()).toReturn(basicSourceCapabilities);
- Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(cm);
-
- CachedFinder finder = new CachedFinder(repo, vdb);
-
- // Test
- SourceCapabilities actual = finder.findCapabilities(modelName);
- assertEquals("Did not get expected capabilities", true, actual.supportsFunction(functionName)); //$NON-NLS-1$
- }
-
-
- 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;
- }
- };
-
- 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$
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,92 @@
+/*
+ * 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.util.ArrayList;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.adminapi.impl.ModelMetaData;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.dqp.internal.datamgr.CapabilitiesConverter;
+import org.teiid.dqp.internal.datamgr.ConnectorManager;
+import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
+import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities;
+import org.teiid.translator.ExecutionFactory;
+import org.teiid.translator.TranslatorException;
+
+
+/**
+ */
+ at SuppressWarnings("nls")
+public class TestConnectorCapabilitiesFinder {
+
+ @Test public void testFind() throws Exception {
+ String modelName = "model"; //$NON-NLS-1$
+ String functionName = "fakeFunction"; //$NON-NLS-1$
+
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setFunctionSupport("fakeFunction", true); //$NON-NLS-1$
+
+ ArrayList<String> bindings = new ArrayList<String>();
+ bindings.add(modelName);
+
+ VDBMetaData vdb = Mockito.mock(VDBMetaData.class);
+ ModelMetaData model = Mockito.mock(ModelMetaData.class);
+ Mockito.stub(vdb.getModel(modelName)).toReturn(model);
+ Mockito.stub(model.getSourceNames()).toReturn(bindings);
+
+ BasicSourceCapabilities basicSourceCapabilities = new BasicSourceCapabilities();
+ basicSourceCapabilities.setFunctionSupport(functionName, true);
+
+ ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
+ ConnectorManager cm = Mockito.mock(ConnectorManager.class);
+ Mockito.stub(cm.getCapabilities()).toReturn(basicSourceCapabilities);
+ Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(cm);
+
+ CachedFinder finder = new CachedFinder(repo, vdb);
+
+ // Test
+ SourceCapabilities actual = finder.findCapabilities(modelName);
+ assertEquals("Did not get expected capabilities", true, actual.supportsFunction(functionName)); //$NON-NLS-1$
+ }
+
+
+ @Test public void testPushdownFunctionSupport() throws Exception {
+ ExecutionFactory<Object, Object> ef = new ExecutionFactory<Object, Object>(){
+
+ @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$
+ assertTrue("Did not get expected capabilities", bsc.supportsFunction("ns.func")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,452 +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 static org.junit.Assert.*;
-
-import java.sql.ResultSet;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.cache.CacheConfiguration;
-import org.teiid.cache.DefaultCacheFactory;
-import org.teiid.client.RequestMessage;
-import org.teiid.client.ResultsMessage;
-import org.teiid.client.RequestMessage.StatementType;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.BufferManagerFactory;
-import org.teiid.common.buffer.impl.BufferManagerImpl;
-import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
-import org.teiid.dqp.internal.datamgr.FakeTransactionService;
-import org.teiid.dqp.internal.process.AbstractWorkItem.ThreadState;
-import org.teiid.dqp.service.AutoGenDataService;
-import org.teiid.dqp.service.BufferService;
-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;
-
- at SuppressWarnings("nls")
-public class TestDQPCore {
-
- 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"));
- context.getVDB().getModel("BQT3").setVisible(false); //$NON-NLS-1$
- context.getVDB().getModel("VQT").setVisible(false); //$NON-NLS-1$
-
- ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
- context.getVDB().addAttchment(ConnectorManagerRepository.class, repo);
- Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(agds);
-
- core = new DQPCore();
- core.setBufferService(new BufferService() {
-
- @Override
- public BufferManager getBufferManager() {
- return BufferManagerFactory.createBufferManager();
- }
- });
- core.setCacheFactory(new DefaultCacheFactory());
- core.setTransactionService(new FakeTransactionService());
-
- config = new DQPConfiguration();
- config.setMaxActivePlans(1);
- config.setUserRequestSourceConcurrency(2);
- config.setResultsetCacheConfig(new CacheConfiguration());
- core.start(config);
- core.getPrepPlanCache().setModTime(1);
- core.getRsCache().setModTime(1);
- }
-
- @After public void tearDown() throws Exception {
- DQPWorkContext.setWorkContext(new DQPWorkContext());
- core.stop();
- }
-
- public RequestMessage exampleRequestMessage(String sql) {
- RequestMessage msg = new RequestMessage(sql);
- msg.setCursorType(ResultSet.TYPE_SCROLL_INSENSITIVE);
- msg.setFetchSize(10);
- msg.setPartialResults(false);
- msg.setExecutionId(100);
- return msg;
- }
-
- @Test public void testConfigurationSets() {
- assertEquals(1, core.getMaxActivePlans());
- assertEquals(2, core.getUserRequestSourceConcurrency());
- }
-
- @Test public void testRequest1() throws Exception {
- helpExecute("SELECT IntKey FROM BQT1.SmallA", "a"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testUser1() throws Exception {
- String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() = 'logon'"; //$NON-NLS-1$
- String userName = "logon"; //$NON-NLS-1$
- helpExecute(sql, userName);
- }
-
- @Test public void testUser2() throws Exception {
- String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() LIKE 'logon'"; //$NON-NLS-1$
- String userName = "logon"; //$NON-NLS-1$
- helpExecute(sql, userName);
- }
-
- @Test public void testUser3() throws Exception {
- String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() IN ('logon3') AND StringKey LIKE '1'"; //$NON-NLS-1$
- String userName = "logon3"; //$NON-NLS-1$
- helpExecute(sql, userName);
- }
-
- @Test public void testUser4() throws Exception {
- String sql = "SELECT IntKey FROM BQT1.SmallA WHERE 'logon4' = user() AND StringKey = '1'"; //$NON-NLS-1$
- String userName = "logon4"; //$NON-NLS-1$
- helpExecute(sql, userName);
- }
-
- @Test public void testUser5() throws Exception {
- String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() IS NULL "; //$NON-NLS-1$
- String userName = "logon"; //$NON-NLS-1$
- helpExecute(sql, userName);
- }
-
- @Test public void testUser6() throws Exception {
- String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() = 'logon33' "; //$NON-NLS-1$
- String userName = "logon"; //$NON-NLS-1$
- helpExecute(sql, userName);
- }
-
- @Test public void testUser7() throws Exception {
- String sql = "UPDATE BQT1.SmallA SET IntKey = 2 WHERE user() = 'logon' AND StringKey = '1' "; //$NON-NLS-1$
- String userName = "logon"; //$NON-NLS-1$
- helpExecute(sql, userName);
- }
-
- @Test public void testUser8() throws Exception {
- String sql = "SELECT user(), StringKey FROM BQT1.SmallA WHERE IntKey = 1 "; //$NON-NLS-1$
- String userName = "logon"; //$NON-NLS-1$
- helpExecute(sql, userName);
- }
-
- @Test public void testUser9() throws Exception {
- String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() = StringKey AND StringKey = '1' "; //$NON-NLS-1$
- String userName = "1"; //$NON-NLS-1$
- helpExecute(sql, userName);
- }
-
- @Test public void testEnvSessionId() throws Exception {
- String sql = "SELECT env('sessionid') as SessionID"; //$NON-NLS-1$
- String userName = "1"; //$NON-NLS-1$
- ResultsMessage rm = helpExecute(sql, userName);
- assertEquals("1", rm.getResults()[0].get(0)); //$NON-NLS-1$
- }
-
- @Test public void testEnvSessionIdMixedCase() throws Exception {
- String sql = "SELECT env('sEsSIonId') as SessionID"; //$NON-NLS-1$
- String userName = "1"; //$NON-NLS-1$
- ResultsMessage rm = helpExecute(sql, userName);
- assertEquals("1", rm.getResults()[0].get(0)); //$NON-NLS-1$
- }
-
- @Test public void testTxnAutoWrap() throws Exception {
- String sql = "SELECT * FROM BQT1.SmallA"; //$NON-NLS-1$
- helpExecute(sql, "a", 1, true); //$NON-NLS-1$
- }
-
- /**
- * Ensures that VQT visibility does not affect the view query
- */
- @Test public void testViewVisibility() throws Exception {
- String sql = "SELECT * FROM VQT.SmallA_2589g"; //$NON-NLS-1$
- helpExecute(sql, "a"); //$NON-NLS-1$
- }
-
- @Test public void testLimitCompensation() throws Exception {
- String sql = "SELECT * FROM VQT.SmallA_2589g LIMIT 1, 1"; //$NON-NLS-1$
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- agds.setCaps(caps);
- ResultsMessage rm = helpExecute(sql, "a"); //$NON-NLS-1$
- //we test for > 0 here because the autogen service doesn't obey the limit
- assertTrue(rm.getResults().length > 0);
- }
-
- @Test public void testLimitCompensation1() throws Exception {
- String sql = "SELECT * FROM VQT.SmallA_2589g LIMIT 1, 1"; //$NON-NLS-1$
- ResultsMessage rm = helpExecute(sql, "a"); //$NON-NLS-1$
- assertEquals(1, rm.getResults().length);
- }
-
-
- /**
- * Tests whether an exception result is sent when an exception occurs
- * @since 4.3
- */
- @Test public void testPlanningException() throws Exception {
- String sql = "SELECT IntKey FROM BQT1.BadIdea "; //$NON-NLS-1$
-
- RequestMessage reqMsg = exampleRequestMessage(sql);
-
- Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
- try {
- message.get(5000, TimeUnit.MILLISECONDS);
- } catch (ExecutionException e) {
- assertTrue(e.getCause() instanceof QueryResolverException);
- }
- }
-
- @Ignore("visibility no longer ristricts access")
- @Test public void testLookupVisibility() throws Exception {
- helpTestVisibilityFails("select lookup('bqt3.smalla', 'intkey', 'stringkey', '?')"); //$NON-NLS-1$
- }
-
- @Test public void testCancel() throws Exception {
- assertFalse(this.core.cancelRequest(1L));
- }
-
- @Test public void testBufferLimit() throws Exception {
- //the sql should return 100 rows
- String sql = "SELECT A.IntKey FROM BQT1.SmallA as A, BQT1.SmallA as B"; //$NON-NLS-1$
- String userName = "1"; //$NON-NLS-1$
- String sessionid = "1"; //$NON-NLS-1$
-
- RequestMessage reqMsg = exampleRequestMessage(sql);
- reqMsg.setCursorType(ResultSet.TYPE_FORWARD_ONLY);
- DQPWorkContext.getWorkContext().getSession().setSessionId(sessionid);
- DQPWorkContext.getWorkContext().getSession().setUserName(userName);
- ((BufferManagerImpl)core.getBufferManager()).setProcessorBatchSize(2);
- Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
- ResultsMessage rm = message.get(500000, TimeUnit.MILLISECONDS);
- assertNull(rm.getException());
- assertEquals(2, rm.getResults().length);
- RequestWorkItem item = core.getRequestWorkItem(DQPWorkContext.getWorkContext().getRequestID(reqMsg.getExecutionId()));
-
- message = core.processCursorRequest(reqMsg.getExecutionId(), 3, 2);
- rm = message.get(500000, TimeUnit.MILLISECONDS);
- assertNull(rm.getException());
- assertEquals(2, rm.getResults().length);
- //ensure that we are idle
- for (int i = 0; i < 10 && item.getThreadState() != ThreadState.IDLE; i++) {
- Thread.sleep(100);
- }
- assertEquals(ThreadState.IDLE, item.getThreadState());
- assertTrue(item.resultsBuffer.getManagedRowCount() <= 46);
- //pull the rest of the results
- for (int j = 0; j < 48; j++) {
- item = core.getRequestWorkItem(DQPWorkContext.getWorkContext().getRequestID(reqMsg.getExecutionId()));
-
- message = core.processCursorRequest(reqMsg.getExecutionId(), j * 2 + 5, 2);
- rm = message.get(5000, TimeUnit.MILLISECONDS);
- assertNull(rm.getException());
- assertEquals(2, rm.getResults().length);
- }
- }
-
- @Test public void testBufferReuse() throws Exception {
- //the sql should return 100 rows
- String sql = "SELECT A.IntKey FROM BQT1.SmallA as A, BQT1.SmallA as B ORDER BY A.IntKey"; //$NON-NLS-1$
- String userName = "1"; //$NON-NLS-1$
- String sessionid = "1"; //$NON-NLS-1$
-
- RequestMessage reqMsg = exampleRequestMessage(sql);
- reqMsg.setCursorType(ResultSet.TYPE_FORWARD_ONLY);
- DQPWorkContext.getWorkContext().getSession().setSessionId(sessionid);
- DQPWorkContext.getWorkContext().getSession().setUserName(userName);
- ((BufferManagerImpl)core.getBufferManager()).setProcessorBatchSize(2);
- Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
- ResultsMessage rm = message.get(500000, TimeUnit.MILLISECONDS);
- assertNull(rm.getException());
- assertEquals(2, rm.getResults().length);
- RequestWorkItem item = core.getRequestWorkItem(DQPWorkContext.getWorkContext().getRequestID(reqMsg.getExecutionId()));
- assertEquals(100, item.resultsBuffer.getRowCount());
- }
-
- @Test public void testSourceConcurrency() throws Exception {
- //setup default of 2
- agds.setSleep(100);
- StringBuffer sql = new StringBuffer();
- int branches = 20;
- for (int i = 0; i < branches; i++) {
- if (i > 0) {
- sql.append(" union all ");
- }
- sql.append("select intkey || " + i + " from bqt1.smalla");
- }
- sql.append(" limit 2");
- helpExecute(sql.toString(), "a");
- //there's isn't a hard guarantee that only two requests will get started
- assertTrue(agds.getExecuteCount().get() <= 6);
-
- //20 concurrent
- core.setUserRequestSourceConcurrency(20);
- agds.getExecuteCount().set(0);
- helpExecute(sql.toString(), "a");
- assertTrue(agds.getExecuteCount().get() <= 20);
- assertTrue(agds.getExecuteCount().get() > 10);
-
- //serial
- core.setUserRequestSourceConcurrency(1);
- agds.getExecuteCount().set(0);
- helpExecute(sql.toString(), "a");
- assertEquals(1, agds.getExecuteCount().get());
- }
-
- @Test public void testPreparedPlanInvalidation() throws Exception {
- String sql = "insert into #temp select * FROM vqt.SmallB"; //$NON-NLS-1$
- String userName = "1"; //$NON-NLS-1$
- int sessionid = 1; //$NON-NLS-1$
- RequestMessage reqMsg = exampleRequestMessage(sql);
- ResultsMessage rm = execute(userName, sessionid, reqMsg);
- assertEquals(1, rm.getResults().length); //$NON-NLS-1$
-
- sql = "select * from #temp"; //$NON-NLS-1$
- reqMsg = exampleRequestMessage(sql);
- reqMsg.setStatementType(StatementType.PREPARED);
- rm = execute(userName, sessionid, reqMsg);
- assertEquals(10, rm.getResults().length); //$NON-NLS-1$
-
- sql = "select * from #temp"; //$NON-NLS-1$
- reqMsg = exampleRequestMessage(sql);
- reqMsg.setStatementType(StatementType.PREPARED);
- rm = execute(userName, sessionid, reqMsg);
- assertEquals(10, rm.getResults().length); //$NON-NLS-1$
-
- assertEquals(1, this.core.getPrepPlanCache().getCacheHitCount());
-
- Thread.sleep(100);
-
- //perform a minor update, we should still use the cache
- sql = "delete from #temp where a12345 = '11'"; //$NON-NLS-1$
- reqMsg = exampleRequestMessage(sql);
- rm = execute(userName, sessionid, reqMsg);
- assertEquals(1, rm.getResults().length); //$NON-NLS-1$
-
- sql = "select * from #temp"; //$NON-NLS-1$
- reqMsg = exampleRequestMessage(sql);
- reqMsg.setStatementType(StatementType.PREPARED);
- rm = execute(userName, sessionid, reqMsg);
- assertEquals(10, rm.getResults().length); //$NON-NLS-1$
-
- assertEquals(2, this.core.getPrepPlanCache().getCacheHitCount());
-
- //perform a major update, we will purge the plan
- sql = "delete from #temp"; //$NON-NLS-1$
- reqMsg = exampleRequestMessage(sql);
- rm = execute(userName, sessionid, reqMsg);
- assertEquals(1, rm.getResults().length); //$NON-NLS-1$
-
- sql = "select * from #temp"; //$NON-NLS-1$
- reqMsg = exampleRequestMessage(sql);
- reqMsg.setStatementType(StatementType.PREPARED);
- rm = execute(userName, sessionid, reqMsg);
- assertEquals(0, rm.getResults().length); //$NON-NLS-1$
-
- assertEquals(2, this.core.getPrepPlanCache().getCacheHitCount());
- }
-
- @Test public void testRsCacheInvalidation() throws Exception {
- String sql = "select * FROM vqt.SmallB"; //$NON-NLS-1$
- String userName = "1"; //$NON-NLS-1$
- int sessionid = 1; //$NON-NLS-1$
- RequestMessage reqMsg = exampleRequestMessage(sql);
- reqMsg.setUseResultSetCache(true);
- ResultsMessage rm = execute(userName, sessionid, reqMsg);
- assertEquals(10, rm.getResults().length); //$NON-NLS-1$
-
- sql = "select * FROM vqt.SmallB"; //$NON-NLS-1$
- reqMsg = exampleRequestMessage(sql);
- reqMsg.setUseResultSetCache(true);
- rm = execute(userName, sessionid, reqMsg);
- assertEquals(10, rm.getResults().length); //$NON-NLS-1$
-
- assertEquals(1, this.core.getRsCache().getCacheHitCount());
-
- Thread.sleep(100);
-
- sql = "delete from bqt1.smalla"; //$NON-NLS-1$
- reqMsg = exampleRequestMessage(sql);
- rm = execute(userName, sessionid, reqMsg);
- assertEquals(1, rm.getResults().length); //$NON-NLS-1$
-
- sql = "select * FROM vqt.SmallB"; //$NON-NLS-1$
- reqMsg = exampleRequestMessage(sql);
- reqMsg.setUseResultSetCache(true);
- rm = execute(userName, sessionid, reqMsg);
- assertEquals(10, rm.getResults().length); //$NON-NLS-1$
-
- assertEquals(1, this.core.getRsCache().getCacheHitCount());
- }
-
- public void helpTestVisibilityFails(String sql) throws Exception {
- RequestMessage reqMsg = exampleRequestMessage(sql);
- reqMsg.setTxnAutoWrapMode(RequestMessage.TXN_WRAP_OFF);
- Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
- ResultsMessage results = message.get(5000, TimeUnit.MILLISECONDS);
- assertEquals("[QueryValidatorException]Group does not exist: BQT3.SmallA", results.getException().toString()); //$NON-NLS-1$
- }
-
- ///////////////////////////Helper method///////////////////////////////////
- private ResultsMessage helpExecute(String sql, String userName) throws Exception {
- return helpExecute(sql, userName, 1, false);
- }
-
- private ResultsMessage helpExecute(String sql, String userName, int sessionid, boolean txnAutoWrap) throws Exception {
- RequestMessage reqMsg = exampleRequestMessage(sql);
- if (txnAutoWrap) {
- reqMsg.setTxnAutoWrapMode(RequestMessage.TXN_WRAP_ON);
- }
- ResultsMessage results = execute(userName, sessionid, reqMsg);
- core.terminateSession(String.valueOf(sessionid));
- assertNull(core.getClientState(String.valueOf(sessionid), false));
- if (results.getException() != null) {
- throw results.getException();
- }
- return results;
- }
-
- private ResultsMessage execute(String userName, int sessionid, RequestMessage reqMsg)
- throws InterruptedException, ExecutionException, TimeoutException {
- DQPWorkContext.getWorkContext().getSession().setSessionId(String.valueOf(sessionid));
- DQPWorkContext.getWorkContext().getSession().setUserName(userName);
-
- Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
- assertNotNull(core.getClientState(String.valueOf(sessionid), false));
- ResultsMessage results = message.get(500000, TimeUnit.MILLISECONDS);
- return results;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,451 @@
+/*
+ * 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.sql.ResultSet;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.cache.CacheConfiguration;
+import org.teiid.cache.DefaultCacheFactory;
+import org.teiid.client.RequestMessage;
+import org.teiid.client.ResultsMessage;
+import org.teiid.client.RequestMessage.StatementType;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.BufferManagerFactory;
+import org.teiid.common.buffer.impl.BufferManagerImpl;
+import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
+import org.teiid.dqp.internal.datamgr.FakeTransactionService;
+import org.teiid.dqp.internal.process.AbstractWorkItem.ThreadState;
+import org.teiid.dqp.service.AutoGenDataService;
+import org.teiid.dqp.service.BufferService;
+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.RealMetadataFactory;
+
+ at SuppressWarnings("nls")
+public class TestDQPCore {
+
+ private DQPCore core;
+ private DQPConfiguration config;
+ private AutoGenDataService agds;
+
+ @Before public void setUp() throws Exception {
+ agds = new AutoGenDataService();
+ 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$
+
+ ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
+ context.getVDB().addAttchment(ConnectorManagerRepository.class, repo);
+ Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(agds);
+
+ core = new DQPCore();
+ core.setBufferService(new BufferService() {
+
+ @Override
+ public BufferManager getBufferManager() {
+ return BufferManagerFactory.createBufferManager();
+ }
+ });
+ core.setCacheFactory(new DefaultCacheFactory());
+ core.setTransactionService(new FakeTransactionService());
+
+ config = new DQPConfiguration();
+ config.setMaxActivePlans(1);
+ config.setUserRequestSourceConcurrency(2);
+ config.setResultsetCacheConfig(new CacheConfiguration());
+ core.start(config);
+ core.getPrepPlanCache().setModTime(1);
+ core.getRsCache().setModTime(1);
+ }
+
+ @After public void tearDown() throws Exception {
+ DQPWorkContext.setWorkContext(new DQPWorkContext());
+ core.stop();
+ }
+
+ public RequestMessage exampleRequestMessage(String sql) {
+ RequestMessage msg = new RequestMessage(sql);
+ msg.setCursorType(ResultSet.TYPE_SCROLL_INSENSITIVE);
+ msg.setFetchSize(10);
+ msg.setPartialResults(false);
+ msg.setExecutionId(100);
+ return msg;
+ }
+
+ @Test public void testConfigurationSets() {
+ assertEquals(1, core.getMaxActivePlans());
+ assertEquals(2, core.getUserRequestSourceConcurrency());
+ }
+
+ @Test public void testRequest1() throws Exception {
+ helpExecute("SELECT IntKey FROM BQT1.SmallA", "a"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testUser1() throws Exception {
+ String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() = 'logon'"; //$NON-NLS-1$
+ String userName = "logon"; //$NON-NLS-1$
+ helpExecute(sql, userName);
+ }
+
+ @Test public void testUser2() throws Exception {
+ String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() LIKE 'logon'"; //$NON-NLS-1$
+ String userName = "logon"; //$NON-NLS-1$
+ helpExecute(sql, userName);
+ }
+
+ @Test public void testUser3() throws Exception {
+ String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() IN ('logon3') AND StringKey LIKE '1'"; //$NON-NLS-1$
+ String userName = "logon3"; //$NON-NLS-1$
+ helpExecute(sql, userName);
+ }
+
+ @Test public void testUser4() throws Exception {
+ String sql = "SELECT IntKey FROM BQT1.SmallA WHERE 'logon4' = user() AND StringKey = '1'"; //$NON-NLS-1$
+ String userName = "logon4"; //$NON-NLS-1$
+ helpExecute(sql, userName);
+ }
+
+ @Test public void testUser5() throws Exception {
+ String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() IS NULL "; //$NON-NLS-1$
+ String userName = "logon"; //$NON-NLS-1$
+ helpExecute(sql, userName);
+ }
+
+ @Test public void testUser6() throws Exception {
+ String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() = 'logon33' "; //$NON-NLS-1$
+ String userName = "logon"; //$NON-NLS-1$
+ helpExecute(sql, userName);
+ }
+
+ @Test public void testUser7() throws Exception {
+ String sql = "UPDATE BQT1.SmallA SET IntKey = 2 WHERE user() = 'logon' AND StringKey = '1' "; //$NON-NLS-1$
+ String userName = "logon"; //$NON-NLS-1$
+ helpExecute(sql, userName);
+ }
+
+ @Test public void testUser8() throws Exception {
+ String sql = "SELECT user(), StringKey FROM BQT1.SmallA WHERE IntKey = 1 "; //$NON-NLS-1$
+ String userName = "logon"; //$NON-NLS-1$
+ helpExecute(sql, userName);
+ }
+
+ @Test public void testUser9() throws Exception {
+ String sql = "SELECT IntKey FROM BQT1.SmallA WHERE user() = StringKey AND StringKey = '1' "; //$NON-NLS-1$
+ String userName = "1"; //$NON-NLS-1$
+ helpExecute(sql, userName);
+ }
+
+ @Test public void testEnvSessionId() throws Exception {
+ String sql = "SELECT env('sessionid') as SessionID"; //$NON-NLS-1$
+ String userName = "1"; //$NON-NLS-1$
+ ResultsMessage rm = helpExecute(sql, userName);
+ assertEquals("1", rm.getResults()[0].get(0)); //$NON-NLS-1$
+ }
+
+ @Test public void testEnvSessionIdMixedCase() throws Exception {
+ String sql = "SELECT env('sEsSIonId') as SessionID"; //$NON-NLS-1$
+ String userName = "1"; //$NON-NLS-1$
+ ResultsMessage rm = helpExecute(sql, userName);
+ assertEquals("1", rm.getResults()[0].get(0)); //$NON-NLS-1$
+ }
+
+ @Test public void testTxnAutoWrap() throws Exception {
+ String sql = "SELECT * FROM BQT1.SmallA"; //$NON-NLS-1$
+ helpExecute(sql, "a", 1, true); //$NON-NLS-1$
+ }
+
+ /**
+ * Ensures that VQT visibility does not affect the view query
+ */
+ @Test public void testViewVisibility() throws Exception {
+ String sql = "SELECT * FROM VQT.SmallA_2589g"; //$NON-NLS-1$
+ helpExecute(sql, "a"); //$NON-NLS-1$
+ }
+
+ @Test public void testLimitCompensation() throws Exception {
+ String sql = "SELECT * FROM VQT.SmallA_2589g LIMIT 1, 1"; //$NON-NLS-1$
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ agds.setCaps(caps);
+ ResultsMessage rm = helpExecute(sql, "a"); //$NON-NLS-1$
+ //we test for > 0 here because the autogen service doesn't obey the limit
+ assertTrue(rm.getResults().length > 0);
+ }
+
+ @Test public void testLimitCompensation1() throws Exception {
+ String sql = "SELECT * FROM VQT.SmallA_2589g LIMIT 1, 1"; //$NON-NLS-1$
+ ResultsMessage rm = helpExecute(sql, "a"); //$NON-NLS-1$
+ assertEquals(1, rm.getResults().length);
+ }
+
+
+ /**
+ * Tests whether an exception result is sent when an exception occurs
+ * @since 4.3
+ */
+ @Test public void testPlanningException() throws Exception {
+ String sql = "SELECT IntKey FROM BQT1.BadIdea "; //$NON-NLS-1$
+
+ RequestMessage reqMsg = exampleRequestMessage(sql);
+
+ Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
+ try {
+ message.get(5000, TimeUnit.MILLISECONDS);
+ } catch (ExecutionException e) {
+ assertTrue(e.getCause() instanceof QueryResolverException);
+ }
+ }
+
+ @Ignore("visibility no longer ristricts access")
+ @Test public void testLookupVisibility() throws Exception {
+ helpTestVisibilityFails("select lookup('bqt3.smalla', 'intkey', 'stringkey', '?')"); //$NON-NLS-1$
+ }
+
+ @Test public void testCancel() throws Exception {
+ assertFalse(this.core.cancelRequest(1L));
+ }
+
+ @Test public void testBufferLimit() throws Exception {
+ //the sql should return 100 rows
+ String sql = "SELECT A.IntKey FROM BQT1.SmallA as A, BQT1.SmallA as B"; //$NON-NLS-1$
+ String userName = "1"; //$NON-NLS-1$
+ String sessionid = "1"; //$NON-NLS-1$
+
+ RequestMessage reqMsg = exampleRequestMessage(sql);
+ reqMsg.setCursorType(ResultSet.TYPE_FORWARD_ONLY);
+ DQPWorkContext.getWorkContext().getSession().setSessionId(sessionid);
+ DQPWorkContext.getWorkContext().getSession().setUserName(userName);
+ ((BufferManagerImpl)core.getBufferManager()).setProcessorBatchSize(2);
+ Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
+ ResultsMessage rm = message.get(500000, TimeUnit.MILLISECONDS);
+ assertNull(rm.getException());
+ assertEquals(2, rm.getResults().length);
+ RequestWorkItem item = core.getRequestWorkItem(DQPWorkContext.getWorkContext().getRequestID(reqMsg.getExecutionId()));
+
+ message = core.processCursorRequest(reqMsg.getExecutionId(), 3, 2);
+ rm = message.get(500000, TimeUnit.MILLISECONDS);
+ assertNull(rm.getException());
+ assertEquals(2, rm.getResults().length);
+ //ensure that we are idle
+ for (int i = 0; i < 10 && item.getThreadState() != ThreadState.IDLE; i++) {
+ Thread.sleep(100);
+ }
+ assertEquals(ThreadState.IDLE, item.getThreadState());
+ assertTrue(item.resultsBuffer.getManagedRowCount() <= 46);
+ //pull the rest of the results
+ for (int j = 0; j < 48; j++) {
+ item = core.getRequestWorkItem(DQPWorkContext.getWorkContext().getRequestID(reqMsg.getExecutionId()));
+
+ message = core.processCursorRequest(reqMsg.getExecutionId(), j * 2 + 5, 2);
+ rm = message.get(5000, TimeUnit.MILLISECONDS);
+ assertNull(rm.getException());
+ assertEquals(2, rm.getResults().length);
+ }
+ }
+
+ @Test public void testBufferReuse() throws Exception {
+ //the sql should return 100 rows
+ String sql = "SELECT A.IntKey FROM BQT1.SmallA as A, BQT1.SmallA as B ORDER BY A.IntKey"; //$NON-NLS-1$
+ String userName = "1"; //$NON-NLS-1$
+ String sessionid = "1"; //$NON-NLS-1$
+
+ RequestMessage reqMsg = exampleRequestMessage(sql);
+ reqMsg.setCursorType(ResultSet.TYPE_FORWARD_ONLY);
+ DQPWorkContext.getWorkContext().getSession().setSessionId(sessionid);
+ DQPWorkContext.getWorkContext().getSession().setUserName(userName);
+ ((BufferManagerImpl)core.getBufferManager()).setProcessorBatchSize(2);
+ Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
+ ResultsMessage rm = message.get(500000, TimeUnit.MILLISECONDS);
+ assertNull(rm.getException());
+ assertEquals(2, rm.getResults().length);
+ RequestWorkItem item = core.getRequestWorkItem(DQPWorkContext.getWorkContext().getRequestID(reqMsg.getExecutionId()));
+ assertEquals(100, item.resultsBuffer.getRowCount());
+ }
+
+ @Test public void testSourceConcurrency() throws Exception {
+ //setup default of 2
+ agds.setSleep(100);
+ StringBuffer sql = new StringBuffer();
+ int branches = 20;
+ for (int i = 0; i < branches; i++) {
+ if (i > 0) {
+ sql.append(" union all ");
+ }
+ sql.append("select intkey || " + i + " from bqt1.smalla");
+ }
+ sql.append(" limit 2");
+ helpExecute(sql.toString(), "a");
+ //there's isn't a hard guarantee that only two requests will get started
+ assertTrue(agds.getExecuteCount().get() <= 6);
+
+ //20 concurrent
+ core.setUserRequestSourceConcurrency(20);
+ agds.getExecuteCount().set(0);
+ helpExecute(sql.toString(), "a");
+ assertTrue(agds.getExecuteCount().get() <= 20);
+ assertTrue(agds.getExecuteCount().get() > 10);
+
+ //serial
+ core.setUserRequestSourceConcurrency(1);
+ agds.getExecuteCount().set(0);
+ helpExecute(sql.toString(), "a");
+ assertEquals(1, agds.getExecuteCount().get());
+ }
+
+ @Test public void testPreparedPlanInvalidation() throws Exception {
+ String sql = "insert into #temp select * FROM vqt.SmallB"; //$NON-NLS-1$
+ String userName = "1"; //$NON-NLS-1$
+ int sessionid = 1; //$NON-NLS-1$
+ RequestMessage reqMsg = exampleRequestMessage(sql);
+ ResultsMessage rm = execute(userName, sessionid, reqMsg);
+ assertEquals(1, rm.getResults().length); //$NON-NLS-1$
+
+ sql = "select * from #temp"; //$NON-NLS-1$
+ reqMsg = exampleRequestMessage(sql);
+ reqMsg.setStatementType(StatementType.PREPARED);
+ rm = execute(userName, sessionid, reqMsg);
+ assertEquals(10, rm.getResults().length); //$NON-NLS-1$
+
+ sql = "select * from #temp"; //$NON-NLS-1$
+ reqMsg = exampleRequestMessage(sql);
+ reqMsg.setStatementType(StatementType.PREPARED);
+ rm = execute(userName, sessionid, reqMsg);
+ assertEquals(10, rm.getResults().length); //$NON-NLS-1$
+
+ assertEquals(1, this.core.getPrepPlanCache().getCacheHitCount());
+
+ Thread.sleep(100);
+
+ //perform a minor update, we should still use the cache
+ sql = "delete from #temp where a12345 = '11'"; //$NON-NLS-1$
+ reqMsg = exampleRequestMessage(sql);
+ rm = execute(userName, sessionid, reqMsg);
+ assertEquals(1, rm.getResults().length); //$NON-NLS-1$
+
+ sql = "select * from #temp"; //$NON-NLS-1$
+ reqMsg = exampleRequestMessage(sql);
+ reqMsg.setStatementType(StatementType.PREPARED);
+ rm = execute(userName, sessionid, reqMsg);
+ assertEquals(10, rm.getResults().length); //$NON-NLS-1$
+
+ assertEquals(2, this.core.getPrepPlanCache().getCacheHitCount());
+
+ //perform a major update, we will purge the plan
+ sql = "delete from #temp"; //$NON-NLS-1$
+ reqMsg = exampleRequestMessage(sql);
+ rm = execute(userName, sessionid, reqMsg);
+ assertEquals(1, rm.getResults().length); //$NON-NLS-1$
+
+ sql = "select * from #temp"; //$NON-NLS-1$
+ reqMsg = exampleRequestMessage(sql);
+ reqMsg.setStatementType(StatementType.PREPARED);
+ rm = execute(userName, sessionid, reqMsg);
+ assertEquals(0, rm.getResults().length); //$NON-NLS-1$
+
+ assertEquals(2, this.core.getPrepPlanCache().getCacheHitCount());
+ }
+
+ @Test public void testRsCacheInvalidation() throws Exception {
+ String sql = "select * FROM vqt.SmallB"; //$NON-NLS-1$
+ String userName = "1"; //$NON-NLS-1$
+ int sessionid = 1; //$NON-NLS-1$
+ RequestMessage reqMsg = exampleRequestMessage(sql);
+ reqMsg.setUseResultSetCache(true);
+ ResultsMessage rm = execute(userName, sessionid, reqMsg);
+ assertEquals(10, rm.getResults().length); //$NON-NLS-1$
+
+ sql = "select * FROM vqt.SmallB"; //$NON-NLS-1$
+ reqMsg = exampleRequestMessage(sql);
+ reqMsg.setUseResultSetCache(true);
+ rm = execute(userName, sessionid, reqMsg);
+ assertEquals(10, rm.getResults().length); //$NON-NLS-1$
+
+ assertEquals(1, this.core.getRsCache().getCacheHitCount());
+
+ Thread.sleep(100);
+
+ sql = "delete from bqt1.smalla"; //$NON-NLS-1$
+ reqMsg = exampleRequestMessage(sql);
+ rm = execute(userName, sessionid, reqMsg);
+ assertEquals(1, rm.getResults().length); //$NON-NLS-1$
+
+ sql = "select * FROM vqt.SmallB"; //$NON-NLS-1$
+ reqMsg = exampleRequestMessage(sql);
+ reqMsg.setUseResultSetCache(true);
+ rm = execute(userName, sessionid, reqMsg);
+ assertEquals(10, rm.getResults().length); //$NON-NLS-1$
+
+ assertEquals(1, this.core.getRsCache().getCacheHitCount());
+ }
+
+ public void helpTestVisibilityFails(String sql) throws Exception {
+ RequestMessage reqMsg = exampleRequestMessage(sql);
+ reqMsg.setTxnAutoWrapMode(RequestMessage.TXN_WRAP_OFF);
+ Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
+ ResultsMessage results = message.get(5000, TimeUnit.MILLISECONDS);
+ assertEquals("[QueryValidatorException]Group does not exist: BQT3.SmallA", results.getException().toString()); //$NON-NLS-1$
+ }
+
+ ///////////////////////////Helper method///////////////////////////////////
+ private ResultsMessage helpExecute(String sql, String userName) throws Exception {
+ return helpExecute(sql, userName, 1, false);
+ }
+
+ private ResultsMessage helpExecute(String sql, String userName, int sessionid, boolean txnAutoWrap) throws Exception {
+ RequestMessage reqMsg = exampleRequestMessage(sql);
+ if (txnAutoWrap) {
+ reqMsg.setTxnAutoWrapMode(RequestMessage.TXN_WRAP_ON);
+ }
+ ResultsMessage results = execute(userName, sessionid, reqMsg);
+ core.terminateSession(String.valueOf(sessionid));
+ assertNull(core.getClientState(String.valueOf(sessionid), false));
+ if (results.getException() != null) {
+ throw results.getException();
+ }
+ return results;
+ }
+
+ private ResultsMessage execute(String userName, int sessionid, RequestMessage reqMsg)
+ throws InterruptedException, ExecutionException, TimeoutException {
+ DQPWorkContext.getWorkContext().getSession().setSessionId(String.valueOf(sessionid));
+ DQPWorkContext.getWorkContext().getSession().setUserName(userName);
+
+ Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
+ assertNotNull(core.getClientState(String.valueOf(sessionid), false));
+ ResultsMessage results = message.get(500000, TimeUnit.MILLISECONDS);
+ return results;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,171 +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 static org.junit.Assert.*;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.cache.DefaultCacheFactory;
-import org.teiid.client.RequestMessage;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
-import org.teiid.dqp.internal.datamgr.FakeTransactionService;
-import org.teiid.dqp.message.AtomicRequestMessage;
-import org.teiid.dqp.message.RequestID;
-import org.teiid.dqp.service.AutoGenDataService;
-import org.teiid.dqp.service.FakeBufferService;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
-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.util.CommandContext;
-
-public class TestDataTierManager {
-
- private DQPCore rm;
- private DataTierManagerImpl dtm;
- private CommandContext context;
- private AtomicRequestMessage request;
- private Command command;
- private DataTierTupleSource info;
- private AutoGenDataService connectorManager = new AutoGenDataService();
- private RequestWorkItem workItem;
- private int limit = -1;
-
- @Before public void setUp() {
- limit = -1;
- connectorManager = new AutoGenDataService();
- }
-
- private static Command helpGetCommand(String sql, QueryMetadataInterface metadata) throws Exception {
- Command command = QueryParser.getQueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(command, metadata);
- return command;
- }
-
- private void helpSetup(int nodeId) throws Exception {
- helpSetup("SELECT * FROM BQT1.SmallA", nodeId); //$NON-NLS-1$
- }
-
- private void helpSetup(String sql, int nodeId) throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
- DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, FakeMetadataFactory.exampleBQTVDB());
-
- rm = new DQPCore();
- rm.setTransactionService(new FakeTransactionService());
- rm.setBufferService(new FakeBufferService());
- rm.setCacheFactory(new DefaultCacheFactory());
- rm.start(new DQPConfiguration());
- FakeBufferService bs = new FakeBufferService();
-
- ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
- Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(connectorManager);
-
-
- dtm = new DataTierManagerImpl(rm,
- bs, true);
- command = helpGetCommand(sql, metadata);
-
- RequestMessage original = new RequestMessage();
- original.setExecutionId(1);
- original.setPartialResults(true);
- RequestID requestID = workContext.getRequestID(original.getExecutionId());
-
- context = new CommandContext();
- context.setProcessorID(requestID);
- context.setVdbName("test"); //$NON-NLS-1$
- context.setVdbVersion(1);
- context.setQueryProcessorFactory(new QueryProcessorFactoryImpl(bs.getBufferManager(), dtm, new DefaultCapabilitiesFinder(), null, metadata));
- workItem = TestDQPCoreRequestHandling.addRequest(rm, original, requestID, null, workContext);
-
- request = new AtomicRequestMessage(original, workContext, nodeId);
- request.setCommand(command);
- request.setConnectorName("FakeConnectorID"); //$NON-NLS-1$
- info = new DataTierTupleSource(request, workItem, connectorManager.registerRequest(request), dtm, limit);
- }
-
- @Test public void testDataTierTupleSource() throws Exception {
- helpSetup(1);
- for (int i = 0; i < 10;) {
- try {
- info.nextTuple();
- i++;
- } catch (BlockedException e) {
- Thread.sleep(50);
- }
- }
- assertNotNull(workItem.getConnectorRequest(request.getAtomicRequestID()));
- assertNull(info.nextTuple());
- info.closeSource();
- assertNull(workItem.getConnectorRequest(request.getAtomicRequestID()));
- }
-
- @Test public void testDataTierTupleSourceLimit() throws Exception {
- limit = 1;
- helpSetup(1);
- for (int i = 0; i < 1;) {
- try {
- info.nextTuple();
- i++;
- } catch (BlockedException e) {
- Thread.sleep(50);
- }
- }
- assertNotNull(workItem.getConnectorRequest(request.getAtomicRequestID()));
- assertNull(info.nextTuple());
- info.closeSource();
- assertNull(workItem.getConnectorRequest(request.getAtomicRequestID()));
- }
-
- @Test public void testPartialResults() throws Exception {
- helpSetup(1);
- connectorManager.throwExceptionOnExecute = true;
- for (int i = 0; i < 10; i++) {
- try {
- assertNull(info.nextTuple());
- return;
- } catch (BlockedException e) {
- Thread.sleep(50);
- }
- }
- fail();
- }
-
- @Test public void testNoRowsException() throws Exception {
- this.connectorManager.setRows(0);
- helpSetup(3);
- while (true) {
- try {
- assertNull(info.nextTuple());
- break;
- } catch (BlockedException e) {
- Thread.sleep(50);
- }
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,171 @@
+/*
+ * 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 org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.cache.DefaultCacheFactory;
+import org.teiid.client.RequestMessage;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
+import org.teiid.dqp.internal.datamgr.FakeTransactionService;
+import org.teiid.dqp.message.AtomicRequestMessage;
+import org.teiid.dqp.message.RequestID;
+import org.teiid.dqp.service.AutoGenDataService;
+import org.teiid.dqp.service.FakeBufferService;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+public class TestDataTierManager {
+
+ private DQPCore rm;
+ private DataTierManagerImpl dtm;
+ private CommandContext context;
+ private AtomicRequestMessage request;
+ private Command command;
+ private DataTierTupleSource info;
+ private AutoGenDataService connectorManager = new AutoGenDataService();
+ private RequestWorkItem workItem;
+ private int limit = -1;
+
+ @Before public void setUp() {
+ limit = -1;
+ connectorManager = new AutoGenDataService();
+ }
+
+ private static Command helpGetCommand(String sql, QueryMetadataInterface metadata) throws Exception {
+ Command command = QueryParser.getQueryParser().parseCommand(sql);
+ QueryResolver.resolveCommand(command, metadata);
+ return command;
+ }
+
+ private void helpSetup(int nodeId) throws Exception {
+ helpSetup("SELECT * FROM BQT1.SmallA", nodeId); //$NON-NLS-1$
+ }
+
+ private void helpSetup(String sql, int nodeId) throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+ DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(metadata, RealMetadataFactory.exampleBQTVDB());
+
+ rm = new DQPCore();
+ rm.setTransactionService(new FakeTransactionService());
+ rm.setBufferService(new FakeBufferService());
+ rm.setCacheFactory(new DefaultCacheFactory());
+ rm.start(new DQPConfiguration());
+ FakeBufferService bs = new FakeBufferService();
+
+ ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
+ Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(connectorManager);
+
+
+ dtm = new DataTierManagerImpl(rm,
+ bs, true);
+ command = helpGetCommand(sql, metadata);
+
+ RequestMessage original = new RequestMessage();
+ original.setExecutionId(1);
+ original.setPartialResults(true);
+ RequestID requestID = workContext.getRequestID(original.getExecutionId());
+
+ context = new CommandContext();
+ context.setProcessorID(requestID);
+ context.setVdbName("test"); //$NON-NLS-1$
+ context.setVdbVersion(1);
+ context.setQueryProcessorFactory(new QueryProcessorFactoryImpl(bs.getBufferManager(), dtm, new DefaultCapabilitiesFinder(), null, metadata));
+ workItem = TestDQPCoreRequestHandling.addRequest(rm, original, requestID, null, workContext);
+
+ request = new AtomicRequestMessage(original, workContext, nodeId);
+ request.setCommand(command);
+ request.setConnectorName("FakeConnectorID"); //$NON-NLS-1$
+ info = new DataTierTupleSource(request, workItem, connectorManager.registerRequest(request), dtm, limit);
+ }
+
+ @Test public void testDataTierTupleSource() throws Exception {
+ helpSetup(1);
+ for (int i = 0; i < 10;) {
+ try {
+ info.nextTuple();
+ i++;
+ } catch (BlockedException e) {
+ Thread.sleep(50);
+ }
+ }
+ assertNotNull(workItem.getConnectorRequest(request.getAtomicRequestID()));
+ assertNull(info.nextTuple());
+ info.closeSource();
+ assertNull(workItem.getConnectorRequest(request.getAtomicRequestID()));
+ }
+
+ @Test public void testDataTierTupleSourceLimit() throws Exception {
+ limit = 1;
+ helpSetup(1);
+ for (int i = 0; i < 1;) {
+ try {
+ info.nextTuple();
+ i++;
+ } catch (BlockedException e) {
+ Thread.sleep(50);
+ }
+ }
+ assertNotNull(workItem.getConnectorRequest(request.getAtomicRequestID()));
+ assertNull(info.nextTuple());
+ info.closeSource();
+ assertNull(workItem.getConnectorRequest(request.getAtomicRequestID()));
+ }
+
+ @Test public void testPartialResults() throws Exception {
+ helpSetup(1);
+ connectorManager.throwExceptionOnExecute = true;
+ for (int i = 0; i < 10; i++) {
+ try {
+ assertNull(info.nextTuple());
+ return;
+ } catch (BlockedException e) {
+ Thread.sleep(50);
+ }
+ }
+ fail();
+ }
+
+ @Test public void testNoRowsException() throws Exception {
+ this.connectorManager.setRows(0);
+ helpSetup(3);
+ while (true) {
+ try {
+ assertNull(info.nextTuple());
+ break;
+ } catch (BlockedException e) {
+ Thread.sleep(50);
+ }
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,225 +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 static org.junit.Assert.*;
-
-import java.util.Map;
-import java.util.Set;
-
-import org.junit.Test;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.client.RequestMessage;
-import org.teiid.client.metadata.MetadataResult;
-import org.teiid.client.metadata.ResultsMetadataConstants;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.dqp.internal.datamgr.FakeTransactionService;
-import org.teiid.dqp.message.RequestID;
-import org.teiid.query.metadata.QueryMetadataInterface;
-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;
-
-
-/**
- */
- at SuppressWarnings({"nls", "unchecked"})
-public class TestMetaDataProcessor {
-
- public Map[] helpGetMetadata(String sql, QueryMetadataInterface metadata, VDBMetaData vdb) throws Exception {
- // Prepare sql
- Command command = QueryParser.getQueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(command, metadata);
-
- // Create components
- SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
- DQPCore requestMgr = new DQPCore();
- requestMgr.setTransactionService(new FakeTransactionService());
-
- DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, vdb);
-
- // Initialize components
- RequestID requestID = workContext.getRequestID(1);
- RequestMessage requestMsg = new RequestMessage(sql);
- TestDQPCoreRequestHandling.addRequest(requestMgr, requestMsg, requestID, command, null);
-
- MetaDataProcessor mdProc = new MetaDataProcessor(requestMgr, prepPlanCache, "MyVDB", 1);
-
- return mdProc.processMessage(requestID, workContext, null, true).getColumnMetadata();
- }
-
- @Test public void testSimpleQuery() throws Exception {
- Map[] metadata = helpGetMetadata("SELECT e1 FROM pm1.g1", FakeMetadataFactory.example1Cached(), FakeMetadataFactory.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$
- assertNull(metadata);
-
- metadata = helpGetMetadata("DELETE FROM pm1.g1 WHERE e1 = 'x'", FakeMetadataFactory.example1Cached(), FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
- assertNull(metadata);
-
- metadata = helpGetMetadata("UPDATE pm1.g1 SET e1='y' WHERE e1 = 'x'", FakeMetadataFactory.example1Cached(), FakeMetadataFactory.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$
- assertNull(metadata);
- }
-
- @Test public void testElementLabel() throws Exception {
- Map[] metadata = helpGetMetadata("SELECT E2 FROM pm1.g1", FakeMetadataFactory.example1Cached(), FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
- assertNotNull(metadata);
- assertEquals(1, metadata.length);
- assertEquals("e2", metadata[0].get(ResultsMetadataConstants.ELEMENT_NAME)); //$NON-NLS-1$
- assertEquals("E2", metadata[0].get(ResultsMetadataConstants.ELEMENT_LABEL)); //$NON-NLS-1$
- }
-
- @Test public void testSimpleExec() throws Exception {
- Map[] metadata = helpGetMetadata("EXEC pm1.sq1()", FakeMetadataFactory.example1Cached(), FakeMetadataFactory.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$
- assertNotNull(metadata);
- assertEquals(0, metadata.length);
- }
-
- private MetadataResult helpTestQuery(QueryMetadataInterface metadata, String sql, VDBMetaData vdb) throws Exception {
- // Create components
- SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
-
- // Initialize components
- MetaDataProcessor mdProc = new MetaDataProcessor(new DQPCore(), prepPlanCache, "MyVDB", 1);
-
- DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, vdb);
- return mdProc.processMessage(workContext.getRequestID(1), workContext, sql, true);
- }
-
- private void helpCheckNumericAttributes(MetadataResult message, int column, int expectedSize, int expectedPrecision, int expectedScale) {
- Map[] md = message.getColumnMetadata();
- assertNotNull(md);
- assertEquals(new Integer(expectedSize), md[column].get(ResultsMetadataConstants.DISPLAY_SIZE));
- assertEquals(new Integer(expectedPrecision), md[column].get(ResultsMetadataConstants.PRECISION));
- assertEquals(new Integer(expectedScale), md[column].get(ResultsMetadataConstants.SCALE));
- }
-
- @Test public void testDefect16629_moneyType() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.examplePrivatePhysicalModel();
- String sql = "SELECT e1 FROM pm1.g2"; //$NON-NLS-1$
-
- MetadataResult response = helpTestQuery(metadata, sql, FakeMetadataFactory.examplePrivatePhysicalModelVDB());
-
- helpCheckNumericAttributes(response, 0, 21, 19, 4);
- }
-
- @Test public void testDefect16629_aggregatesOnMoneyType() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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());
- 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 testMetadataGenerationForAllTypes() throws Exception {
- Set<String> dataTypes = DataTypeManager.getAllDataTypeNames();
- for (String type : dataTypes) {
- Class<?> typeClass = DataTypeManager.getDataTypeClass(type);
- MetaDataProcessor processor = new MetaDataProcessor(null, null, "vdb", 1);
- Map<Integer, Object> columnMetadata = processor.getDefaultColumn("t", "c", typeClass); //$NON-NLS-1$ //$NON-NLS-2$
- verifyColumn(columnMetadata, type);
- }
- }
-
- private void verifyColumn(Map column, String dataType) {
- verifyAttribute(column, ResultsMetadataConstants.AUTO_INCREMENTING, false, Boolean.class, dataType);
- verifyAttribute(column, ResultsMetadataConstants.CASE_SENSITIVE, false, Boolean.class, dataType);
- verifyAttribute(column, ResultsMetadataConstants.CURRENCY, false, Boolean.class, dataType);
-
- Object dt = verifyAttribute(column, ResultsMetadataConstants.DATA_TYPE, false, String.class, dataType);
- assertEquals(dataType, dt);
-
- verifyAttribute(column, ResultsMetadataConstants.DISPLAY_SIZE, false, Integer.class, dataType);
- verifyAttribute(column, ResultsMetadataConstants.ELEMENT_LABEL, true, String.class, dataType);
- verifyAttribute(column, ResultsMetadataConstants.ELEMENT_NAME, false, String.class, dataType);
- verifyAttribute(column, ResultsMetadataConstants.GROUP_NAME, true, String.class, dataType);
-
- Object nullable = verifyAttribute(column, ResultsMetadataConstants.NULLABLE, false, Integer.class, dataType);
- verifyNullable((Integer)nullable);
-
- verifyAttribute(column, ResultsMetadataConstants.PRECISION, false, Integer.class, dataType);
- verifyAttribute(column, ResultsMetadataConstants.RADIX, false, Integer.class, dataType);
- verifyAttribute(column, ResultsMetadataConstants.SCALE, false, Integer.class, dataType);
-
- Object searchable = verifyAttribute(column, ResultsMetadataConstants.SEARCHABLE, false, Integer.class, dataType);
- verifySearchable((Integer)searchable);
-
- verifyAttribute(column, ResultsMetadataConstants.SIGNED, false, Boolean.class, dataType);
-
- verifyAttribute(column, ResultsMetadataConstants.VIRTUAL_DATABASE_NAME, false, String.class, dataType);
- verifyAttribute(column, ResultsMetadataConstants.VIRTUAL_DATABASE_VERSION, false, Integer.class, dataType);
- verifyAttribute(column, ResultsMetadataConstants.WRITABLE, false, Boolean.class, dataType);
- }
-
- private Object verifyAttribute(Map column, Integer attributeType, boolean nullsAllowed, Class<?> expectedClass, String columnDataType) {
- //System.out.println("Checking " + columnDataType + ", attribute " + attributeType); //$NON-NLS-1$ //$NON-NLS-2$
- Object value = column.get(attributeType);
- if(! nullsAllowed) {
- assertNotNull("Got null when not allowed for column of type " + columnDataType, value); //$NON-NLS-1$
- }
-
- if(value != null) {
- assertEquals("Got attribute of incorrect class for column of type " + columnDataType, expectedClass, value.getClass()); //$NON-NLS-1$
- }
-
- return value;
- }
-
- private void verifyNullable(Integer nullable) {
- if(!
- (nullable.equals(ResultsMetadataConstants.NULL_TYPES.NOT_NULL) ||
- nullable.equals(ResultsMetadataConstants.NULL_TYPES.NULLABLE) ||
- nullable.equals(ResultsMetadataConstants.NULL_TYPES.UNKNOWN) ) ) {
-
- fail("Invalid nullable constant value: " + nullable); //$NON-NLS-1$
- }
- }
-
- private void verifySearchable(Integer searchable) {
- if(!
- (searchable.equals(ResultsMetadataConstants.SEARCH_TYPES.ALLEXCEPTLIKE) ||
- searchable.equals(ResultsMetadataConstants.SEARCH_TYPES.LIKE_ONLY) ||
- searchable.equals(ResultsMetadataConstants.SEARCH_TYPES.UNSEARCHABLE) ||
- searchable.equals(ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE) ) ) {
-
- fail("Invalid searchable constant value: " + searchable); //$NON-NLS-1$
- }
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,281 @@
+/*
+ * 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.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;
+import org.teiid.client.metadata.ResultsMetadataConstants;
+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.RealMetadataFactory;
+
+
+/**
+ */
+ at SuppressWarnings({"nls", "unchecked"})
+public class TestMetaDataProcessor {
+
+ public Map[] helpGetMetadata(String sql, QueryMetadataInterface metadata, VDBMetaData vdb) throws Exception {
+ // Prepare sql
+ Command command = QueryParser.getQueryParser().parseCommand(sql);
+ QueryResolver.resolveCommand(command, metadata);
+
+ // Create components
+ SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
+ DQPCore requestMgr = new DQPCore();
+ requestMgr.setTransactionService(new FakeTransactionService());
+
+ DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(metadata, vdb);
+
+ // Initialize components
+ RequestID requestID = workContext.getRequestID(1);
+ RequestMessage requestMsg = new RequestMessage(sql);
+ TestDQPCoreRequestHandling.addRequest(requestMgr, requestMsg, requestID, command, null);
+
+ MetaDataProcessor mdProc = new MetaDataProcessor(requestMgr, prepPlanCache, "MyVDB", 1);
+
+ return mdProc.processMessage(requestID, workContext, null, true).getColumnMetadata();
+ }
+
+ @Test public void testSimpleQuery() throws Exception {
+ 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')", RealMetadataFactory.example1Cached(), RealMetadataFactory.example1VDB()); //$NON-NLS-1$
+ assertNull(metadata);
+
+ 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'", RealMetadataFactory.example1Cached(), RealMetadataFactory.example1VDB()); //$NON-NLS-1$
+ assertNull(metadata);
+
+ 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", RealMetadataFactory.example1Cached(), RealMetadataFactory.example1VDB()); //$NON-NLS-1$
+ assertNotNull(metadata);
+ assertEquals(1, metadata.length);
+ assertEquals("e2", metadata[0].get(ResultsMetadataConstants.ELEMENT_NAME)); //$NON-NLS-1$
+ assertEquals("E2", metadata[0].get(ResultsMetadataConstants.ELEMENT_LABEL)); //$NON-NLS-1$
+ }
+
+ @Test public void testSimpleExec() throws Exception {
+ 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()", RealMetadataFactory.example1Cached(), RealMetadataFactory.example1VDB()); //$NON-NLS-1$
+ assertNotNull(metadata);
+ assertEquals(0, metadata.length);
+ }
+
+ private MetadataResult helpTestQuery(QueryMetadataInterface metadata, String sql, VDBMetaData vdb) throws Exception {
+ // Create components
+ SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
+
+ // Initialize components
+ MetaDataProcessor mdProc = new MetaDataProcessor(new DQPCore(), prepPlanCache, "MyVDB", 1);
+
+ DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(metadata, vdb);
+ return mdProc.processMessage(workContext.getRequestID(1), workContext, sql, true);
+ }
+
+ private void helpCheckNumericAttributes(MetadataResult message, int column, int expectedSize, int expectedPrecision, int expectedScale) {
+ Map[] md = message.getColumnMetadata();
+ assertNotNull(md);
+ assertEquals(new Integer(expectedSize), md[column].get(ResultsMetadataConstants.DISPLAY_SIZE));
+ assertEquals(new Integer(expectedPrecision), md[column].get(ResultsMetadataConstants.PRECISION));
+ assertEquals(new Integer(expectedScale), md[column].get(ResultsMetadataConstants.SCALE));
+ }
+
+ @Test public void testDefect16629_moneyType() throws Exception {
+ QueryMetadataInterface metadata = TestMetaDataProcessor.examplePrivatePhysicalModel();
+ String sql = "SELECT e1 FROM pm1.g2"; //$NON-NLS-1$
+
+ MetadataResult response = helpTestQuery(metadata, sql, TestMetaDataProcessor.examplePrivatePhysicalModelVDB());
+
+ helpCheckNumericAttributes(response, 0, 21, 19, 4);
+ }
+
+ @Test public void testDefect16629_aggregatesOnMoneyType() throws Exception {
+ 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, 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 testMetadataGenerationForAllTypes() throws Exception {
+ Set<String> dataTypes = DataTypeManager.getAllDataTypeNames();
+ for (String type : dataTypes) {
+ Class<?> typeClass = DataTypeManager.getDataTypeClass(type);
+ MetaDataProcessor processor = new MetaDataProcessor(null, null, "vdb", 1);
+ Map<Integer, Object> columnMetadata = processor.getDefaultColumn("t", "c", typeClass); //$NON-NLS-1$ //$NON-NLS-2$
+ verifyColumn(columnMetadata, type);
+ }
+ }
+
+ private void verifyColumn(Map column, String dataType) {
+ verifyAttribute(column, ResultsMetadataConstants.AUTO_INCREMENTING, false, Boolean.class, dataType);
+ verifyAttribute(column, ResultsMetadataConstants.CASE_SENSITIVE, false, Boolean.class, dataType);
+ verifyAttribute(column, ResultsMetadataConstants.CURRENCY, false, Boolean.class, dataType);
+
+ Object dt = verifyAttribute(column, ResultsMetadataConstants.DATA_TYPE, false, String.class, dataType);
+ assertEquals(dataType, dt);
+
+ verifyAttribute(column, ResultsMetadataConstants.DISPLAY_SIZE, false, Integer.class, dataType);
+ verifyAttribute(column, ResultsMetadataConstants.ELEMENT_LABEL, true, String.class, dataType);
+ verifyAttribute(column, ResultsMetadataConstants.ELEMENT_NAME, false, String.class, dataType);
+ verifyAttribute(column, ResultsMetadataConstants.GROUP_NAME, true, String.class, dataType);
+
+ Object nullable = verifyAttribute(column, ResultsMetadataConstants.NULLABLE, false, Integer.class, dataType);
+ verifyNullable((Integer)nullable);
+
+ verifyAttribute(column, ResultsMetadataConstants.PRECISION, false, Integer.class, dataType);
+ verifyAttribute(column, ResultsMetadataConstants.RADIX, false, Integer.class, dataType);
+ verifyAttribute(column, ResultsMetadataConstants.SCALE, false, Integer.class, dataType);
+
+ Object searchable = verifyAttribute(column, ResultsMetadataConstants.SEARCHABLE, false, Integer.class, dataType);
+ verifySearchable((Integer)searchable);
+
+ verifyAttribute(column, ResultsMetadataConstants.SIGNED, false, Boolean.class, dataType);
+
+ verifyAttribute(column, ResultsMetadataConstants.VIRTUAL_DATABASE_NAME, false, String.class, dataType);
+ verifyAttribute(column, ResultsMetadataConstants.VIRTUAL_DATABASE_VERSION, false, Integer.class, dataType);
+ verifyAttribute(column, ResultsMetadataConstants.WRITABLE, false, Boolean.class, dataType);
+ }
+
+ private Object verifyAttribute(Map column, Integer attributeType, boolean nullsAllowed, Class<?> expectedClass, String columnDataType) {
+ //System.out.println("Checking " + columnDataType + ", attribute " + attributeType); //$NON-NLS-1$ //$NON-NLS-2$
+ Object value = column.get(attributeType);
+ if(! nullsAllowed) {
+ assertNotNull("Got null when not allowed for column of type " + columnDataType, value); //$NON-NLS-1$
+ }
+
+ if(value != null) {
+ assertEquals("Got attribute of incorrect class for column of type " + columnDataType, expectedClass, value.getClass()); //$NON-NLS-1$
+ }
+
+ return value;
+ }
+
+ private void verifyNullable(Integer nullable) {
+ if(!
+ (nullable.equals(ResultsMetadataConstants.NULL_TYPES.NOT_NULL) ||
+ nullable.equals(ResultsMetadataConstants.NULL_TYPES.NULLABLE) ||
+ nullable.equals(ResultsMetadataConstants.NULL_TYPES.UNKNOWN) ) ) {
+
+ fail("Invalid nullable constant value: " + nullable); //$NON-NLS-1$
+ }
+ }
+
+ private void verifySearchable(Integer searchable) {
+ if(!
+ (searchable.equals(ResultsMetadataConstants.SEARCH_TYPES.ALLEXCEPTLIKE) ||
+ searchable.equals(ResultsMetadataConstants.SEARCH_TYPES.LIKE_ONLY) ||
+ searchable.equals(ResultsMetadataConstants.SEARCH_TYPES.UNSEARCHABLE) ||
+ searchable.equals(ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE) ) ) {
+
+ 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
+ List<Column> pm1g1e = 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;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,433 +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 static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.client.RequestMessage;
-import org.teiid.client.RequestMessage.StatementType;
-import org.teiid.common.buffer.BufferManagerFactory;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
-import org.teiid.dqp.internal.datamgr.FakeTransactionService;
-import org.teiid.dqp.service.AutoGenDataService;
-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.CapabilitiesFinder;
-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.processor.FakeDataManager;
-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;
-
- at SuppressWarnings({"nls", "unchecked"})
-public class TestPreparedStatement {
-
- private static final int SESSION_ID = 6;
-
- static void helpTestProcessing(String preparedSql, List values, List[] expected, ProcessorDataManager dataManager, QueryMetadataInterface metadata, boolean callableStatement, VDBMetaData vdb) throws Exception {
- helpTestProcessing(preparedSql, values, expected, dataManager, metadata, callableStatement, false, vdb);
- }
-
- static void helpTestProcessing(String preparedSql, List values, List[] expected, ProcessorDataManager dataManager, QueryMetadataInterface metadata, boolean callableStatement, boolean isSessionSpecific, VDBMetaData vdb) throws Exception {
- helpTestProcessing(preparedSql, values, expected, dataManager, (CapabilitiesFinder)null, metadata, null, callableStatement, isSessionSpecific, /* isAlreadyCached */false, vdb);
- }
-
- static public void helpTestProcessing(String preparedSql, List values, List[] expected, ProcessorDataManager dataManager, CapabilitiesFinder capFinder, QueryMetadataInterface metadata, SessionAwareCache<PreparedPlan> prepPlanCache, boolean callableStatement, boolean isSessionSpecific, boolean isAlreadyCached, VDBMetaData vdb) throws Exception {
- if ( dataManager == null ) {
- // Construct data manager with data
- dataManager = new FakeDataManager();
- TestProcessor.sampleData1((FakeDataManager)dataManager);
- }
-
- if ( capFinder == null ) {
- capFinder = new DefaultCapabilitiesFinder();
- }
-
- if ( prepPlanCache == null ) {
- prepPlanCache = new SessionAwareCache<PreparedPlan>();
- }
-
- // expected cache hit count
- int exHitCount = -1;
-
- /*
- * If the plan is already cached we want our expected hit
- * count of the cache to be at least 2 because we will
- * get the plan twice. Otherwise, we want it to be 1.
- */
- if ( isAlreadyCached ) {
- exHitCount = prepPlanCache.getCacheHitCount() + 2;
- } else {
- exHitCount = prepPlanCache.getCacheHitCount() + 1;
- }
-
- //Create plan or used cache plan if isPlanCached
- PreparedStatementRequest plan = TestPreparedStatement.helpGetProcessorPlan(preparedSql, values, capFinder, metadata, prepPlanCache, SESSION_ID, callableStatement, false, vdb);
-
- // Run query
- TestProcessor.doProcess(plan.processPlan, dataManager, expected, plan.context);
-
- //test cached plan
- plan = TestPreparedStatement.helpGetProcessorPlan(preparedSql, values, capFinder, metadata, prepPlanCache, SESSION_ID, callableStatement, false,vdb);
-
- //make sure the plan is only created once
- assertEquals("should reuse the plan", exHitCount, prepPlanCache.getCacheHitCount()); //$NON-NLS-1$
-
- // If we are using FakeDataManager, stop command recording to prevent
- // duplicate commands
- boolean dmir = false;
- if (dataManager instanceof FakeDataManager && ((FakeDataManager) dataManager).isRecordingCommands()) {
- dmir = true;
- ((FakeDataManager) dataManager).setRecordingCommands(false);
- }
- // Run query again
- TestProcessor.doProcess(plan.processPlan, dataManager, expected, plan.context);
-
- // If we are using FakeDataManager and we stopped it from recording,
- // start it back up again
- if (dmir == true) {
- ((FakeDataManager) dataManager).setRecordingCommands(true);
- }
-
- //get the plan again with a new connection
- assertNotNull(TestPreparedStatement.helpGetProcessorPlan(preparedSql, values, capFinder, metadata, prepPlanCache, 7, callableStatement, false, vdb));
-
- /*
- * If the command is not specific to a session we expect
- * another hit against the cache because we will use the
- * cached plan, otherwise, a new plan would have been
- * created and the hit count will be unchanged.
- */
- if ( !isSessionSpecific ) exHitCount++;
- assertEquals(exHitCount, prepPlanCache.getCacheHitCount());
- }
-
- @Test public void testWhere() throws Exception {
- // Create query
- String preparedSql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1 WHERE e2=?"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }) //$NON-NLS-1$
- };
-
- List<?> values = Arrays.asList((short)0);
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
- helpTestProcessing(preparedSql, values, expected, dataManager, FakeMetadataFactory.example1Cached(), false, FakeMetadataFactory.example1VDB());
- }
-
- @Test public void testSessionSpecificFunction() throws Exception {
- // Create query
- System.setProperty("foo", "foo"); //$NON-NLS-1$ //$NON-NLS-2$
- String preparedSql = "SELECT env('foo'), e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1 WHERE e2=?"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "foo", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "foo", new Integer(0), Boolean.FALSE, new Double(2.0) }) //$NON-NLS-1$
- };
-
- List<?> values = Arrays.asList((short)0);
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
- helpTestProcessing(preparedSql, values, expected, dataManager, FakeMetadataFactory.example1Cached(), false, true, FakeMetadataFactory.example1VDB());
- }
-
- @Test public void testFunctionWithReferencePushDown() throws Exception {
- // Create query
- String preparedSql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1 and pm1.g1.e2+2=?"; //$NON-NLS-1$
-
- //Create plan
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport("+", false); //$NON-NLS-1$
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- List values = Arrays.asList(0);
-
- PreparedStatementRequest plan = helpGetProcessorPlan(preparedSql, values, capFinder, metadata, new SessionAwareCache<PreparedPlan>(), SESSION_ID, false, false,FakeMetadataFactory.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());
- }
-
- 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());
- }
-
- static PreparedStatementRequest helpGetProcessorPlan(String preparedSql, List values,
- CapabilitiesFinder capFinder, QueryMetadataInterface metadata, SessionAwareCache<PreparedPlan> prepPlanCache, int conn, boolean callableStatement, boolean limitResults, VDBMetaData vdb)
- throws TeiidComponentException, TeiidProcessingException {
-
- //Create Request
- RequestMessage request = new RequestMessage(preparedSql);
- if (callableStatement) {
- request.setStatementType(StatementType.CALLABLE);
- } else {
- request.setStatementType(StatementType.PREPARED);
- }
- request.setParameterValues(values);
- if (values != null && values.size() > 0 && values.get(0) instanceof List) {
- request.setBatchedUpdate(true);
- }
- if (limitResults) {
- request.setRowLimit(1);
- }
-
- DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, vdb);
- workContext.getSession().setSessionId(String.valueOf(conn));
-
- PreparedStatementRequest serverRequest = new PreparedStatementRequest(prepPlanCache);
-
- ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
- Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(new AutoGenDataService());
-
- serverRequest.initialize(request, BufferManagerFactory.getStandaloneBufferManager(), null, new FakeTransactionService(), null, workContext, prepPlanCache);
- serverRequest.setMetadata(capFinder, metadata, null);
- serverRequest.setAuthorizationValidator(new DataRoleAuthorizationValidator(false, true, true));
- serverRequest.processRequest();
-
- assertNotNull(serverRequest.processPlan);
- return serverRequest;
- }
-
- @Test public void testValidateCorrectValues() throws Exception {
- // Create query
- String preparedSql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1 WHERE pm1.g1.e1=?"; //$NON-NLS-1$
-
- List values = Arrays.asList("a"); //$NON-NLS-1$
-
- //Create plan
- helpGetProcessorPlan(preparedSql, values, new SessionAwareCache<PreparedPlan>());
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e2 IN (SELECT pm1.g2.e2 FROM pm1.g2 WHERE pm1.g2.e1 = ?)*/
- @Test public void testWithSubquery() throws Exception {
- // Create query
- String preparedSql = "SELECT pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e2 IN (SELECT pm1.g2.e2 FROM pm1.g2 WHERE pm1.g2.e1 = ?)"; //$NON-NLS-1$
-
- List values = Arrays.asList("a"); //$NON-NLS-1$
-
- //Create plan
- helpGetProcessorPlan(preparedSql, values, new SessionAwareCache<PreparedPlan>());
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e1 = ? AND pm1.g1.e2 IN (SELECT pm1.g2.e2 FROM pm1.g2 WHERE pm1.g2.e1 = ?) */
- @Test public void testWithSubquery2() throws Exception {
- // Create query
- String preparedSql = "SELECT pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e1 = ? AND pm1.g1.e2 IN (SELECT pm1.g2.e2 FROM pm1.g2 WHERE pm1.g2.e1 = ?)"; //$NON-NLS-1$
-
- List values = Arrays.asList("d", "c"); //$NON-NLS-1$ //$NON-NLS-2$
-
- //Create plan
- helpGetProcessorPlan(preparedSql, values, new SessionAwareCache<PreparedPlan>());
- }
-
- /** SELECT X.e1 FROM (SELECT pm1.g2.e1 FROM pm1.g2 WHERE pm1.g2.e1 = ?) as X */
- @Test public void testWithSubquery3() throws Exception {
- // Create query
- String preparedSql = "SELECT X.e1 FROM (SELECT pm1.g2.e1 FROM pm1.g2 WHERE pm1.g2.e1 = ?) as X"; //$NON-NLS-1$
-
- //Create Request
- List values = Arrays.asList("d"); //$NON-NLS-1$
-
- //Create plan
- helpGetProcessorPlan(preparedSql, values, new SessionAwareCache<PreparedPlan>());
- }
-
- @Test public void testValidateWrongValues() throws Exception {
- // Create query
- String preparedSql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1 WHERE pm1.g1.e2=?"; //$NON-NLS-1$
- SessionAwareCache<PreparedPlan> prepCache = new SessionAwareCache<PreparedPlan>();
-
- //wrong type
- try{
- List values = Arrays.asList("x"); //$NON-NLS-1$
-
- //Create plan
- helpGetProcessorPlan(preparedSql, values, prepCache, SESSION_ID);
- fail();
- }catch(QueryResolverException qe){
- assertEquals("Error converting parameter number 1 with value \"x\" to expected type integer.", qe.getMessage()); //$NON-NLS-1$
- }
- assertEquals(0, prepCache.getCacheHitCount());
-
- //test cached plan
- try{
- List values = new ArrayList();
- values.add("a"); //$NON-NLS-1$
- values.add("b"); //$NON-NLS-1$
- helpGetProcessorPlan(preparedSql, values, prepCache, SESSION_ID);
- fail();
- }catch(QueryResolverException qe){
- assertEquals("The number of bound values '2' does not match the number of parameters '1' in the prepared statement.", qe.getMessage()); //$NON-NLS-1$
- }
-
- assertEquals(1, prepCache.getCacheHitCount());
-
- //wrong number of values
- try{
- List values = new ArrayList();
- values.add("a"); //$NON-NLS-1$
- values.add(new Integer(0));
- helpGetProcessorPlan(preparedSql, values, prepCache);
- fail();
- }catch(QueryResolverException qe){
- assertEquals("The number of bound values '2' does not match the number of parameters '1' in the prepared statement.", qe.getMessage()); //$NON-NLS-1$
- }
-
- }
-
- @Test public void testResolveParameterValues() throws Exception {
- // Create query
- String preparedSql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1 WHERE pm1.g1.e2=?"; //$NON-NLS-1$
-
- List values = Arrays.asList("0"); //$NON-NLS-1$
-
- helpGetProcessorPlan(preparedSql, values, new SessionAwareCache<PreparedPlan>());
- }
-
- /**
- * TODO: there may be other ways of handling this situation in the future
- */
- @Test public void testLimitNoCache() throws Exception {
- // Create query
- String preparedSql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1 WHERE pm1.g1.e2=?"; //$NON-NLS-1$
-
- List values = Arrays.asList("0"); //$NON-NLS-1$
-
- 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(), FakeMetadataFactory.example1Cached(), planCache, SESSION_ID, false, true, FakeMetadataFactory.example1VDB());
- //make sure the plan wasn't reused
- assertEquals(0, planCache.getCacheHitCount());
- }
-
- @Test public void testUpdateProcedureCriteria() throws Exception {
- String preparedSql = "delete from vm1.g37 where e1=?"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(1),
- };
-
- 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());
- }
-
- @Test(expected=QueryValidatorException.class) public void testLimitValidation() throws Exception {
- String preparedSql = "select pm1.g1.e1 from pm1.g1 limit ?"; //$NON-NLS-1$
-
- List values = Arrays.asList(-1);
- FakeDataManager dataManager = new FakeDataManager();
- helpTestProcessing(preparedSql, values, null, dataManager, FakeMetadataFactory.example1Cached(), false, false, FakeMetadataFactory.example1VDB());
- }
-
- @Test public void testExecParam() throws Exception {
- String preparedSql = "exec pm1.sq2(?)"; //$NON-NLS-1$
-
- List<String> values = Arrays.asList("c"); //$NON-NLS-1$
- List[] expected = new List[] {
- Arrays.asList("c", 1),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
- helpTestProcessing(preparedSql, values, expected, dataManager, FakeMetadataFactory.example1Cached(), false, false, FakeMetadataFactory.example1VDB());
- }
-
- @Test public void testLimitParam() throws Exception {
- String preparedSql = "select e1 from pm1.g1 order by e1 desc limit ?"; //$NON-NLS-1$
-
- List<?> values = Arrays.asList(1);
- List[] expected = new List[] {
- Arrays.asList("c"), //$NON-NLS-1$s
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
- helpTestProcessing(preparedSql, values, expected, dataManager, FakeMetadataFactory.example1Cached(), false, false,FakeMetadataFactory.example1VDB());
- }
-
- @Test public void testWithSubqueryPushdown() throws Exception {
- String preparedSql = "SELECT pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e2 IN (SELECT pm1.g2.e2 FROM pm1.g2 WHERE pm1.g2.e1 = ?)"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("a"),
- };
-
- List values = Arrays.asList("a"); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.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());
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,432 @@
+/*
+ * 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.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.client.RequestMessage;
+import org.teiid.client.RequestMessage.StatementType;
+import org.teiid.common.buffer.BufferManagerFactory;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
+import org.teiid.dqp.internal.datamgr.FakeTransactionService;
+import org.teiid.dqp.service.AutoGenDataService;
+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.CapabilitiesFinder;
+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.processor.FakeDataManager;
+import org.teiid.query.processor.HardcodedDataManager;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.processor.TestProcessor;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+ at SuppressWarnings({"nls", "unchecked"})
+public class TestPreparedStatement {
+
+ private static final int SESSION_ID = 6;
+
+ static void helpTestProcessing(String preparedSql, List values, List[] expected, ProcessorDataManager dataManager, QueryMetadataInterface metadata, boolean callableStatement, VDBMetaData vdb) throws Exception {
+ helpTestProcessing(preparedSql, values, expected, dataManager, metadata, callableStatement, false, vdb);
+ }
+
+ static void helpTestProcessing(String preparedSql, List values, List[] expected, ProcessorDataManager dataManager, QueryMetadataInterface metadata, boolean callableStatement, boolean isSessionSpecific, VDBMetaData vdb) throws Exception {
+ helpTestProcessing(preparedSql, values, expected, dataManager, (CapabilitiesFinder)null, metadata, null, callableStatement, isSessionSpecific, /* isAlreadyCached */false, vdb);
+ }
+
+ static public void helpTestProcessing(String preparedSql, List values, List[] expected, ProcessorDataManager dataManager, CapabilitiesFinder capFinder, QueryMetadataInterface metadata, SessionAwareCache<PreparedPlan> prepPlanCache, boolean callableStatement, boolean isSessionSpecific, boolean isAlreadyCached, VDBMetaData vdb) throws Exception {
+ if ( dataManager == null ) {
+ // Construct data manager with data
+ dataManager = new FakeDataManager();
+ TestProcessor.sampleData1((FakeDataManager)dataManager);
+ }
+
+ if ( capFinder == null ) {
+ capFinder = new DefaultCapabilitiesFinder();
+ }
+
+ if ( prepPlanCache == null ) {
+ prepPlanCache = new SessionAwareCache<PreparedPlan>();
+ }
+
+ // expected cache hit count
+ int exHitCount = -1;
+
+ /*
+ * If the plan is already cached we want our expected hit
+ * count of the cache to be at least 2 because we will
+ * get the plan twice. Otherwise, we want it to be 1.
+ */
+ if ( isAlreadyCached ) {
+ exHitCount = prepPlanCache.getCacheHitCount() + 2;
+ } else {
+ exHitCount = prepPlanCache.getCacheHitCount() + 1;
+ }
+
+ //Create plan or used cache plan if isPlanCached
+ PreparedStatementRequest plan = TestPreparedStatement.helpGetProcessorPlan(preparedSql, values, capFinder, metadata, prepPlanCache, SESSION_ID, callableStatement, false, vdb);
+
+ // Run query
+ TestProcessor.doProcess(plan.processPlan, dataManager, expected, plan.context);
+
+ //test cached plan
+ plan = TestPreparedStatement.helpGetProcessorPlan(preparedSql, values, capFinder, metadata, prepPlanCache, SESSION_ID, callableStatement, false,vdb);
+
+ //make sure the plan is only created once
+ assertEquals("should reuse the plan", exHitCount, prepPlanCache.getCacheHitCount()); //$NON-NLS-1$
+
+ // If we are using FakeDataManager, stop command recording to prevent
+ // duplicate commands
+ boolean dmir = false;
+ if (dataManager instanceof FakeDataManager && ((FakeDataManager) dataManager).isRecordingCommands()) {
+ dmir = true;
+ ((FakeDataManager) dataManager).setRecordingCommands(false);
+ }
+ // Run query again
+ TestProcessor.doProcess(plan.processPlan, dataManager, expected, plan.context);
+
+ // If we are using FakeDataManager and we stopped it from recording,
+ // start it back up again
+ if (dmir == true) {
+ ((FakeDataManager) dataManager).setRecordingCommands(true);
+ }
+
+ //get the plan again with a new connection
+ assertNotNull(TestPreparedStatement.helpGetProcessorPlan(preparedSql, values, capFinder, metadata, prepPlanCache, 7, callableStatement, false, vdb));
+
+ /*
+ * If the command is not specific to a session we expect
+ * another hit against the cache because we will use the
+ * cached plan, otherwise, a new plan would have been
+ * created and the hit count will be unchanged.
+ */
+ if ( !isSessionSpecific ) exHitCount++;
+ assertEquals(exHitCount, prepPlanCache.getCacheHitCount());
+ }
+
+ @Test public void testWhere() throws Exception {
+ // Create query
+ String preparedSql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1 WHERE e2=?"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }) //$NON-NLS-1$
+ };
+
+ List<?> values = Arrays.asList((short)0);
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+ helpTestProcessing(preparedSql, values, expected, dataManager, RealMetadataFactory.example1Cached(), false, RealMetadataFactory.example1VDB());
+ }
+
+ @Test public void testSessionSpecificFunction() throws Exception {
+ // Create query
+ System.setProperty("foo", "foo"); //$NON-NLS-1$ //$NON-NLS-2$
+ String preparedSql = "SELECT env('foo'), e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1 WHERE e2=?"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "foo", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "foo", new Integer(0), Boolean.FALSE, new Double(2.0) }) //$NON-NLS-1$
+ };
+
+ List<?> values = Arrays.asList((short)0);
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+ helpTestProcessing(preparedSql, values, expected, dataManager, RealMetadataFactory.example1Cached(), false, true, RealMetadataFactory.example1VDB());
+ }
+
+ @Test public void testFunctionWithReferencePushDown() throws Exception {
+ // Create query
+ String preparedSql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1 and pm1.g1.e2+2=?"; //$NON-NLS-1$
+
+ //Create plan
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport("+", false); //$NON-NLS-1$
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ List values = Arrays.asList(0);
+
+ 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(), 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(), RealMetadataFactory
+ .example1Cached(), prepPlanCache, conn, false, false, RealMetadataFactory.example1VDB());
+ }
+
+ static PreparedStatementRequest helpGetProcessorPlan(String preparedSql, List values,
+ CapabilitiesFinder capFinder, QueryMetadataInterface metadata, SessionAwareCache<PreparedPlan> prepPlanCache, int conn, boolean callableStatement, boolean limitResults, VDBMetaData vdb)
+ throws TeiidComponentException, TeiidProcessingException {
+
+ //Create Request
+ RequestMessage request = new RequestMessage(preparedSql);
+ if (callableStatement) {
+ request.setStatementType(StatementType.CALLABLE);
+ } else {
+ request.setStatementType(StatementType.PREPARED);
+ }
+ request.setParameterValues(values);
+ if (values != null && values.size() > 0 && values.get(0) instanceof List) {
+ request.setBatchedUpdate(true);
+ }
+ if (limitResults) {
+ request.setRowLimit(1);
+ }
+
+ DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(metadata, vdb);
+ workContext.getSession().setSessionId(String.valueOf(conn));
+
+ PreparedStatementRequest serverRequest = new PreparedStatementRequest(prepPlanCache);
+
+ ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
+ Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(new AutoGenDataService());
+
+ serverRequest.initialize(request, BufferManagerFactory.getStandaloneBufferManager(), null, new FakeTransactionService(), null, workContext, prepPlanCache);
+ serverRequest.setMetadata(capFinder, metadata, null);
+ serverRequest.setAuthorizationValidator(new DataRoleAuthorizationValidator(false, true, true));
+ serverRequest.processRequest();
+
+ assertNotNull(serverRequest.processPlan);
+ return serverRequest;
+ }
+
+ @Test public void testValidateCorrectValues() throws Exception {
+ // Create query
+ String preparedSql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1 WHERE pm1.g1.e1=?"; //$NON-NLS-1$
+
+ List values = Arrays.asList("a"); //$NON-NLS-1$
+
+ //Create plan
+ helpGetProcessorPlan(preparedSql, values, new SessionAwareCache<PreparedPlan>());
+ }
+
+ /** SELECT pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e2 IN (SELECT pm1.g2.e2 FROM pm1.g2 WHERE pm1.g2.e1 = ?)*/
+ @Test public void testWithSubquery() throws Exception {
+ // Create query
+ String preparedSql = "SELECT pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e2 IN (SELECT pm1.g2.e2 FROM pm1.g2 WHERE pm1.g2.e1 = ?)"; //$NON-NLS-1$
+
+ List values = Arrays.asList("a"); //$NON-NLS-1$
+
+ //Create plan
+ helpGetProcessorPlan(preparedSql, values, new SessionAwareCache<PreparedPlan>());
+ }
+
+ /** SELECT pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e1 = ? AND pm1.g1.e2 IN (SELECT pm1.g2.e2 FROM pm1.g2 WHERE pm1.g2.e1 = ?) */
+ @Test public void testWithSubquery2() throws Exception {
+ // Create query
+ String preparedSql = "SELECT pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e1 = ? AND pm1.g1.e2 IN (SELECT pm1.g2.e2 FROM pm1.g2 WHERE pm1.g2.e1 = ?)"; //$NON-NLS-1$
+
+ List values = Arrays.asList("d", "c"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ //Create plan
+ helpGetProcessorPlan(preparedSql, values, new SessionAwareCache<PreparedPlan>());
+ }
+
+ /** SELECT X.e1 FROM (SELECT pm1.g2.e1 FROM pm1.g2 WHERE pm1.g2.e1 = ?) as X */
+ @Test public void testWithSubquery3() throws Exception {
+ // Create query
+ String preparedSql = "SELECT X.e1 FROM (SELECT pm1.g2.e1 FROM pm1.g2 WHERE pm1.g2.e1 = ?) as X"; //$NON-NLS-1$
+
+ //Create Request
+ List values = Arrays.asList("d"); //$NON-NLS-1$
+
+ //Create plan
+ helpGetProcessorPlan(preparedSql, values, new SessionAwareCache<PreparedPlan>());
+ }
+
+ @Test public void testValidateWrongValues() throws Exception {
+ // Create query
+ String preparedSql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1 WHERE pm1.g1.e2=?"; //$NON-NLS-1$
+ SessionAwareCache<PreparedPlan> prepCache = new SessionAwareCache<PreparedPlan>();
+
+ //wrong type
+ try{
+ List values = Arrays.asList("x"); //$NON-NLS-1$
+
+ //Create plan
+ helpGetProcessorPlan(preparedSql, values, prepCache, SESSION_ID);
+ fail();
+ }catch(QueryResolverException qe){
+ assertEquals("Error converting parameter number 1 with value \"x\" to expected type integer.", qe.getMessage()); //$NON-NLS-1$
+ }
+ assertEquals(0, prepCache.getCacheHitCount());
+
+ //test cached plan
+ try{
+ List values = new ArrayList();
+ values.add("a"); //$NON-NLS-1$
+ values.add("b"); //$NON-NLS-1$
+ helpGetProcessorPlan(preparedSql, values, prepCache, SESSION_ID);
+ fail();
+ }catch(QueryResolverException qe){
+ assertEquals("The number of bound values '2' does not match the number of parameters '1' in the prepared statement.", qe.getMessage()); //$NON-NLS-1$
+ }
+
+ assertEquals(1, prepCache.getCacheHitCount());
+
+ //wrong number of values
+ try{
+ List values = new ArrayList();
+ values.add("a"); //$NON-NLS-1$
+ values.add(new Integer(0));
+ helpGetProcessorPlan(preparedSql, values, prepCache);
+ fail();
+ }catch(QueryResolverException qe){
+ assertEquals("The number of bound values '2' does not match the number of parameters '1' in the prepared statement.", qe.getMessage()); //$NON-NLS-1$
+ }
+
+ }
+
+ @Test public void testResolveParameterValues() throws Exception {
+ // Create query
+ String preparedSql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1 WHERE pm1.g1.e2=?"; //$NON-NLS-1$
+
+ List values = Arrays.asList("0"); //$NON-NLS-1$
+
+ helpGetProcessorPlan(preparedSql, values, new SessionAwareCache<PreparedPlan>());
+ }
+
+ /**
+ * TODO: there may be other ways of handling this situation in the future
+ */
+ @Test public void testLimitNoCache() throws Exception {
+ // Create query
+ String preparedSql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1 WHERE pm1.g1.e2=?"; //$NON-NLS-1$
+
+ List values = Arrays.asList("0"); //$NON-NLS-1$
+
+ SessionAwareCache<PreparedPlan> planCache = new SessionAwareCache<PreparedPlan>();
+
+ helpGetProcessorPlan(preparedSql, values, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), planCache, SESSION_ID, false, true, RealMetadataFactory.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());
+ }
+
+ @Test public void testUpdateProcedureCriteria() throws Exception {
+ String preparedSql = "delete from vm1.g37 where e1=?"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(1),
+ };
+
+ List<String> values = Arrays.asList("aa "); //$NON-NLS-1$
+ FakeDataManager dataManager = new FakeDataManager();
+ 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 {
+ String preparedSql = "select pm1.g1.e1 from pm1.g1 limit ?"; //$NON-NLS-1$
+
+ List values = Arrays.asList(-1);
+ FakeDataManager dataManager = new FakeDataManager();
+ helpTestProcessing(preparedSql, values, null, dataManager, RealMetadataFactory.example1Cached(), false, false, RealMetadataFactory.example1VDB());
+ }
+
+ @Test public void testExecParam() throws Exception {
+ String preparedSql = "exec pm1.sq2(?)"; //$NON-NLS-1$
+
+ List<String> values = Arrays.asList("c"); //$NON-NLS-1$
+ List[] expected = new List[] {
+ Arrays.asList("c", 1),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+ helpTestProcessing(preparedSql, values, expected, dataManager, RealMetadataFactory.example1Cached(), false, false, RealMetadataFactory.example1VDB());
+ }
+
+ @Test public void testLimitParam() throws Exception {
+ String preparedSql = "select e1 from pm1.g1 order by e1 desc limit ?"; //$NON-NLS-1$
+
+ List<?> values = Arrays.asList(1);
+ List[] expected = new List[] {
+ Arrays.asList("c"), //$NON-NLS-1$s
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+ helpTestProcessing(preparedSql, values, expected, dataManager, RealMetadataFactory.example1Cached(), false, false,RealMetadataFactory.example1VDB());
+ }
+
+ @Test public void testWithSubqueryPushdown() throws Exception {
+ String preparedSql = "SELECT pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e2 IN (SELECT pm1.g2.e2 FROM pm1.g2 WHERE pm1.g2.e1 = ?)"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("a"),
+ };
+
+ List values = Arrays.asList("a"); //$NON-NLS-1$
+
+ 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, RealMetadataFactory.example1VDB());
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatementBatchedUpdate.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatementBatchedUpdate.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatementBatchedUpdate.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,505 +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 static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Test;
-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.FakeDataManager;
-import org.teiid.query.processor.HardcodedDataManager;
-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;
-
-
-/**
- * JUnit TestCase to test planning and caching of <code>PreparedStatement</code>
- * plans that contain batched updates.
- *
- */
-public class TestPreparedStatementBatchedUpdate {
-
- @Test public void testBatchedUpdatePushdown() throws Exception {
- // Create query
- String preparedSql = "UPDATE pm1.g1 SET pm1.g1.e1=?, pm1.g1.e3=? WHERE pm1.g1.e2=?"; //$NON-NLS-1$
-
- // Create a testable prepared plan cache
- SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
-
- // Construct data manager with data
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData("UPDATE pm1.g1 SET e1 = ?, e3 = ? WHERE pm1.g1.e2 = ?", new List[] {Arrays.asList(4)}); //$NON-NLS-1$
- // Source capabilities must support batched updates
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.BULK_UPDATE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // batch with two commands
- ArrayList<ArrayList<Object>> values = new ArrayList<ArrayList<Object>>(2);
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0) }))); //$NON-NLS-1$
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { null, Boolean.FALSE, new Integer(1) })));
-
- List<?>[] expected = new List[] {
- Arrays.asList(4)
- };
-
- // Create the plan and process the query
- TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, FakeMetadataFactory.example1Cached(), prepPlanCache, false, false, false,FakeMetadataFactory.example1VDB());
- Update update = (Update)dataManager.getCommandHistory().iterator().next();
- assertTrue(((Constant)update.getChangeList().getClauses().get(0).getValue()).isMultiValued());
- }
-
- /**
- * Test prepared statements that use batched updates using the same prepared
- * command with same number of commands in the batch.
- * <p>
- * The test verifies that no errors occur when planning and executing the
- * same batched command SQL with the same number of batched command parameter
- * value sets. For example, if the first executeBatch() call were to occur
- * with two batched commands a repeated call with two batched commands
- * should not result in an error during planning or execution and the value
- * used in the second batched command should be used instead of any values
- * from the first batched command.
- * <p>
- * The test also verifies that the correct SQL is pushed to the data manager
- * to verify that the parameter substitution occurred and is correct and the
- * correct number of statements made it to the data manager for the respective
- * batch command.
- * <p>
- * The batched command "UPDATE pm1.g1 SET pm1.g1.e1=?, pm1.g1.e3=? WHERE pm1.g1.e2=?"
- * will appear as:
- * <p>
- * UPDATE pm1.g1 SET pm1.g1.e1='a', pm1.g1.e3=false WHERE pm1.g1.e2=0
- * UPDATE pm1.g1 SET pm1.g1.e1=null, pm1.g1.e3=false WHERE pm1.g1.e2=1
- * <p>
- * UPDATE pm1.g1 SET pm1.g1.e1='a', pm1.g1.e3=false WHERE pm1.g1.e2=0
- * UPDATE pm1.g1 SET pm1.g1.e1='b', pm1.g1.e3=true WHERE pm1.g1.e2=5
- * <p>
- * The result should be that one command is in the plan cache and
- * no plan creation, validation, or execution errors will occur and
- * a predetermined set of queries were executed in the data manager.
- *
- * @throws Exception
- */
- @Test public void testUpdateSameNumCmds() throws Exception {
- // Create query
- String preparedSql = "UPDATE pm1.g1 SET pm1.g1.e1=?, pm1.g1.e3=? WHERE pm1.g1.e2=?"; //$NON-NLS-1$
- // Create a testable prepared plan cache
- SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Source capabilities must support batched updates
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.BATCHED_UPDATES, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Something to hold our final query list
- List<String> finalQueryList = new ArrayList<String>(13);
-
- // Create expected results
- // first command should result in 2 rows affected
- // second command should result in 2 rows affected
- List<?>[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2) })
- };
-
- // batch with two commands
- List<List<Object>> values = new ArrayList<List<Object>>(2);
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0) }))); //$NON-NLS-1$
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { null, Boolean.FALSE, new Integer(1) })));
-
- // Add our expected queries to the final query list
- finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'a', e3 = FALSE WHERE pm1.g1.e2 = 0")); //$NON-NLS-1$
- 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());
-
- // Repeat with different number of commands in batch
- // Create expected results
- // first command should result in 2 rows affected
- expected = new List[] {
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(0) })
- };
-
- // batch with two commands
- values = new ArrayList<List<Object>>(1);
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0) }))); //$NON-NLS-1$
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "b", Boolean.TRUE, new Integer(5) }))); //$NON-NLS-1$
-
- // Add our expected queries to the final query list
- finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'a', e3 = FALSE WHERE pm1.g1.e2 = 0")); //$NON-NLS-1$
- 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());
-
- // Verify all the queries that were run
- assertEquals("Unexpected queries executed -", finalQueryList, dataManager.getQueries()); //$NON-NLS-1$
- }
-
- /**
- * Test prepared statements that use batched updates using the same prepared
- * command with same number of commands in the batch. Update is performed
- * against a view model instead of a source model.
- * <p>
- * The test verifies that no errors occur when planning and executing the
- * same batched command SQL with the same number of batched command parameter
- * value sets. For example, if the first executeBatch() call were to occur
- * with two batched commands a repeated call with two batched commands
- * should not result in an error during planning or execution and the value
- * used in the second batched command should be used instead of any values
- * from the first batched command.
- * <p>
- * The test also verifies that the correct SQL is pushed to the data manager
- * to verify that the parameter substitution occurred and is correct and the
- * correct number of statements made it to the data manager for the respective
- * batch command.
- * <p>
- * The batched command "UPDATE vm1.g1 SET vm1.g1.e2=? WHERE vm1.g1.e1=?"
- * will appear as:
- * <p>
- * UPDATE pm1.g1 SET e2=0 WHERE pm1.g1.e1='a'
- * UPDATE pm1.g1 SET e2=1 WHERE pm1.g1.e1='b'
- * <p>
- * UPDATE pm1.g1 SET e2=2 WHERE pm1.g1.e1='c'
- * UPDATE pm1.g1 SET e2=3 WHERE pm1.g1.e1='d'
- * <p>
- * The result should be that one command is in the plan cache and
- * no plan creation, validation, or execution errors will occur and
- * a predetermined set of queries were executed in the data manager.
- *
- * @throws Exception
- */
- @Test public void testUpdateSameNumCmds_Virtual() throws Exception {
- // Create query
- String preparedSql = "UPDATE vm1.g1 SET vm1.g1.e2=? WHERE vm1.g1.e1=?"; //$NON-NLS-1$
- // Create a testable prepared plan cache
- SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Source capabilities must support batched updates
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.BATCHED_UPDATES, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Something to hold our final query list
- List<String> finalQueryList = new ArrayList<String>();
-
- // Create expected results
- List<?>[] expected = new List[] {
- Arrays.asList(3),
- Arrays.asList(1)
- };
-
- // batch with two commands
- ArrayList<ArrayList<Object>> values = new ArrayList<ArrayList<Object>>(2);
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(0), "a" }))); //$NON-NLS-1$
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(1), "b" }))); //$NON-NLS-1$
-
- // Add our expected queries to the final query list
- finalQueryList.add(new String("UPDATE pm1.g1 SET e2 = 0 WHERE pm1.g1.e1 = 'a'")); //$NON-NLS-1$
- 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());
-
- // Repeat
- expected = new List[] {
- Arrays.asList(1),
- Arrays.asList(0)
- };
-
- // batch with two commands
- values = new ArrayList<ArrayList<Object>>(1);
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(2), "c" }))); //$NON-NLS-1$
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(3), "d" }))); //$NON-NLS-1$
-
- // Add our expected queries to the final query list
- finalQueryList.add(new String("UPDATE pm1.g1 SET e2 = 2 WHERE pm1.g1.e1 = 'c'")); //$NON-NLS-1$
- 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());
-
- // Verify all the queries that were run
- assertEquals("Unexpected queries executed -", finalQueryList, dataManager.getQueries()); //$NON-NLS-1$
- }
-
- /**
- * Test prepared statements that use batched updates using the same prepared
- * command with varying number of commands in the batch.
- * <p>
- * The test verifies that no errors occur when planning and executing the
- * same batched command SQL with varying number of batched command parameter
- * value sets. For example, if the first executeBatch() call were to occur
- * with two batched commands a repeated call with only one batched command
- * should not result in an error during planning or execution.
- * <p>
- * The test also verifies that the correct SQL is pushed to the data manager
- * to verify that the parameter substitution occurred and is correct and the
- * correct number of statements made it to the data manager for the respective
- * batch command.
- * <p>
- * The batched command "UPDATE pm1.g1 SET pm1.g1.e1=?, pm1.g1.e3=? WHERE pm1.g1.e2=?"
- * will appear as:
- * <p>
- * UPDATE pm1.g1 SET pm1.g1.e1='a', pm1.g1.e3=false WHERE pm1.g1.e2=0
- * UPDATE pm1.g1 SET pm1.g1.e1=null, pm1.g1.e3=false WHERE pm1.g1.e2=1
- * <p>
- * UPDATE pm1.g1 SET pm1.g1.e1='a', pm1.g1.e3=false WHERE pm1.g1.e2=0
- * <p>
- * UPDATE pm1.g1 SET pm1.g1.e1='a', pm1.g1.e3=false WHERE pm1.g1.e2=0
- * UPDATE pm1.g1 SET pm1.g1.e1=null, pm1.g1.e3=false WHERE pm1.g1.e2=1
- * UPDATE pm1.g1 SET pm1.g1.e1='c', pm1.g1.e3=true WHERE pm1.g1.e2=4
- * UPDATE pm1.g1 SET pm1.g1.e1='b', pm1.g1.e3=true WHERE pm1.g1.e2=5
- * <p>
- * The result should be that three commands are in the plan cache and
- * no plan creation, validation, or execution errors will occur and
- * a predetermined set of queries were executed in the data manager.
- *
- * @throws Exception
- */
- @Test public void testUpdateVarNumCmds() throws Exception {
- // Create query
- String preparedSql = "UPDATE pm1.g1 SET pm1.g1.e1=?, pm1.g1.e3=? WHERE pm1.g1.e2=?"; //$NON-NLS-1$
- // Create a testable prepared plan cache
- SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Source capabilities must support batched updates
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.BATCHED_UPDATES, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Something to hold our final query list
- List<String> finalQueryList = new ArrayList<String>(13);
-
- // Create expected results
- // first command should result in 2 rows affected
- // second command should result in 2 rows affected
- List<?>[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2) })
- };
-
- // batch with two commands
- ArrayList<ArrayList<Object>> values = new ArrayList<ArrayList<Object>>(2);
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0) }))); //$NON-NLS-1$
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { null, Boolean.FALSE, new Integer(1) })));
-
- // Add our expected queries to the final query list
- finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'a', e3 = FALSE WHERE pm1.g1.e2 = 0")); //$NON-NLS-1$
- 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());
-
- // Repeat with different number of commands in batch
- // Create expected results
- // first command should result in 2 rows affected
- expected = new List[] {
- Arrays.asList(new Object[] { new Integer(2) })
- };
-
- // batch with one command
- values = new ArrayList<ArrayList<Object>>(1);
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0) }))); //$NON-NLS-1$
-
- // Add our expected queries to the final query list
- 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());
-
- // Repeat with different number of commands in batch
- // Create expected results
- // first command should result in 2 rows affected
- // second command should result in 2 rows affected
- // third command should result in 0 rows affected
- // fourth command should result in 0 rows affected
- expected = new List[] {
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(0) })
- };
-
- // batch with four commands
- values = new ArrayList<ArrayList<Object>>(4);
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0)} ))); //$NON-NLS-1$
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { null, Boolean.FALSE, new Integer(1)} )));
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "c", Boolean.TRUE, new Integer(4)} ))); //$NON-NLS-1$
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "b", Boolean.TRUE, new Integer(5)} ))); //$NON-NLS-1$
-
- // Add our expected queries to the final query list
- finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'a', e3 = FALSE WHERE pm1.g1.e2 = 0")); //$NON-NLS-1$
- finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = null, e3 = FALSE WHERE pm1.g1.e2 = 1")); //$NON-NLS-1$
- 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());
-
- // Verify all the queries that were run
- assertEquals("Unexpected queries executed -", finalQueryList, dataManager.getQueries()); //$NON-NLS-1$
- }
-
- /**
- * Test prepared statements that use batched updates using the same prepared
- * command with varying number of commands in the batch. Update is
- * performed against a view model instead of a source model.
- * <p>
- * The test verifies that no errors occur when planning and executing the
- * same batched command SQL with varying number of batched command parameter
- * value sets. For example, if the first executeBatch() call were to occur
- * with two batched commands a repeated call with only one batched command
- * should not result in an error during planning or execution.
- * <p>
- * The test also verifies that the correct SQL is pushed to the data manager
- * to verify that the parameter substitution occurred and is correct and the
- * correct number of statements made it to the data manager for the respective
- * batch command.
- * <p>
- * The batched command "UPDATE vm1.g1 SET vm1.g1.e1=?, vm1.g1.e3=? WHERE vm1.g1.e2=?"
- * will appear as:
- * <p>
- * UPDATE pm1.g1 SET e1='a', e3=false WHERE pm1.g1.e2=0
- * UPDATE pm1.g1 SET e1='b', e3=true WHERE pm1.g1.e2=1
- * <p>
- * UPDATE pm1.g1 SET e1='c', e3=false WHERE pm1.g1.e2=1
- * <p>
- * UPDATE pm1.g1 SET e1='d', e3=false WHERE pm1.g1.e2=1
- * UPDATE pm1.g1 SET e1='e', e3=false WHERE pm1.g1.e2=0
- * UPDATE pm1.g1 SET e1='f', e3=true WHERE pm1.g1.e2=2
- * UPDATE pm1.g1 SET e1='g', e3=true WHERE pm1.g1.e2=3
- * <p>
- * The result should be that three commands are in the plan cache and
- * no plan creation, validation, or execution errors will occur and
- * a predetermined set of queries were executed in the data manager.
- *
- * @throws Exception
- */
- @Test public void testUpdateVarNumCmds_Virtual() throws Exception {
- // Create query
- String preparedSql = "UPDATE vm1.g1 SET vm1.g1.e1=?, vm1.g1.e3=? WHERE vm1.g1.e2=?"; //$NON-NLS-1$
- // Create a testable prepared plan cache
- SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Source capabilities must support batched updates
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.BATCHED_UPDATES, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Something to hold our final query list
- List<String> finalQueryList = new ArrayList<String>(13);
-
- // Create expected results
- List<?>[] expected = new List[] {
- Arrays.asList(2),
- Arrays.asList(2)
- };
-
- // batch with two commands
- ArrayList<ArrayList<Object>> values = new ArrayList<ArrayList<Object>>(2);
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0) }))); //$NON-NLS-1$
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "b", Boolean.TRUE, new Integer(1) }))); //$NON-NLS-1$
-
- // Add our expected queries to the final query list
- finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'a', e3 = FALSE WHERE pm1.g1.e2 = 0")); //$NON-NLS-1$
- 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());
-
- // Repeat with different number of commands in batch
- expected = new List[] {
- Arrays.asList(new Object[] { new Integer(2) })
- };
-
- // batch with one command
- values = new ArrayList<ArrayList<Object>>(1);
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "c", Boolean.FALSE, new Integer(1) }))); //$NON-NLS-1$
-
- // Add our expected queries to the final query list
- 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());
-
- // Repeat with different number of commands in batch
- expected = new List[] {
- Arrays.asList(2),
- Arrays.asList(2),
- Arrays.asList(1),
- Arrays.asList(1)
- };
-
- // batch with four commands
- values = new ArrayList<ArrayList<Object>>(4);
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "d", Boolean.FALSE, new Integer(1)} ))); //$NON-NLS-1$
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "e", Boolean.FALSE, new Integer(0)} ))); //$NON-NLS-1$
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "f", Boolean.TRUE, new Integer(2)} ))); //$NON-NLS-1$
- values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "g", Boolean.TRUE, new Integer(3)} ))); //$NON-NLS-1$
-
- // Add our expected queries to the final query list
- finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'd', e3 = FALSE WHERE pm1.g1.e2 = 1")); //$NON-NLS-1$
- finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'e', e3 = FALSE WHERE pm1.g1.e2 = 0")); //$NON-NLS-1$
- 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());
-
- // Verify all the queries that were run
- assertEquals("Unexpected queries executed -", finalQueryList, dataManager.getQueries()); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatementBatchedUpdate.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatementBatchedUpdate.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatementBatchedUpdate.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatementBatchedUpdate.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,505 @@
+/*
+ * 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.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+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.FakeDataManager;
+import org.teiid.query.processor.HardcodedDataManager;
+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.RealMetadataFactory;
+
+
+/**
+ * JUnit TestCase to test planning and caching of <code>PreparedStatement</code>
+ * plans that contain batched updates.
+ *
+ */
+public class TestPreparedStatementBatchedUpdate {
+
+ @Test public void testBatchedUpdatePushdown() throws Exception {
+ // Create query
+ String preparedSql = "UPDATE pm1.g1 SET pm1.g1.e1=?, pm1.g1.e3=? WHERE pm1.g1.e2=?"; //$NON-NLS-1$
+
+ // Create a testable prepared plan cache
+ SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
+
+ // Construct data manager with data
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("UPDATE pm1.g1 SET e1 = ?, e3 = ? WHERE pm1.g1.e2 = ?", new List[] {Arrays.asList(4)}); //$NON-NLS-1$
+ // Source capabilities must support batched updates
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.BULK_UPDATE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // batch with two commands
+ ArrayList<ArrayList<Object>> values = new ArrayList<ArrayList<Object>>(2);
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0) }))); //$NON-NLS-1$
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { null, Boolean.FALSE, new Integer(1) })));
+
+ List<?>[] expected = new List[] {
+ Arrays.asList(4)
+ };
+
+ // Create the plan and process the query
+ 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());
+ }
+
+ /**
+ * Test prepared statements that use batched updates using the same prepared
+ * command with same number of commands in the batch.
+ * <p>
+ * The test verifies that no errors occur when planning and executing the
+ * same batched command SQL with the same number of batched command parameter
+ * value sets. For example, if the first executeBatch() call were to occur
+ * with two batched commands a repeated call with two batched commands
+ * should not result in an error during planning or execution and the value
+ * used in the second batched command should be used instead of any values
+ * from the first batched command.
+ * <p>
+ * The test also verifies that the correct SQL is pushed to the data manager
+ * to verify that the parameter substitution occurred and is correct and the
+ * correct number of statements made it to the data manager for the respective
+ * batch command.
+ * <p>
+ * The batched command "UPDATE pm1.g1 SET pm1.g1.e1=?, pm1.g1.e3=? WHERE pm1.g1.e2=?"
+ * will appear as:
+ * <p>
+ * UPDATE pm1.g1 SET pm1.g1.e1='a', pm1.g1.e3=false WHERE pm1.g1.e2=0
+ * UPDATE pm1.g1 SET pm1.g1.e1=null, pm1.g1.e3=false WHERE pm1.g1.e2=1
+ * <p>
+ * UPDATE pm1.g1 SET pm1.g1.e1='a', pm1.g1.e3=false WHERE pm1.g1.e2=0
+ * UPDATE pm1.g1 SET pm1.g1.e1='b', pm1.g1.e3=true WHERE pm1.g1.e2=5
+ * <p>
+ * The result should be that one command is in the plan cache and
+ * no plan creation, validation, or execution errors will occur and
+ * a predetermined set of queries were executed in the data manager.
+ *
+ * @throws Exception
+ */
+ @Test public void testUpdateSameNumCmds() throws Exception {
+ // Create query
+ String preparedSql = "UPDATE pm1.g1 SET pm1.g1.e1=?, pm1.g1.e3=? WHERE pm1.g1.e2=?"; //$NON-NLS-1$
+ // Create a testable prepared plan cache
+ SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Source capabilities must support batched updates
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.BATCHED_UPDATES, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Something to hold our final query list
+ List<String> finalQueryList = new ArrayList<String>(13);
+
+ // Create expected results
+ // first command should result in 2 rows affected
+ // second command should result in 2 rows affected
+ List<?>[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2) })
+ };
+
+ // batch with two commands
+ List<List<Object>> values = new ArrayList<List<Object>>(2);
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0) }))); //$NON-NLS-1$
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { null, Boolean.FALSE, new Integer(1) })));
+
+ // Add our expected queries to the final query list
+ finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'a', e3 = FALSE WHERE pm1.g1.e2 = 0")); //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, false,RealMetadataFactory.example1VDB());
+
+ // Repeat with different number of commands in batch
+ // Create expected results
+ // first command should result in 2 rows affected
+ expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(0) })
+ };
+
+ // batch with two commands
+ values = new ArrayList<List<Object>>(1);
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0) }))); //$NON-NLS-1$
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "b", Boolean.TRUE, new Integer(5) }))); //$NON-NLS-1$
+
+ // Add our expected queries to the final query list
+ finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'a', e3 = FALSE WHERE pm1.g1.e2 = 0")); //$NON-NLS-1$
+ 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, 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$
+ }
+
+ /**
+ * Test prepared statements that use batched updates using the same prepared
+ * command with same number of commands in the batch. Update is performed
+ * against a view model instead of a source model.
+ * <p>
+ * The test verifies that no errors occur when planning and executing the
+ * same batched command SQL with the same number of batched command parameter
+ * value sets. For example, if the first executeBatch() call were to occur
+ * with two batched commands a repeated call with two batched commands
+ * should not result in an error during planning or execution and the value
+ * used in the second batched command should be used instead of any values
+ * from the first batched command.
+ * <p>
+ * The test also verifies that the correct SQL is pushed to the data manager
+ * to verify that the parameter substitution occurred and is correct and the
+ * correct number of statements made it to the data manager for the respective
+ * batch command.
+ * <p>
+ * The batched command "UPDATE vm1.g1 SET vm1.g1.e2=? WHERE vm1.g1.e1=?"
+ * will appear as:
+ * <p>
+ * UPDATE pm1.g1 SET e2=0 WHERE pm1.g1.e1='a'
+ * UPDATE pm1.g1 SET e2=1 WHERE pm1.g1.e1='b'
+ * <p>
+ * UPDATE pm1.g1 SET e2=2 WHERE pm1.g1.e1='c'
+ * UPDATE pm1.g1 SET e2=3 WHERE pm1.g1.e1='d'
+ * <p>
+ * The result should be that one command is in the plan cache and
+ * no plan creation, validation, or execution errors will occur and
+ * a predetermined set of queries were executed in the data manager.
+ *
+ * @throws Exception
+ */
+ @Test public void testUpdateSameNumCmds_Virtual() throws Exception {
+ // Create query
+ String preparedSql = "UPDATE vm1.g1 SET vm1.g1.e2=? WHERE vm1.g1.e1=?"; //$NON-NLS-1$
+ // Create a testable prepared plan cache
+ SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Source capabilities must support batched updates
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.BATCHED_UPDATES, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Something to hold our final query list
+ List<String> finalQueryList = new ArrayList<String>();
+
+ // Create expected results
+ List<?>[] expected = new List[] {
+ Arrays.asList(3),
+ Arrays.asList(1)
+ };
+
+ // batch with two commands
+ ArrayList<ArrayList<Object>> values = new ArrayList<ArrayList<Object>>(2);
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(0), "a" }))); //$NON-NLS-1$
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(1), "b" }))); //$NON-NLS-1$
+
+ // Add our expected queries to the final query list
+ finalQueryList.add(new String("UPDATE pm1.g1 SET e2 = 0 WHERE pm1.g1.e1 = 'a'")); //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, false, RealMetadataFactory.example1VDB());
+
+ // Repeat
+ expected = new List[] {
+ Arrays.asList(1),
+ Arrays.asList(0)
+ };
+
+ // batch with two commands
+ values = new ArrayList<ArrayList<Object>>(1);
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(2), "c" }))); //$NON-NLS-1$
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { new Integer(3), "d" }))); //$NON-NLS-1$
+
+ // Add our expected queries to the final query list
+ finalQueryList.add(new String("UPDATE pm1.g1 SET e2 = 2 WHERE pm1.g1.e1 = 'c'")); //$NON-NLS-1$
+ 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, 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$
+ }
+
+ /**
+ * Test prepared statements that use batched updates using the same prepared
+ * command with varying number of commands in the batch.
+ * <p>
+ * The test verifies that no errors occur when planning and executing the
+ * same batched command SQL with varying number of batched command parameter
+ * value sets. For example, if the first executeBatch() call were to occur
+ * with two batched commands a repeated call with only one batched command
+ * should not result in an error during planning or execution.
+ * <p>
+ * The test also verifies that the correct SQL is pushed to the data manager
+ * to verify that the parameter substitution occurred and is correct and the
+ * correct number of statements made it to the data manager for the respective
+ * batch command.
+ * <p>
+ * The batched command "UPDATE pm1.g1 SET pm1.g1.e1=?, pm1.g1.e3=? WHERE pm1.g1.e2=?"
+ * will appear as:
+ * <p>
+ * UPDATE pm1.g1 SET pm1.g1.e1='a', pm1.g1.e3=false WHERE pm1.g1.e2=0
+ * UPDATE pm1.g1 SET pm1.g1.e1=null, pm1.g1.e3=false WHERE pm1.g1.e2=1
+ * <p>
+ * UPDATE pm1.g1 SET pm1.g1.e1='a', pm1.g1.e3=false WHERE pm1.g1.e2=0
+ * <p>
+ * UPDATE pm1.g1 SET pm1.g1.e1='a', pm1.g1.e3=false WHERE pm1.g1.e2=0
+ * UPDATE pm1.g1 SET pm1.g1.e1=null, pm1.g1.e3=false WHERE pm1.g1.e2=1
+ * UPDATE pm1.g1 SET pm1.g1.e1='c', pm1.g1.e3=true WHERE pm1.g1.e2=4
+ * UPDATE pm1.g1 SET pm1.g1.e1='b', pm1.g1.e3=true WHERE pm1.g1.e2=5
+ * <p>
+ * The result should be that three commands are in the plan cache and
+ * no plan creation, validation, or execution errors will occur and
+ * a predetermined set of queries were executed in the data manager.
+ *
+ * @throws Exception
+ */
+ @Test public void testUpdateVarNumCmds() throws Exception {
+ // Create query
+ String preparedSql = "UPDATE pm1.g1 SET pm1.g1.e1=?, pm1.g1.e3=? WHERE pm1.g1.e2=?"; //$NON-NLS-1$
+ // Create a testable prepared plan cache
+ SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Source capabilities must support batched updates
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.BATCHED_UPDATES, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Something to hold our final query list
+ List<String> finalQueryList = new ArrayList<String>(13);
+
+ // Create expected results
+ // first command should result in 2 rows affected
+ // second command should result in 2 rows affected
+ List<?>[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2) })
+ };
+
+ // batch with two commands
+ ArrayList<ArrayList<Object>> values = new ArrayList<ArrayList<Object>>(2);
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0) }))); //$NON-NLS-1$
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { null, Boolean.FALSE, new Integer(1) })));
+
+ // Add our expected queries to the final query list
+ finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'a', e3 = FALSE WHERE pm1.g1.e2 = 0")); //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, false, RealMetadataFactory.example1VDB());
+
+ // Repeat with different number of commands in batch
+ // Create expected results
+ // first command should result in 2 rows affected
+ expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(2) })
+ };
+
+ // batch with one command
+ values = new ArrayList<ArrayList<Object>>(1);
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0) }))); //$NON-NLS-1$
+
+ // Add our expected queries to the final query list
+ 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, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, true, RealMetadataFactory.example1VDB());
+
+ // Repeat with different number of commands in batch
+ // Create expected results
+ // first command should result in 2 rows affected
+ // second command should result in 2 rows affected
+ // third command should result in 0 rows affected
+ // fourth command should result in 0 rows affected
+ expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(0) })
+ };
+
+ // batch with four commands
+ values = new ArrayList<ArrayList<Object>>(4);
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0)} ))); //$NON-NLS-1$
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { null, Boolean.FALSE, new Integer(1)} )));
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "c", Boolean.TRUE, new Integer(4)} ))); //$NON-NLS-1$
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "b", Boolean.TRUE, new Integer(5)} ))); //$NON-NLS-1$
+
+ // Add our expected queries to the final query list
+ finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'a', e3 = FALSE WHERE pm1.g1.e2 = 0")); //$NON-NLS-1$
+ finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = null, e3 = FALSE WHERE pm1.g1.e2 = 1")); //$NON-NLS-1$
+ 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, 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$
+ }
+
+ /**
+ * Test prepared statements that use batched updates using the same prepared
+ * command with varying number of commands in the batch. Update is
+ * performed against a view model instead of a source model.
+ * <p>
+ * The test verifies that no errors occur when planning and executing the
+ * same batched command SQL with varying number of batched command parameter
+ * value sets. For example, if the first executeBatch() call were to occur
+ * with two batched commands a repeated call with only one batched command
+ * should not result in an error during planning or execution.
+ * <p>
+ * The test also verifies that the correct SQL is pushed to the data manager
+ * to verify that the parameter substitution occurred and is correct and the
+ * correct number of statements made it to the data manager for the respective
+ * batch command.
+ * <p>
+ * The batched command "UPDATE vm1.g1 SET vm1.g1.e1=?, vm1.g1.e3=? WHERE vm1.g1.e2=?"
+ * will appear as:
+ * <p>
+ * UPDATE pm1.g1 SET e1='a', e3=false WHERE pm1.g1.e2=0
+ * UPDATE pm1.g1 SET e1='b', e3=true WHERE pm1.g1.e2=1
+ * <p>
+ * UPDATE pm1.g1 SET e1='c', e3=false WHERE pm1.g1.e2=1
+ * <p>
+ * UPDATE pm1.g1 SET e1='d', e3=false WHERE pm1.g1.e2=1
+ * UPDATE pm1.g1 SET e1='e', e3=false WHERE pm1.g1.e2=0
+ * UPDATE pm1.g1 SET e1='f', e3=true WHERE pm1.g1.e2=2
+ * UPDATE pm1.g1 SET e1='g', e3=true WHERE pm1.g1.e2=3
+ * <p>
+ * The result should be that three commands are in the plan cache and
+ * no plan creation, validation, or execution errors will occur and
+ * a predetermined set of queries were executed in the data manager.
+ *
+ * @throws Exception
+ */
+ @Test public void testUpdateVarNumCmds_Virtual() throws Exception {
+ // Create query
+ String preparedSql = "UPDATE vm1.g1 SET vm1.g1.e1=?, vm1.g1.e3=? WHERE vm1.g1.e2=?"; //$NON-NLS-1$
+ // Create a testable prepared plan cache
+ SessionAwareCache<PreparedPlan> prepPlanCache = new SessionAwareCache<PreparedPlan>();
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Source capabilities must support batched updates
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.BATCHED_UPDATES, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Something to hold our final query list
+ List<String> finalQueryList = new ArrayList<String>(13);
+
+ // Create expected results
+ List<?>[] expected = new List[] {
+ Arrays.asList(2),
+ Arrays.asList(2)
+ };
+
+ // batch with two commands
+ ArrayList<ArrayList<Object>> values = new ArrayList<ArrayList<Object>>(2);
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "a", Boolean.FALSE, new Integer(0) }))); //$NON-NLS-1$
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "b", Boolean.TRUE, new Integer(1) }))); //$NON-NLS-1$
+
+ // Add our expected queries to the final query list
+ finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'a', e3 = FALSE WHERE pm1.g1.e2 = 0")); //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, false, RealMetadataFactory.example1VDB());
+
+ // Repeat with different number of commands in batch
+ expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(2) })
+ };
+
+ // batch with one command
+ values = new ArrayList<ArrayList<Object>>(1);
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "c", Boolean.FALSE, new Integer(1) }))); //$NON-NLS-1$
+
+ // Add our expected queries to the final query list
+ 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, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, true, RealMetadataFactory.example1VDB());
+
+ // Repeat with different number of commands in batch
+ expected = new List[] {
+ Arrays.asList(2),
+ Arrays.asList(2),
+ Arrays.asList(1),
+ Arrays.asList(1)
+ };
+
+ // batch with four commands
+ values = new ArrayList<ArrayList<Object>>(4);
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "d", Boolean.FALSE, new Integer(1)} ))); //$NON-NLS-1$
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "e", Boolean.FALSE, new Integer(0)} ))); //$NON-NLS-1$
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "f", Boolean.TRUE, new Integer(2)} ))); //$NON-NLS-1$
+ values.add(new ArrayList<Object>(Arrays.asList(new Object[] { "g", Boolean.TRUE, new Integer(3)} ))); //$NON-NLS-1$
+
+ // Add our expected queries to the final query list
+ finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'd', e3 = FALSE WHERE pm1.g1.e2 = 1")); //$NON-NLS-1$
+ finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'e', e3 = FALSE WHERE pm1.g1.e2 = 0")); //$NON-NLS-1$
+ 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, 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$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,172 +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 java.util.ArrayList;
-
-import junit.framework.TestCase;
-
-import org.mockito.Mockito;
-import org.teiid.client.RequestMessage;
-import org.teiid.client.RequestMessage.StatementType;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
-import org.teiid.dqp.internal.datamgr.FakeTransactionService;
-import org.teiid.dqp.service.AutoGenDataService;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.FakeDataManager;
-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.util.ContextProperties;
-
-
-
-/**
- * @since 4.2
- */
-public class TestRequest extends TestCase {
-
- private static final TempTableStore TEMP_TABLE_STORE = new TempTableStore("1"); //$NON-NLS-1$
- private final static String QUERY = "SELECT * FROM pm1.g1"; //$NON-NLS-1$
-
- /**
- * Constructor for TestRequest.
- * @param name
- */
- public TestRequest(String name) {
- super(name);
- }
-
- /**
- * Test Request.validateEntitlement().
- * Make sure that this can be called both before and after metadata is initialized.
- * See defect 17209.
- * @throws Exception
- * @since 4.2
- */
- public void testValidateEntitlement() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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());
-
- request.initialize(message, null, null,new FakeTransactionService(), TEMP_TABLE_STORE, workContext, null);
- request.initMetadata();
- request.setAuthorizationValidator(new DataRoleAuthorizationValidator(true, true, true));
- request.validateAccess(command);
- }
-
-
- /**
- * Test Request.processRequest().
- * Test processing the same query twice, and make sure that doesn't cause problems.
- * See defect 17209.
- * @throws Exception
- * @since 4.2
- */
- public void testProcessRequest() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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());
-
- helpProcessMessage(message, null, workContext);
-
- //Try again, now that plan is already cached.
- //If this doesn't throw an exception, assume it was successful.
- message = new RequestMessage(QUERY);
- helpProcessMessage(message, null, workContext);
- }
-
- public void testCommandContext() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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());
-
- Request request = helpProcessMessage(message, null, workContext);
- assertEquals("1", request.context.getEnvironmentProperties().get(ContextProperties.SESSION_ID)); //$NON-NLS-1$
- }
-
- private Request helpProcessMessage(RequestMessage message, SessionAwareCache<PreparedPlan> cache, DQPWorkContext workContext) throws TeiidComponentException,
- TeiidProcessingException {
- Request request = null;
- if (cache != null) {
- request = new PreparedStatementRequest(cache);
- } else {
- request = new Request();
- }
- ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
- workContext.getVDB().addAttchment(ConnectorManagerRepository.class, repo);
- Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(new AutoGenDataService());
-
- request.initialize(message, Mockito.mock(BufferManager.class),
- new FakeDataManager(), new FakeTransactionService(), TEMP_TABLE_STORE, workContext, null);
- request.setAuthorizationValidator(new DataRoleAuthorizationValidator(false, true, true));
- request.processRequest();
- return request;
- }
-
- /**
- * Test PreparedStatementRequest.processRequest().
- * Test processing the same query twice, and make sure that doesn't cause problems.
- * @throws Exception
- * @since 4.2
- */
- public void testProcessRequestPreparedStatement() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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());
-
- message.setStatementType(StatementType.PREPARED);
- message.setParameterValues(new ArrayList());
-
- helpProcessMessage(message, cache, workContext);
-
- //Try again, now that plan is already cached.
- //If this doesn't throw an exception, assume it was successful.
- message = new RequestMessage(QUERY);
- message.setStatementType(StatementType.PREPARED);
- message.setParameterValues(new ArrayList());
-
- helpProcessMessage(message, cache, workContext);
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,173 @@
+/*
+ * 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 java.util.ArrayList;
+
+import junit.framework.TestCase;
+
+import org.mockito.Mockito;
+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;
+import org.teiid.dqp.internal.datamgr.FakeTransactionService;
+import org.teiid.dqp.service.AutoGenDataService;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.FakeDataManager;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.tempdata.TempTableStore;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.util.ContextProperties;
+
+
+
+/**
+ * @since 4.2
+ */
+public class TestRequest extends TestCase {
+
+ private static final TempTableStore TEMP_TABLE_STORE = new TempTableStore("1"); //$NON-NLS-1$
+ private final static String QUERY = "SELECT * FROM pm1.g1"; //$NON-NLS-1$
+
+ /**
+ * Constructor for TestRequest.
+ * @param name
+ */
+ public TestRequest(String name) {
+ super(name);
+ }
+
+ /**
+ * Test Request.validateEntitlement().
+ * Make sure that this can be called both before and after metadata is initialized.
+ * See defect 17209.
+ * @throws Exception
+ * @since 4.2
+ */
+ public void testValidateEntitlement() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ Request request = new Request();
+ Command command = QueryParser.getQueryParser().parseCommand(QUERY);
+ QueryResolver.resolveCommand(command, metadata);
+
+ RequestMessage message = new RequestMessage();
+ DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(metadata, RealMetadataFactory.example1VDB());
+
+ request.initialize(message, BufferManagerFactory.getStandaloneBufferManager(), null,new FakeTransactionService(), TEMP_TABLE_STORE, workContext, null);
+ request.initMetadata();
+ request.setAuthorizationValidator(new DataRoleAuthorizationValidator(true, true, true));
+ request.validateAccess(command);
+ }
+
+
+ /**
+ * Test Request.processRequest().
+ * Test processing the same query twice, and make sure that doesn't cause problems.
+ * See defect 17209.
+ * @throws Exception
+ * @since 4.2
+ */
+ public void testProcessRequest() throws Exception {
+ 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 = RealMetadataFactory.buildWorkContext(metadata, RealMetadataFactory.example1VDB());
+
+ helpProcessMessage(message, null, workContext);
+
+ //Try again, now that plan is already cached.
+ //If this doesn't throw an exception, assume it was successful.
+ message = new RequestMessage(QUERY);
+ helpProcessMessage(message, null, workContext);
+ }
+
+ public void testCommandContext() throws Exception {
+ 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 = RealMetadataFactory.buildWorkContext(metadata, RealMetadataFactory.example1VDB());
+
+ Request request = helpProcessMessage(message, null, workContext);
+ assertEquals("1", request.context.getEnvironmentProperties().get(ContextProperties.SESSION_ID)); //$NON-NLS-1$
+ }
+
+ private Request helpProcessMessage(RequestMessage message, SessionAwareCache<PreparedPlan> cache, DQPWorkContext workContext) throws TeiidComponentException,
+ TeiidProcessingException {
+ Request request = null;
+ if (cache != null) {
+ request = new PreparedStatementRequest(cache);
+ } else {
+ request = new Request();
+ }
+ ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
+ workContext.getVDB().addAttchment(ConnectorManagerRepository.class, repo);
+ Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(new AutoGenDataService());
+
+ request.initialize(message, Mockito.mock(BufferManager.class),
+ new FakeDataManager(), new FakeTransactionService(), TEMP_TABLE_STORE, workContext, null);
+ request.setAuthorizationValidator(new DataRoleAuthorizationValidator(false, true, true));
+ request.processRequest();
+ return request;
+ }
+
+ /**
+ * Test PreparedStatementRequest.processRequest().
+ * Test processing the same query twice, and make sure that doesn't cause problems.
+ * @throws Exception
+ * @since 4.2
+ */
+ public void testProcessRequestPreparedStatement() throws Exception {
+ 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 = RealMetadataFactory.buildWorkContext(metadata, RealMetadataFactory.example1VDB());
+
+ message.setStatementType(StatementType.PREPARED);
+ message.setParameterValues(new ArrayList());
+
+ helpProcessMessage(message, cache, workContext);
+
+ //Try again, now that plan is already cached.
+ //If this doesn't throw an exception, assume it was successful.
+ message = new RequestMessage(QUERY);
+ message.setStatementType(StatementType.PREPARED);
+ message.setParameterValues(new ArrayList());
+
+ helpProcessMessage(message, cache, workContext);
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,156 +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 static org.junit.Assert.*;
-
-import org.junit.Test;
-
-
-public class TestWorkItemState {
-
- private class TestWorkItem extends AbstractWorkItem {
-
- private boolean isDone;
- private boolean callMoreWork;
- private boolean resumed;
-
- private TestWorkItem() {
- this(false, false);
- }
-
- private TestWorkItem(boolean done, boolean callMoreWork) {
- super(false);
- this.isDone = done;
- this.callMoreWork = callMoreWork;
- }
-
- @Override
- protected boolean isDoneProcessing() {
- return isDone;
- }
-
- @Override
- protected void process() {
- assertWorkingState();
- if (callMoreWork) {
- this.moreWork();
- }
- }
-
- @Override
- protected void resumeProcessing() {
- this.resumed = true;
- }
-
- @Override
- public String toString() {
- return "TestItem"; //$NON-NLS-1$
- }
-
- private void checkState(ThreadState expectedState) {
- assertEquals(expectedState, getThreadState());
- }
-
- private void assertIdleState() {
- checkState(ThreadState.IDLE);
- }
-
- private void assertMoreWorkState() {
- checkState(ThreadState.MORE_WORK);
- }
-
- private void assertWorkingState() {
- checkState(ThreadState.WORKING);
- }
-
- private void assertDoneState() {
- checkState(ThreadState.DONE);
- }
- }
-
- @Test public void testInitialState() {
- TestWorkItem item = new TestWorkItem();
- item.assertMoreWorkState();
- }
-
- @Test public void testGotoIdleState() {
- TestWorkItem item = new TestWorkItem();
- item.run();
- item.assertIdleState();
- }
-
- @Test public void testGotoMoreWorkState() {
- TestWorkItem item = new TestWorkItem();
- item.run();
- item.moreWork();
- item.assertMoreWorkState();
- }
-
- @Test public void testGotoWorkingState() {
- TestWorkItem item = new TestWorkItem();
- item.run();
- item.moreWork();
- item.run();
- }
-
- @Test public void testResume() {
- TestWorkItem item = new TestWorkItem();
- item.run();
- assertFalse(item.resumed);
- item.moreWork();
- assertTrue(item.resumed);
- }
-
- @Test public void testResumeDuringWorking() {
- TestWorkItem item = new TestWorkItem(false, true);
- assertFalse(item.resumed);
- item.run();
- assertTrue(item.resumed);
- }
-
- @Test public void testRunAfterDone() {
- TestWorkItem item = new TestWorkItem(true, false);
- item.run();
- item.assertDoneState();
- try {
- item.run();
- fail("exception expected"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
-
- }
- }
-
- @Test public void testRunDuringIdle() {
- TestWorkItem item = new TestWorkItem();
- item.run();
- item.assertIdleState();
- try {
- item.run();
- fail("exception expected"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
-
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,192 @@
+/*
+ * 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 org.junit.Test;
+import org.teiid.dqp.internal.process.AbstractWorkItem.ThreadState;
+
+
+public class TestWorkItemState {
+
+ private final class WorkItemRunner implements Runnable {
+ TestWorkItem workItem;
+
+ @Override
+ public void run() {
+ workItem.run();
+ }
+ }
+
+ private class TestWorkItem extends AbstractWorkItem {
+
+ private boolean isDone;
+ private boolean callMoreWork;
+ private boolean resumed;
+
+ private TestWorkItem() {
+ this(false, false);
+ }
+
+ private TestWorkItem(boolean done, boolean callMoreWork) {
+ this(done, callMoreWork, null);
+ }
+
+ private TestWorkItem(boolean done, boolean callMoreWork, Thread callingThread) {
+ super(callingThread);
+ this.isDone = done;
+ this.callMoreWork = callMoreWork;
+ }
+
+ @Override
+ protected boolean isDoneProcessing() {
+ return isDone;
+ }
+
+ @Override
+ protected void process() {
+ assertWorkingState();
+ if (callMoreWork) {
+ this.moreWork();
+ }
+ }
+
+ @Override
+ protected void resumeProcessing() {
+ this.resumed = true;
+ }
+
+ @Override
+ public String toString() {
+ return "TestItem"; //$NON-NLS-1$
+ }
+
+ private void checkState(ThreadState expectedState) {
+ assertEquals(expectedState, getThreadState());
+ }
+
+ private void assertIdleState() {
+ checkState(ThreadState.IDLE);
+ }
+
+ private void assertMoreWorkState() {
+ checkState(ThreadState.MORE_WORK);
+ }
+
+ private void assertWorkingState() {
+ checkState(ThreadState.WORKING);
+ }
+
+ private void assertDoneState() {
+ checkState(ThreadState.DONE);
+ }
+ }
+
+ @Test public void testInitialState() {
+ TestWorkItem item = new TestWorkItem();
+ item.assertMoreWorkState();
+ }
+
+ @Test public void testGotoIdleState() {
+ TestWorkItem item = new TestWorkItem();
+ item.run();
+ item.assertIdleState();
+ }
+
+ @Test public void testGotoMoreWorkState() {
+ TestWorkItem item = new TestWorkItem();
+ item.run();
+ item.moreWork();
+ item.assertMoreWorkState();
+ }
+
+ @Test public void testGotoWorkingState() {
+ TestWorkItem item = new TestWorkItem();
+ item.run();
+ item.moreWork();
+ item.run();
+ }
+
+ @Test public void testResume() {
+ TestWorkItem item = new TestWorkItem();
+ item.run();
+ assertFalse(item.resumed);
+ item.moreWork();
+ assertTrue(item.resumed);
+ }
+
+ @Test public void testResumeDuringWorking() {
+ TestWorkItem item = new TestWorkItem(false, true);
+ assertFalse(item.resumed);
+ item.run();
+ assertTrue(item.resumed);
+ }
+
+ @Test public void testRunAfterDone() {
+ TestWorkItem item = new TestWorkItem(true, false);
+ item.run();
+ item.assertDoneState();
+ try {
+ item.run();
+ fail("exception expected"); //$NON-NLS-1$
+ } catch (IllegalStateException e) {
+
+ }
+ }
+
+ @Test public void testRunDuringIdle() {
+ TestWorkItem item = new TestWorkItem();
+ item.run();
+ item.assertIdleState();
+ try {
+ item.run();
+ fail("exception expected"); //$NON-NLS-1$
+ } catch (IllegalStateException e) {
+
+ }
+ }
+
+ @Test public void testUsingCallingThreadIdle() throws Exception {
+ WorkItemRunner r = new WorkItemRunner();
+ Thread t = new Thread(r);
+ final TestWorkItem item = new TestWorkItem(false, false, t) {
+ @Override
+ protected boolean shouldPause() {
+ return true;
+ }
+ };
+ r.workItem = item;
+ t.start();
+ for (int i = 0; i < 10 && item.getThreadState() != ThreadState.IDLE; i++) {
+ Thread.sleep(100);
+ }
+ if (item.getThreadState() != ThreadState.IDLE) {
+ fail();
+ }
+ item.moreWork();
+ //if we don't return from this call, that means that this thread has been hijacked -
+ //we should instead use t.
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceElementReplacementVisitor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceElementReplacementVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceElementReplacementVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.dqp.internal.process.multisource;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import junit.framework.TestCase;
-
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.parser.QueryParser;
-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;
-
-
-
-/**
- * @since 4.2
- */
-public class TestMultiSourceElementReplacementVisitor extends TestCase {
-
- public QueryMetadataInterface getMetadata() throws Exception {
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
- Set<String> multiSourceModels = new HashSet<String>();
- multiSourceModels.add("MultiModel"); //$NON-NLS-1$
- MultiSourceMetadataWrapper wrapper = new MultiSourceMetadataWrapper(metadata, multiSourceModels);
-
- return wrapper;
- }
-
- public void helpTest(String sql, QueryMetadataInterface metadata, String expected) throws Exception {
- QueryParser parser = new QueryParser();
- Command command = parser.parseCommand(sql);
- QueryResolver.resolveCommand(command, metadata);
-
- MultiSourceElementReplacementVisitor visitor = new MultiSourceElementReplacementVisitor("x"); //$NON-NLS-1$
- DeepPostOrderNavigator.doVisit(command, visitor);
-
- assertEquals(expected, command.toString());
- }
-
- public void testCommon() throws Exception {
- helpTest("SELECT a, b, SOURCE_NAME FROM MultiModel.Phys WHERE SOURCE_NAME = SOURCE_NAME", //$NON-NLS-1$
- getMetadata(),
- "SELECT a, b, 'x' FROM MultiModel.Phys WHERE 'x' = 'x'"); //$NON-NLS-1$
- }
-
- public void testLike() throws Exception {
- helpTest("SELECT a, b FROM MultiModel.Phys WHERE SOURCE_NAME LIKE SOURCE_NAME", //$NON-NLS-1$
- getMetadata(),
- "SELECT a, b FROM MultiModel.Phys WHERE 'x' LIKE 'x'"); //$NON-NLS-1$
- }
-
- public void testIn() throws Exception {
- helpTest("SELECT a, b FROM MultiModel.Phys WHERE SOURCE_NAME IN ('a', 'b', SOURCE_NAME)", //$NON-NLS-1$
- getMetadata(),
- "SELECT a, b FROM MultiModel.Phys WHERE 'x' IN ('a', 'b', 'x')"); //$NON-NLS-1$
- }
-
- public void testNot() throws Exception {
- helpTest("SELECT a, b FROM MultiModel.Phys WHERE NOT (SOURCE_NAME IN ('a', 'b', SOURCE_NAME))", //$NON-NLS-1$
- getMetadata(),
- "SELECT a, b FROM MultiModel.Phys WHERE NOT ('x' IN ('a', 'b', 'x'))"); //$NON-NLS-1$
- }
-
- public void testCompound() throws Exception {
- helpTest("SELECT a, b FROM MultiModel.Phys WHERE ('x' IN ('a', 'b', SOURCE_NAME)) AND (SOURCE_NAME = 'y')", //$NON-NLS-1$
- getMetadata(),
- "SELECT a, b FROM MultiModel.Phys WHERE ('x' IN ('a', 'b', 'x')) AND ('x' = 'y')"); //$NON-NLS-1$
- }
-
- public void testFunction() throws Exception {
- helpTest("SELECT length(concat(SOURCE_NAME, 'a')) FROM MultiModel.Phys", //$NON-NLS-1$
- getMetadata(),
- "SELECT length(concat('x', 'a')) FROM MultiModel.Phys"); //$NON-NLS-1$
- }
-
- public void testBetween() throws Exception {
- helpTest("SELECT SOURCE_NAME FROM MultiModel.Phys WHERE SOURCE_NAME BETWEEN SOURCE_NAME AND SOURCE_NAME", //$NON-NLS-1$
- getMetadata(),
- "SELECT 'x' FROM MultiModel.Phys WHERE 'x' BETWEEN 'x' AND 'x'"); //$NON-NLS-1$
- }
-
- public void testIsNull() throws Exception {
- helpTest("SELECT a FROM MultiModel.Phys WHERE SOURCE_NAME IS NULL", //$NON-NLS-1$
- getMetadata(),
- "SELECT a FROM MultiModel.Phys WHERE 'x' IS NULL"); //$NON-NLS-1$
- }
-
- public void testInSubquery() throws Exception {
- helpTest("SELECT a FROM MultiModel.Phys WHERE SOURCE_NAME IN (SELECT b FROM MultiModel.Phys WHERE SOURCE_NAME IN ('x'))", //$NON-NLS-1$
- getMetadata(),
- "SELECT a FROM MultiModel.Phys WHERE 'x' IN (SELECT b FROM MultiModel.Phys WHERE 'x' IN ('x'))"); //$NON-NLS-1$
- }
-
- public void testCompareSubquery() throws Exception {
- helpTest("SELECT a FROM MultiModel.Phys WHERE SOURCE_NAME = (SELECT b FROM MultiModel.Phys WHERE SOURCE_NAME IN ('x'))", //$NON-NLS-1$
- getMetadata(),
- "SELECT a FROM MultiModel.Phys WHERE 'x' = (SELECT b FROM MultiModel.Phys WHERE 'x' IN ('x'))"); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceElementReplacementVisitor.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceElementReplacementVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceElementReplacementVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceElementReplacementVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,125 @@
+/*
+ * 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.multisource;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import junit.framework.TestCase;
+
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.parser.QueryParser;
+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.RealMetadataFactory;
+
+
+
+/**
+ * @since 4.2
+ */
+public class TestMultiSourceElementReplacementVisitor extends TestCase {
+
+ public QueryMetadataInterface getMetadata() throws Exception {
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
+ Set<String> multiSourceModels = new HashSet<String>();
+ multiSourceModels.add("MultiModel"); //$NON-NLS-1$
+ MultiSourceMetadataWrapper wrapper = new MultiSourceMetadataWrapper(metadata, multiSourceModels);
+
+ return wrapper;
+ }
+
+ public void helpTest(String sql, QueryMetadataInterface metadata, String expected) throws Exception {
+ QueryParser parser = new QueryParser();
+ Command command = parser.parseCommand(sql);
+ QueryResolver.resolveCommand(command, metadata);
+
+ MultiSourceElementReplacementVisitor visitor = new MultiSourceElementReplacementVisitor("x"); //$NON-NLS-1$
+ DeepPostOrderNavigator.doVisit(command, visitor);
+
+ assertEquals(expected, command.toString());
+ }
+
+ public void testCommon() throws Exception {
+ helpTest("SELECT a, b, SOURCE_NAME FROM MultiModel.Phys WHERE SOURCE_NAME = SOURCE_NAME", //$NON-NLS-1$
+ getMetadata(),
+ "SELECT a, b, 'x' FROM MultiModel.Phys WHERE 'x' = 'x'"); //$NON-NLS-1$
+ }
+
+ public void testLike() throws Exception {
+ helpTest("SELECT a, b FROM MultiModel.Phys WHERE SOURCE_NAME LIKE SOURCE_NAME", //$NON-NLS-1$
+ getMetadata(),
+ "SELECT a, b FROM MultiModel.Phys WHERE 'x' LIKE 'x'"); //$NON-NLS-1$
+ }
+
+ public void testIn() throws Exception {
+ helpTest("SELECT a, b FROM MultiModel.Phys WHERE SOURCE_NAME IN ('a', 'b', SOURCE_NAME)", //$NON-NLS-1$
+ getMetadata(),
+ "SELECT a, b FROM MultiModel.Phys WHERE 'x' IN ('a', 'b', 'x')"); //$NON-NLS-1$
+ }
+
+ public void testNot() throws Exception {
+ helpTest("SELECT a, b FROM MultiModel.Phys WHERE NOT (SOURCE_NAME IN ('a', 'b', SOURCE_NAME))", //$NON-NLS-1$
+ getMetadata(),
+ "SELECT a, b FROM MultiModel.Phys WHERE NOT ('x' IN ('a', 'b', 'x'))"); //$NON-NLS-1$
+ }
+
+ public void testCompound() throws Exception {
+ helpTest("SELECT a, b FROM MultiModel.Phys WHERE ('x' IN ('a', 'b', SOURCE_NAME)) AND (SOURCE_NAME = 'y')", //$NON-NLS-1$
+ getMetadata(),
+ "SELECT a, b FROM MultiModel.Phys WHERE ('x' IN ('a', 'b', 'x')) AND ('x' = 'y')"); //$NON-NLS-1$
+ }
+
+ public void testFunction() throws Exception {
+ helpTest("SELECT length(concat(SOURCE_NAME, 'a')) FROM MultiModel.Phys", //$NON-NLS-1$
+ getMetadata(),
+ "SELECT length(concat('x', 'a')) FROM MultiModel.Phys"); //$NON-NLS-1$
+ }
+
+ public void testBetween() throws Exception {
+ helpTest("SELECT SOURCE_NAME FROM MultiModel.Phys WHERE SOURCE_NAME BETWEEN SOURCE_NAME AND SOURCE_NAME", //$NON-NLS-1$
+ getMetadata(),
+ "SELECT 'x' FROM MultiModel.Phys WHERE 'x' BETWEEN 'x' AND 'x'"); //$NON-NLS-1$
+ }
+
+ public void testIsNull() throws Exception {
+ helpTest("SELECT a FROM MultiModel.Phys WHERE SOURCE_NAME IS NULL", //$NON-NLS-1$
+ getMetadata(),
+ "SELECT a FROM MultiModel.Phys WHERE 'x' IS NULL"); //$NON-NLS-1$
+ }
+
+ public void testInSubquery() throws Exception {
+ helpTest("SELECT a FROM MultiModel.Phys WHERE SOURCE_NAME IN (SELECT b FROM MultiModel.Phys WHERE SOURCE_NAME IN ('x'))", //$NON-NLS-1$
+ getMetadata(),
+ "SELECT a FROM MultiModel.Phys WHERE 'x' IN (SELECT b FROM MultiModel.Phys WHERE 'x' IN ('x'))"); //$NON-NLS-1$
+ }
+
+ public void testCompareSubquery() throws Exception {
+ helpTest("SELECT a FROM MultiModel.Phys WHERE SOURCE_NAME = (SELECT b FROM MultiModel.Phys WHERE SOURCE_NAME IN ('x'))", //$NON-NLS-1$
+ getMetadata(),
+ "SELECT a FROM MultiModel.Phys WHERE 'x' = (SELECT b FROM MultiModel.Phys WHERE 'x' IN ('x'))"); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceMetadataWrapper.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceMetadataWrapper.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceMetadataWrapper.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.dqp.internal.process.multisource;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Properties;
-
-import junit.framework.TestCase;
-
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
-
-
-/**
- * @since 4.2
- */
-public class TestMultiSourceMetadataWrapper extends TestCase {
-
- public void testMultiSourcePseudoElement() throws Exception {
- HashSet<String> multiSourceModels = new HashSet<String>();
- multiSourceModels.add("BQT1");
- MultiSourceMetadataWrapper wrapper = new MultiSourceMetadataWrapper(FakeMetadataFactory.exampleBQTCached(), multiSourceModels);
-
- Object groupID = wrapper.getGroupID("BQT1.SmallA"); //$NON-NLS-1$
- List elements = wrapper.getElementIDsInGroupID(groupID);
- assertEquals(18, elements.size());
-
- Object instanceElementID = elements.get(elements.size()-1);
- assertTrue(instanceElementID instanceof MultiSourceElement);
- String fullName = wrapper.getFullName(instanceElementID);
- assertEquals("BQT1.SmallA." + MultiSourceElement.MULTI_SOURCE_ELEMENT_NAME, fullName); //$NON-NLS-1$
-
- assertEquals(instanceElementID, wrapper.getElementID(fullName));
-
- assertEquals(groupID, wrapper.getGroupIDForElementID(instanceElementID));
- assertEquals(null, wrapper.getMaximumValue(instanceElementID));
- assertEquals(null, wrapper.getMinimumValue(instanceElementID));
- assertEquals(wrapper.getModelID(groupID), wrapper.getModelID(instanceElementID));
- assertEquals(null, wrapper.getDefaultValue(instanceElementID));
- assertEquals(255, wrapper.getElementLength(instanceElementID));
- assertEquals(DataTypeManager.DefaultDataTypes.STRING, wrapper.getElementType(instanceElementID));
- assertEquals(new Properties(), wrapper.getExtensionProperties(instanceElementID));
- assertEquals(null, wrapper.getNameInSource(instanceElementID));
- assertEquals(null, wrapper.getNativeType(instanceElementID));
- assertEquals(18, wrapper.getPosition(instanceElementID));
- assertEquals(0, wrapper.getPrecision(instanceElementID));
- assertEquals(0, wrapper.getScale(instanceElementID));
- assertEquals(0, wrapper.getRadix(instanceElementID));
- assertEquals(MultiSourceElement.MULTI_SOURCE_ELEMENT_NAME, SingleElementSymbol.getShortName(fullName));
- assertEquals(fullName, wrapper.getFullName(groupID) + SingleElementSymbol.SEPARATOR + MultiSourceElement.MULTI_SOURCE_ELEMENT_NAME);
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceMetadataWrapper.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceMetadataWrapper.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceMetadataWrapper.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceMetadataWrapper.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,75 @@
+/*
+ * 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.multisource;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Properties;
+
+import junit.framework.TestCase;
+
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+
+
+/**
+ * @since 4.2
+ */
+public class TestMultiSourceMetadataWrapper extends TestCase {
+
+ public void testMultiSourcePseudoElement() throws Exception {
+ HashSet<String> multiSourceModels = new HashSet<String>();
+ multiSourceModels.add("BQT1");
+ MultiSourceMetadataWrapper wrapper = new MultiSourceMetadataWrapper(RealMetadataFactory.exampleBQTCached(), multiSourceModels);
+
+ Object groupID = wrapper.getGroupID("BQT1.SmallA"); //$NON-NLS-1$
+ List elements = wrapper.getElementIDsInGroupID(groupID);
+ assertEquals(18, elements.size());
+
+ Object instanceElementID = elements.get(elements.size()-1);
+ assertTrue(instanceElementID instanceof MultiSourceElement);
+ String fullName = wrapper.getFullName(instanceElementID);
+ assertEquals("BQT1.SmallA." + MultiSourceElement.MULTI_SOURCE_ELEMENT_NAME, fullName); //$NON-NLS-1$
+
+ assertEquals(instanceElementID, wrapper.getElementID(fullName));
+
+ assertEquals(groupID, wrapper.getGroupIDForElementID(instanceElementID));
+ assertEquals(null, wrapper.getMaximumValue(instanceElementID));
+ assertEquals(null, wrapper.getMinimumValue(instanceElementID));
+ assertEquals(wrapper.getModelID(groupID), wrapper.getModelID(instanceElementID));
+ assertEquals(null, wrapper.getDefaultValue(instanceElementID));
+ assertEquals(255, wrapper.getElementLength(instanceElementID));
+ assertEquals(DataTypeManager.DefaultDataTypes.STRING, wrapper.getElementType(instanceElementID));
+ assertEquals(new Properties(), wrapper.getExtensionProperties(instanceElementID));
+ assertEquals(null, wrapper.getNameInSource(instanceElementID));
+ assertEquals(null, wrapper.getNativeType(instanceElementID));
+ assertEquals(18, wrapper.getPosition(instanceElementID));
+ assertEquals(0, wrapper.getPrecision(instanceElementID));
+ assertEquals(0, wrapper.getScale(instanceElementID));
+ assertEquals(0, wrapper.getRadix(instanceElementID));
+ assertEquals(MultiSourceElement.MULTI_SOURCE_ELEMENT_NAME, SingleElementSymbol.getShortName(fullName));
+ assertEquals(fullName, wrapper.getFullName(groupID) + SingleElementSymbol.SEPARATOR + MultiSourceElement.MULTI_SOURCE_ELEMENT_NAME);
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,330 +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.multisource;
-
-import static org.junit.Assert.*;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-
-import org.junit.Test;
-import org.teiid.adminapi.impl.ModelMetaData;
-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;
-import org.teiid.query.optimizer.QueryOptimizer;
-import org.teiid.query.optimizer.TestOptimizer;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
-import org.teiid.query.processor.HardcodedDataManager;
-import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.TestProcessor;
-import org.teiid.query.resolver.TestResolver;
-import org.teiid.query.rewriter.QueryRewriter;
-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.util.CommandContext;
-
-/**
- * It's important here that the MultiSourceCapabilityFinder is used since some capabilities
- * will never be pushed to the source
- *
- * @since 4.2
- */
-public class TestMultiSourcePlanToProcessConverter {
-
- private final class MultiSourceDataManager extends HardcodedDataManager {
-
- public MultiSourceDataManager() {
- setMustRegisterCommands(false);
- }
-
- public TupleSource registerRequest(CommandContext context, Command command, String modelName, String connectorBindingId, int nodeID, int limit) throws org.teiid.core.TeiidComponentException {
- assertNotNull(connectorBindingId);
-
- Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(command, true, true);
-
- for (ElementSymbol symbol : elements) {
- if (symbol.getMetadataID() instanceof MultiSourceElement) {
- fail("Query Contains a MultiSourceElement -- MultiSource expansion did not happen"); //$NON-NLS-1$
- }
- }
- return super.registerRequest(context, command, modelName, connectorBindingId, nodeID, limit);
- }
- }
-
- private static final boolean DEBUG = false;
-
- 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);
-
- Set<String> multiSourceModels = vdb.getMultiSourceModelNames();
- for (String model:multiSourceModels) {
- char sourceID = 'a';
- // by default every model has one binding associated, but for multi-source there were none assigned.
- ModelMetaData m = vdb.getModel(model);
- int x = m.getSourceNames().size();
- for(int i=x; i<sourceCount; i++, sourceID++) {
- m.addSourceMapping("" + sourceID, "translator", null); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- MultiSourceMetadataWrapper wrapper = new MultiSourceMetadataWrapper(metadata, multiSourceModels);
- AnalysisRecord analysis = new AnalysisRecord(false, DEBUG);
-
- Command command = TestResolver.helpResolve(userSql, wrapper);
-
- // Plan
- command = QueryRewriter.rewrite(command, wrapper, null);
- FakeCapabilitiesFinder fakeFinder = new FakeCapabilitiesFinder();
- fakeFinder.addCapabilities(multiModel, TestOptimizer.getTypicalCapabilities());
-
- 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$
- context.setPlanToProcessConverter(new MultiSourcePlanToProcessConverter(metadata, idGenerator, analysis, finder, multiSourceModels, dqpContext, context));
-
- ProcessorPlan plan = QueryOptimizer.optimizePlan(command, wrapper, idGenerator, finder, analysis, context);
-
- if(DEBUG) {
- System.out.println("\nMultiSource Plan:"); //$NON-NLS-1$
- System.out.println(plan);
- }
-
- TestProcessor.helpProcess(plan, context, dataMgr, expectedResults);
- }
-
- @Test public void testNoReplacement() throws Exception {
- final QueryMetadataInterface metadata = FakeMetadataFactory.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());
- }
-
- @Test public void testSingleReplacement() throws Exception {
- final QueryMetadataInterface metadata = FakeMetadataFactory.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;
- final List[] expected =
- 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());
- }
-
- @Test public void testMultiReplacement() throws Exception {
- final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
- final String userSql = "SELECT * FROM MultiModel.Phys"; //$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, null}),
- 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());
- }
-
- @Test public void testMultiReplacementWithOrderBy() throws Exception {
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleMultiBinding();
-
- final String userSql = "SELECT * FROM MultiModel.Phys order by a"; //$NON-NLS-1$
- final String multiModel = "MultiModel"; //$NON-NLS-1$
- final int sources = 2;
- final List[] expected = 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$
- Arrays.asList("x", "z", "a"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList("y", "z", "a"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- };
- final HardcodedDataManager dataMgr = new HardcodedDataManager();
- dataMgr.addData("SELECT g_0.a, g_0.b, 'a' FROM MultiModel.Phys AS g_0", //$NON-NLS-1$
- new List[] {
- Arrays.asList("y", "z", "a"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList("x", "z", "a")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- dataMgr.addData("SELECT g_0.a, g_0.b, 'b' FROM MultiModel.Phys AS g_0", //$NON-NLS-1$
- 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());
- }
-
- @Test public void testMultiReplacementWithLimit() throws Exception {
- final QueryMetadataInterface metadata = FakeMetadataFactory.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;
- final List[] expected = new List[] {
- Arrays.asList("e", "z", "b"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- };
- final HardcodedDataManager dataMgr = new HardcodedDataManager();
- dataMgr.addData("SELECT g_0.a, g_0.b, 'a' FROM MultiModel.Phys AS g_0", //$NON-NLS-1$
- new List[] {
- Arrays.asList("y", "z", "a"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList("x", "z", "a")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- dataMgr.addData("SELECT g_0.a, g_0.b, 'b' FROM MultiModel.Phys AS g_0", //$NON-NLS-1$
- 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());
- }
-
- @Test public void testMultiDependentJoin() throws Exception {
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- final int sources = 2;
- final List[] expected =
- new List[] { Arrays.asList(new Object[] { "x"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "x"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "x"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "x"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "y"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "y"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "y"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "y"})}; //$NON-NLS-1$
-
- final HardcodedDataManager dataMgr = new HardcodedDataManager();
- dataMgr.addData("SELECT g_0.a FROM MultiModel.Phys AS g_0", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { "x" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "y" })}); //$NON-NLS-1$
- 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());
- }
-
- @Test public void testSingleReplacementInDynamicCommand() throws Exception {
- final QueryMetadataInterface metadata = FakeMetadataFactory.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());
- }
-
- @Test public void testSingleReplacementInDynamicCommandNullValue() throws Exception {
- final QueryMetadataInterface metadata = FakeMetadataFactory.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());
- }
-
- @Test public void testMultiUpdateAll() throws Exception {
- final QueryMetadataInterface metadata = FakeMetadataFactory.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;
- final List[] expected = new List[] { Arrays.asList(3)};
- 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());
- }
-
- @Test public void testInsertMatching() throws Exception {
- final QueryMetadataInterface metadata = FakeMetadataFactory.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;
- final List[] expected = new List[] { Arrays.asList(1)};
- 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());
- }
-
- @Test public void testInsertNotMatching() throws Exception {
- final QueryMetadataInterface metadata = FakeMetadataFactory.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());
- }
-
- @Test public void testInsertAll() throws Exception {
- final QueryMetadataInterface metadata = FakeMetadataFactory.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;
- final List[] expected = new List[] { Arrays.asList(3)};
- 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());
- }
-
- @Test public void testProcedure() throws Exception {
- final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
- final String userSql = "exec MultiModel.proc('b', 'a')"; //$NON-NLS-1$
- final String multiModel = "MultiModel"; //$NON-NLS-1$
- final int sources = 3;
- final List[] expected = new List[] { Arrays.asList(1)};
- 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());
- }
-
- @Test public void testProcedureAll() throws Exception {
- final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
- final String userSql = "exec MultiModel.proc(\"in\"=>'b')"; //$NON-NLS-1$
- final String multiModel = "MultiModel"; //$NON-NLS-1$
- final int sources = 3;
- final List[] expected = new List[] { Arrays.asList(1), Arrays.asList(1), Arrays.asList(1)};
- 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());
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java (from rev 3218, trunk/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,329 @@
+/*
+ * 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.multisource;
+
+import static org.junit.Assert.*;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+
+import org.junit.Test;
+import org.teiid.adminapi.impl.ModelMetaData;
+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;
+import org.teiid.query.optimizer.QueryOptimizer;
+import org.teiid.query.optimizer.TestOptimizer;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
+import org.teiid.query.processor.HardcodedDataManager;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.TestProcessor;
+import org.teiid.query.resolver.TestResolver;
+import org.teiid.query.rewriter.QueryRewriter;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+/**
+ * It's important here that the MultiSourceCapabilityFinder is used since some capabilities
+ * will never be pushed to the source
+ *
+ * @since 4.2
+ */
+public class TestMultiSourcePlanToProcessConverter {
+
+ private final class MultiSourceDataManager extends HardcodedDataManager {
+
+ public MultiSourceDataManager() {
+ setMustRegisterCommands(false);
+ }
+
+ public TupleSource registerRequest(CommandContext context, Command command, String modelName, String connectorBindingId, int nodeID, int limit) throws org.teiid.core.TeiidComponentException {
+ assertNotNull(connectorBindingId);
+
+ Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(command, true, true);
+
+ for (ElementSymbol symbol : elements) {
+ if (symbol.getMetadataID() instanceof MultiSourceElement) {
+ fail("Query Contains a MultiSourceElement -- MultiSource expansion did not happen"); //$NON-NLS-1$
+ }
+ }
+ return super.registerRequest(context, command, modelName, connectorBindingId, nodeID, limit);
+ }
+ }
+
+ private static final boolean DEBUG = false;
+
+ public void helpTestMultiSourcePlan(QueryMetadataInterface metadata, String userSql, String multiModel, int sourceCount, ProcessorDataManager dataMgr, List[] expectedResults, VDBMetaData vdb) throws Exception {
+
+ DQPWorkContext dqpContext = RealMetadataFactory.buildWorkContext(metadata, vdb);
+
+ Set<String> multiSourceModels = vdb.getMultiSourceModelNames();
+ for (String model:multiSourceModels) {
+ char sourceID = 'a';
+ // by default every model has one binding associated, but for multi-source there were none assigned.
+ ModelMetaData m = vdb.getModel(model);
+ int x = m.getSourceNames().size();
+ for(int i=x; i<sourceCount; i++, sourceID++) {
+ m.addSourceMapping("" + sourceID, "translator", null); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ MultiSourceMetadataWrapper wrapper = new MultiSourceMetadataWrapper(metadata, multiSourceModels);
+ AnalysisRecord analysis = new AnalysisRecord(false, DEBUG);
+
+ Command command = TestResolver.helpResolve(userSql, wrapper);
+
+ // Plan
+ command = QueryRewriter.rewrite(command, wrapper, null);
+ FakeCapabilitiesFinder fakeFinder = new FakeCapabilitiesFinder();
+ fakeFinder.addCapabilities(multiModel, TestOptimizer.getTypicalCapabilities());
+
+ 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$
+ context.setPlanToProcessConverter(new MultiSourcePlanToProcessConverter(metadata, idGenerator, analysis, finder, multiSourceModels, dqpContext, context));
+
+ ProcessorPlan plan = QueryOptimizer.optimizePlan(command, wrapper, idGenerator, finder, analysis, context);
+
+ if(DEBUG) {
+ System.out.println("\nMultiSource Plan:"); //$NON-NLS-1$
+ System.out.println(plan);
+ }
+
+ TestProcessor.helpProcess(plan, context, dataMgr, expectedResults);
+ }
+
+ @Test public void testNoReplacement() throws Exception {
+ 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, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+ @Test public void testSingleReplacement() throws Exception {
+ 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;
+ final List[] expected =
+ new List[] { Arrays.asList(new Object[] { null, null, null}) };
+ final HardcodedDataManager dataMgr = new MultiSourceDataManager();
+ dataMgr.setMustRegisterCommands(false);
+ helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+ @Test public void testMultiReplacement() throws Exception {
+ 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;
+ final List[] expected =
+ new List[] { Arrays.asList(new Object[] { null, null, null}),
+ 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, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+ @Test public void testMultiReplacementWithOrderBy() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
+
+ final String userSql = "SELECT * FROM MultiModel.Phys order by a"; //$NON-NLS-1$
+ final String multiModel = "MultiModel"; //$NON-NLS-1$
+ final int sources = 2;
+ final List[] expected = 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$
+ Arrays.asList("x", "z", "a"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList("y", "z", "a"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ };
+ final HardcodedDataManager dataMgr = new HardcodedDataManager();
+ dataMgr.addData("SELECT g_0.a, g_0.b, 'a' FROM MultiModel.Phys AS g_0", //$NON-NLS-1$
+ new List[] {
+ Arrays.asList("y", "z", "a"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList("x", "z", "a")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ dataMgr.addData("SELECT g_0.a, g_0.b, 'b' FROM MultiModel.Phys AS g_0", //$NON-NLS-1$
+ 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, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+ @Test public void testMultiReplacementWithLimit() throws Exception {
+ 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;
+ final List[] expected = new List[] {
+ Arrays.asList("e", "z", "b"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ };
+ final HardcodedDataManager dataMgr = new HardcodedDataManager();
+ dataMgr.addData("SELECT g_0.a, g_0.b, 'a' FROM MultiModel.Phys AS g_0", //$NON-NLS-1$
+ new List[] {
+ Arrays.asList("y", "z", "a"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList("x", "z", "a")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ dataMgr.addData("SELECT g_0.a, g_0.b, 'b' FROM MultiModel.Phys AS g_0", //$NON-NLS-1$
+ 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, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+ @Test public void testMultiDependentJoin() throws Exception {
+ 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$
+ final int sources = 2;
+ final List[] expected =
+ new List[] { Arrays.asList(new Object[] { "x"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "x"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "x"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "x"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "y"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "y"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "y"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "y"})}; //$NON-NLS-1$
+
+ final HardcodedDataManager dataMgr = new HardcodedDataManager();
+ dataMgr.addData("SELECT g_0.a FROM MultiModel.Phys AS g_0", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { "x" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "y" })}); //$NON-NLS-1$
+ 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, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+ @Test public void testSingleReplacementInDynamicCommand() throws Exception {
+ 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, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+ @Test public void testSingleReplacementInDynamicCommandNullValue() throws Exception {
+ 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, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+ @Test public void testMultiUpdateAll() throws Exception {
+ 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;
+ final List[] expected = new List[] { Arrays.asList(3)};
+ 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, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+ @Test public void testInsertMatching() throws Exception {
+ 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;
+ final List[] expected = new List[] { Arrays.asList(1)};
+ 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, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+ @Test public void testInsertNotMatching() throws Exception {
+ 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, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+ @Test public void testInsertAll() throws Exception {
+ 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;
+ final List[] expected = new List[] { Arrays.asList(3)};
+ 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, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+ @Test public void testProcedure() throws Exception {
+ 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;
+ final List[] expected = new List[] { Arrays.asList(1)};
+ 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, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+ @Test public void testProcedureAll() throws Exception {
+ 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;
+ final List[] expected = new List[] { Arrays.asList(1), Arrays.asList(1), Arrays.asList(1)};
+ 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, RealMetadataFactory.exampleMultiBindingVDB());
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1411 +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.function;
-
-import static org.junit.Assert.*;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.Date;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Properties;
-import java.util.TimeZone;
-
-import javax.sql.rowset.serial.SerialBlob;
-import javax.sql.rowset.serial.SerialClob;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.teiid.api.exception.query.FunctionExecutionException;
-import org.teiid.common.buffer.BufferManagerFactory;
-import org.teiid.core.types.BlobType;
-import org.teiid.core.types.ClobType;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.types.NullType;
-import org.teiid.core.types.XMLType;
-import org.teiid.core.types.DataTypeManager.DefaultDataClasses;
-import org.teiid.core.util.Base64;
-import org.teiid.core.util.ObjectConverterUtil;
-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.TimestampUtil;
-import org.teiid.query.util.CommandContext;
-import org.teiid.translator.SourceSystemFunctions;
-
-
- at SuppressWarnings("nls")
-public class TestFunctionLibrary {
-
- // These are just used as shorthand convenience to make unit tests more readable below
- private static final Class<String> T_STRING = DataTypeManager.DefaultDataClasses.STRING;
- private static final Class<Integer> T_INTEGER = DataTypeManager.DefaultDataClasses.INTEGER;
- private static final Class<BigInteger> T_BIG_INTEGER = DataTypeManager.DefaultDataClasses.BIG_INTEGER;
- private static final Class<? extends BigDecimal> T_BIG_DECIMAL = DataTypeManager.DefaultDataClasses.BIG_DECIMAL;
- private static final Class<Long> T_LONG = DataTypeManager.DefaultDataClasses.LONG;
- private static final Class<Float> T_FLOAT = DataTypeManager.DefaultDataClasses.FLOAT;
- private static final Class<Double> T_DOUBLE = DataTypeManager.DefaultDataClasses.DOUBLE;
- private static final Class<NullType> T_NULL = DataTypeManager.DefaultDataClasses.NULL;
- private static final Class<Time> T_TIME = DataTypeManager.DefaultDataClasses.TIME;
- 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());
-
- @Before public void setUp() {
- TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("GMT-06:00")); //$NON-NLS-1$
- }
-
- @After public void tearDown() {
- TimestampWithTimezone.resetCalendar(null);
- }
-
- // ################################## TEST HELPERS ################################
-
- private FunctionDescriptor helpCreateDescriptor(String name, Class<?>[] types) {
- final String fname = name;
- final Class<?>[] ftypes = types;
- return new FunctionDescriptor() {
- public String getName() {
- return fname;
- }
- public PushDown getPushdown() {
- return PushDown.CAN_PUSHDOWN;
- }
- public Class<?>[] getTypes() {
- return ftypes;
- }
- public Class<?> getReturnType() {
- return null;
- }
-
- public String toString() {
- StringBuffer str = new StringBuffer(fname);
- str.append("("); //$NON-NLS-1$
- for(int i=0; i<ftypes.length; i++) {
- if(ftypes[i] != null) {
- str.append(ftypes[i].getName());
- } else {
- str.append("null"); //$NON-NLS-1$
- }
- if(i<(ftypes.length-1)) {
- str.append(", "); //$NON-NLS-1$
- }
- }
- return str.toString();
- }
- public boolean requiresContext() {
- return false;
- }
- public boolean isNullDependent() {
- return true;
- }
-
- };
- }
-
- private void helpFindFunction(String fname, Class<?>[] types, FunctionDescriptor expected) {
- FunctionDescriptor actual = library.findFunction(fname, types);
-
- assertEquals("Function names do not match: ", expected.getName().toLowerCase(), actual.getName().toLowerCase()); //$NON-NLS-1$
- assertEquals("Arg lengths do not match: ", expected.getTypes().length, actual.getTypes().length); //$NON-NLS-1$
- }
-
- private void helpFindFunctionFail(String fname, Class<?>[] types) {
- FunctionDescriptor actual = library.findFunction(fname, types);
- assertNull("Function was found but should not have been: " + actual, actual); //$NON-NLS-1$
- }
-
- private void helpFindConversions(String fname, Class<?>[] types, FunctionDescriptor[] expected) {
-
- FunctionDescriptor[] actual = library.determineNecessaryConversions(fname, null, types, false);
-
- if(expected == null) {
- if(actual != null) {
- fail("Expected to find no conversion for " + fname + Arrays.asList(types) + " but found: " + Arrays.asList(actual)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } else {
- if(actual == null) {
- fail("Expected to find conversion for " + fname + Arrays.asList(types) + " but found none"); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- // Compare returned descriptors with expected descriptor
- for(int i=0; i<expected.length; i++) {
- if(expected[i] == null) {
- if(actual[i] != null) {
- fail("Expected no conversion at index " + i + ", but found: " + actual[i]); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } else {
- if(actual[i] == null) {
- fail("Expected conversion at index " + i + ", but found none."); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- assertEquals("Expected conversion function names do not match: ", expected[i].getName(), actual[i].getName()); //$NON-NLS-1$
- assertEquals("Expected conversion arg lengths do not match: ", expected[i].getTypes().length, actual[i].getTypes().length); //$NON-NLS-1$
- }
- }
- }
- }
- }
- }
-
- private void helpFindForm(String fname, int numArgs) {
- FunctionForm form = library.findFunctionForm(fname, numArgs);
- assertNotNull("Failed to find function '" + fname + "' with " + numArgs + " args", form); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- assertEquals("Function names do not match: ", fname.toUpperCase(), form.getName().toUpperCase()); //$NON-NLS-1$
- assertEquals("Arg lengths do not match: ", numArgs, form.getArgNames().size()); //$NON-NLS-1$
- }
-
- private void helpInvokeMethod(String fname, Object[] inputs, Object expectedOutput) {
- try {
- helpInvokeMethod(fname, null, inputs, null, expectedOutput);
- } catch (Exception err) {
- throw new RuntimeException(err);
- }
- }
-
- private void helpInvokeMethod(String fname, Class<?>[] types, Object[] inputs, CommandContext context, Object expectedOutput) throws FunctionExecutionException {
- Object actualOutput = helpInvokeMethod(fname, types, inputs, context);
- assertEquals("Actual function output not equal to expected: ", expectedOutput, actualOutput); //$NON-NLS-1$
- }
-
- private Object helpInvokeMethod(String fname, Class<?>[] types,
- Object[] inputs, CommandContext context)
- throws FunctionExecutionException {
- if (types == null) {
- // Build type signature
- types = new Class<?>[inputs.length];
- for(int i=0; i<inputs.length; i++) {
- types[i] = DataTypeManager.determineDataTypeClass(inputs[i]);
- }
- }
- if (context == null) {
- context = new CommandContext();
- }
- Object actualOutput = null;
- // Find function descriptor
- FunctionDescriptor descriptor = library.findFunction(fname, types);
- if (descriptor.requiresContext()) {
- // Invoke function with inputs
- Object[] in = new Object[inputs.length+1];
- in[0] = context;
- for (int i = 0; i < inputs.length; i++) {
- in[i+1] = inputs[i];
- }
- actualOutput = descriptor.invokeFunction(in);
- }
- else {
- // Invoke function with inputs
- actualOutput = descriptor.invokeFunction(inputs);
- }
- return actualOutput;
- }
-
- private void helpInvokeMethodFail(String fname, Object[] inputs) {
- helpInvokeMethodFail(fname, null, inputs);
- }
-
- private void helpInvokeMethodFail(String fname, Class<?> types[], Object[] inputs) {
- try {
- helpInvokeMethod(fname, types, inputs, null);
- fail("expected exception"); //$NON-NLS-1$
- } catch (FunctionExecutionException err) {
- }
- }
- // ################################## ACTUAL TESTS ################################
-
- @Test public void testFindFunction1() {
- helpFindFunction("convert", new Class<?>[] { T_INTEGER, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_INTEGER, T_STRING }) );
- }
-
- @Test public void testFindFunction2() {
- helpFindFunction("cast", new Class<?>[] { T_INTEGER, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor(FunctionLibrary.CAST, new Class<?>[] { T_INTEGER, T_STRING }) );
- }
-
- @Test public void testFindFunction3() {
- helpFindFunction("curdate", new Class<?>[0], //$NON-NLS-1$
- helpCreateDescriptor("curdate", new Class<?>[0])); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction4() {
- helpFindFunctionFail("curdate", new Class<?>[] { T_INTEGER }); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction5() {
- helpFindFunction("+", new Class<?>[] { T_INTEGER, T_INTEGER }, //$NON-NLS-1$
- helpCreateDescriptor("+", new Class<?>[] { T_INTEGER, T_INTEGER }) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction6() {
- helpFindFunctionFail("+", new Class<?>[] {T_INTEGER, T_FLOAT}); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction7() {
- helpFindFunctionFail("+", new Class<?>[] {T_INTEGER, T_FLOAT, T_INTEGER}); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction8() {
- helpFindFunctionFail("+", new Class<?>[] {T_INTEGER}); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction9() {
- helpFindFunctionFail("+", new Class<?>[] {T_INTEGER, T_NULL }); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction10() {
- helpFindFunction("substring", new Class<?>[] { T_STRING, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
- helpCreateDescriptor("substring", new Class<?>[] { T_STRING, T_INTEGER, T_INTEGER }) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction11() {
- helpFindFunction("substring", new Class<?>[] { T_STRING, T_INTEGER }, //$NON-NLS-1$
- helpCreateDescriptor("substring", new Class<?>[] { T_STRING, T_INTEGER }) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction12() {
- helpFindFunction("context", new Class<?>[] { T_STRING, T_INTEGER }, //$NON-NLS-1$
- helpCreateDescriptor("context", new Class<?>[] { T_STRING, T_INTEGER }) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction12a() {
- helpFindFunction("rowlimit", new Class<?>[] { T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("rowlimit", new Class<?>[] { T_STRING }) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction12b() {
- helpFindFunction("rowlimitexception", new Class<?>[] { T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("rowlimitexception", new Class<?>[] { T_STRING }) ); //$NON-NLS-1$
- }
-
- @Test public void testFind0ArgConversion1() {
- helpFindConversions(
- "curdate", new Class<?>[] {}, //$NON-NLS-1$
- new FunctionDescriptor[0] );
- }
-
- @Test public void testFind0ArgConversion2() {
- helpFindConversions(
- "curdate", new Class<?>[] { T_INTEGER }, //$NON-NLS-1$
- null );
- }
-
- @Test public void testFind1ArgConversion1() {
- helpFindConversions(
- "length", new Class<?>[] { T_STRING }, //$NON-NLS-1$
- new FunctionDescriptor[1] );
- }
-
- @Test public void testFind1ArgConversion2() {
- helpFindConversions(
- "length", new Class<?>[] { T_INTEGER }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_INTEGER, T_STRING })
- } );
- }
-
- @Test public void testFind1ArgConversion3() {
- helpFindConversions(
- "length", new Class<?>[] { DataTypeManager.DefaultDataClasses.TIMESTAMP }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.TIMESTAMP, T_STRING })
- } );
- }
-
- @Test public void testFind2ArgConversion1() {
- helpFindConversions(
- "+", new Class<?>[] { T_INTEGER, T_INTEGER }, //$NON-NLS-1$
- new FunctionDescriptor[2] );
- }
-
- @Test public void testFind2ArgConversion2() {
- helpFindConversions(
- "+", new Class<?>[] { T_INTEGER, T_FLOAT }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_INTEGER, T_STRING }),
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_FLOAT, T_STRING }) } );
- }
-
- @Test public void testFind2ArgConversion3() {
- helpFindConversions(
- "+", new Class<?>[] { T_FLOAT, T_INTEGER }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_FLOAT, T_STRING }),
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_INTEGER, T_STRING }) } );
- }
-
- @Test public void testFind2ArgConversion4() {
- helpFindConversions(
- "+", new Class<?>[] { T_STRING, T_FLOAT }, //$NON-NLS-1$
- null );
- }
-
- @Test public void testFind2ArgConversion5() {
- helpFindConversions(
- "+", new Class<?>[] { T_NULL, T_NULL }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }) } );
- }
-
- @Test public void testFind2ArgConversion6() {
- helpFindConversions(
- "+", new Class<?>[] { T_NULL, T_INTEGER }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
- null } );
- }
-
- @Test public void testFind2ArgConversion7() {
- helpFindConversions(
- "+", new Class<?>[] { T_INTEGER, T_NULL }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- null,
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }) } );
- }
-
- @Test public void testFind3ArgConversion1() {
- helpFindConversions(
- "substring", new Class<?>[] { T_STRING, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
- new FunctionDescriptor[3] );
- }
-
- @Test public void testFind3ArgConversion2() {
- helpFindConversions(
- "substring", new Class<?>[] { T_INTEGER, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_INTEGER, T_STRING }),
- null,
- null
- } );
- }
-
- @Test public void testFind3ArgConversion3() {
- helpFindConversions(
- "substring", new Class<?>[] { T_INTEGER, T_INTEGER, DataTypeManager.DefaultDataClasses.SHORT }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_INTEGER, T_STRING }),
- null,
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING })
- } );
- }
-
- @Test public void testFind3ArgConversion4() {
- helpFindConversions(
- "substring", new Class<?>[] { T_STRING, T_INTEGER, DataTypeManager.DefaultDataClasses.TIMESTAMP }, //$NON-NLS-1$
- null );
- }
-
- @Test public void testFind3ArgConversion5() {
- helpFindConversions(
- "substring", new Class<?>[] { T_STRING, DataTypeManager.DefaultDataClasses.SHORT, DataTypeManager.DefaultDataClasses.SHORT }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- null,
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING }),
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING })
- } );
- }
-
- @Test public void testFind3ArgConversion6() {
- helpFindConversions(
- "substring", new Class<?>[] { T_INTEGER, DataTypeManager.DefaultDataClasses.SHORT, DataTypeManager.DefaultDataClasses.SHORT }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.INTEGER, T_STRING }),
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING }),
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING })
- } );
- }
-
- @Test public void testFind3ArgConversion7() {
- helpFindConversions(
- "substring", new Class<?>[] { T_NULL, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
- null,
- null }
- );
- }
-
- @Test public void testFind3ArgConversion8() {
- helpFindConversions(
- "substring", new Class<?>[] { T_NULL, T_NULL, T_INTEGER }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
- null }
- );
- }
-
- @Test public void testFind3ArgConversion9() {
- helpFindConversions(
- "substring", new Class<?>[] { T_NULL, T_NULL, T_NULL }, //$NON-NLS-1$
- new FunctionDescriptor[] {
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
- helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }) }
- );
- }
-
- // Walk through all functions by metadata
- @Test public void testEnumerateForms() {
- Collection<String> categories = library.getFunctionCategories();
- for (String category : categories) {
- //System.out.println("Category: " + category);
-
- Collection<FunctionForm> functions = library.getFunctionForms(category);
- for (FunctionForm form : functions) {
- //System.out.println("\tFunction: " + form.getDisplayString());
-
- // Lookup this form
- helpFindForm(form.getName(), form.getArgNames().size());
- }
- }
- }
-
- @Test public void testFindForm1() {
- helpFindForm("convert", 2); //$NON-NLS-1$
- }
-
- @Test public void testFindForm2() {
- helpFindForm("locate", 2); //$NON-NLS-1$
- }
-
- @Test public void testFindForm3() {
- helpFindForm("locate", 3); //$NON-NLS-1$
- }
-
- @Test public void testFindForm4() {
- helpFindForm("substring", 2); //$NON-NLS-1$
- }
-
- @Test public void testFindForm5() {
- helpFindForm("substring", 3); //$NON-NLS-1$
- }
-
- @Test public void testFindForm6() {
- helpFindForm("now", 0); //$NON-NLS-1$
- }
-
- @Test public void testInvokePlus1() {
- helpInvokeMethod("+", new Object[] { new Integer(3), new Integer(2) }, new Integer(5)); //$NON-NLS-1$
- }
-
- @Test public void testInvokePlus2() {
- helpInvokeMethod("+", new Object[] { new Long(3), new Long(2) }, new Long(5)); //$NON-NLS-1$
- }
-
- @Test public void testInvokePlus3() {
- helpInvokeMethod("+", new Object[] { new Float(3), new Float(2) }, new Float(5)); //$NON-NLS-1$
- }
-
- @Test public void testInvokePlus4() {
- helpInvokeMethod("+", new Object[] { new Double(3), new Double(2) }, new Double(5)); //$NON-NLS-1$
- }
-
- @Test public void testInvokePlus5() {
- helpInvokeMethod("+", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("5")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokePlus6() {
- helpInvokeMethod("+", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("5")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeMinus1() {
- helpInvokeMethod("-", new Object[] { new Integer(3), new Integer(2) }, new Integer(1)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeMinus2() {
- helpInvokeMethod("-", new Object[] { new Long(3), new Long(2) }, new Long(1)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeMinus3() {
- helpInvokeMethod("-", new Object[] { new Float(3), new Float(2) }, new Float(1)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeMinus4() {
- helpInvokeMethod("-", new Object[] { new Double(3), new Double(2) }, new Double(1)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeMinus5() {
- helpInvokeMethod("-", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeMinus6() {
- helpInvokeMethod("-", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeMultiply1() {
- helpInvokeMethod("*", new Object[] { new Integer(3), new Integer(2) }, new Integer(6)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeMultiply2() {
- helpInvokeMethod("*", new Object[] { new Long(3), new Long(2) }, new Long(6)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeMultiply3() {
- helpInvokeMethod("*", new Object[] { new Float(3), new Float(2) }, new Float(6)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeMultiply4() {
- helpInvokeMethod("*", new Object[] { new Double(3), new Double(2) }, new Double(6)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeMultiply5() {
- helpInvokeMethod("*", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("6")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeMultiply6() {
- helpInvokeMethod("*", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("6")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeDivide1() {
- helpInvokeMethod("/", new Object[] { new Integer(3), new Integer(2) }, new Integer(1)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeDivide2() {
- helpInvokeMethod("/", new Object[] { new Long(3), new Long(2) }, new Long(1)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeDivide3() {
- helpInvokeMethod("/", new Object[] { new Float(3), new Float(2) }, new Float(1.5)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeDivide4() {
- helpInvokeMethod("/", new Object[] { new Double(3), new Double(2) }, new Double(1.5)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeDivide5() {
- helpInvokeMethod("/", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- // one digit precision
- @Test public void testInvokeDivide6() {
- helpInvokeMethod("/", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("1.5")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeDivide7() throws Exception {
- helpInvokeMethodFail("/", new Object[] { new Float("3"), new Float("0") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeDivideMod() {
- helpInvokeMethod("mod", new Object[] { new BigDecimal("3.1"), new BigDecimal("2") }, new BigDecimal("1.1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeAbs1() {
- helpInvokeMethod("abs", new Object[] { new Integer(-3) }, new Integer(3)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeAbs2() {
- helpInvokeMethod("abs", new Object[] { new Long(-3) }, new Long(3)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeAbs3() {
- helpInvokeMethod("abs", new Object[] { new Float(-3) }, new Float(3)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeAbs4() {
- helpInvokeMethod("abs", new Object[] { new Double(-3) }, new Double(3)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeAbs5() {
- helpInvokeMethod("abs", new Object[] { new BigInteger("-3") }, new BigInteger("3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeAbs6() {
- helpInvokeMethod("abs", new Object[] { new BigDecimal("-3") }, new BigDecimal("3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeAcos() {
- helpInvokeMethod("acos", new Object[] { new Double(0.05) }, new Double(1.5207754699891267)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeAsin() {
- helpInvokeMethod("asin", new Object[] { new Double(0.05) }, new Double(0.050020856805770016)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeAtan() {
- helpInvokeMethod("atan", new Object[] { new Double(0.05) }, new Double(0.049958395721942765)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeAtan2() {
- helpInvokeMethod("atan2", new Object[] { new Double(0.05), new Double(0.07) }, new Double(0.6202494859828215)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeAtanBigDecimal() {
- helpInvokeMethod("atan", new Object[] { new BigDecimal(0.05) }, new Double(0.049958395721942765)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeAtan2BigDecimal() {
- helpInvokeMethod("atan2", new Object[] { new BigDecimal(0.05), new BigDecimal(0.07) }, new Double(0.6202494859828215)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeCos() {
- helpInvokeMethod("cos", new Object[] { new Double(1.57) }, new Double(7.963267107332633E-4)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeCot() {
- helpInvokeMethod("cot", new Object[] { new Double(1.57) }, new Double(7.963269632231926E-4)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeDegrees() {
- helpInvokeMethod("degrees", new Object[] { new Double(1.57) }, new Double(89.95437383553926)); //$NON-NLS-1$
- }
-
- @Test public void testInvokePI() {
- helpInvokeMethod("pi", new Object[] { }, new Double(3.141592653589793)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeRadians() {
- helpInvokeMethod("radians", new Object[] { new Double(89.95437383553926) }, new Double(1.57)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeSin() {
- helpInvokeMethod("sin", new Object[] { new Double(1.57) }, new Double(0.9999996829318346)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeTan() {
- helpInvokeMethod("tan", new Object[] { new Double(0.785) }, new Double(0.9992039901050427)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeAscii() {
- helpInvokeMethod("ascii", new Object[] { " " }, new Integer(32)); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testInvokeChr() {
- helpInvokeMethod("chr", new Object[] { new Integer(32) }, new Character(' ')); //$NON-NLS-1$
- }
-
- @Test public void testInvokeNvl() {
- helpInvokeMethod("nvl", new Object[] { new Integer(5), new Integer(10) }, new Integer(5) ); //$NON-NLS-1$
- }
-
- @Test public void testInvokeConcatOperator() {
- helpInvokeMethod("||", new Object[] { "a", "b" }, "ab" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeInitcap() {
- helpInvokeMethod("initcap", new Object[] { "my test\ndata" }, "My Test\nData" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeLpad1() {
- helpInvokeMethod("lpad", new Object[] { "x", new Integer(3) }, " x" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeLpad2() {
- helpInvokeMethod("lpad", new Object[] { "x", new Integer(3), "y" }, "yyx" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeRpad1() {
- helpInvokeMethod("rpad", new Object[] { "x", new Integer(3) }, "x " ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeRpad2() {
- helpInvokeMethod("rpad", new Object[] { "x", new Integer(3), "y" }, "xyy" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeTranslate() {
- helpInvokeMethod("translate", new Object[] { "ababcd", "ad", "da" }, "dbdbca" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- @Test public void testFindFunction13() {
- helpFindFunction("formatTime", new Class<?>[] { T_TIME, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("formatTime", new Class<?>[] { T_TIME, T_STRING }) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction14() {
- helpFindFunction("formatDate", new Class<?>[] { T_DATE, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("formatDate", new Class<?>[] { T_DATE, T_STRING }) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction15() {
- helpFindFunction("formatTimestamp", new Class<?>[] { T_TIMESTAMP, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("formatTimestamp", new Class<?>[] { T_TIMESTAMP, T_STRING }) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction16() {
- helpFindFunction("parseTime", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("parseTime", new Class<?>[] { T_STRING, T_STRING }) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction17() {
- helpFindFunction("parseDate", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("parseDate", new Class<?>[] { T_STRING, T_STRING }) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction18() {
- helpFindFunction("parseTimestamp", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("parseTimestamp", new Class<?>[] { T_STRING, T_STRING }) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFunction19() {
- helpFindFunction("env", new Class<?>[] {T_STRING}, //$NON-NLS-1$
- helpCreateDescriptor("env", new Class<?>[] {T_STRING})); //$NON-NLS-1$
- }
-
- @Test public void testInvokeFormatTimestamp1() {
- helpInvokeMethod("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("mm/dd/yy h:mm a") }, "04/05/03 3:04 AM"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeFormatTimestamp2() {
- helpInvokeMethod("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("yyyy-mm-dd k:mm a z") }, "2003-04-05 3:04 AM GMT-06:00"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeFormatTimestamp3() {
- helpInvokeMethod("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("yyyy-mm-dd hh:mm:ss.SSSS") }, "2003-04-05 03:04:12.0000"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeFormatTimestampFail() throws Exception {
- helpInvokeMethodFail("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("mm/dd/nn h:mm a") }); //$NON-NLS-1$
- }
-
- @Test public void testInvokeParseTimestamp1() {
- helpInvokeMethod("parseTimestamp", new Object[] {new String("05 Mar 2003 03:12:23 CST"), new String("dd MMM yyyy HH:mm:ss z") }, TimestampUtil.createTimestamp(103, 2, 5, 3, 12, 23, 0)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeParseTimestamp2() {
- helpInvokeMethod("parseTimestamp", new Object[] {new String("05 Mar 2003 03:12:23.333"), new String("dd MMM yyyy HH:mm:ss.SSS") }, TimestampUtil.createTimestamp(103, 2, 5, 3, 12, 23, 333*1000000)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testFindFormatInteger() {
- helpFindFunction("formatInteger", new Class<?>[] { T_INTEGER, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("formatInteger", new Class<?>[] { T_INTEGER, T_STRING}) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFormatFloat() {
- helpFindFunction("formatFloat", new Class<?>[] { T_FLOAT, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("formatFloat", new Class<?>[] { T_FLOAT, T_STRING}) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFormatDouble() {
- helpFindFunction("formatDouble", new Class<?>[] { T_DOUBLE, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("formatDouble", new Class<?>[] { T_DOUBLE, T_STRING}) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFormatLong() {
- helpFindFunction("formatLong", new Class<?>[] { T_LONG, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("formatLong", new Class<?>[] { T_LONG, T_STRING}) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFormatBigInteger() {
- helpFindFunction("formatBigInteger", new Class<?>[] { T_BIG_INTEGER, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("formatBigInteger", new Class<?>[] { T_BIG_INTEGER, T_STRING}) ); //$NON-NLS-1$
- }
-
- @Test public void testFindFormatBigDecimal() {
- helpFindFunction("formatBigDecimal", new Class<?>[] { T_BIG_DECIMAL, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("formatBigDecimal", new Class<?>[] { T_BIG_DECIMAL, T_STRING}) ); //$NON-NLS-1$
- }
-
- @Test public void testFindParseInteger() {
- helpFindFunction("parseInteger", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("parseInteger", new Class<?>[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
- }
-
- @Test public void testFindParseLong() {
- helpFindFunction("parseLong", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("parseLong", new Class<?>[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
- }
-
- @Test public void testFindParseDouble() {
- helpFindFunction("parseDouble", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("parseDouble", new Class<?>[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
- }
- @Test public void testFindParseFloat() {
- helpFindFunction("parseFloat", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("parseFloat", new Class<?>[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
- }
-
- @Test public void testFindParseBigInteger() {
- helpFindFunction("parseBigInteger", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("parseBigInteger", new Class<?>[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
- }
-
- @Test public void testFindParseBigDecimal() {
- helpFindFunction("parseBigDecimal", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
- helpCreateDescriptor("parseBigDecimal", new Class<?>[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
- }
-
- @Test public void testInvokeParseInteger() {
- helpInvokeMethod("parseInteger", new Object[] {new String("-1234"), new String("######")}, new Integer(-1234)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeParseLong() {
- helpInvokeMethod("parseLong", new Object[] {new String("123456"), new String("######.##")}, new Long(123456)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeParseDouble() {
- helpInvokeMethod("parseDouble", new Object[] {new String("123456.78"), new String("#####.#")}, new Double(123456.78)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeParseFloat() {
- helpInvokeMethod("parseFloat", new Object[] {new String("1234.56"), new String("####.###")}, new Float(1234.56)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeParseBigInteger() {
- helpInvokeMethod("parseBigInteger", new Object[] {new String("12345678"), new String("###,###")}, new BigInteger("12345678")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeParseBigDecimal() {
- helpInvokeMethod("parseBigDecimal", new Object[] {new String("1234.56"), new String("#####")}, new BigDecimal("1234.56")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeFormatInteger() {
- helpInvokeMethod("formatInteger", new Object[] {new Integer(-1234), new String("######")}, "-1234"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeFormatLong() {
- helpInvokeMethod("formatLong", new Object[] {new Long(123456788), new String("##,###,#")}, "1,2,3,4,5,6,7,8,8"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeFormatDouble() {
- helpInvokeMethod("formatDouble", new Object[] {new Double(1234.67), new String("####.##")}, "1234.67"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeFormatFloat() {
- helpInvokeMethod("formatFloat", new Object[] {new Float(1234.67), new String("###.###")}, "1234.67"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeFormatBigInteger() {
- helpInvokeMethod("formatBigInteger", new Object[] {new BigInteger("45"), new String("###.###")}, "45"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeFormatBigDecimal() {
- helpInvokeMethod("formatBigDecimal", new Object[] {new BigDecimal("1234.56"), new String("###.###")}, "1234.56"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokeQuarter1() {
- // 2003-5-15
- helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 4, 15)}, new Integer(2)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeQuarter2() {
- // 2003-5-1
- helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 3, 31)}, new Integer(2)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeQuarter3() {
- // 2003-1-31
- helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 0, 31)}, new Integer(1)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeQuarter4() {
- // 2003-9-30
- helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 8, 30)}, new Integer(3)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeQuarter5() {
- // 2003-12-31
- helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 11, 31)}, new Integer(4)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeQuarter6() {
- //bad date such as 2003-13-45
- helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 12, 45)}, new Integer(1)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeIfNull() {
- helpInvokeMethod("ifnull", new Object[] {new Integer(5), new Integer(10)}, new Integer(5)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeLower() {
- helpInvokeMethod("lower", new Object[] {new String("LOWER")}, new String("lower")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeUpper() {
- helpInvokeMethod("upper", new Object[] {new String("upper")}, new String("UPPER")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeRepeat() {
- helpInvokeMethod("repeat", new Object[] {new String("cat"), new Integer(3)}, new String("catcatcat")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeChar() {
- helpInvokeMethod("char", new Object[] {new Integer(32) }, new Character(' ')); //$NON-NLS-1$
- }
-
- /** normal input */
- @Test public void testInvokeInsert1() {
- helpInvokeMethod("insert", new Object[] {new String("Downtown"), new Integer(4), //$NON-NLS-1$ //$NON-NLS-2$
- new Integer(2), new String("cat")}, new String("Dowcatown")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** empty string2 */
- @Test public void testInvokeInsert2() {
- helpInvokeMethod("insert", new Object[] {new String("Downtown"), new Integer(4), //$NON-NLS-1$ //$NON-NLS-2$
- new Integer(2), new String("")}, new String("Dowown")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** empty string1 with start = 1 and length = 0, so result is just string2 */
- @Test public void testInvokeInsert3() {
- helpInvokeMethod("insert", new Object[] {new String(""), new Integer(1), //$NON-NLS-1$ //$NON-NLS-2$
- new Integer(0), new String("cat")}, new String("cat")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** should fail, with start > string1.length() */
- @Test public void testInvokeInsert4() throws Exception {
- helpInvokeMethodFail("insert", new Object[] {new String(""), new Integer(2), //$NON-NLS-1$ //$NON-NLS-2$
- new Integer(0), new String("cat")}); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** should fail, with length > 0 and input string1.length() = 0 */
- @Test public void testInvokeInsert5() throws Exception {
- helpInvokeMethodFail("insert", new Object[] {new String(""), new Integer(1), //$NON-NLS-1$ //$NON-NLS-2$
- new Integer(1), new String("cat")}); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** (length + start) > string1.length(), then just append str2 starting at start position */
- @Test public void testInvokeInsert6() {
- helpInvokeMethod("insert", new Object[] {new String("Downtown"), new Integer(7), //$NON-NLS-1$ //$NON-NLS-2$
- new Integer(5), new String("cat")}, new String("Downtocat")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testInvokeTimestampAddDate_ignore_case() {
- helpInvokeMethod("timestampAdd", new Object[] {"sql_TSI_day", //$NON-NLS-1$ //$NON-NLS-2$
- new Integer(28), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(103, 5, 12).getTime()));
- }
-
- /** date + month --> count=18, inteval=month, result should be 2004-11-15 */
- @Test public void testInvokeTimestampAddDate2() {
- helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_MONTH, //$NON-NLS-1$
- new Integer(18), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(104, 10, 15).getTime()));
- }
-
- /** date + month --> count=-18, inteval=month, result should be 2001-11-15 */
- @Test public void testInvokeTimestampAddDate2a() {
- helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_MONTH, //$NON-NLS-1$
- new Integer(-18), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(101, 10, 15).getTime()));
- }
-
- /** date + week --> count=6, inteval=week, result should be 2003-04-03 */
- @Test public void testInvokeTimestampAddDate3() {
- helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_WEEK, //$NON-NLS-1$
- new Integer(-6), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(103, 3, 3).getTime()));
- }
-
- /** date + quarter --> count=3, inteval=quarter, result should be 2004-2-15 */
- @Test public void testInvokeTimestampAddDate4() {
- helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_QUARTER, //$NON-NLS-1$
- new Integer(3), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(104, 1, 15).getTime()));
- }
-
- /** date + year --> count=-1, inteval=year, result should be 2002-5-15 */
- @Test public void testInvokeTimestampAddDate5() {
- helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_YEAR, //$NON-NLS-1$
- new Integer(-1), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(102, 4, 15).getTime()));
- }
-
- /** time + minute --> count=23, inteval=3, result should be 03:32:12 */
- @Test public void testInvokeTimestampAddTime1() {
- helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_MINUTE, //$NON-NLS-1$
- new Integer(23), new Timestamp(TimestampUtil.createTime(3, 9, 12).getTime())}, new Timestamp(TimestampUtil.createTime(3, 32, 12).getTime()));
- }
-
- /** time + hour --> count=21, inteval=4, result should be 00:09:12 and overflow */
- @Test public void testInvokeTimestampAddTime2() {
- helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_HOUR, //$NON-NLS-1$
- new Integer(21), new Timestamp(TimestampUtil.createTime(3, 9, 12).getTime())}, TimestampUtil.createTimestamp(70, 0, 2, 0, 9, 12, 0));
- }
-
- /** time + hour --> count=2, inteval=4, result should be 01:12:12*/
- @Test public void testInvokeTimestampAddTime3() {
- helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_HOUR, //$NON-NLS-1$
- new Integer(2), new Timestamp(TimestampUtil.createTime(23, 12, 12).getTime())}, TimestampUtil.createTimestamp(70, 0, 2, 1, 12, 12, 0));
- }
-
- /** time + second --> count=23, inteval=2, result should be 03:10:01 */
- @Test public void testInvokeTimestampAddTime4() {
- helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_SECOND, //$NON-NLS-1$
- new Integer(49), new Timestamp(TimestampUtil.createTime(3, 9, 12).getTime())}, new Timestamp(TimestampUtil.createTime(3, 10, 1).getTime()));
- }
-
- /** timestamp + second --> count=23, inteval=2, result should be 2003-05-15 03:09:35.100 */
- @Test public void testInvokeTimestampAddTimestamp1() {
- helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_SECOND, //$NON-NLS-1$
- new Integer(23), TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 12, 100)},
- TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 35, 100));
- }
-
- /** timestamp + nanos --> count=1, inteval=1, result should be 2003-05-15 03:09:12.000000101 */
- @Test public void testInvokeTimestampAddTimestamp2() {
- helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND, //$NON-NLS-1$
- new Integer(1), TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 12, 100)},
- TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 12, 101));
- }
-
- /** timestamp + nanos --> count=2100000000, inteval=1, result should be 2003-05-15 03:10:01.100000003
- * with increase in second and minutes, because second already at 59 sec originally
- */
- @Test public void testInvokeTimestampAddTimestamp3() {
- helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND, //$NON-NLS-1$
- new Integer(2100000000), TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 59, 1)},
- TimestampUtil.createTimestamp(103, 4, 15, 3, 10, 1, 100000003));
- }
-
- /** time --> interval=hour, time1 = 03:04:45, time2= 05:05:36 return = 2 */
- @Test public void testInvokeTimestampDiffTime1() {
- helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_HOUR, //$NON-NLS-1$
- new Timestamp(TimestampUtil.createTime(3, 4, 45).getTime()), new Timestamp(TimestampUtil.createTime(5, 5, 36).getTime()) },
- new Long(2));
- }
-
- @Test public void testInvokeTimestampDiffTime1_ignorecase() {
- helpInvokeMethod("timestampDiff", new Object[] {"SQL_tsi_HOUR", //$NON-NLS-1$ //$NON-NLS-2$
- new Timestamp(TimestampUtil.createTime(3, 4, 45).getTime()), new Timestamp(TimestampUtil.createTime(5, 5, 36).getTime()) },
- new Long(2));
- }
-
- /**
- * timestamp --> interval=week, time1 = 2002-06-21 03:09:35.100,
- * time2= 2003-05-02 05:19:35.500 return = 45
- */
- @Test public void testInvokeTimestampDiffTimestamp1() {
- helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_WEEK, //$NON-NLS-1$
- TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 100), TimestampUtil.createTimestamp(103, 4, 2, 5, 19, 35, 500) },
- new Long(45));
- }
-
- /**
- * timestamp --> interval=frac_second, time1 = 2002-06-21 03:09:35.000000001,
- * time2= 2002-06-21 03:09:35.100000000 return = 999999999
- */
- @Test public void testInvokeTimestampDiffTimestamp2() {
- helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND, //$NON-NLS-1$
- TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 1), TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 100000000) },
- new Long(99999999));
- }
-
- /**
- * timestamp --> interval=frac_second, time1 = 2002-06-21 03:09:35.000000002,
- * time2= 2002-06-22 03:09:35.000000001 return =
- */
- @Test public void testInvokeTimestampDiffTimestamp3() {
- helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND, //$NON-NLS-1$
- TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 2), TimestampUtil.createTimestamp(102, 5, 22, 3, 9, 35, 1) },
- new Long(86399999999999L));
- }
-
- @Test public void testInvokeTimestampCreate1() {
- helpInvokeMethod("timestampCreate", new Object[] {TimestampUtil.createDate(103, 4, 15), //$NON-NLS-1$
- TimestampUtil.createTime(23, 59, 59)},
- TimestampUtil.createTimestamp(103, 4, 15, 23, 59, 59, 0));
- }
-
- @Test public void testInvokeBitand() {
- helpInvokeMethod("bitand", new Object[] {new Integer(0xFFF), new Integer(0x0F0)}, new Integer(0x0F0)); //$NON-NLS-1$
- }
- @Test public void testInvokeBitor() {
- helpInvokeMethod("bitor", new Object[] {new Integer(0xFFF), new Integer(0x0F0)}, new Integer(0xFFF)); //$NON-NLS-1$
- }
- @Test public void testInvokeBitxor() {
- helpInvokeMethod("bitxor", new Object[] {new Integer(0xFFF), new Integer(0x0F0)}, new Integer(0xF0F)); //$NON-NLS-1$
- }
- @Test public void testInvokeBitnot() {
- helpInvokeMethod("bitnot", new Object[] {new Integer(0xF0F)}, new Integer(0xFFFFF0F0)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeRound1() {
- helpInvokeMethod("round", new Object[] {new Integer(123), new Integer(-1)}, new Integer(120)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeRound2() {
- helpInvokeMethod("round", new Object[] {new Float(123.456), new Integer(2)}, new Float(123.46)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeRound3() {
- helpInvokeMethod("round", new Object[] {new Double(123.456), new Integer(2)}, new Double(123.46)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeRound4() {
- helpInvokeMethod("round", new Object[] {new BigDecimal("123.456"), new Integer(2)}, new BigDecimal("123.460")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- /** defect 10941 */
- @Test public void testInvokeConvertTime() {
- helpInvokeMethod("convert", new Object[] {"05:00:00", "time"}, TimestampUtil.createTime(5, 0, 0)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeXpath1() {
- helpInvokeMethod("xpathValue", //$NON-NLS-1$
- new Object[] {
- "<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>", //$NON-NLS-1$
- "a/b/c"}, //$NON-NLS-1$
- "test"); //$NON-NLS-1$
- }
-
- @Test public void testInvokeXpathWithNill() {
- helpInvokeMethod("xpathValue", //$NON-NLS-1$
- new Object[] {
- "<?xml version=\"1.0\" encoding=\"utf-8\" ?><a xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><b xsi:nil=\"true\"/></a>", //$NON-NLS-1$
- "//*[local-name()='b' and not(@*[local-name()='nil' and string()='true'])]"}, //$NON-NLS-1$
- null);
- }
-
- @Test public void testInvokeXpathWithNill1() {
- helpInvokeMethod("xpathValue", //$NON-NLS-1$
- new Object[] {
- "<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b>value</b></a>", //$NON-NLS-1$
- "//*[local-name()='b' and not(@*[local-name()='nil' and string()='true'])]"}, //$NON-NLS-1$
- "value"); //$NON-NLS-1$
- }
-
- @Test public void testInvokeModifyTimeZone() {
- Timestamp ts = Timestamp.valueOf("2004-10-03 23:59:59.123"); //$NON-NLS-1$
- Timestamp out = Timestamp.valueOf("2004-10-03 22:59:59.123"); //$NON-NLS-1$
- helpInvokeMethod("modifyTimeZone", new Object[] {ts, "America/Chicago", "America/New_York" }, out); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- // TimestampWithTimezone has a static copy the default timezone object which makes this test not execute properly
- public void defer_testInvokeModifyTimeZoneFromLocal() {
- Timestamp ts = Timestamp.valueOf("2004-10-03 23:59:59.123"); //$NON-NLS-1$
- Timestamp out = Timestamp.valueOf("2004-10-03 21:59:59.123"); //$NON-NLS-1$
- helpInvokeMethod("modifyTimeZone", new Object[] {ts, "America/New_York" }, out); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testInvokeRand() throws Exception {
- helpInvokeMethod("rand", new Object[] {new Integer(100)}, new Double(0.7220096548596434)); //$NON-NLS-1$
- // this does not actually fail but returns a result
- assertNotNull(helpInvokeMethod("rand", new Class<?>[] {Integer.class}, new Object[] {null}, null)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeUser() throws Exception {
- CommandContext c = new CommandContext();
- c.setUserName("foodude"); //$NON-NLS-1$
- helpInvokeMethod("user", new Class<?>[] {}, new Object[] {}, c, "foodude"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testInvokeEnv() throws Exception {
- CommandContext c = new CommandContext();
- Properties props = new Properties();
- props.setProperty("env_test", "env_value"); //$NON-NLS-1$ //$NON-NLS-2$
- c.setEnvironmentProperties(props);
- helpInvokeMethod("env", new Class<?>[] {String.class}, new Object[] {"env_test"}, c, "env_value"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- helpInvokeMethod("env", new Class<?>[] {String.class}, new Object[] {null}, c, null); //$NON-NLS-1$
- }
-
- @Test public void testInvokeCommandPayload() throws Exception {
- CommandContext c = new CommandContext();
- c.setCommandPayload("payload_too heavy"); //$NON-NLS-1$
- helpInvokeMethod("commandpayload", new Class<?>[] {}, new Object[] {}, c, "payload_too heavy"); //$NON-NLS-1$ //$NON-NLS-2$
- helpInvokeMethod("commandpayload", new Class<?>[] {String.class}, new Object[] {null}, c, null); //$NON-NLS-1$
- Properties props = new Properties();
- props.setProperty("payload", "payload_too heavy"); //$NON-NLS-1$ //$NON-NLS-2$
- c.setCommandPayload(props);
- helpInvokeMethod("commandpayload", new Class<?>[] {String.class}, new Object[] {"payload"}, c, "payload_too heavy"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testNullDependent() {
- FunctionDescriptor actual = library.findFunction("concat2", new Class<?>[] {String.class, String.class}); //$NON-NLS-1$
- assertTrue(actual.isNullDependent());
-
- actual = library.findFunction("concat", new Class<?>[] {String.class, String.class}); //$NON-NLS-1$
- assertFalse(actual.isNullDependent());
- }
-
- @Test public void testInvokeCeiling() {
- helpInvokeMethod("ceiling", new Object[] { new Double("3.14") }, new Double("4")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeFloor() {
- helpInvokeMethod("floor", new Object[] { new Double("3.14") }, new Double("3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeExp() {
- helpInvokeMethod("exp", new Object[] { new Double("0") }, new Double("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeLog() {
- helpInvokeMethod("log", new Object[] { new Double("1") }, new Double("0")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeLog10() {
- helpInvokeMethod("log10", new Object[] { new Double("10") }, new Double("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeLog10Error() throws Exception {
- helpInvokeMethodFail("log10", new Object[] { new Double("0") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokePower() {
- helpInvokeMethod("power", new Object[] { new Double("10"), new Double("2") }, new Double("100")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testInvokePower1() {
- helpInvokeMethod("power", new Object[] { new BigDecimal("10"), new Integer(2) }, new BigDecimal("100")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeSqrt() {
- helpInvokeMethod("sqrt", new Object[] { new Double("4")}, new Double("2")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testInvokeDayName() {
- for (int i = 0; i < FunctionMethods.dayNames.length; i++) {
- Date time = TimestampUtil.createDate(100, 0, i + 2);
- helpInvokeMethod("dayName", new Object[] { time }, FunctionMethods.dayNames[i]); //$NON-NLS-1$
- }
- }
-
- @Test public void testInvokeDayOfMonth() {
- Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
- helpInvokeMethod("dayOfMonth", new Object[] { time }, new Integer(1)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeDayOfWeek() {
- Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
- helpInvokeMethod("dayOfWeek", new Object[] { time }, new Integer(7)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeDayOfYear() {
- Timestamp time = TimestampUtil.createTimestamp(100, 0, 2, 1, 2, 3, 4);
- helpInvokeMethod("dayOfYear", new Object[] { time }, new Integer(2)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeMonth() {
- Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
- helpInvokeMethod("month", new Object[] { time }, new Integer(1)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeMonthName() {
- for (int i = 0; i < FunctionMethods.monthNames.length; i++) {
- Date time = TimestampUtil.createDate(100, i, 1);
- helpInvokeMethod("monthName", new Object[] { time }, FunctionMethods.monthNames[i]); //$NON-NLS-1$
- }
- }
-
- @Test public void testInvokeMinute() {
- Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
- helpInvokeMethod("minute", new Object[] { time }, new Integer(2)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeSecond() {
- Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
- helpInvokeMethod("second", new Object[] { time }, new Integer(3)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeWeek() {
- Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
- helpInvokeMethod("week", new Object[] { time }, new Integer(1)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeYear() {
- Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
- helpInvokeMethod("year", new Object[] { time }, new Integer(2000)); //$NON-NLS-1$
- }
-
- @Test public void testInvokeCoalesce() {
- helpInvokeMethod(FunctionLibrary.COALESCE, new Object[] { Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2) }, Integer.valueOf(0));
- }
-
- @Test public void testInvokeCoalesce1() {
- helpInvokeMethod(FunctionLibrary.COALESCE, new Object[] { null, null}, null);
- }
-
- @Test public void testInvokeNull() throws Exception {
- helpInvokeMethod(SourceSystemFunctions.LTRIM, new Class<?>[] {DataTypeManager.DefaultDataClasses.STRING}, new Object[] { null }, null, null);
- }
-
- @Test public void testInvokeNull1() throws Exception {
- helpInvokeMethod(SourceSystemFunctions.CONCAT, new Class<?>[] {DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING}, new Object[] { null, String.valueOf(1) }, null, null);
- }
-
- @Test public void testInvokeXslTransform() throws Exception {
- CommandContext c = new CommandContext();
- c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
- ClobType result = (ClobType)helpInvokeMethod("xsltransform", new Class<?>[] {DataTypeManager.DefaultDataClasses.XML, DataTypeManager.DefaultDataClasses.XML},
- new Object[] {DataTypeManager.transformValue("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name><Quantity>5</Quantity></Item></Items></Catalog></Catalogs>", DataTypeManager.DefaultDataClasses.XML),
- DataTypeManager.transformValue("<?xml version=\"1.0\" encoding=\"UTF-8\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match=\"@*|node()\"><xsl:copy><xsl:apply-templates select=\"@*|node()\"/></xsl:copy></xsl:template><xsl:template match=\"Quantity\"/></xsl:stylesheet>", DataTypeManager.DefaultDataClasses.XML)}, c);
-
- String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
- assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name></Item></Items></Catalog></Catalogs>", xml);
- }
-
- @Test public void testInvokeXmlConcat() throws Exception {
- CommandContext c = new CommandContext();
- c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
- XMLType result = (XMLType)helpInvokeMethod("xmlconcat", new Class<?>[] {DataTypeManager.DefaultDataClasses.XML, DataTypeManager.DefaultDataClasses.XML},
- new Object[] {DataTypeManager.transformValue("<bar/>", DataTypeManager.DefaultDataClasses.XML), DataTypeManager.transformValue("<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name><Quantity>5</Quantity></Item></Items></Catalog></Catalogs>", DataTypeManager.DefaultDataClasses.XML)}, c);
-
- String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
- assertEquals("<bar/><Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name><Quantity>5</Quantity></Item></Items></Catalog></Catalogs>", xml);
- }
-
- @Test public void testInvokeXmlComment() throws Exception {
- CommandContext c = new CommandContext();
- c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
- XMLType result = (XMLType)helpInvokeMethod("xmlcomment", new Class<?>[] {DataTypeManager.DefaultDataClasses.STRING},
- new Object[] {"comment"}, c);
-
- String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
- assertEquals("<!--comment-->", xml);
- }
-
- @Test public void testToChars() throws Exception {
- Clob result = (Clob)helpInvokeMethod("to_chars", new Class<?>[] {DefaultDataClasses.BLOB, DefaultDataClasses.STRING}, new Object[] { new BlobType(new SerialBlob("hello world".getBytes("ASCII"))), "ASCII" }, null); //$NON-NLS-1$
- String string = result.getSubString(1, (int)result.length());
- assertEquals("hello world", string);
- }
-
- @Test public void testToBytes() throws Exception {
- Blob result = (Blob)helpInvokeMethod("to_bytes", new Class<?>[] {DefaultDataClasses.CLOB, DefaultDataClasses.STRING}, new Object[] { new ClobType(new SerialClob("hello world".toCharArray())), "UTF32" }, null); //$NON-NLS-1$
- assertEquals(44, result.length()); //4 bytes / char
- }
-
- @Test public void testToChars1() throws Exception {
- Clob result = (Clob)helpInvokeMethod("to_chars", new Class<?>[] {DefaultDataClasses.BLOB, DefaultDataClasses.STRING}, new Object[] { new BlobType(new SerialBlob("hello world".getBytes("ASCII"))), "BASE64" }, null); //$NON-NLS-1$
- String string = result.getSubString(1, (int)result.length());
- assertEquals("hello world", new String(Base64.decode(string), "ASCII"));
- }
-
- @Test public void testToChars2() throws Exception {
- Clob result = (Clob)helpInvokeMethod("to_chars", new Class<?>[] {DefaultDataClasses.BLOB, DefaultDataClasses.STRING}, new Object[] { new BlobType(new SerialBlob("hello world".getBytes("ASCII"))), "HEX" }, null); //$NON-NLS-1$
- String string = result.getSubString(1, (int)result.length());
- assertEquals("68656C6C6F20776F726C64", string);
- }
-
- @Test public void testToBytes2() throws Exception {
- Blob result = (Blob)helpInvokeMethod("to_bytes", new Class<?>[] {DefaultDataClasses.CLOB, DefaultDataClasses.STRING}, new Object[] { new ClobType(new SerialClob("68656C6C6F20776F726C64".toCharArray())), "HEX" }, null); //$NON-NLS-1$
- assertEquals("hello world", new String(ObjectConverterUtil.convertToCharArray(result.getBinaryStream(), -1, "ASCII")));
- }
-
- @Test(expected=FunctionExecutionException.class) public void testToBytes3() throws Exception {
- helpInvokeMethod("to_bytes", new Class<?>[] {DefaultDataClasses.CLOB, DefaultDataClasses.STRING}, new Object[] { new ClobType(new SerialClob("a".toCharArray())), "BASE64" }, null); //$NON-NLS-1$
- }
-
- @Test() public void testUnescape() throws Exception {
- assertEquals("\r\t", helpInvokeMethod("unescape", new Class<?>[] {DefaultDataClasses.STRING}, new Object[] { "\r\\\t" }, null)); //$NON-NLS-1$
- }
-
- @Test() public void testUuid() throws Exception {
- assertNotNull(helpInvokeMethod("uuid", new Class<?>[] {}, new Object[] {}, null)); //$NON-NLS-1$
- }
-
- @Test() public void testArrayGet() throws Exception {
- assertEquals(1, helpInvokeMethod("array_get", new Class<?>[] {DefaultDataClasses.OBJECT, DefaultDataClasses.INTEGER}, new Object[] {new Object[] {1}, 1}, null)); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1411 @@
+/*
+ * 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;
+
+import static org.junit.Assert.*;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Properties;
+import java.util.TimeZone;
+
+import javax.sql.rowset.serial.SerialBlob;
+import javax.sql.rowset.serial.SerialClob;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.teiid.api.exception.query.FunctionExecutionException;
+import org.teiid.common.buffer.BufferManagerFactory;
+import org.teiid.core.types.BlobType;
+import org.teiid.core.types.ClobType;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.NullType;
+import org.teiid.core.types.XMLType;
+import org.teiid.core.types.DataTypeManager.DefaultDataClasses;
+import org.teiid.core.util.Base64;
+import org.teiid.core.util.ObjectConverterUtil;
+import org.teiid.core.util.TimestampWithTimezone;
+import org.teiid.language.SQLConstants.NonReserved;
+import org.teiid.metadata.FunctionMethod.PushDown;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.unittest.TimestampUtil;
+import org.teiid.query.util.CommandContext;
+import org.teiid.translator.SourceSystemFunctions;
+
+
+ at SuppressWarnings("nls")
+public class TestFunctionLibrary {
+
+ // These are just used as shorthand convenience to make unit tests more readable below
+ private static final Class<String> T_STRING = DataTypeManager.DefaultDataClasses.STRING;
+ private static final Class<Integer> T_INTEGER = DataTypeManager.DefaultDataClasses.INTEGER;
+ private static final Class<BigInteger> T_BIG_INTEGER = DataTypeManager.DefaultDataClasses.BIG_INTEGER;
+ private static final Class<? extends BigDecimal> T_BIG_DECIMAL = DataTypeManager.DefaultDataClasses.BIG_DECIMAL;
+ private static final Class<Long> T_LONG = DataTypeManager.DefaultDataClasses.LONG;
+ private static final Class<Float> T_FLOAT = DataTypeManager.DefaultDataClasses.FLOAT;
+ private static final Class<Double> T_DOUBLE = DataTypeManager.DefaultDataClasses.DOUBLE;
+ private static final Class<NullType> T_NULL = DataTypeManager.DefaultDataClasses.NULL;
+ private static final Class<Time> T_TIME = DataTypeManager.DefaultDataClasses.TIME;
+ 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(RealMetadataFactory.SFM.getSystemFunctions());
+
+ @Before public void setUp() {
+ TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("GMT-06:00")); //$NON-NLS-1$
+ }
+
+ @After public void tearDown() {
+ TimestampWithTimezone.resetCalendar(null);
+ }
+
+ // ################################## TEST HELPERS ################################
+
+ private FunctionDescriptor helpCreateDescriptor(String name, Class<?>[] types) {
+ final String fname = name;
+ final Class<?>[] ftypes = types;
+ return new FunctionDescriptor() {
+ public String getName() {
+ return fname;
+ }
+ public PushDown getPushdown() {
+ return PushDown.CAN_PUSHDOWN;
+ }
+ public Class<?>[] getTypes() {
+ return ftypes;
+ }
+ public Class<?> getReturnType() {
+ return null;
+ }
+
+ public String toString() {
+ StringBuffer str = new StringBuffer(fname);
+ str.append("("); //$NON-NLS-1$
+ for(int i=0; i<ftypes.length; i++) {
+ if(ftypes[i] != null) {
+ str.append(ftypes[i].getName());
+ } else {
+ str.append("null"); //$NON-NLS-1$
+ }
+ if(i<(ftypes.length-1)) {
+ str.append(", "); //$NON-NLS-1$
+ }
+ }
+ return str.toString();
+ }
+ public boolean requiresContext() {
+ return false;
+ }
+ public boolean isNullDependent() {
+ return true;
+ }
+
+ };
+ }
+
+ private void helpFindFunction(String fname, Class<?>[] types, FunctionDescriptor expected) {
+ FunctionDescriptor actual = library.findFunction(fname, types);
+
+ assertEquals("Function names do not match: ", expected.getName().toLowerCase(), actual.getName().toLowerCase()); //$NON-NLS-1$
+ assertEquals("Arg lengths do not match: ", expected.getTypes().length, actual.getTypes().length); //$NON-NLS-1$
+ }
+
+ private void helpFindFunctionFail(String fname, Class<?>[] types) {
+ FunctionDescriptor actual = library.findFunction(fname, types);
+ assertNull("Function was found but should not have been: " + actual, actual); //$NON-NLS-1$
+ }
+
+ private void helpFindConversions(String fname, Class<?>[] types, FunctionDescriptor[] expected) {
+
+ FunctionDescriptor[] actual = library.determineNecessaryConversions(fname, null, types, false);
+
+ if(expected == null) {
+ if(actual != null) {
+ fail("Expected to find no conversion for " + fname + Arrays.asList(types) + " but found: " + Arrays.asList(actual)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ } else {
+ if(actual == null) {
+ fail("Expected to find conversion for " + fname + Arrays.asList(types) + " but found none"); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ // Compare returned descriptors with expected descriptor
+ for(int i=0; i<expected.length; i++) {
+ if(expected[i] == null) {
+ if(actual[i] != null) {
+ fail("Expected no conversion at index " + i + ", but found: " + actual[i]); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ } else {
+ if(actual[i] == null) {
+ fail("Expected conversion at index " + i + ", but found none."); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ assertEquals("Expected conversion function names do not match: ", expected[i].getName(), actual[i].getName()); //$NON-NLS-1$
+ assertEquals("Expected conversion arg lengths do not match: ", expected[i].getTypes().length, actual[i].getTypes().length); //$NON-NLS-1$
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private void helpFindForm(String fname, int numArgs) {
+ FunctionForm form = library.findFunctionForm(fname, numArgs);
+ assertNotNull("Failed to find function '" + fname + "' with " + numArgs + " args", form); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ assertEquals("Function names do not match: ", fname.toUpperCase(), form.getName().toUpperCase()); //$NON-NLS-1$
+ assertEquals("Arg lengths do not match: ", numArgs, form.getArgNames().size()); //$NON-NLS-1$
+ }
+
+ private void helpInvokeMethod(String fname, Object[] inputs, Object expectedOutput) {
+ try {
+ helpInvokeMethod(fname, null, inputs, null, expectedOutput);
+ } catch (Exception err) {
+ throw new RuntimeException(err);
+ }
+ }
+
+ private void helpInvokeMethod(String fname, Class<?>[] types, Object[] inputs, CommandContext context, Object expectedOutput) throws FunctionExecutionException {
+ Object actualOutput = helpInvokeMethod(fname, types, inputs, context);
+ assertEquals("Actual function output not equal to expected: ", expectedOutput, actualOutput); //$NON-NLS-1$
+ }
+
+ private Object helpInvokeMethod(String fname, Class<?>[] types,
+ Object[] inputs, CommandContext context)
+ throws FunctionExecutionException {
+ if (types == null) {
+ // Build type signature
+ types = new Class<?>[inputs.length];
+ for(int i=0; i<inputs.length; i++) {
+ types[i] = DataTypeManager.determineDataTypeClass(inputs[i]);
+ }
+ }
+ if (context == null) {
+ context = new CommandContext();
+ }
+ Object actualOutput = null;
+ // Find function descriptor
+ FunctionDescriptor descriptor = library.findFunction(fname, types);
+ if (descriptor.requiresContext()) {
+ // Invoke function with inputs
+ Object[] in = new Object[inputs.length+1];
+ in[0] = context;
+ for (int i = 0; i < inputs.length; i++) {
+ in[i+1] = inputs[i];
+ }
+ actualOutput = descriptor.invokeFunction(in);
+ }
+ else {
+ // Invoke function with inputs
+ actualOutput = descriptor.invokeFunction(inputs);
+ }
+ return actualOutput;
+ }
+
+ private void helpInvokeMethodFail(String fname, Object[] inputs) {
+ helpInvokeMethodFail(fname, null, inputs);
+ }
+
+ private void helpInvokeMethodFail(String fname, Class<?> types[], Object[] inputs) {
+ try {
+ helpInvokeMethod(fname, types, inputs, null);
+ fail("expected exception"); //$NON-NLS-1$
+ } catch (FunctionExecutionException err) {
+ }
+ }
+ // ################################## ACTUAL TESTS ################################
+
+ @Test public void testFindFunction1() {
+ helpFindFunction("convert", new Class<?>[] { T_INTEGER, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_INTEGER, T_STRING }) );
+ }
+
+ @Test public void testFindFunction2() {
+ helpFindFunction("cast", new Class<?>[] { T_INTEGER, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor(FunctionLibrary.CAST, new Class<?>[] { T_INTEGER, T_STRING }) );
+ }
+
+ @Test public void testFindFunction3() {
+ helpFindFunction("curdate", new Class<?>[0], //$NON-NLS-1$
+ helpCreateDescriptor("curdate", new Class<?>[0])); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction4() {
+ helpFindFunctionFail("curdate", new Class<?>[] { T_INTEGER }); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction5() {
+ helpFindFunction("+", new Class<?>[] { T_INTEGER, T_INTEGER }, //$NON-NLS-1$
+ helpCreateDescriptor("+", new Class<?>[] { T_INTEGER, T_INTEGER }) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction6() {
+ helpFindFunctionFail("+", new Class<?>[] {T_INTEGER, T_FLOAT}); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction7() {
+ helpFindFunctionFail("+", new Class<?>[] {T_INTEGER, T_FLOAT, T_INTEGER}); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction8() {
+ helpFindFunctionFail("+", new Class<?>[] {T_INTEGER}); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction9() {
+ helpFindFunctionFail("+", new Class<?>[] {T_INTEGER, T_NULL }); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction10() {
+ helpFindFunction("substring", new Class<?>[] { T_STRING, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
+ helpCreateDescriptor("substring", new Class<?>[] { T_STRING, T_INTEGER, T_INTEGER }) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction11() {
+ helpFindFunction("substring", new Class<?>[] { T_STRING, T_INTEGER }, //$NON-NLS-1$
+ helpCreateDescriptor("substring", new Class<?>[] { T_STRING, T_INTEGER }) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction12() {
+ helpFindFunction("context", new Class<?>[] { T_STRING, T_INTEGER }, //$NON-NLS-1$
+ helpCreateDescriptor("context", new Class<?>[] { T_STRING, T_INTEGER }) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction12a() {
+ helpFindFunction("rowlimit", new Class<?>[] { T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("rowlimit", new Class<?>[] { T_STRING }) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction12b() {
+ helpFindFunction("rowlimitexception", new Class<?>[] { T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("rowlimitexception", new Class<?>[] { T_STRING }) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFind0ArgConversion1() {
+ helpFindConversions(
+ "curdate", new Class<?>[] {}, //$NON-NLS-1$
+ new FunctionDescriptor[0] );
+ }
+
+ @Test public void testFind0ArgConversion2() {
+ helpFindConversions(
+ "curdate", new Class<?>[] { T_INTEGER }, //$NON-NLS-1$
+ null );
+ }
+
+ @Test public void testFind1ArgConversion1() {
+ helpFindConversions(
+ "length", new Class<?>[] { T_STRING }, //$NON-NLS-1$
+ new FunctionDescriptor[1] );
+ }
+
+ @Test public void testFind1ArgConversion2() {
+ helpFindConversions(
+ "length", new Class<?>[] { T_INTEGER }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_INTEGER, T_STRING })
+ } );
+ }
+
+ @Test public void testFind1ArgConversion3() {
+ helpFindConversions(
+ "length", new Class<?>[] { DataTypeManager.DefaultDataClasses.TIMESTAMP }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.TIMESTAMP, T_STRING })
+ } );
+ }
+
+ @Test public void testFind2ArgConversion1() {
+ helpFindConversions(
+ "+", new Class<?>[] { T_INTEGER, T_INTEGER }, //$NON-NLS-1$
+ new FunctionDescriptor[2] );
+ }
+
+ @Test public void testFind2ArgConversion2() {
+ helpFindConversions(
+ "+", new Class<?>[] { T_INTEGER, T_FLOAT }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_INTEGER, T_STRING }),
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_FLOAT, T_STRING }) } );
+ }
+
+ @Test public void testFind2ArgConversion3() {
+ helpFindConversions(
+ "+", new Class<?>[] { T_FLOAT, T_INTEGER }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_FLOAT, T_STRING }),
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_INTEGER, T_STRING }) } );
+ }
+
+ @Test public void testFind2ArgConversion4() {
+ helpFindConversions(
+ "+", new Class<?>[] { T_STRING, T_FLOAT }, //$NON-NLS-1$
+ null );
+ }
+
+ @Test public void testFind2ArgConversion5() {
+ helpFindConversions(
+ "+", new Class<?>[] { T_NULL, T_NULL }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }) } );
+ }
+
+ @Test public void testFind2ArgConversion6() {
+ helpFindConversions(
+ "+", new Class<?>[] { T_NULL, T_INTEGER }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
+ null } );
+ }
+
+ @Test public void testFind2ArgConversion7() {
+ helpFindConversions(
+ "+", new Class<?>[] { T_INTEGER, T_NULL }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ null,
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }) } );
+ }
+
+ @Test public void testFind3ArgConversion1() {
+ helpFindConversions(
+ "substring", new Class<?>[] { T_STRING, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
+ new FunctionDescriptor[3] );
+ }
+
+ @Test public void testFind3ArgConversion2() {
+ helpFindConversions(
+ "substring", new Class<?>[] { T_INTEGER, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_INTEGER, T_STRING }),
+ null,
+ null
+ } );
+ }
+
+ @Test public void testFind3ArgConversion3() {
+ helpFindConversions(
+ "substring", new Class<?>[] { T_INTEGER, T_INTEGER, DataTypeManager.DefaultDataClasses.SHORT }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_INTEGER, T_STRING }),
+ null,
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING })
+ } );
+ }
+
+ @Test public void testFind3ArgConversion4() {
+ helpFindConversions(
+ "substring", new Class<?>[] { T_STRING, T_INTEGER, DataTypeManager.DefaultDataClasses.TIMESTAMP }, //$NON-NLS-1$
+ null );
+ }
+
+ @Test public void testFind3ArgConversion5() {
+ helpFindConversions(
+ "substring", new Class<?>[] { T_STRING, DataTypeManager.DefaultDataClasses.SHORT, DataTypeManager.DefaultDataClasses.SHORT }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ null,
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING }),
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING })
+ } );
+ }
+
+ @Test public void testFind3ArgConversion6() {
+ helpFindConversions(
+ "substring", new Class<?>[] { T_INTEGER, DataTypeManager.DefaultDataClasses.SHORT, DataTypeManager.DefaultDataClasses.SHORT }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.INTEGER, T_STRING }),
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING }),
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING })
+ } );
+ }
+
+ @Test public void testFind3ArgConversion7() {
+ helpFindConversions(
+ "substring", new Class<?>[] { T_NULL, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
+ null,
+ null }
+ );
+ }
+
+ @Test public void testFind3ArgConversion8() {
+ helpFindConversions(
+ "substring", new Class<?>[] { T_NULL, T_NULL, T_INTEGER }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
+ null }
+ );
+ }
+
+ @Test public void testFind3ArgConversion9() {
+ helpFindConversions(
+ "substring", new Class<?>[] { T_NULL, T_NULL, T_NULL }, //$NON-NLS-1$
+ new FunctionDescriptor[] {
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }),
+ helpCreateDescriptor(FunctionLibrary.CONVERT, new Class<?>[] { T_NULL, T_STRING }) }
+ );
+ }
+
+ // Walk through all functions by metadata
+ @Test public void testEnumerateForms() {
+ Collection<String> categories = library.getFunctionCategories();
+ for (String category : categories) {
+ //System.out.println("Category: " + category);
+
+ Collection<FunctionForm> functions = library.getFunctionForms(category);
+ for (FunctionForm form : functions) {
+ //System.out.println("\tFunction: " + form.getDisplayString());
+
+ // Lookup this form
+ helpFindForm(form.getName(), form.getArgNames().size());
+ }
+ }
+ }
+
+ @Test public void testFindForm1() {
+ helpFindForm("convert", 2); //$NON-NLS-1$
+ }
+
+ @Test public void testFindForm2() {
+ helpFindForm("locate", 2); //$NON-NLS-1$
+ }
+
+ @Test public void testFindForm3() {
+ helpFindForm("locate", 3); //$NON-NLS-1$
+ }
+
+ @Test public void testFindForm4() {
+ helpFindForm("substring", 2); //$NON-NLS-1$
+ }
+
+ @Test public void testFindForm5() {
+ helpFindForm("substring", 3); //$NON-NLS-1$
+ }
+
+ @Test public void testFindForm6() {
+ helpFindForm("now", 0); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokePlus1() {
+ helpInvokeMethod("+", new Object[] { new Integer(3), new Integer(2) }, new Integer(5)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokePlus2() {
+ helpInvokeMethod("+", new Object[] { new Long(3), new Long(2) }, new Long(5)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokePlus3() {
+ helpInvokeMethod("+", new Object[] { new Float(3), new Float(2) }, new Float(5)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokePlus4() {
+ helpInvokeMethod("+", new Object[] { new Double(3), new Double(2) }, new Double(5)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokePlus5() {
+ helpInvokeMethod("+", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("5")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokePlus6() {
+ helpInvokeMethod("+", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("5")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeMinus1() {
+ helpInvokeMethod("-", new Object[] { new Integer(3), new Integer(2) }, new Integer(1)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeMinus2() {
+ helpInvokeMethod("-", new Object[] { new Long(3), new Long(2) }, new Long(1)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeMinus3() {
+ helpInvokeMethod("-", new Object[] { new Float(3), new Float(2) }, new Float(1)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeMinus4() {
+ helpInvokeMethod("-", new Object[] { new Double(3), new Double(2) }, new Double(1)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeMinus5() {
+ helpInvokeMethod("-", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeMinus6() {
+ helpInvokeMethod("-", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeMultiply1() {
+ helpInvokeMethod("*", new Object[] { new Integer(3), new Integer(2) }, new Integer(6)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeMultiply2() {
+ helpInvokeMethod("*", new Object[] { new Long(3), new Long(2) }, new Long(6)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeMultiply3() {
+ helpInvokeMethod("*", new Object[] { new Float(3), new Float(2) }, new Float(6)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeMultiply4() {
+ helpInvokeMethod("*", new Object[] { new Double(3), new Double(2) }, new Double(6)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeMultiply5() {
+ helpInvokeMethod("*", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("6")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeMultiply6() {
+ helpInvokeMethod("*", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("6")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeDivide1() {
+ helpInvokeMethod("/", new Object[] { new Integer(3), new Integer(2) }, new Integer(1)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeDivide2() {
+ helpInvokeMethod("/", new Object[] { new Long(3), new Long(2) }, new Long(1)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeDivide3() {
+ helpInvokeMethod("/", new Object[] { new Float(3), new Float(2) }, new Float(1.5)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeDivide4() {
+ helpInvokeMethod("/", new Object[] { new Double(3), new Double(2) }, new Double(1.5)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeDivide5() {
+ helpInvokeMethod("/", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ // one digit precision
+ @Test public void testInvokeDivide6() {
+ helpInvokeMethod("/", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("1.5")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeDivide7() throws Exception {
+ helpInvokeMethodFail("/", new Object[] { new Float("3"), new Float("0") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeDivideMod() {
+ helpInvokeMethod("mod", new Object[] { new BigDecimal("3.1"), new BigDecimal("2") }, new BigDecimal("1.1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeAbs1() {
+ helpInvokeMethod("abs", new Object[] { new Integer(-3) }, new Integer(3)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeAbs2() {
+ helpInvokeMethod("abs", new Object[] { new Long(-3) }, new Long(3)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeAbs3() {
+ helpInvokeMethod("abs", new Object[] { new Float(-3) }, new Float(3)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeAbs4() {
+ helpInvokeMethod("abs", new Object[] { new Double(-3) }, new Double(3)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeAbs5() {
+ helpInvokeMethod("abs", new Object[] { new BigInteger("-3") }, new BigInteger("3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeAbs6() {
+ helpInvokeMethod("abs", new Object[] { new BigDecimal("-3") }, new BigDecimal("3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeAcos() {
+ helpInvokeMethod("acos", new Object[] { new Double(0.05) }, new Double(1.5207754699891267)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeAsin() {
+ helpInvokeMethod("asin", new Object[] { new Double(0.05) }, new Double(0.050020856805770016)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeAtan() {
+ helpInvokeMethod("atan", new Object[] { new Double(0.05) }, new Double(0.049958395721942765)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeAtan2() {
+ helpInvokeMethod("atan2", new Object[] { new Double(0.05), new Double(0.07) }, new Double(0.6202494859828215)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeAtanBigDecimal() {
+ helpInvokeMethod("atan", new Object[] { new BigDecimal(0.05) }, new Double(0.049958395721942765)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeAtan2BigDecimal() {
+ helpInvokeMethod("atan2", new Object[] { new BigDecimal(0.05), new BigDecimal(0.07) }, new Double(0.6202494859828215)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeCos() {
+ helpInvokeMethod("cos", new Object[] { new Double(1.57) }, new Double(7.963267107332633E-4)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeCot() {
+ helpInvokeMethod("cot", new Object[] { new Double(1.57) }, new Double(7.963269632231926E-4)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeDegrees() {
+ helpInvokeMethod("degrees", new Object[] { new Double(1.57) }, new Double(89.95437383553926)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokePI() {
+ helpInvokeMethod("pi", new Object[] { }, new Double(3.141592653589793)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeRadians() {
+ helpInvokeMethod("radians", new Object[] { new Double(89.95437383553926) }, new Double(1.57)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeSin() {
+ helpInvokeMethod("sin", new Object[] { new Double(1.57) }, new Double(0.9999996829318346)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeTan() {
+ helpInvokeMethod("tan", new Object[] { new Double(0.785) }, new Double(0.9992039901050427)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeAscii() {
+ helpInvokeMethod("ascii", new Object[] { " " }, new Integer(32)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInvokeChr() {
+ helpInvokeMethod("chr", new Object[] { new Integer(32) }, new Character(' ')); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeNvl() {
+ helpInvokeMethod("nvl", new Object[] { new Integer(5), new Integer(10) }, new Integer(5) ); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeConcatOperator() {
+ helpInvokeMethod("||", new Object[] { "a", "b" }, "ab" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeInitcap() {
+ helpInvokeMethod("initcap", new Object[] { "my test\ndata" }, "My Test\nData" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeLpad1() {
+ helpInvokeMethod("lpad", new Object[] { "x", new Integer(3) }, " x" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeLpad2() {
+ helpInvokeMethod("lpad", new Object[] { "x", new Integer(3), "y" }, "yyx" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeRpad1() {
+ helpInvokeMethod("rpad", new Object[] { "x", new Integer(3) }, "x " ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeRpad2() {
+ helpInvokeMethod("rpad", new Object[] { "x", new Integer(3), "y" }, "xyy" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeTranslate() {
+ helpInvokeMethod("translate", new Object[] { "ababcd", "ad", "da" }, "dbdbca" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ @Test public void testFindFunction13() {
+ helpFindFunction("formatTime", new Class<?>[] { T_TIME, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("formatTime", new Class<?>[] { T_TIME, T_STRING }) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction14() {
+ helpFindFunction("formatDate", new Class<?>[] { T_DATE, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("formatDate", new Class<?>[] { T_DATE, T_STRING }) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction15() {
+ helpFindFunction("formatTimestamp", new Class<?>[] { T_TIMESTAMP, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("formatTimestamp", new Class<?>[] { T_TIMESTAMP, T_STRING }) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction16() {
+ helpFindFunction("parseTime", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("parseTime", new Class<?>[] { T_STRING, T_STRING }) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction17() {
+ helpFindFunction("parseDate", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("parseDate", new Class<?>[] { T_STRING, T_STRING }) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction18() {
+ helpFindFunction("parseTimestamp", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("parseTimestamp", new Class<?>[] { T_STRING, T_STRING }) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFunction19() {
+ helpFindFunction("env", new Class<?>[] {T_STRING}, //$NON-NLS-1$
+ helpCreateDescriptor("env", new Class<?>[] {T_STRING})); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeFormatTimestamp1() {
+ helpInvokeMethod("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("mm/dd/yy h:mm a") }, "04/05/03 3:04 AM"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeFormatTimestamp2() {
+ helpInvokeMethod("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("yyyy-mm-dd k:mm a z") }, "2003-04-05 3:04 AM GMT-06:00"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeFormatTimestamp3() {
+ helpInvokeMethod("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("yyyy-mm-dd hh:mm:ss.SSSS") }, "2003-04-05 03:04:12.0000"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeFormatTimestampFail() throws Exception {
+ helpInvokeMethodFail("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("mm/dd/nn h:mm a") }); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeParseTimestamp1() {
+ helpInvokeMethod("parseTimestamp", new Object[] {new String("05 Mar 2003 03:12:23 CST"), new String("dd MMM yyyy HH:mm:ss z") }, TimestampUtil.createTimestamp(103, 2, 5, 3, 12, 23, 0)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeParseTimestamp2() {
+ helpInvokeMethod("parseTimestamp", new Object[] {new String("05 Mar 2003 03:12:23.333"), new String("dd MMM yyyy HH:mm:ss.SSS") }, TimestampUtil.createTimestamp(103, 2, 5, 3, 12, 23, 333*1000000)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testFindFormatInteger() {
+ helpFindFunction("formatInteger", new Class<?>[] { T_INTEGER, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("formatInteger", new Class<?>[] { T_INTEGER, T_STRING}) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFormatFloat() {
+ helpFindFunction("formatFloat", new Class<?>[] { T_FLOAT, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("formatFloat", new Class<?>[] { T_FLOAT, T_STRING}) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFormatDouble() {
+ helpFindFunction("formatDouble", new Class<?>[] { T_DOUBLE, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("formatDouble", new Class<?>[] { T_DOUBLE, T_STRING}) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFormatLong() {
+ helpFindFunction("formatLong", new Class<?>[] { T_LONG, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("formatLong", new Class<?>[] { T_LONG, T_STRING}) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFormatBigInteger() {
+ helpFindFunction("formatBigInteger", new Class<?>[] { T_BIG_INTEGER, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("formatBigInteger", new Class<?>[] { T_BIG_INTEGER, T_STRING}) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindFormatBigDecimal() {
+ helpFindFunction("formatBigDecimal", new Class<?>[] { T_BIG_DECIMAL, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("formatBigDecimal", new Class<?>[] { T_BIG_DECIMAL, T_STRING}) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindParseInteger() {
+ helpFindFunction("parseInteger", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("parseInteger", new Class<?>[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindParseLong() {
+ helpFindFunction("parseLong", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("parseLong", new Class<?>[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindParseDouble() {
+ helpFindFunction("parseDouble", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("parseDouble", new Class<?>[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
+ }
+ @Test public void testFindParseFloat() {
+ helpFindFunction("parseFloat", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("parseFloat", new Class<?>[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindParseBigInteger() {
+ helpFindFunction("parseBigInteger", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("parseBigInteger", new Class<?>[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
+ }
+
+ @Test public void testFindParseBigDecimal() {
+ helpFindFunction("parseBigDecimal", new Class<?>[] { T_STRING, T_STRING }, //$NON-NLS-1$
+ helpCreateDescriptor("parseBigDecimal", new Class<?>[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeParseInteger() {
+ helpInvokeMethod("parseInteger", new Object[] {new String("-1234"), new String("######")}, new Integer(-1234)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeParseLong() {
+ helpInvokeMethod("parseLong", new Object[] {new String("123456"), new String("######.##")}, new Long(123456)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeParseDouble() {
+ helpInvokeMethod("parseDouble", new Object[] {new String("123456.78"), new String("#####.#")}, new Double(123456.78)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeParseFloat() {
+ helpInvokeMethod("parseFloat", new Object[] {new String("1234.56"), new String("####.###")}, new Float(1234.56)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeParseBigInteger() {
+ helpInvokeMethod("parseBigInteger", new Object[] {new String("12345678"), new String("###,###")}, new BigInteger("12345678")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeParseBigDecimal() {
+ helpInvokeMethod("parseBigDecimal", new Object[] {new String("1234.56"), new String("#####")}, new BigDecimal("1234.56")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeFormatInteger() {
+ helpInvokeMethod("formatInteger", new Object[] {new Integer(-1234), new String("######")}, "-1234"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeFormatLong() {
+ helpInvokeMethod("formatLong", new Object[] {new Long(123456788), new String("##,###,#")}, "1,2,3,4,5,6,7,8,8"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeFormatDouble() {
+ helpInvokeMethod("formatDouble", new Object[] {new Double(1234.67), new String("####.##")}, "1234.67"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeFormatFloat() {
+ helpInvokeMethod("formatFloat", new Object[] {new Float(1234.67), new String("###.###")}, "1234.67"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeFormatBigInteger() {
+ helpInvokeMethod("formatBigInteger", new Object[] {new BigInteger("45"), new String("###.###")}, "45"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeFormatBigDecimal() {
+ helpInvokeMethod("formatBigDecimal", new Object[] {new BigDecimal("1234.56"), new String("###.###")}, "1234.56"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokeQuarter1() {
+ // 2003-5-15
+ helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 4, 15)}, new Integer(2)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeQuarter2() {
+ // 2003-5-1
+ helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 3, 31)}, new Integer(2)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeQuarter3() {
+ // 2003-1-31
+ helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 0, 31)}, new Integer(1)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeQuarter4() {
+ // 2003-9-30
+ helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 8, 30)}, new Integer(3)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeQuarter5() {
+ // 2003-12-31
+ helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 11, 31)}, new Integer(4)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeQuarter6() {
+ //bad date such as 2003-13-45
+ helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 12, 45)}, new Integer(1)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeIfNull() {
+ helpInvokeMethod("ifnull", new Object[] {new Integer(5), new Integer(10)}, new Integer(5)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeLower() {
+ helpInvokeMethod("lower", new Object[] {new String("LOWER")}, new String("lower")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeUpper() {
+ helpInvokeMethod("upper", new Object[] {new String("upper")}, new String("UPPER")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeRepeat() {
+ helpInvokeMethod("repeat", new Object[] {new String("cat"), new Integer(3)}, new String("catcatcat")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeChar() {
+ helpInvokeMethod("char", new Object[] {new Integer(32) }, new Character(' ')); //$NON-NLS-1$
+ }
+
+ /** normal input */
+ @Test public void testInvokeInsert1() {
+ helpInvokeMethod("insert", new Object[] {new String("Downtown"), new Integer(4), //$NON-NLS-1$ //$NON-NLS-2$
+ new Integer(2), new String("cat")}, new String("Dowcatown")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** empty string2 */
+ @Test public void testInvokeInsert2() {
+ helpInvokeMethod("insert", new Object[] {new String("Downtown"), new Integer(4), //$NON-NLS-1$ //$NON-NLS-2$
+ new Integer(2), new String("")}, new String("Dowown")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** empty string1 with start = 1 and length = 0, so result is just string2 */
+ @Test public void testInvokeInsert3() {
+ helpInvokeMethod("insert", new Object[] {new String(""), new Integer(1), //$NON-NLS-1$ //$NON-NLS-2$
+ new Integer(0), new String("cat")}, new String("cat")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** should fail, with start > string1.length() */
+ @Test public void testInvokeInsert4() throws Exception {
+ helpInvokeMethodFail("insert", new Object[] {new String(""), new Integer(2), //$NON-NLS-1$ //$NON-NLS-2$
+ new Integer(0), new String("cat")}); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** should fail, with length > 0 and input string1.length() = 0 */
+ @Test public void testInvokeInsert5() throws Exception {
+ helpInvokeMethodFail("insert", new Object[] {new String(""), new Integer(1), //$NON-NLS-1$ //$NON-NLS-2$
+ new Integer(1), new String("cat")}); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** (length + start) > string1.length(), then just append str2 starting at start position */
+ @Test public void testInvokeInsert6() {
+ helpInvokeMethod("insert", new Object[] {new String("Downtown"), new Integer(7), //$NON-NLS-1$ //$NON-NLS-2$
+ new Integer(5), new String("cat")}, new String("Downtocat")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInvokeTimestampAddDate_ignore_case() {
+ helpInvokeMethod("timestampAdd", new Object[] {"sql_TSI_day", //$NON-NLS-1$ //$NON-NLS-2$
+ new Integer(28), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(103, 5, 12).getTime()));
+ }
+
+ /** date + month --> count=18, inteval=month, result should be 2004-11-15 */
+ @Test public void testInvokeTimestampAddDate2() {
+ helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_MONTH, //$NON-NLS-1$
+ new Integer(18), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(104, 10, 15).getTime()));
+ }
+
+ /** date + month --> count=-18, inteval=month, result should be 2001-11-15 */
+ @Test public void testInvokeTimestampAddDate2a() {
+ helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_MONTH, //$NON-NLS-1$
+ new Integer(-18), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(101, 10, 15).getTime()));
+ }
+
+ /** date + week --> count=6, inteval=week, result should be 2003-04-03 */
+ @Test public void testInvokeTimestampAddDate3() {
+ helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_WEEK, //$NON-NLS-1$
+ new Integer(-6), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(103, 3, 3).getTime()));
+ }
+
+ /** date + quarter --> count=3, inteval=quarter, result should be 2004-2-15 */
+ @Test public void testInvokeTimestampAddDate4() {
+ helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_QUARTER, //$NON-NLS-1$
+ new Integer(3), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(104, 1, 15).getTime()));
+ }
+
+ /** date + year --> count=-1, inteval=year, result should be 2002-5-15 */
+ @Test public void testInvokeTimestampAddDate5() {
+ helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_YEAR, //$NON-NLS-1$
+ new Integer(-1), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(102, 4, 15).getTime()));
+ }
+
+ /** time + minute --> count=23, inteval=3, result should be 03:32:12 */
+ @Test public void testInvokeTimestampAddTime1() {
+ helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_MINUTE, //$NON-NLS-1$
+ new Integer(23), new Timestamp(TimestampUtil.createTime(3, 9, 12).getTime())}, new Timestamp(TimestampUtil.createTime(3, 32, 12).getTime()));
+ }
+
+ /** time + hour --> count=21, inteval=4, result should be 00:09:12 and overflow */
+ @Test public void testInvokeTimestampAddTime2() {
+ helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_HOUR, //$NON-NLS-1$
+ new Integer(21), new Timestamp(TimestampUtil.createTime(3, 9, 12).getTime())}, TimestampUtil.createTimestamp(70, 0, 2, 0, 9, 12, 0));
+ }
+
+ /** time + hour --> count=2, inteval=4, result should be 01:12:12*/
+ @Test public void testInvokeTimestampAddTime3() {
+ helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_HOUR, //$NON-NLS-1$
+ new Integer(2), new Timestamp(TimestampUtil.createTime(23, 12, 12).getTime())}, TimestampUtil.createTimestamp(70, 0, 2, 1, 12, 12, 0));
+ }
+
+ /** time + second --> count=23, inteval=2, result should be 03:10:01 */
+ @Test public void testInvokeTimestampAddTime4() {
+ helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_SECOND, //$NON-NLS-1$
+ new Integer(49), new Timestamp(TimestampUtil.createTime(3, 9, 12).getTime())}, new Timestamp(TimestampUtil.createTime(3, 10, 1).getTime()));
+ }
+
+ /** timestamp + second --> count=23, inteval=2, result should be 2003-05-15 03:09:35.100 */
+ @Test public void testInvokeTimestampAddTimestamp1() {
+ helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_SECOND, //$NON-NLS-1$
+ new Integer(23), TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 12, 100)},
+ TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 35, 100));
+ }
+
+ /** timestamp + nanos --> count=1, inteval=1, result should be 2003-05-15 03:09:12.000000101 */
+ @Test public void testInvokeTimestampAddTimestamp2() {
+ helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND, //$NON-NLS-1$
+ new Integer(1), TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 12, 100)},
+ TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 12, 101));
+ }
+
+ /** timestamp + nanos --> count=2100000000, inteval=1, result should be 2003-05-15 03:10:01.100000003
+ * with increase in second and minutes, because second already at 59 sec originally
+ */
+ @Test public void testInvokeTimestampAddTimestamp3() {
+ helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND, //$NON-NLS-1$
+ new Integer(2100000000), TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 59, 1)},
+ TimestampUtil.createTimestamp(103, 4, 15, 3, 10, 1, 100000003));
+ }
+
+ /** time --> interval=hour, time1 = 03:04:45, time2= 05:05:36 return = 2 */
+ @Test public void testInvokeTimestampDiffTime1() {
+ helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_HOUR, //$NON-NLS-1$
+ new Timestamp(TimestampUtil.createTime(3, 4, 45).getTime()), new Timestamp(TimestampUtil.createTime(5, 5, 36).getTime()) },
+ new Long(2));
+ }
+
+ @Test public void testInvokeTimestampDiffTime1_ignorecase() {
+ helpInvokeMethod("timestampDiff", new Object[] {"SQL_tsi_HOUR", //$NON-NLS-1$ //$NON-NLS-2$
+ new Timestamp(TimestampUtil.createTime(3, 4, 45).getTime()), new Timestamp(TimestampUtil.createTime(5, 5, 36).getTime()) },
+ new Long(2));
+ }
+
+ /**
+ * timestamp --> interval=week, time1 = 2002-06-21 03:09:35.100,
+ * time2= 2003-05-02 05:19:35.500 return = 45
+ */
+ @Test public void testInvokeTimestampDiffTimestamp1() {
+ helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_WEEK, //$NON-NLS-1$
+ TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 100), TimestampUtil.createTimestamp(103, 4, 2, 5, 19, 35, 500) },
+ new Long(45));
+ }
+
+ /**
+ * timestamp --> interval=frac_second, time1 = 2002-06-21 03:09:35.000000001,
+ * time2= 2002-06-21 03:09:35.100000000 return = 999999999
+ */
+ @Test public void testInvokeTimestampDiffTimestamp2() {
+ helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND, //$NON-NLS-1$
+ TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 1), TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 100000000) },
+ new Long(99999999));
+ }
+
+ /**
+ * timestamp --> interval=frac_second, time1 = 2002-06-21 03:09:35.000000002,
+ * time2= 2002-06-22 03:09:35.000000001 return =
+ */
+ @Test public void testInvokeTimestampDiffTimestamp3() {
+ helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND, //$NON-NLS-1$
+ TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 2), TimestampUtil.createTimestamp(102, 5, 22, 3, 9, 35, 1) },
+ new Long(86399999999999L));
+ }
+
+ @Test public void testInvokeTimestampCreate1() {
+ helpInvokeMethod("timestampCreate", new Object[] {TimestampUtil.createDate(103, 4, 15), //$NON-NLS-1$
+ TimestampUtil.createTime(23, 59, 59)},
+ TimestampUtil.createTimestamp(103, 4, 15, 23, 59, 59, 0));
+ }
+
+ @Test public void testInvokeBitand() {
+ helpInvokeMethod("bitand", new Object[] {new Integer(0xFFF), new Integer(0x0F0)}, new Integer(0x0F0)); //$NON-NLS-1$
+ }
+ @Test public void testInvokeBitor() {
+ helpInvokeMethod("bitor", new Object[] {new Integer(0xFFF), new Integer(0x0F0)}, new Integer(0xFFF)); //$NON-NLS-1$
+ }
+ @Test public void testInvokeBitxor() {
+ helpInvokeMethod("bitxor", new Object[] {new Integer(0xFFF), new Integer(0x0F0)}, new Integer(0xF0F)); //$NON-NLS-1$
+ }
+ @Test public void testInvokeBitnot() {
+ helpInvokeMethod("bitnot", new Object[] {new Integer(0xF0F)}, new Integer(0xFFFFF0F0)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeRound1() {
+ helpInvokeMethod("round", new Object[] {new Integer(123), new Integer(-1)}, new Integer(120)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeRound2() {
+ helpInvokeMethod("round", new Object[] {new Float(123.456), new Integer(2)}, new Float(123.46)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeRound3() {
+ helpInvokeMethod("round", new Object[] {new Double(123.456), new Integer(2)}, new Double(123.46)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeRound4() {
+ helpInvokeMethod("round", new Object[] {new BigDecimal("123.456"), new Integer(2)}, new BigDecimal("123.460")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ /** defect 10941 */
+ @Test public void testInvokeConvertTime() {
+ helpInvokeMethod("convert", new Object[] {"05:00:00", "time"}, TimestampUtil.createTime(5, 0, 0)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeXpath1() {
+ helpInvokeMethod("xpathValue", //$NON-NLS-1$
+ new Object[] {
+ "<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>", //$NON-NLS-1$
+ "a/b/c"}, //$NON-NLS-1$
+ "test"); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeXpathWithNill() {
+ helpInvokeMethod("xpathValue", //$NON-NLS-1$
+ new Object[] {
+ "<?xml version=\"1.0\" encoding=\"utf-8\" ?><a xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><b xsi:nil=\"true\"/></a>", //$NON-NLS-1$
+ "//*[local-name()='b' and not(@*[local-name()='nil' and string()='true'])]"}, //$NON-NLS-1$
+ null);
+ }
+
+ @Test public void testInvokeXpathWithNill1() {
+ helpInvokeMethod("xpathValue", //$NON-NLS-1$
+ new Object[] {
+ "<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b>value</b></a>", //$NON-NLS-1$
+ "//*[local-name()='b' and not(@*[local-name()='nil' and string()='true'])]"}, //$NON-NLS-1$
+ "value"); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeModifyTimeZone() {
+ Timestamp ts = Timestamp.valueOf("2004-10-03 23:59:59.123"); //$NON-NLS-1$
+ Timestamp out = Timestamp.valueOf("2004-10-03 22:59:59.123"); //$NON-NLS-1$
+ helpInvokeMethod("modifyTimeZone", new Object[] {ts, "America/Chicago", "America/New_York" }, out); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ // TimestampWithTimezone has a static copy the default timezone object which makes this test not execute properly
+ public void defer_testInvokeModifyTimeZoneFromLocal() {
+ Timestamp ts = Timestamp.valueOf("2004-10-03 23:59:59.123"); //$NON-NLS-1$
+ Timestamp out = Timestamp.valueOf("2004-10-03 21:59:59.123"); //$NON-NLS-1$
+ helpInvokeMethod("modifyTimeZone", new Object[] {ts, "America/New_York" }, out); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInvokeRand() throws Exception {
+ helpInvokeMethod("rand", new Object[] {new Integer(100)}, new Double(0.7220096548596434)); //$NON-NLS-1$
+ // this does not actually fail but returns a result
+ assertNotNull(helpInvokeMethod("rand", new Class<?>[] {Integer.class}, new Object[] {null}, null)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeUser() throws Exception {
+ CommandContext c = new CommandContext();
+ c.setUserName("foodude"); //$NON-NLS-1$
+ helpInvokeMethod("user", new Class<?>[] {}, new Object[] {}, c, "foodude"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInvokeEnv() throws Exception {
+ CommandContext c = new CommandContext();
+ Properties props = new Properties();
+ props.setProperty("env_test", "env_value"); //$NON-NLS-1$ //$NON-NLS-2$
+ c.setEnvironmentProperties(props);
+ helpInvokeMethod("env", new Class<?>[] {String.class}, new Object[] {"env_test"}, c, "env_value"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ helpInvokeMethod("env", new Class<?>[] {String.class}, new Object[] {null}, c, null); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeCommandPayload() throws Exception {
+ CommandContext c = new CommandContext();
+ c.setCommandPayload("payload_too heavy"); //$NON-NLS-1$
+ helpInvokeMethod("commandpayload", new Class<?>[] {}, new Object[] {}, c, "payload_too heavy"); //$NON-NLS-1$ //$NON-NLS-2$
+ helpInvokeMethod("commandpayload", new Class<?>[] {String.class}, new Object[] {null}, c, null); //$NON-NLS-1$
+ Properties props = new Properties();
+ props.setProperty("payload", "payload_too heavy"); //$NON-NLS-1$ //$NON-NLS-2$
+ c.setCommandPayload(props);
+ helpInvokeMethod("commandpayload", new Class<?>[] {String.class}, new Object[] {"payload"}, c, "payload_too heavy"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testNullDependent() {
+ FunctionDescriptor actual = library.findFunction("concat2", new Class<?>[] {String.class, String.class}); //$NON-NLS-1$
+ assertTrue(actual.isNullDependent());
+
+ actual = library.findFunction("concat", new Class<?>[] {String.class, String.class}); //$NON-NLS-1$
+ assertFalse(actual.isNullDependent());
+ }
+
+ @Test public void testInvokeCeiling() {
+ helpInvokeMethod("ceiling", new Object[] { new Double("3.14") }, new Double("4")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeFloor() {
+ helpInvokeMethod("floor", new Object[] { new Double("3.14") }, new Double("3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeExp() {
+ helpInvokeMethod("exp", new Object[] { new Double("0") }, new Double("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeLog() {
+ helpInvokeMethod("log", new Object[] { new Double("1") }, new Double("0")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeLog10() {
+ helpInvokeMethod("log10", new Object[] { new Double("10") }, new Double("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeLog10Error() throws Exception {
+ helpInvokeMethodFail("log10", new Object[] { new Double("0") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokePower() {
+ helpInvokeMethod("power", new Object[] { new Double("10"), new Double("2") }, new Double("100")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testInvokePower1() {
+ helpInvokeMethod("power", new Object[] { new BigDecimal("10"), new Integer(2) }, new BigDecimal("100")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeSqrt() {
+ helpInvokeMethod("sqrt", new Object[] { new Double("4")}, new Double("2")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testInvokeDayName() {
+ for (int i = 0; i < FunctionMethods.dayNames.length; i++) {
+ Date time = TimestampUtil.createDate(100, 0, i + 2);
+ helpInvokeMethod("dayName", new Object[] { time }, FunctionMethods.dayNames[i]); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testInvokeDayOfMonth() {
+ Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+ helpInvokeMethod("dayOfMonth", new Object[] { time }, new Integer(1)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeDayOfWeek() {
+ Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+ helpInvokeMethod("dayOfWeek", new Object[] { time }, new Integer(7)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeDayOfYear() {
+ Timestamp time = TimestampUtil.createTimestamp(100, 0, 2, 1, 2, 3, 4);
+ helpInvokeMethod("dayOfYear", new Object[] { time }, new Integer(2)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeMonth() {
+ Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+ helpInvokeMethod("month", new Object[] { time }, new Integer(1)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeMonthName() {
+ for (int i = 0; i < FunctionMethods.monthNames.length; i++) {
+ Date time = TimestampUtil.createDate(100, i, 1);
+ helpInvokeMethod("monthName", new Object[] { time }, FunctionMethods.monthNames[i]); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testInvokeMinute() {
+ Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+ helpInvokeMethod("minute", new Object[] { time }, new Integer(2)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeSecond() {
+ Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+ helpInvokeMethod("second", new Object[] { time }, new Integer(3)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeWeek() {
+ Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+ helpInvokeMethod("week", new Object[] { time }, new Integer(1)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeYear() {
+ Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+ helpInvokeMethod("year", new Object[] { time }, new Integer(2000)); //$NON-NLS-1$
+ }
+
+ @Test public void testInvokeCoalesce() {
+ helpInvokeMethod(FunctionLibrary.COALESCE, new Object[] { Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2) }, Integer.valueOf(0));
+ }
+
+ @Test public void testInvokeCoalesce1() {
+ helpInvokeMethod(FunctionLibrary.COALESCE, new Object[] { null, null}, null);
+ }
+
+ @Test public void testInvokeNull() throws Exception {
+ helpInvokeMethod(SourceSystemFunctions.LTRIM, new Class<?>[] {DataTypeManager.DefaultDataClasses.STRING}, new Object[] { null }, null, null);
+ }
+
+ @Test public void testInvokeNull1() throws Exception {
+ helpInvokeMethod(SourceSystemFunctions.CONCAT, new Class<?>[] {DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING}, new Object[] { null, String.valueOf(1) }, null, null);
+ }
+
+ @Test public void testInvokeXslTransform() throws Exception {
+ CommandContext c = new CommandContext();
+ c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
+ ClobType result = (ClobType)helpInvokeMethod("xsltransform", new Class<?>[] {DataTypeManager.DefaultDataClasses.XML, DataTypeManager.DefaultDataClasses.XML},
+ new Object[] {DataTypeManager.transformValue("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name><Quantity>5</Quantity></Item></Items></Catalog></Catalogs>", DataTypeManager.DefaultDataClasses.XML),
+ DataTypeManager.transformValue("<?xml version=\"1.0\" encoding=\"UTF-8\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match=\"@*|node()\"><xsl:copy><xsl:apply-templates select=\"@*|node()\"/></xsl:copy></xsl:template><xsl:template match=\"Quantity\"/></xsl:stylesheet>", DataTypeManager.DefaultDataClasses.XML)}, c);
+
+ String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
+ assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name></Item></Items></Catalog></Catalogs>", xml);
+ }
+
+ @Test public void testInvokeXmlConcat() throws Exception {
+ CommandContext c = new CommandContext();
+ c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
+ XMLType result = (XMLType)helpInvokeMethod("xmlconcat", new Class<?>[] {DataTypeManager.DefaultDataClasses.XML, DataTypeManager.DefaultDataClasses.XML},
+ new Object[] {DataTypeManager.transformValue("<bar/>", DataTypeManager.DefaultDataClasses.XML), DataTypeManager.transformValue("<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name><Quantity>5</Quantity></Item></Items></Catalog></Catalogs>", DataTypeManager.DefaultDataClasses.XML)}, c);
+
+ String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
+ assertEquals("<bar/><Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name><Quantity>5</Quantity></Item></Items></Catalog></Catalogs>", xml);
+ }
+
+ @Test public void testInvokeXmlComment() throws Exception {
+ CommandContext c = new CommandContext();
+ c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
+ XMLType result = (XMLType)helpInvokeMethod("xmlcomment", new Class<?>[] {DataTypeManager.DefaultDataClasses.STRING},
+ new Object[] {"comment"}, c);
+
+ String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
+ assertEquals("<!--comment-->", xml);
+ }
+
+ @Test public void testToChars() throws Exception {
+ Clob result = (Clob)helpInvokeMethod("to_chars", new Class<?>[] {DefaultDataClasses.BLOB, DefaultDataClasses.STRING}, new Object[] { new BlobType(new SerialBlob("hello world".getBytes("ASCII"))), "ASCII" }, null); //$NON-NLS-1$
+ String string = result.getSubString(1, (int)result.length());
+ assertEquals("hello world", string);
+ }
+
+ @Test public void testToBytes() throws Exception {
+ Blob result = (Blob)helpInvokeMethod("to_bytes", new Class<?>[] {DefaultDataClasses.CLOB, DefaultDataClasses.STRING}, new Object[] { new ClobType(new SerialClob("hello world".toCharArray())), "UTF32" }, null); //$NON-NLS-1$
+ assertEquals(44, result.length()); //4 bytes / char
+ }
+
+ @Test public void testToChars1() throws Exception {
+ Clob result = (Clob)helpInvokeMethod("to_chars", new Class<?>[] {DefaultDataClasses.BLOB, DefaultDataClasses.STRING}, new Object[] { new BlobType(new SerialBlob("hello world".getBytes("ASCII"))), "BASE64" }, null); //$NON-NLS-1$
+ String string = result.getSubString(1, (int)result.length());
+ assertEquals("hello world", new String(Base64.decode(string), "ASCII"));
+ }
+
+ @Test public void testToChars2() throws Exception {
+ Clob result = (Clob)helpInvokeMethod("to_chars", new Class<?>[] {DefaultDataClasses.BLOB, DefaultDataClasses.STRING}, new Object[] { new BlobType(new SerialBlob("hello world".getBytes("ASCII"))), "HEX" }, null); //$NON-NLS-1$
+ String string = result.getSubString(1, (int)result.length());
+ assertEquals("68656C6C6F20776F726C64", string);
+ }
+
+ @Test public void testToBytes2() throws Exception {
+ Blob result = (Blob)helpInvokeMethod("to_bytes", new Class<?>[] {DefaultDataClasses.CLOB, DefaultDataClasses.STRING}, new Object[] { new ClobType(new SerialClob("68656C6C6F20776F726C64".toCharArray())), "HEX" }, null); //$NON-NLS-1$
+ assertEquals("hello world", new String(ObjectConverterUtil.convertToCharArray(result.getBinaryStream(), -1, "ASCII")));
+ }
+
+ @Test(expected=FunctionExecutionException.class) public void testToBytes3() throws Exception {
+ helpInvokeMethod("to_bytes", new Class<?>[] {DefaultDataClasses.CLOB, DefaultDataClasses.STRING}, new Object[] { new ClobType(new SerialClob("a".toCharArray())), "BASE64" }, null); //$NON-NLS-1$
+ }
+
+ @Test() public void testUnescape() throws Exception {
+ assertEquals("\r\t", helpInvokeMethod("unescape", new Class<?>[] {DefaultDataClasses.STRING}, new Object[] { "\r\\\t" }, null)); //$NON-NLS-1$
+ }
+
+ @Test() public void testUuid() throws Exception {
+ assertNotNull(helpInvokeMethod("uuid", new Class<?>[] {}, new Object[] {}, null)); //$NON-NLS-1$
+ }
+
+ @Test() public void testArrayGet() throws Exception {
+ assertEquals(1, helpInvokeMethod("array_get", new Class<?>[] {DefaultDataClasses.OBJECT, DefaultDataClasses.INTEGER}, new Object[] {new Object[] {1}, 1}, null)); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,190 +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.function;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.util.Arrays;
-import java.util.Collection;
-
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.FunctionParameter;
-import org.teiid.metadata.FunctionMethod.PushDown;
-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;
-
- at SuppressWarnings("nls")
-public class TestFunctionTree {
-
- /**
- * Walk through all functions by metadata and verify that we can look
- * each one up by signature
- */
- @Test public void testWalkTree() {
- SystemSource source = new SystemSource(false);
- FunctionTree ft = new FunctionTree("foo", source);
-
- Collection<String> categories = ft.getCategories();
- for (String category : categories) {
- Collection<FunctionForm> functions = ft.getFunctionForms(category);
- assertTrue(functions.size() > 0);
- }
- }
-
- public String z() {
- return null;
- }
-
- protected static String x() {
- return null;
- }
-
- public static String y() {
- return null;
- }
-
- @Test public void testLoadErrors() {
- FunctionMethod method = new FunctionMethod(
- "dummy", null, null, PushDown.CAN_PUSHDOWN, "nonexistentClass", "noMethod", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- new FunctionParameter[0],
- 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))));
-
- //should fail, no class
- try {
- new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
- fail();
- } catch (TeiidRuntimeException e) {
-
- }
-
- method.setInvocationClass(TestFunctionTree.class.getName());
-
- //should fail, no method
- try {
- new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
- fail();
- } catch (TeiidRuntimeException e) {
-
- }
-
- method.setInvocationMethod("testLoadErrors");
-
- //should fail, not void
- try {
- new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
- fail();
- } catch (TeiidRuntimeException e) {
-
- }
-
- method.setInvocationMethod("x");
-
- //should fail, not public
- try {
- new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
- fail();
- } catch (TeiidRuntimeException e) {
-
- }
-
- method.setInvocationMethod("z");
-
- //should fail, not static
- try {
- new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
- fail();
- } catch (TeiidRuntimeException e) {
-
- }
-
- method.setInvocationMethod("y");
-
- //valid!
- new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
- }
-
- @Test public void testNullCategory() {
- FunctionMethod method = new FunctionMethod(
- "dummy", null, null, PushDown.MUST_PUSHDOWN, "nonexistentClass", "noMethod", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- new FunctionParameter[0],
- new FunctionParameter("output", DataTypeManager.DefaultDataTypes.STRING), //$NON-NLS-1$
- false, Determinism.DETERMINISTIC);
-
- Collection<org.teiid.metadata.FunctionMethod> list = Arrays.asList(method);
- FunctionMetadataSource fms = Mockito.mock(FunctionMetadataSource.class);
- Mockito.stub(fms.getFunctionMethods()).toReturn(list);
- FunctionTree ft = new FunctionTree("foo", fms);
- assertEquals(1, ft.getFunctionForms(FunctionCategoryConstants.MISCELLANEOUS).size());
- }
-
-/*
-
-//DEBUGGING CODE - this will print out the tree root in readable form
-//(This code will either have to be pasted in to FunctionTree class, or
-//somehow the Map treeRoot must be gotten from the FunctionTree)
-
- private static void debugPrintTreeRoot(Map treeRoot){
- System.out.println("<!><!><!><!><!><!><!><!><!><!><!><!>");
- System.out.println("FunctionTree treeRoot");
- StringBuffer s = new StringBuffer();
- debugPrintNode(treeRoot, 0, s);
- System.out.println(s.toString());
- System.out.println("<!><!><!><!><!><!><!><!><!><!><!><!>");
- }
-
- private static void debugPrintNode(Map node, int depth, StringBuffer s){
- Iterator i = node.entrySet().iterator();
- Map.Entry anEntry = null;
- while(i.hasNext()) {
- anEntry = (Map.Entry)i.next();
- appendLine(s, depth, "Key: " + anEntry.getKey());
- Object value = anEntry.getValue();
- if (value instanceof Map){
- s.append(" Map... ");
- debugPrintNode((Map)value, depth + 1, s);
- } else {
- s.append(" Value: " + value);
- }
- }
- }
-
- private static void appendLine(StringBuffer s, int depth, String value){
- s.append("\n");
- for (int i = 0; i< depth; i++){
- s.append(" ");
- }
- s.append(value);
- }
-*/
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,190 @@
+/*
+ * 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;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.FunctionMethod;
+import org.teiid.metadata.FunctionParameter;
+import org.teiid.metadata.FunctionMethod.PushDown;
+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.RealMetadataFactory;
+
+ at SuppressWarnings("nls")
+public class TestFunctionTree {
+
+ /**
+ * Walk through all functions by metadata and verify that we can look
+ * each one up by signature
+ */
+ @Test public void testWalkTree() {
+ SystemSource source = new SystemSource(false);
+ FunctionTree ft = new FunctionTree("foo", source);
+
+ Collection<String> categories = ft.getCategories();
+ for (String category : categories) {
+ Collection<FunctionForm> functions = ft.getFunctionForms(category);
+ assertTrue(functions.size() > 0);
+ }
+ }
+
+ public String z() {
+ return null;
+ }
+
+ protected static String x() {
+ return null;
+ }
+
+ public static String y() {
+ return null;
+ }
+
+ @Test public void testLoadErrors() {
+ FunctionMethod method = new FunctionMethod(
+ "dummy", null, null, PushDown.CAN_PUSHDOWN, "nonexistentClass", "noMethod", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ new FunctionParameter[0],
+ new FunctionParameter("output", DataTypeManager.DefaultDataTypes.STRING), false, Determinism.DETERMINISTIC); //$NON-NLS-1$
+
+ //allowed, since we're not validating the class
+ new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method))));
+
+ //should fail, no class
+ try {
+ new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
+ fail();
+ } catch (TeiidRuntimeException e) {
+
+ }
+
+ method.setInvocationClass(TestFunctionTree.class.getName());
+
+ //should fail, no method
+ try {
+ new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
+ fail();
+ } catch (TeiidRuntimeException e) {
+
+ }
+
+ method.setInvocationMethod("testLoadErrors");
+
+ //should fail, not void
+ try {
+ new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
+ fail();
+ } catch (TeiidRuntimeException e) {
+
+ }
+
+ method.setInvocationMethod("x");
+
+ //should fail, not public
+ try {
+ new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
+ fail();
+ } catch (TeiidRuntimeException e) {
+
+ }
+
+ method.setInvocationMethod("z");
+
+ //should fail, not static
+ try {
+ new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
+ fail();
+ } catch (TeiidRuntimeException e) {
+
+ }
+
+ method.setInvocationMethod("y");
+
+ //valid!
+ new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
+ }
+
+ @Test public void testNullCategory() {
+ FunctionMethod method = new FunctionMethod(
+ "dummy", null, null, PushDown.MUST_PUSHDOWN, "nonexistentClass", "noMethod", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ new FunctionParameter[0],
+ new FunctionParameter("output", DataTypeManager.DefaultDataTypes.STRING), //$NON-NLS-1$
+ false, Determinism.DETERMINISTIC);
+
+ Collection<org.teiid.metadata.FunctionMethod> list = Arrays.asList(method);
+ FunctionMetadataSource fms = Mockito.mock(FunctionMetadataSource.class);
+ Mockito.stub(fms.getFunctionMethods()).toReturn(list);
+ FunctionTree ft = new FunctionTree("foo", fms);
+ assertEquals(1, ft.getFunctionForms(FunctionCategoryConstants.MISCELLANEOUS).size());
+ }
+
+/*
+
+//DEBUGGING CODE - this will print out the tree root in readable form
+//(This code will either have to be pasted in to FunctionTree class, or
+//somehow the Map treeRoot must be gotten from the FunctionTree)
+
+ private static void debugPrintTreeRoot(Map treeRoot){
+ System.out.println("<!><!><!><!><!><!><!><!><!><!><!><!>");
+ System.out.println("FunctionTree treeRoot");
+ StringBuffer s = new StringBuffer();
+ debugPrintNode(treeRoot, 0, s);
+ System.out.println(s.toString());
+ System.out.println("<!><!><!><!><!><!><!><!><!><!><!><!>");
+ }
+
+ private static void debugPrintNode(Map node, int depth, StringBuffer s){
+ Iterator i = node.entrySet().iterator();
+ Map.Entry anEntry = null;
+ while(i.hasNext()) {
+ anEntry = (Map.Entry)i.next();
+ appendLine(s, depth, "Key: " + anEntry.getKey());
+ Object value = anEntry.getValue();
+ if (value instanceof Map){
+ s.append(" Map... ");
+ debugPrintNode((Map)value, depth + 1, s);
+ } else {
+ s.append(" Value: " + value);
+ }
+ }
+ }
+
+ private static void appendLine(StringBuffer s, int depth, String value){
+ s.append("\n");
+ for (int i = 0; i< depth; i++){
+ s.append(" ");
+ }
+ s.append(value);
+ }
+*/
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,97 +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.function;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.QueryParserException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.eval.Evaluator;
-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 junit.framework.TestCase;
-
-
-public class TestResolvedFunctions extends TestCase {
-
- public void testPowerIntegers() throws Exception {
-
- String sql = "power(10, 10)"; //$NON-NLS-1$
-
- //BigInteger is a closer match here since the second argument matches
- assertEquals(DataTypeManager.DefaultDataClasses.BIG_INTEGER, getFunctionResult(sql).getClass());
- }
-
- public void testPowerDoubles() throws Exception {
-
- String sql = "power(10.01, 10.01)"; //$NON-NLS-1$
-
- assertEquals(DataTypeManager.DefaultDataClasses.DOUBLE, getFunctionResult(sql).getClass());
- }
-
- public void testPowerFloats() throws Exception {
-
- String sql = "power(convert(10.01, float), convert(10.01, float))"; //$NON-NLS-1$
-
- //since the second argument cannot be converted to an integer, the result is a double
- assertEquals(DataTypeManager.DefaultDataClasses.DOUBLE, getFunctionResult(sql).getClass());
- }
-
- public void testPowerBigInteger() throws Exception {
-
- String sql = "power(convert(10.01, BigInteger), 10)"; //$NON-NLS-1$
-
- assertEquals(DataTypeManager.DefaultDataClasses.BIG_INTEGER, getFunctionResult(sql).getClass());
- }
-
- //there should only be one signature for ceiling. The float argument will be converted to a double
- public void testCeilingFloat() throws Exception {
-
- String sql = "ceiling(convert(10.01, float))"; //$NON-NLS-1$
-
- assertEquals(DataTypeManager.DefaultDataClasses.DOUBLE, getFunctionResult(sql).getClass());
- }
-
- //same as above
- public void testFloorFloat() throws Exception {
-
- String sql = "floor(convert(10.01, float))"; //$NON-NLS-1$
-
- assertEquals(DataTypeManager.DefaultDataClasses.DOUBLE, getFunctionResult(sql).getClass());
- }
-
- private Object getFunctionResult(String sql) throws QueryParserException,
- ExpressionEvaluationException,
- BlockedException,
- TeiidComponentException, QueryResolverException {
- Expression expr = QueryParser.getQueryParser().parseExpression(sql);
- ResolverVisitor.resolveLanguageObject(expr, FakeMetadataFactory.example1Cached());
- return Evaluator.evaluate(expr);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,97 @@
+/*
+ * 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;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.QueryParserException;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.query.eval.Evaluator;
+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.RealMetadataFactory;
+
+import junit.framework.TestCase;
+
+
+public class TestResolvedFunctions extends TestCase {
+
+ public void testPowerIntegers() throws Exception {
+
+ String sql = "power(10, 10)"; //$NON-NLS-1$
+
+ //BigInteger is a closer match here since the second argument matches
+ assertEquals(DataTypeManager.DefaultDataClasses.BIG_INTEGER, getFunctionResult(sql).getClass());
+ }
+
+ public void testPowerDoubles() throws Exception {
+
+ String sql = "power(10.01, 10.01)"; //$NON-NLS-1$
+
+ assertEquals(DataTypeManager.DefaultDataClasses.DOUBLE, getFunctionResult(sql).getClass());
+ }
+
+ public void testPowerFloats() throws Exception {
+
+ String sql = "power(convert(10.01, float), convert(10.01, float))"; //$NON-NLS-1$
+
+ //since the second argument cannot be converted to an integer, the result is a double
+ assertEquals(DataTypeManager.DefaultDataClasses.DOUBLE, getFunctionResult(sql).getClass());
+ }
+
+ public void testPowerBigInteger() throws Exception {
+
+ String sql = "power(convert(10.01, BigInteger), 10)"; //$NON-NLS-1$
+
+ assertEquals(DataTypeManager.DefaultDataClasses.BIG_INTEGER, getFunctionResult(sql).getClass());
+ }
+
+ //there should only be one signature for ceiling. The float argument will be converted to a double
+ public void testCeilingFloat() throws Exception {
+
+ String sql = "ceiling(convert(10.01, float))"; //$NON-NLS-1$
+
+ assertEquals(DataTypeManager.DefaultDataClasses.DOUBLE, getFunctionResult(sql).getClass());
+ }
+
+ //same as above
+ public void testFloorFloat() throws Exception {
+
+ String sql = "floor(convert(10.01, float))"; //$NON-NLS-1$
+
+ assertEquals(DataTypeManager.DefaultDataClasses.DOUBLE, getFunctionResult(sql).getClass());
+ }
+
+ private Object getFunctionResult(String sql) throws QueryParserException,
+ ExpressionEvaluationException,
+ BlockedException,
+ TeiidComponentException, QueryResolverException {
+ Expression expr = QueryParser.getQueryParser().parseExpression(sql);
+ ResolverVisitor.resolveLanguageObject(expr, RealMetadataFactory.example1Cached());
+ return Evaluator.evaluate(expr);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/mapping/xml/TestMappingElement.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/mapping/xml/TestMappingElement.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/mapping/xml/TestMappingElement.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,238 +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.mapping.xml;
-
-import java.util.List;
-
-import org.teiid.query.mapping.xml.MappingAllNode;
-import org.teiid.query.mapping.xml.MappingAttribute;
-import org.teiid.query.mapping.xml.MappingChoiceNode;
-import org.teiid.query.mapping.xml.MappingCommentNode;
-import org.teiid.query.mapping.xml.MappingDocument;
-import org.teiid.query.mapping.xml.MappingElement;
-import org.teiid.query.mapping.xml.MappingNodeConstants;
-import org.teiid.query.mapping.xml.MappingRecursiveElement;
-import org.teiid.query.mapping.xml.MappingSequenceNode;
-import org.teiid.query.mapping.xml.Namespace;
-
-import junit.framework.TestCase;
-
-
-/**
- * Test the Mapping Element
- */
-public class TestMappingElement extends TestCase {
-
- public void testRecusrive() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertFalse(element.isRecursive());
- }
-
- public void testNamespace() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertEquals("Test", element.getName()); //$NON-NLS-1$
- assertNull(element.getNamespacePrefix());
-
- Namespace namespace = new Namespace("foo", "protocol://someuri"); //$NON-NLS-1$ //$NON-NLS-2$
- element = new MappingElement("Test", namespace); //$NON-NLS-1$
- assertEquals("foo", element.getNamespacePrefix()); //$NON-NLS-1$
- assertEquals(element.getNamespaces().length, 0);
-
- element.addNamespace(namespace);
- assertEquals(element.getNamespaces().length, 1);
-
- element.addNamespace(new Namespace("ns1", "http://mm.com")); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals(element.getNamespaces().length, 2);
-
- // they may be switch some times, need a better way to test this?
- assertEquals("ns1", element.getNamespaces()[0].getPrefix()); //$NON-NLS-1$
- assertEquals("foo", element.getNamespaces()[1].getPrefix()); //$NON-NLS-1$
- }
-
-
- public void testNameInSource() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertNull(element.getNameInSource());
-
- element.setNameInSource(null);
- assertNull(element.getNameInSource());
-
- element.setNameInSource("sourceName"); //$NON-NLS-1$
- assertEquals("sourceName", element.getNameInSource()); //$NON-NLS-1$
-
- element = new MappingElement("Test", "sourceName"); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("sourceName", element.getNameInSource()); //$NON-NLS-1$
- }
-
- public void testNillable() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertFalse(element.isNillable());
-
- element.setNillable(true);
- assertTrue(element.isNillable());
- }
-
- public void testDefaultValue() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertNull(element.getDefaultValue());
-
- element.setDefaultValue("foo"); //$NON-NLS-1$
- assertEquals("foo", element.getDefaultValue()); //$NON-NLS-1$
- }
-
- public void testFixedValue() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertNull(element.getValue());
-
- element.setValue("foo"); //$NON-NLS-1$
- assertEquals("foo", element.getValue()); //$NON-NLS-1$
- }
-
- public void testOptional() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertFalse(element.isOptional());
-
- element.setOptional(true);
- assertTrue(element.isOptional());
- }
-
- public void testNormalizeText() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertEquals(MappingNodeConstants.Defaults.DEFAULT_NORMALIZE_TEXT, element.getNormalizeText());
-
- element.setNormalizeText("foo"); //$NON-NLS-1$
- assertEquals("foo", element.getNormalizeText()); //$NON-NLS-1$
- }
-
- public void testType() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertNull(element.getType());
-
- element.setType("int"); //$NON-NLS-1$
- assertEquals("int", element.getType());//$NON-NLS-1$
- }
-
- public void testInclude() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertTrue(element.isAlwaysInclude());
-
- element.setAlwaysInclude(false);
- assertFalse(element.isAlwaysInclude());
- }
-
- public void testMinOccurence() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertEquals(1, element.getMinOccurence());
-
- element.setMinOccurrs(2);
- assertEquals(2, element.getMinOccurence());
- }
-
- public void testMaxOccurence() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertEquals(1, element.getMaxOccurence());
-
- element.setMaxOccurrs(2);
- assertEquals(2, element.getMaxOccurence());
- }
-
- public void testExclude() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertFalse(element.isExcluded());
-
- element.setExclude(true);
- assertTrue(element.isExcluded());
- }
-
- public void testSource() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- assertNull(element.getSource());
- }
-
- public void testChildren() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
-
- element.addCommentNode(new MappingCommentNode("this is comment text")); //$NON-NLS-1$
- element.addAttribute(new MappingAttribute("foo", "fooReal")); //$NON-NLS-1$ //$NON-NLS-2$
- element.addChildElement(new MappingElement("child1")); //$NON-NLS-1$
- element.addChoiceNode(new MappingChoiceNode());
- element.addSequenceNode(new MappingSequenceNode());
- element.addAllNode(new MappingAllNode());
-
- assertEquals(5, element.getNodeChildren().size());
- assertEquals(1, element.getAttributes().size());
-
- List list = element.getNodeChildren();
- assertTrue(list.get(0) instanceof MappingCommentNode);
- assertTrue(list.get(1) instanceof MappingElement);
- assertTrue(list.get(2) instanceof MappingChoiceNode);
- assertTrue(list.get(3) instanceof MappingSequenceNode);
- assertTrue(list.get(4) instanceof MappingAllNode);
- }
-
- public void testAddRecursiveElement() {
- MappingDocument doc = new MappingDocument(false);
- MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
- MappingElement nodeA = root.addChildElement(new MappingElement("NodeA", "test.nodea")); //$NON-NLS-1$ //$NON-NLS-2$
- nodeA.setSource("recursive.test"); //$NON-NLS-1$
-
- MappingSequenceNode seq = nodeA.addSequenceNode(new MappingSequenceNode());
- MappingElement nodeB = seq.addChildElement(new MappingElement("NodeB", "test.nodeb")); //$NON-NLS-1$ //$NON-NLS-2$
-
- assertFalse(nodeA.isRootRecursiveNode());
-
- MappingRecursiveElement rElem = (MappingRecursiveElement)nodeB.addChildElement(new MappingRecursiveElement("RecursiveNodeA", "recursive.test")); //$NON-NLS-1$ //$NON-NLS-2$
-
- assertTrue(rElem.isRecursive());
-
- assertTrue(nodeA.isRootRecursiveNode());
- }
-
- public void testAddBADRecursiveElement() {
- MappingDocument doc = new MappingDocument(false);
- MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
- MappingElement nodeA = root.addChildElement(new MappingElement("NodeA", "test.nodea")); //$NON-NLS-1$ //$NON-NLS-2$
- nodeA.setSource("recursive.test"); //$NON-NLS-1$
-
- MappingSequenceNode seq = nodeA.addSequenceNode(new MappingSequenceNode());
- MappingElement nodeB = seq.addChildElement(new MappingElement("NodeB", "test.nodeb")); //$NON-NLS-1$ //$NON-NLS-2$
-
- assertFalse(nodeA.isRootRecursiveNode());
-
- try {
- nodeB.addChildElement(new MappingRecursiveElement("RecursiveNodeA", "unknown mapping")); //$NON-NLS-1$ //$NON-NLS-2$
- fail("should have failed to add a node with unknown mapping class"); //$NON-NLS-1$
- } catch (RuntimeException e) {
- //e.printStackTrace();
- }
- }
-
- public void testAddNullStagingTable() {
- MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
- element.addStagingTable(null);
- List stagingTables = element.getStagingTables();
- assertTrue(stagingTables.isEmpty());
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/mapping/xml/TestMappingElement.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/mapping/xml/TestMappingElement.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/mapping/xml/TestMappingElement.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/mapping/xml/TestMappingElement.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,238 @@
+/*
+ * 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.mapping.xml;
+
+import java.util.List;
+
+import org.teiid.query.mapping.xml.MappingAllNode;
+import org.teiid.query.mapping.xml.MappingAttribute;
+import org.teiid.query.mapping.xml.MappingChoiceNode;
+import org.teiid.query.mapping.xml.MappingCommentNode;
+import org.teiid.query.mapping.xml.MappingDocument;
+import org.teiid.query.mapping.xml.MappingElement;
+import org.teiid.query.mapping.xml.MappingNodeConstants;
+import org.teiid.query.mapping.xml.MappingRecursiveElement;
+import org.teiid.query.mapping.xml.MappingSequenceNode;
+import org.teiid.query.mapping.xml.Namespace;
+
+import junit.framework.TestCase;
+
+
+/**
+ * Test the Mapping Element
+ */
+public class TestMappingElement extends TestCase {
+
+ public void testRecusrive() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertFalse(element.isRecursive());
+ }
+
+ public void testNamespace() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertEquals("Test", element.getName()); //$NON-NLS-1$
+ assertNull(element.getNamespacePrefix());
+
+ Namespace namespace = new Namespace("foo", "protocol://someuri"); //$NON-NLS-1$ //$NON-NLS-2$
+ element = new MappingElement("Test", namespace); //$NON-NLS-1$
+ assertEquals("foo", element.getNamespacePrefix()); //$NON-NLS-1$
+ assertEquals(element.getNamespaces().length, 0);
+
+ element.addNamespace(namespace);
+ assertEquals(element.getNamespaces().length, 1);
+
+ element.addNamespace(new Namespace("ns1", "http://mm.com")); //$NON-NLS-1$ //$NON-NLS-2$
+ assertEquals(element.getNamespaces().length, 2);
+
+ // they may be switch some times, need a better way to test this?
+ assertEquals("ns1", element.getNamespaces()[0].getPrefix()); //$NON-NLS-1$
+ assertEquals("foo", element.getNamespaces()[1].getPrefix()); //$NON-NLS-1$
+ }
+
+
+ public void testNameInSource() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertNull(element.getNameInSource());
+
+ element.setNameInSource(null);
+ assertNull(element.getNameInSource());
+
+ element.setNameInSource("sourceName"); //$NON-NLS-1$
+ assertEquals("sourceName", element.getNameInSource()); //$NON-NLS-1$
+
+ element = new MappingElement("Test", "sourceName"); //$NON-NLS-1$ //$NON-NLS-2$
+ assertEquals("sourceName", element.getNameInSource()); //$NON-NLS-1$
+ }
+
+ public void testNillable() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertFalse(element.isNillable());
+
+ element.setNillable(true);
+ assertTrue(element.isNillable());
+ }
+
+ public void testDefaultValue() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertNull(element.getDefaultValue());
+
+ element.setDefaultValue("foo"); //$NON-NLS-1$
+ assertEquals("foo", element.getDefaultValue()); //$NON-NLS-1$
+ }
+
+ public void testFixedValue() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertNull(element.getValue());
+
+ element.setValue("foo"); //$NON-NLS-1$
+ assertEquals("foo", element.getValue()); //$NON-NLS-1$
+ }
+
+ public void testOptional() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertFalse(element.isOptional());
+
+ element.setOptional(true);
+ assertTrue(element.isOptional());
+ }
+
+ public void testNormalizeText() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertEquals(MappingNodeConstants.Defaults.DEFAULT_NORMALIZE_TEXT, element.getNormalizeText());
+
+ element.setNormalizeText("foo"); //$NON-NLS-1$
+ assertEquals("foo", element.getNormalizeText()); //$NON-NLS-1$
+ }
+
+ public void testType() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertNull(element.getType());
+
+ element.setType("int"); //$NON-NLS-1$
+ assertEquals("int", element.getType());//$NON-NLS-1$
+ }
+
+ public void testInclude() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertTrue(element.isAlwaysInclude());
+
+ element.setAlwaysInclude(false);
+ assertFalse(element.isAlwaysInclude());
+ }
+
+ public void testMinOccurence() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertEquals(1, element.getMinOccurence());
+
+ element.setMinOccurrs(2);
+ assertEquals(2, element.getMinOccurence());
+ }
+
+ public void testMaxOccurence() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertEquals(1, element.getMaxOccurence());
+
+ element.setMaxOccurrs(2);
+ assertEquals(2, element.getMaxOccurence());
+ }
+
+ public void testExclude() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertFalse(element.isExcluded());
+
+ element.setExclude(true);
+ assertTrue(element.isExcluded());
+ }
+
+ public void testSource() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ assertNull(element.getSource());
+ }
+
+ public void testChildren() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+
+ element.addCommentNode(new MappingCommentNode("this is comment text")); //$NON-NLS-1$
+ element.addAttribute(new MappingAttribute("foo", "fooReal")); //$NON-NLS-1$ //$NON-NLS-2$
+ element.addChildElement(new MappingElement("child1")); //$NON-NLS-1$
+ element.addChoiceNode(new MappingChoiceNode());
+ element.addSequenceNode(new MappingSequenceNode());
+ element.addAllNode(new MappingAllNode());
+
+ assertEquals(5, element.getNodeChildren().size());
+ assertEquals(1, element.getAttributes().size());
+
+ List list = element.getNodeChildren();
+ assertTrue(list.get(0) instanceof MappingCommentNode);
+ assertTrue(list.get(1) instanceof MappingElement);
+ assertTrue(list.get(2) instanceof MappingChoiceNode);
+ assertTrue(list.get(3) instanceof MappingSequenceNode);
+ assertTrue(list.get(4) instanceof MappingAllNode);
+ }
+
+ public void testAddRecursiveElement() {
+ MappingDocument doc = new MappingDocument(false);
+ MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+ MappingElement nodeA = root.addChildElement(new MappingElement("NodeA", "test.nodea")); //$NON-NLS-1$ //$NON-NLS-2$
+ nodeA.setSource("recursive.test"); //$NON-NLS-1$
+
+ MappingSequenceNode seq = nodeA.addSequenceNode(new MappingSequenceNode());
+ MappingElement nodeB = seq.addChildElement(new MappingElement("NodeB", "test.nodeb")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ assertFalse(nodeA.isRootRecursiveNode());
+
+ MappingRecursiveElement rElem = (MappingRecursiveElement)nodeB.addChildElement(new MappingRecursiveElement("RecursiveNodeA", "recursive.test")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ assertTrue(rElem.isRecursive());
+
+ assertTrue(nodeA.isRootRecursiveNode());
+ }
+
+ public void testAddBADRecursiveElement() {
+ MappingDocument doc = new MappingDocument(false);
+ MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+ MappingElement nodeA = root.addChildElement(new MappingElement("NodeA", "test.nodea")); //$NON-NLS-1$ //$NON-NLS-2$
+ nodeA.setSource("recursive.test"); //$NON-NLS-1$
+
+ MappingSequenceNode seq = nodeA.addSequenceNode(new MappingSequenceNode());
+ MappingElement nodeB = seq.addChildElement(new MappingElement("NodeB", "test.nodeb")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ assertFalse(nodeA.isRootRecursiveNode());
+
+ try {
+ nodeB.addChildElement(new MappingRecursiveElement("RecursiveNodeA", "unknown mapping")); //$NON-NLS-1$ //$NON-NLS-2$
+ fail("should have failed to add a node with unknown mapping class"); //$NON-NLS-1$
+ } catch (RuntimeException e) {
+ //e.printStackTrace();
+ }
+ }
+
+ public void testAddNullStagingTable() {
+ MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
+ element.addStagingTable(null);
+ List<String> stagingTables = element.getStagingTables();
+ assertTrue(stagingTables.isEmpty());
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/metadata/TestTransformationMetadata.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/metadata/TestTransformationMetadata.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/metadata/TestTransformationMetadata.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,161 +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.metadata;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-import org.jboss.virtual.VirtualFile;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.adminapi.Model;
-import org.teiid.adminapi.impl.ModelMetaData;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.metadata.Datatype;
-import org.teiid.metadata.MetadataFactory;
-import org.teiid.metadata.Table;
-import org.teiid.query.metadata.CompositeMetadataStore;
-import org.teiid.query.metadata.TransformationMetadata;
-import org.teiid.query.metadata.TransformationMetadata.Resource;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.translator.TranslatorException;
-
- at SuppressWarnings("nls")
-public class TestTransformationMetadata {
-
- @Test public void testAmbiguousProc() throws Exception {
- TransformationMetadata tm = exampleTransformationMetadata();
-
- try {
- tm.getStoredProcedureInfoForProcedure("y"); //$NON-NLS-1$
- fail("expected exception"); //$NON-NLS-1$
- } catch (QueryMetadataException e) {
- assertEquals("Procedure 'y' is ambiguous, use the fully qualified name instead", e.getMessage()); //$NON-NLS-1$
- }
- }
-
- @Test public void testProcVisibility() throws Exception {
- TransformationMetadata tm = exampleTransformationMetadata();
- VDBMetaData vdb = tm.getVdbMetaData();
- vdb.getModel("x").setVisible(false);
- StoredProcedureInfo spi = tm.getStoredProcedureInfoForProcedure("y"); //$NON-NLS-1$
- assertEquals("x1.y", spi.getProcedureCallableName());
- spi = tm.getStoredProcedureInfoForProcedure("x.y"); //$NON-NLS-1$
- assertEquals("x.y", spi.getProcedureCallableName());
- }
-
- private TransformationMetadata exampleTransformationMetadata()
- throws TranslatorException {
- Map<String, Datatype> datatypes = new HashMap<String, Datatype>();
- datatypes.put(DataTypeManager.DefaultDataTypes.STRING, new Datatype());
- MetadataFactory mf = new MetadataFactory("x", datatypes, new Properties()); //$NON-NLS-1$
- mf.addProcedure("y"); //$NON-NLS-1$
-
- Table t = mf.addTable("foo");
- mf.addColumn("col", DataTypeManager.DefaultDataTypes.STRING, t);
-
- MetadataFactory mf1 = new MetadataFactory("x1", datatypes, new Properties()); //$NON-NLS-1$
- mf1.addProcedure("y"); //$NON-NLS-1$
-
- Table table = mf1.addTable("doc");
- table.setSchemaPaths(Arrays.asList("../../x.xsd"));
- 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));
-
- CompositeMetadataStore cms = new CompositeMetadataStore(Arrays.asList(mf.getMetadataStore(), mf1.getMetadataStore()));
-
- VDBMetaData vdb = new VDBMetaData();
- vdb.setName("vdb");
- vdb.setVersion(1);
-
- vdb.addModel(buildModel("x"));
- vdb.addModel(buildModel("x1"));
- vdb.addModel(buildModel("y"));
-
- return new TransformationMetadata(vdb, cms, resources, FakeMetadataFactory.SFM.getSystemFunctions(), null);
- }
-
- ModelMetaData buildModel(String name) {
- ModelMetaData model = new ModelMetaData();
- model.setName(name);
- model.setModelType(Model.Type.PHYSICAL);
- model.setVisible(true);
- return model;
- }
-
- @Test public void testAmbiguousTableWithPrivateModel() throws Exception {
- Map<String, Datatype> datatypes = new HashMap<String, Datatype>();
- datatypes.put(DataTypeManager.DefaultDataTypes.STRING, new Datatype());
- MetadataFactory mf = new MetadataFactory("x", datatypes, new Properties()); //$NON-NLS-1$
- mf.addTable("y"); //$NON-NLS-1$
- MetadataFactory mf1 = new MetadataFactory("x1", datatypes, new Properties()); //$NON-NLS-1$
- mf1.addTable("y"); //$NON-NLS-1$
- CompositeMetadataStore cms = new CompositeMetadataStore(Arrays.asList(mf.getMetadataStore(), mf1.getMetadataStore()));
-
- VDBMetaData vdb = new VDBMetaData();
- vdb.setName("foo");
- vdb.setVersion(1);
-
- ModelMetaData model = new ModelMetaData();
- model.setName("x1");
- vdb.addModel(model);
-
- ModelMetaData model2 = new ModelMetaData();
- model2.setName("x");
- model2.setVisible(true);
- vdb.addModel(model2);
-
- TransformationMetadata tm = new TransformationMetadata(vdb, cms, null, FakeMetadataFactory.SFM.getSystemFunctions(), null);
- Collection result = tm.getGroupsForPartialName("y"); //$NON-NLS-1$
- assertEquals(2, result.size());
-
- FakeMetadataFactory.buildWorkContext(tm, vdb);
-
- model.setVisible(false);
-
- tm = new TransformationMetadata(vdb, cms, null, FakeMetadataFactory.SFM.getSystemFunctions(), null);
- result = tm.getGroupsForPartialName("y"); //$NON-NLS-1$
- assertEquals(1, result.size());
- }
-
- @Test public void testElementId() throws Exception {
- TransformationMetadata tm = exampleTransformationMetadata();
- tm.getElementID("x.FoO.coL");
- }
-
- @Test public void testRelativeSchemas() throws Exception {
- TransformationMetadata tm = exampleTransformationMetadata();
- assertEquals(1, tm.getXMLSchemas(tm.getGroupID("x1.doc")).size());
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/metadata/TestTransformationMetadata.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/metadata/TestTransformationMetadata.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/metadata/TestTransformationMetadata.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/metadata/TestTransformationMetadata.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,161 @@
+/*
+ * 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.metadata;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import org.jboss.virtual.VirtualFile;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.adminapi.Model;
+import org.teiid.adminapi.impl.ModelMetaData;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.Datatype;
+import org.teiid.metadata.MetadataFactory;
+import org.teiid.metadata.Table;
+import org.teiid.query.metadata.CompositeMetadataStore;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.metadata.TransformationMetadata.Resource;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.translator.TranslatorException;
+
+ at SuppressWarnings("nls")
+public class TestTransformationMetadata {
+
+ @Test public void testAmbiguousProc() throws Exception {
+ TransformationMetadata tm = exampleTransformationMetadata();
+
+ try {
+ tm.getStoredProcedureInfoForProcedure("y"); //$NON-NLS-1$
+ fail("expected exception"); //$NON-NLS-1$
+ } catch (QueryMetadataException e) {
+ assertEquals("Procedure 'y' is ambiguous, use the fully qualified name instead", e.getMessage()); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testProcVisibility() throws Exception {
+ TransformationMetadata tm = exampleTransformationMetadata();
+ VDBMetaData vdb = tm.getVdbMetaData();
+ vdb.getModel("x").setVisible(false);
+ StoredProcedureInfo spi = tm.getStoredProcedureInfoForProcedure("y"); //$NON-NLS-1$
+ assertEquals("x1.y", spi.getProcedureCallableName());
+ spi = tm.getStoredProcedureInfoForProcedure("x.y"); //$NON-NLS-1$
+ assertEquals("x.y", spi.getProcedureCallableName());
+ }
+
+ private TransformationMetadata exampleTransformationMetadata()
+ throws TranslatorException {
+ Map<String, Datatype> datatypes = new HashMap<String, Datatype>();
+ datatypes.put(DataTypeManager.DefaultDataTypes.STRING, new Datatype());
+ MetadataFactory mf = new MetadataFactory("x", datatypes, new Properties()); //$NON-NLS-1$
+ mf.addProcedure("y"); //$NON-NLS-1$
+
+ Table t = mf.addTable("foo");
+ mf.addColumn("col", DataTypeManager.DefaultDataTypes.STRING, t);
+
+ MetadataFactory mf1 = new MetadataFactory("x1", datatypes, new Properties()); //$NON-NLS-1$
+ mf1.addProcedure("y"); //$NON-NLS-1$
+
+ Table table = mf1.addTable("doc");
+ table.setSchemaPaths(Arrays.asList("../../x.xsd"));
+ 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));
+
+ CompositeMetadataStore cms = new CompositeMetadataStore(Arrays.asList(mf.getMetadataStore(), mf1.getMetadataStore()));
+
+ VDBMetaData vdb = new VDBMetaData();
+ vdb.setName("vdb");
+ vdb.setVersion(1);
+
+ vdb.addModel(buildModel("x"));
+ vdb.addModel(buildModel("x1"));
+ vdb.addModel(buildModel("y"));
+
+ return new TransformationMetadata(vdb, cms, resources, RealMetadataFactory.SFM.getSystemFunctions(), null);
+ }
+
+ ModelMetaData buildModel(String name) {
+ ModelMetaData model = new ModelMetaData();
+ model.setName(name);
+ model.setModelType(Model.Type.PHYSICAL);
+ model.setVisible(true);
+ return model;
+ }
+
+ @Test public void testAmbiguousTableWithPrivateModel() throws Exception {
+ Map<String, Datatype> datatypes = new HashMap<String, Datatype>();
+ datatypes.put(DataTypeManager.DefaultDataTypes.STRING, new Datatype());
+ MetadataFactory mf = new MetadataFactory("x", datatypes, new Properties()); //$NON-NLS-1$
+ mf.addTable("y"); //$NON-NLS-1$
+ MetadataFactory mf1 = new MetadataFactory("x1", datatypes, new Properties()); //$NON-NLS-1$
+ mf1.addTable("y"); //$NON-NLS-1$
+ CompositeMetadataStore cms = new CompositeMetadataStore(Arrays.asList(mf.getMetadataStore(), mf1.getMetadataStore()));
+
+ VDBMetaData vdb = new VDBMetaData();
+ vdb.setName("foo");
+ vdb.setVersion(1);
+
+ ModelMetaData model = new ModelMetaData();
+ model.setName("x1");
+ vdb.addModel(model);
+
+ ModelMetaData model2 = new ModelMetaData();
+ model2.setName("x");
+ model2.setVisible(true);
+ vdb.addModel(model2);
+
+ TransformationMetadata tm = new TransformationMetadata(vdb, cms, null, RealMetadataFactory.SFM.getSystemFunctions(), null);
+ Collection result = tm.getGroupsForPartialName("y"); //$NON-NLS-1$
+ assertEquals(2, result.size());
+
+ RealMetadataFactory.buildWorkContext(tm, vdb);
+
+ model.setVisible(false);
+
+ tm = new TransformationMetadata(vdb, cms, null, RealMetadataFactory.SFM.getSystemFunctions(), null);
+ result = tm.getGroupsForPartialName("y"); //$NON-NLS-1$
+ assertEquals(1, result.size());
+ }
+
+ @Test public void testElementId() throws Exception {
+ TransformationMetadata tm = exampleTransformationMetadata();
+ tm.getElementID("x.FoO.coL");
+ }
+
+ @Test public void testRelativeSchemas() throws Exception {
+ TransformationMetadata tm = exampleTransformationMetadata();
+ assertEquals(1, tm.getXMLSchemas(tm.getGroupID("x1.doc")).size());
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,294 +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.optimizer;
-
-import org.junit.Test;
-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.validator.TestValidator;
-
-
-
-public class TestAccessPatterns {
-
- /**
- * The virtual access patterns should get satisfied
- */
- @Test public void testVirtualAccessPatternPassing() {
- String sql = "SELECT e0, e2 FROM vTest.vGroup2 where e0=1 and e1='2'"; //$NON-NLS-1$
- TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), new String[] {"SELECT test.\"group\".e0, test.\"group\".e2 FROM test.\"group\" WHERE (test.\"group\".e0 = 1) AND (test.\"group\".e1 = '2')"}); //$NON-NLS-1$
- }
-
- @Test public void testVirtualAccessPatternPassing1() {
- String sql = "delete from vm1.g37 where e1 = 1"; //$NON-NLS-1$
- TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), new String[] {});
- }
-
- @Test public void testVirtualAccessPatternFailing() {
- String sql = "SELECT e0, e2 FROM vTest.vGroup2 where e0=1"; //$NON-NLS-1$
- TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, null, null, TestOptimizer.SHOULD_FAIL);
- }
-
- @Test public void testVirtualAccessPatternFailing1() {
- String sql = "delete from vm1.g37"; //$NON-NLS-1$
- TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, null, null, TestOptimizer.SHOULD_FAIL);
- }
-
- @Test public void testAccessPattern1() throws Exception {
- String sql = "SELECT e0, e2 FROM vTest.vGroup where e0=1 and e1='2'"; //$NON-NLS-1$
- TestOptimizer.helpPlan(sql,
- TestValidator.exampleMetadata4(),
- new String[] {"SELECT g_0.e0, g_0.e2 FROM test.\"group\" AS g_0 WHERE (g_0.e0 = 1) AND (g_0.e1 = '2')" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
- }
-
- @Test public void testAccessPattern2() {
- String sql = "SELECT e0, e2 FROM vTest.vGroup where e0=1"; //$NON-NLS-1$
- TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, null, null, TestOptimizer.SHOULD_FAIL);
- }
-
- @Test public void testAccessPattern3() {
- String sql = "SELECT e0, e2 FROM vTest.vGroup where e0=1 and e2='2'"; //$NON-NLS-1$
- TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, null, null, TestOptimizer.SHOULD_FAIL);
- }
-
- @Test public void testAccessPattern4() throws Exception {
- String sql = "(SELECT e0, e2 FROM vTest.vGroup where e0=1 and e1='2') union all (SELECT e0, e2 FROM vTest.vGroup where e0=1 and e1='2')"; //$NON-NLS-1$
- TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), new String[] {"SELECT g_0.e0, g_0.e2 FROM test.\"group\" AS g_0 WHERE (g_0.e0 = 1) AND (g_0.e1 = '2')"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
- }
-
- @Test public void testAccessPattern5() {
- String sql = "(SELECT e0, e2 FROM vTest.vGroup where e0=1 and e1='2') union all (SELECT e0, e2 FROM vTest.vGroup where e0=1)"; //$NON-NLS-1$
- TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, null, null, TestOptimizer.SHOULD_FAIL);
- }
-
- @Test public void testAccessPattern6() {
- String sql = "SELECT e0, e2 FROM test.group where e1 IN (SELECT e2 FROM vTest.vGroup where e0=1 and e1='2')"; //$NON-NLS-1$
- TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), new String[] {"SELECT e1, e0, e2 FROM test.\"group\""}); //$NON-NLS-1$
- }
-
- @Test public void testAccessPattern7() {
- String sql = "SELECT e0, e2 FROM test.group where e1 IN (SELECT e2 FROM vTest.vGroup where e0=1)"; //$NON-NLS-1$
- TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, null, null, TestOptimizer.SHOULD_FAIL);
- }
-
- @Test public void testAccessPattern8() {
- String sql = "SELECT e0, e2 FROM vTest.vGroup"; //$NON-NLS-1$
- TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, null, null, TestOptimizer.SHOULD_FAIL);
- }
-
- /**
- * Tests two access nodes, each with access patterns, but one already
- * 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$
- 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$
- }
-
- /**
- * Tests two access nodes, each with access patterns, but one already
- * satisfied by user criteria - the other should be made dependent
- * (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$
- 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$
- }
-
- /**
- * Self join - tests that both access nodes are satisfied by the select
- * 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$
- 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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @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$
- null, null, null,
- TestOptimizer.SHOULD_FAIL);
- }
-
- @Test public void testAccessPatternsFails2() {
- TestOptimizer.helpPlan("select pm4.g2.e1 from pm4.g2", FakeMetadataFactory.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(),
- 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(),
- 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$
- 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$
- 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(),
- 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$
- }
-
- /**
- * Similar to the query above, except the OR instead of an AND produces a
- * completely different query plan which can't satisfy the access pattern.
- * @see #testAccessPatternPartialMatch
- */
- @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(),
- null, null, null,
- TestOptimizer.SHOULD_FAIL);
- }
-
- /**
- * Access patterns on models that support joins requires that the access patterns are satisfied prior to
- * RulePlanJoins
- */
- @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(),
- null, null, null, TestOptimizer.SHOULD_FAIL);
- }
-
- // ==================================================================================
- // ACCESS PATTERNS
- // ==================================================================================
-
- @Test public void testPushingCriteriaThroughFrameAccessPattern0() {
- TestOptimizer.helpPlan("select * from vm1.g9 where vm1.g9.e1='abc'", FakeMetadataFactory.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$
- }
-
- /**
- * 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$
- 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$
- 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$
- 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$
- }
-
- /**
- * 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$
- null, TestOptimizer.SHOULD_FAIL );
- }
-
- /**
- * TODO: in this case we should perform a criteria optimization to create set criteria
- */
- @Test public void testCase6425() {
- String sql = "SELECT e1 FROM pm4.g1 WHERE e1 = '1' OR e1 = '2'"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, new String[] {"SELECT e1 FROM pm4.g1 WHERE (e1 = '1') OR (e1 = '2')"}); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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();
-
- 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$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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();
-
- TestOptimizer.helpPlan(sql, metadata, null, TestOptimizer.ComparisonMode.FAILED_PLANNING);
- }
-
- /*
- * Criteria was preventing rule choose dependent from creating the appropriate dependent join
- */
- @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();
-
- TestOptimizer.helpPlan(sql, metadata,
- new String[] {
- "SELECT g_0.e2, g_0.e1 FROM pm5.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", //$NON-NLS-1$
- "SELECT g_0.e1, g_0.e2, g_0.e3, g_0.e4 FROM pm1.g1 AS g_0", //$NON-NLS-1$
- "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)" }, TestOptimizer.getGenericFinder(false), ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,294 @@
+/*
+ * 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;
+
+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.RealMetadataFactory;
+import org.teiid.query.validator.TestValidator;
+
+
+
+public class TestAccessPatterns {
+
+ /**
+ * The virtual access patterns should get satisfied
+ */
+ @Test public void testVirtualAccessPatternPassing() {
+ String sql = "SELECT e0, e2 FROM vTest.vGroup2 where e0=1 and e1='2'"; //$NON-NLS-1$
+ TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), new String[] {"SELECT test.\"group\".e0, test.\"group\".e2 FROM test.\"group\" WHERE (test.\"group\".e0 = 1) AND (test.\"group\".e1 = '2')"}); //$NON-NLS-1$
+ }
+
+ @Test public void testVirtualAccessPatternPassing1() {
+ String sql = "delete from vm1.g37 where e1 = 1"; //$NON-NLS-1$
+ TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {});
+ }
+
+ @Test public void testVirtualAccessPatternFailing() {
+ String sql = "SELECT e0, e2 FROM vTest.vGroup2 where e0=1"; //$NON-NLS-1$
+ TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, null, null, TestOptimizer.SHOULD_FAIL);
+ }
+
+ @Test public void testVirtualAccessPatternFailing1() {
+ String sql = "delete from vm1.g37"; //$NON-NLS-1$
+ TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, null, null, TestOptimizer.SHOULD_FAIL);
+ }
+
+ @Test public void testAccessPattern1() throws Exception {
+ String sql = "SELECT e0, e2 FROM vTest.vGroup where e0=1 and e1='2'"; //$NON-NLS-1$
+ TestOptimizer.helpPlan(sql,
+ TestValidator.exampleMetadata4(),
+ new String[] {"SELECT g_0.e0, g_0.e2 FROM test.\"group\" AS g_0 WHERE (g_0.e0 = 1) AND (g_0.e1 = '2')" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
+ }
+
+ @Test public void testAccessPattern2() {
+ String sql = "SELECT e0, e2 FROM vTest.vGroup where e0=1"; //$NON-NLS-1$
+ TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, null, null, TestOptimizer.SHOULD_FAIL);
+ }
+
+ @Test public void testAccessPattern3() {
+ String sql = "SELECT e0, e2 FROM vTest.vGroup where e0=1 and e2='2'"; //$NON-NLS-1$
+ TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, null, null, TestOptimizer.SHOULD_FAIL);
+ }
+
+ @Test public void testAccessPattern4() throws Exception {
+ String sql = "(SELECT e0, e2 FROM vTest.vGroup where e0=1 and e1='2') union all (SELECT e0, e2 FROM vTest.vGroup where e0=1 and e1='2')"; //$NON-NLS-1$
+ TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), new String[] {"SELECT g_0.e0, g_0.e2 FROM test.\"group\" AS g_0 WHERE (g_0.e0 = 1) AND (g_0.e1 = '2')"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+ }
+
+ @Test public void testAccessPattern5() {
+ String sql = "(SELECT e0, e2 FROM vTest.vGroup where e0=1 and e1='2') union all (SELECT e0, e2 FROM vTest.vGroup where e0=1)"; //$NON-NLS-1$
+ TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, null, null, TestOptimizer.SHOULD_FAIL);
+ }
+
+ @Test public void testAccessPattern6() {
+ String sql = "SELECT e0, e2 FROM test.group where e1 IN (SELECT e2 FROM vTest.vGroup where e0=1 and e1='2')"; //$NON-NLS-1$
+ TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), new String[] {"SELECT e1, e0, e2 FROM test.\"group\""}); //$NON-NLS-1$
+ }
+
+ @Test public void testAccessPattern7() {
+ String sql = "SELECT e0, e2 FROM test.group where e1 IN (SELECT e2 FROM vTest.vGroup where e0=1)"; //$NON-NLS-1$
+ TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, null, null, TestOptimizer.SHOULD_FAIL);
+ }
+
+ @Test public void testAccessPattern8() {
+ String sql = "SELECT e0, e2 FROM vTest.vGroup"; //$NON-NLS-1$
+ TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, null, null, TestOptimizer.SHOULD_FAIL);
+ }
+
+ /**
+ * Tests two access nodes, each with access patterns, but one already
+ * 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", 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$
+ }
+
+ /**
+ * Tests two access nodes, each with access patterns, but one already
+ * satisfied by user criteria - the other should be made dependent
+ * (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'", 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$
+ }
+
+ /**
+ * Self join - tests that both access nodes are satisfied by the select
+ * 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", 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @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", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ null, null, null,
+ TestOptimizer.SHOULD_FAIL);
+ }
+
+ @Test public void testAccessPatternsFails2() {
+ 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$
+ 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$
+ 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'", 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", 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$
+ 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$
+ }
+
+ /**
+ * Similar to the query above, except the OR instead of an AND produces a
+ * completely different query plan which can't satisfy the access pattern.
+ * @see #testAccessPatternPartialMatch
+ */
+ @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$
+ RealMetadataFactory.example1Cached(),
+ null, null, null,
+ TestOptimizer.SHOULD_FAIL);
+ }
+
+ /**
+ * Access patterns on models that support joins requires that the access patterns are satisfied prior to
+ * RulePlanJoins
+ */
+ @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$
+ RealMetadataFactory.example1Cached(),
+ null, null, null, TestOptimizer.SHOULD_FAIL);
+ }
+
+ // ==================================================================================
+ // ACCESS PATTERNS
+ // ==================================================================================
+
+ @Test public void testPushingCriteriaThroughFrameAccessPattern0() {
+ 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$
+ }
+
+ /**
+ * 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", 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", 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", 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$
+ }
+
+ /**
+ * 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'", RealMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), //$NON-NLS-1$
+ null, TestOptimizer.SHOULD_FAIL );
+ }
+
+ /**
+ * TODO: in this case we should perform a criteria optimization to create set criteria
+ */
+ @Test public void testCase6425() {
+ String sql = "SELECT e1 FROM pm4.g1 WHERE e1 = '1' OR e1 = '2'"; //$NON-NLS-1$
+
+ 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$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testCase6425_2() {
+ String sql = "SELECT e1 FROM pm4.g1 WHERE e1 = '1' OR (e1 = '2' AND e2 = 3)"; //$NON-NLS-1$
+
+ 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$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testCase6425_4() throws Exception {
+ String sql = "SELECT e1 FROM pm4.g1 WHERE e1 = '1' OR e2 = '2'"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ TestOptimizer.helpPlan(sql, metadata, null, TestOptimizer.ComparisonMode.FAILED_PLANNING);
+ }
+
+ /*
+ * Criteria was preventing rule choose dependent from creating the appropriate dependent join
+ */
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ TestOptimizer.helpPlan(sql, metadata,
+ new String[] {
+ "SELECT g_0.e2, g_0.e1 FROM pm5.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", //$NON-NLS-1$
+ "SELECT g_0.e1, g_0.e2, g_0.e3, g_0.e4 FROM pm1.g1 AS g_0", //$NON-NLS-1$
+ "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)" }, TestOptimizer.getGenericFinder(false), ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,933 +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.optimizer;
-
-import static org.teiid.query.optimizer.TestOptimizer.*;
-
-import org.junit.Test;
-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.CapabilitiesFinder;
-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.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.translator.SourceSystemFunctions;
-
- at SuppressWarnings("nls")
-public class TestAggregatePushdown {
-
- public static BasicSourceCapabilities getAggregateCapabilities() {
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MIN, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
- caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_HAVING, true);
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- return caps;
- }
-
- public static CapabilitiesFinder getAggregatesFinder() {
- return new DefaultCapabilitiesFinder(getAggregateCapabilities());
- }
-
- @Test public void testCase6327() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getAggregateCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 1, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Note that intnum is retrieved from each source
- *
- * Note also that this test shows that the max aggregate is not placed on the bqt2 query since it would be on one of the group by expressions
- */
- @Test public void testAggregateOfJoinExpression() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getAggregateCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- 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,
- 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[] {
- 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 testAggregateOfJoinExpression1() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getAggregateCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- 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,
- 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[] {
- 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
- });
- }
-
- /**
- * Note that even though this grouping is join invariant, we still do not remove the top level group by
- * since we are not checking the uniqueness of the x side join expressions
- */
- @Test public void testInvariantAggregate() 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 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,
- 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[] {
- 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 of an aggregate nested in an expression symbol
- */
- @Test public void testCase6211() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getAggregateCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
- 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$
-
- 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
- });
- }
-
- /**
- * 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();
- 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$
-
- 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$
- TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // 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 testAggregatePushdown2() throws Exception {
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
-
- 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$
- TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Average requires the creation of staged sum and count aggregates
- */
- @Test public void testAvgAggregate() 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) 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$
-
- 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();
- caps.setFunctionSupport(SourceSystemFunctions.POWER, true);
- caps.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- 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$
-
- 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 testCountAggregate() 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 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$
-
- 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 testOuterJoinPreventsPushdown() 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 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,
- 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
- 1, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Test to ensure count(*) isn't mistakenly pushed to either side
- */
- @Test public void testCase5724() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getAggregateCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
- metadata, null, capFinder,
- new String[] {
- "SELECT a.intkey, a.intnum FROM bqt1.smalla AS a", "SELECT b.intkey FROM bqt2.smallb AS b"}, //$NON-NLS-1$ //$NON-NLS-2$
- true);
-
- 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 testCase6210() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getAggregateCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- caps.setFunctionSupport("/", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
- 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,
- 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[] {
- 3, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testNoGroupAggregatePushdown() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, false);
- 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();
-
- ProcessorPlan plan = TestOptimizer.helpPlan(
- "select count(*) from bqt1.smalla", //$NON-NLS-1$
- metadata, null, capFinder,
- new String[] {
- "SELECT count(*) from bqt1.smalla"}, //$NON-NLS-1$
- true);
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testNoHavingAggregate() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
- 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();
-
- ProcessorPlan plan = TestOptimizer.helpPlan(
- "select stringkey, max(intkey) from bqt1.smalla group by stringkey having count(intkey) = 1", //$NON-NLS-1$
- metadata, null, capFinder,
- new String[] {
- "SELECT COUNT(g_0.intkey), g_0.stringkey, MAX(g_0.intkey) FROM bqt1.smalla AS g_0 GROUP BY g_0.stringkey"}, //$NON-NLS-1$
- ComparisonMode.EXACT_COMMAND_STRING);
-
- TestOptimizer.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 testHavingCriteriaPushDown() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- 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$
- 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
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testBusObjQuestion1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
-
- capFinder.addCapabilities("db2model", caps); //$NON-NLS-1$
- capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
- capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- "FULL OUTER JOIN " + //$NON-NLS-1$
- "(SELECT SUM(COSTS) AS C, REGION FROM ORACLE_TABLE WHERE \"YEAR\" = '1999' GROUP BY REGION) Q2 " + //$NON-NLS-1$
- "ON Q1.REGION = Q2.REGION"; //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {"SELECT REGION, SUM(SALES), PRODUCT FROM db2model.DB2_TABLE WHERE PRODUCT IN ('GUNS', 'TOYS', 'VIDEOTAPES') GROUP BY REGION, PRODUCT", //$NON-NLS-1$
- "SELECT REGION, SUM(COSTS) FROM oraclemodel.Oracle_table WHERE \"YEAR\" = '1999' GROUP BY REGION"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testBusObjQuestion2() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
-
- capFinder.addCapabilities("db2model", caps); //$NON-NLS-1$
- capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
- capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- "WHERE (F.CITY = G.CITY) AND (F.MONTH = T.MONTH) " + //$NON-NLS-1$
- "AND G.REGION IN ('BORDEAUX', 'POLINESIA') AND T.YEAR = '1999' " + //$NON-NLS-1$
- "GROUP BY G.REGION, T.YEAR"; //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {"SELECT g_0.\"MONTH\" AS c_0, g_0.\"YEAR\" AS c_1 FROM msModel.\"TIME\" AS g_0 WHERE g_0.\"YEAR\" = '1999' ORDER BY c_0", //$NON-NLS-1$
- "SELECT g_0.\"MONTH\" AS c_0, g_0.CITY AS c_1, SUM(g_0.SALES) AS c_2 FROM db2model.SALES AS g_0 WHERE (g_0.\"MONTH\" IN (<dependent values>)) AND (g_0.CITY IN (<dependent values>)) GROUP BY g_0.\"MONTH\", g_0.CITY ORDER BY c_0", //$NON-NLS-1$
- "SELECT g_0.CITY AS c_0, g_0.REGION AS c_1 FROM oraclemodel.GEOGRAPHY AS g_0 WHERE g_0.REGION IN ('BORDEAUX', 'POLINESIA') ORDER BY c_0"}, //$NON-NLS-1$
- ComparisonMode.EXACT_COMMAND_STRING );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testBusObjQuestion2Hint() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
-
- capFinder.addCapabilities("db2model", caps); //$NON-NLS-1$
- capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
- capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- "WHERE (F.CITY = G.CITY) AND (F.MONTH = T.MONTH) " + //$NON-NLS-1$
- "AND G.REGION IN ('BORDEAUX', 'POLINESIA') AND T.YEAR = '1999' " + //$NON-NLS-1$
- "GROUP BY G.REGION, T.YEAR"; //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {"SELECT g_0.\"MONTH\" AS c_0, g_0.\"YEAR\" AS c_1 FROM msModel.\"TIME\" AS g_0 WHERE g_0.\"YEAR\" = '1999' ORDER BY c_0", //$NON-NLS-1$
- "SELECT g_0.\"MONTH\" AS c_0, g_0.CITY AS c_1, SUM(g_0.SALES) AS c_2 FROM db2model.SALES AS g_0 WHERE (g_0.\"MONTH\" IN (<dependent values>)) AND (g_0.CITY IN (<dependent values>)) GROUP BY g_0.\"MONTH\", g_0.CITY ORDER BY c_0", //$NON-NLS-1$
- "SELECT g_0.CITY AS c_0, g_0.REGION AS c_1 FROM oraclemodel.GEOGRAPHY AS g_0 WHERE g_0.REGION IN ('BORDEAUX', 'POLINESIA') ORDER BY c_0"}, //$NON-NLS-1$
- ComparisonMode.EXACT_COMMAND_STRING );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testBusObjQuestion2HintVariation() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
-
- capFinder.addCapabilities("db2model", caps); //$NON-NLS-1$
- capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
- capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- "WHERE (F.CITY = G.CITY) AND (F.MONTH = T.MONTH) " + //$NON-NLS-1$
- "AND G.REGION IN ('BORDEAUX', 'POLINESIA') AND T.YEAR = '1999' " + //$NON-NLS-1$
- "GROUP BY G.REGION, T.YEAR"; //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {"SELECT g_0.\"MONTH\" AS c_0, g_1.REGION AS c_1, SUM(g_0.SALES) AS c_2 FROM db2model.SALES AS g_0, db2model.GEOGRAPHY2 AS g_1 WHERE (g_0.CITY = g_1.CITY) AND (g_1.REGION IN ('BORDEAUX', 'POLINESIA')) AND (g_0.\"MONTH\" IN (<dependent values>)) GROUP BY g_0.\"MONTH\", g_1.REGION ORDER BY c_0", //$NON-NLS-1$
- "SELECT g_0.\"MONTH\" AS c_0, g_0.\"YEAR\" AS c_1 FROM msModel.\"TIME\" AS g_0 WHERE g_0.\"YEAR\" = '1999' ORDER BY c_0"}, //$NON-NLS-1$
- ComparisonMode.EXACT_COMMAND_STRING );
-
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // 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 testBusObjQuestion3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
-
- capFinder.addCapabilities("db2model", caps); //$NON-NLS-1$
- capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
- capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testPushDownOverUnion() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- 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$
- 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[] {
- 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$
- 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[] {
- 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
- });
- }
-
- /**
- * We won't do the pushdown here since the aggregate depends upon the cardinality
- */
- @Test public void testPushDownOverUnion2() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- 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$
- 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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 1, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- @Test public void testPushDownOverUnionMixed() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getAggregateCapabilities();
- 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$
- 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[] {
- 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
- });
- }
-
- /**
- * Ensures that we do not raise criteria over a group by
- * TODO: check if the criteria only depends on grouping columns
- */
- @Test public void testForCase836073GroupBy() throws Exception {
- String sql = "select count(*) from bqt1.smallb where formatdate(bqt1.smallb.DateValue,'yyyyMM') = '200309'";
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql,
- FakeMetadataFactory.exampleBQTCached(),
- null, getAggregatesFinder(),
- new String[] {"SELECT g_0.DateValue FROM bqt1.smallb AS g_0"},
- TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,932 @@
+/*
+ * 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;
+
+import static org.teiid.query.optimizer.TestOptimizer.*;
+
+import org.junit.Test;
+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.CapabilitiesFinder;
+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.processor.ProcessorPlan;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.translator.SourceSystemFunctions;
+
+ at SuppressWarnings("nls")
+public class TestAggregatePushdown {
+
+ public static BasicSourceCapabilities getAggregateCapabilities() {
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_HAVING, true);
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ return caps;
+ }
+
+ public static CapabilitiesFinder getAggregatesFinder() {
+ return new DefaultCapabilitiesFinder(getAggregateCapabilities());
+ }
+
+ @Test public void testCase6327() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getAggregateCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ 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, 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' group by a12.intkey"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 1, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Note that intnum is retrieved from each source
+ *
+ * Note also that this test shows that the max aggregate is not placed on the bqt2 query since it would be on one of the group by expressions
+ */
+ @Test public void testAggregateOfJoinExpression() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getAggregateCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ 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, 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[] {
+ 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 testAggregateOfJoinExpression1() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getAggregateCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ 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, 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[] {
+ 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
+ });
+ }
+
+ /**
+ * Note that even though this grouping is join invariant, we still do not remove the top level group by
+ * since we are not checking the uniqueness of the x side join expressions
+ */
+ @Test public void testInvariantAggregate() 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 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, 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[] {
+ 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 of an aggregate nested in an expression symbol
+ */
+ @Test public void testCase6211() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getAggregateCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ 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, 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 GROUP BY g_0.intkey"}, 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
+ });
+ }
+
+ /**
+ * Note that until we can test the other side cardinality, we cannot fully push the group node
+ */
+ @Test public void testAggregatePushdown1() throws Exception {
+ 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$
+
+ 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, 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[] {
+ 1, // Access
+ 1, // 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 testAggregatePushdown2() throws Exception {
+ 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$
+
+ 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, 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[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Average requires the creation of staged sum and count aggregates
+ */
+ @Test public void testAvgAggregate() 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) 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 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$
+
+ 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();
+ caps.setFunctionSupport(SourceSystemFunctions.POWER, true);
+ caps.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ 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, 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 GROUP BY g_0.e3, g_0.e2 ORDER BY c_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 testCountAggregate() 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 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, RealMetadataFactory.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$
+
+ 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 testOuterJoinPreventsPushdown() 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 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, 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
+ 1, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Test to ensure count(*) isn't mistakenly pushed to either side
+ */
+ @Test public void testCase5724() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getAggregateCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ 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$
+ metadata, null, capFinder,
+ new String[] {
+ "SELECT a.intkey, a.intnum FROM bqt1.smalla AS a", "SELECT b.intkey FROM bqt2.smallb AS b"}, //$NON-NLS-1$ //$NON-NLS-2$
+ true);
+
+ 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 testCase6210() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getAggregateCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ caps.setFunctionSupport("/", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ 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, 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[] {
+ 3, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testNoGroupAggregatePushdown() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, false);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(
+ "select count(*) from bqt1.smalla", //$NON-NLS-1$
+ metadata, null, capFinder,
+ new String[] {
+ "SELECT count(*) from bqt1.smalla"}, //$NON-NLS-1$
+ true);
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testNoHavingAggregate() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ 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$
+ metadata, null, capFinder,
+ new String[] {
+ "SELECT COUNT(g_0.intkey), g_0.stringkey, MAX(g_0.intkey) FROM bqt1.smalla AS g_0 GROUP BY g_0.stringkey"}, //$NON-NLS-1$
+ ComparisonMode.EXACT_COMMAND_STRING);
+
+ TestOptimizer.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 testHavingCriteriaPushDown() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ 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", 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testBusObjQuestion1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
+
+ capFinder.addCapabilities("db2model", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
+
+ 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$
+ "FULL OUTER JOIN " + //$NON-NLS-1$
+ "(SELECT SUM(COSTS) AS C, REGION FROM ORACLE_TABLE WHERE \"YEAR\" = '1999' GROUP BY REGION) Q2 " + //$NON-NLS-1$
+ "ON Q1.REGION = Q2.REGION"; //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT REGION, SUM(SALES), PRODUCT FROM db2model.DB2_TABLE WHERE PRODUCT IN ('GUNS', 'TOYS', 'VIDEOTAPES') GROUP BY REGION, PRODUCT", //$NON-NLS-1$
+ "SELECT REGION, SUM(COSTS) FROM oraclemodel.Oracle_table WHERE \"YEAR\" = '1999' GROUP BY REGION"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testBusObjQuestion2() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
+
+ capFinder.addCapabilities("db2model", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
+
+ 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$
+ "WHERE (F.CITY = G.CITY) AND (F.MONTH = T.MONTH) " + //$NON-NLS-1$
+ "AND G.REGION IN ('BORDEAUX', 'POLINESIA') AND T.YEAR = '1999' " + //$NON-NLS-1$
+ "GROUP BY G.REGION, T.YEAR"; //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT g_0.\"MONTH\" AS c_0, g_0.\"YEAR\" AS c_1 FROM msModel.\"TIME\" AS g_0 WHERE g_0.\"YEAR\" = '1999' ORDER BY c_0", //$NON-NLS-1$
+ "SELECT g_0.\"MONTH\" AS c_0, g_0.CITY AS c_1, SUM(g_0.SALES) AS c_2 FROM db2model.SALES AS g_0 WHERE (g_0.\"MONTH\" IN (<dependent values>)) AND (g_0.CITY IN (<dependent values>)) GROUP BY g_0.\"MONTH\", g_0.CITY ORDER BY c_0", //$NON-NLS-1$
+ "SELECT g_0.CITY AS c_0, g_0.REGION AS c_1 FROM oraclemodel.GEOGRAPHY AS g_0 WHERE g_0.REGION IN ('BORDEAUX', 'POLINESIA') ORDER BY c_0"}, //$NON-NLS-1$
+ ComparisonMode.EXACT_COMMAND_STRING );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testBusObjQuestion2Hint() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
+
+ capFinder.addCapabilities("db2model", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
+
+ 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$
+ "WHERE (F.CITY = G.CITY) AND (F.MONTH = T.MONTH) " + //$NON-NLS-1$
+ "AND G.REGION IN ('BORDEAUX', 'POLINESIA') AND T.YEAR = '1999' " + //$NON-NLS-1$
+ "GROUP BY G.REGION, T.YEAR"; //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT g_0.\"MONTH\" AS c_0, g_0.\"YEAR\" AS c_1 FROM msModel.\"TIME\" AS g_0 WHERE g_0.\"YEAR\" = '1999' ORDER BY c_0", //$NON-NLS-1$
+ "SELECT g_0.\"MONTH\" AS c_0, g_0.CITY AS c_1, SUM(g_0.SALES) AS c_2 FROM db2model.SALES AS g_0 WHERE (g_0.\"MONTH\" IN (<dependent values>)) AND (g_0.CITY IN (<dependent values>)) GROUP BY g_0.\"MONTH\", g_0.CITY ORDER BY c_0", //$NON-NLS-1$
+ "SELECT g_0.CITY AS c_0, g_0.REGION AS c_1 FROM oraclemodel.GEOGRAPHY AS g_0 WHERE g_0.REGION IN ('BORDEAUX', 'POLINESIA') ORDER BY c_0"}, //$NON-NLS-1$
+ ComparisonMode.EXACT_COMMAND_STRING );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testBusObjQuestion2HintVariation() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
+
+ capFinder.addCapabilities("db2model", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
+
+ 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$
+ "WHERE (F.CITY = G.CITY) AND (F.MONTH = T.MONTH) " + //$NON-NLS-1$
+ "AND G.REGION IN ('BORDEAUX', 'POLINESIA') AND T.YEAR = '1999' " + //$NON-NLS-1$
+ "GROUP BY G.REGION, T.YEAR"; //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT g_0.\"MONTH\" AS c_0, g_1.REGION AS c_1, SUM(g_0.SALES) AS c_2 FROM db2model.SALES AS g_0, db2model.GEOGRAPHY2 AS g_1 WHERE (g_0.CITY = g_1.CITY) AND (g_1.REGION IN ('BORDEAUX', 'POLINESIA')) AND (g_0.\"MONTH\" IN (<dependent values>)) GROUP BY g_0.\"MONTH\", g_1.REGION ORDER BY c_0", //$NON-NLS-1$
+ "SELECT g_0.\"MONTH\" AS c_0, g_0.\"YEAR\" AS c_1 FROM msModel.\"TIME\" AS g_0 WHERE g_0.\"YEAR\" = '1999' ORDER BY c_0"}, //$NON-NLS-1$
+ ComparisonMode.EXACT_COMMAND_STRING );
+
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // 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 testBusObjQuestion3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
+
+ capFinder.addCapabilities("db2model", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
+
+ 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$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testPushDownOverUnion() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ 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", 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[] {
+ 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", 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[] {
+ 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
+ });
+ }
+
+ /**
+ * We won't do the pushdown here since the aggregate depends upon the cardinality
+ */
+ @Test public void testPushDownOverUnion2() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ 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", 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 1, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ @Test public void testPushDownOverUnionMixed() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getAggregateCapabilities();
+ 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", 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[] {
+ 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
+ });
+ }
+
+ /**
+ * Ensures that we do not raise criteria over a group by
+ * TODO: check if the criteria only depends on grouping columns
+ */
+ @Test public void testForCase836073GroupBy() throws Exception {
+ String sql = "select count(*) from bqt1.smallb where formatdate(bqt1.smallb.DateValue,'yyyyMM') = '200309'";
+
+ // Plan query
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql,
+ RealMetadataFactory.exampleBQTCached(),
+ null, getAggregatesFinder(),
+ new String[] {"SELECT g_0.DateValue FROM bqt1.smallb AS g_0"},
+ TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,57 +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.optimizer;
-
-import org.junit.Test;
-import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
-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.unittest.FakeMetadataFactory;
-
-
-public class TestAnsiJoinPushdown {
-
- /**
- * See {@link TestOptimizer.testPushMultiGroupCriteria}
- *
- * Notice that the non-join criteria is still in the on clause.
- */
- @Test public void testAnsiInnerJoin() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_ANSI_JOIN, true);
- capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
-
- 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(),
- 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$
- ComparisonMode.EXACT_COMMAND_STRING);
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,57 @@
+/*
+ * 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;
+
+import org.junit.Test;
+import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
+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.unittest.RealMetadataFactory;
+
+
+public class TestAnsiJoinPushdown {
+
+ /**
+ * See {@link TestOptimizer.testPushMultiGroupCriteria}
+ *
+ * Notice that the non-join criteria is still in the on clause.
+ */
+ @Test public void testAnsiInnerJoin() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_ANSI_JOIN, true);
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ 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$
+ 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$
+ ComparisonMode.EXACT_COMMAND_STRING);
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,230 +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.optimizer;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-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.query.analysis.AnalysisRecord;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.QueryOptimizer;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.BatchedUpdatePlan;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.relational.AccessNode;
-import org.teiid.query.processor.relational.BatchedUpdateNode;
-import org.teiid.query.processor.relational.ProjectNode;
-import org.teiid.query.processor.relational.RelationalNode;
-import org.teiid.query.processor.relational.RelationalPlan;
-import org.teiid.query.resolver.QueryResolver;
-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.validator.Validator;
-import org.teiid.query.validator.ValidatorReport;
-
-import junit.framework.TestCase;
-
-
-
-/**
- * @since 4.2
- */
-public class TestBatchedUpdatePlanner extends TestCase {
-
- public TestBatchedUpdatePlanner(String name) {
- super(name);
- }
-
- public static List<Command> helpGetCommands(String[] sql, QueryMetadataInterface md) throws TeiidComponentException, TeiidProcessingException {
- if(DEBUG) System.out.println("\n####################################\n" + sql); //$NON-NLS-1$
- List<Command> commands = new ArrayList<Command>(sql.length);
- for (int i = 0; i < sql.length; i++) {
- Command command = QueryParser.getQueryParser().parseCommand(sql[i]);
- QueryResolver.resolveCommand(command, md);
- ValidatorReport repo = Validator.validate(command, md);
- Collection failures = new ArrayList();
- repo.collectInvalidObjects(failures);
- if (failures.size() > 0){
- fail("Exception during validation (" + repo); //$NON-NLS-1$
- }
-
- command = QueryRewriter.rewrite(command, md, null);
- commands.add(command);
- }
- return commands;
- }
-
- private BatchedUpdateCommand helpGetCommand(String[] sql, QueryMetadataInterface md) throws TeiidComponentException, TeiidProcessingException {
- BatchedUpdateCommand command = new BatchedUpdateCommand(helpGetCommands(sql, md));
- return command;
- }
-
- private BatchedUpdatePlan helpPlanCommand(Command command, QueryMetadataInterface md, CapabilitiesFinder capFinder, boolean shouldSucceed) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- // plan
- ProcessorPlan plan = null;
- AnalysisRecord analysisRecord = new AnalysisRecord(false, DEBUG);
- if (shouldSucceed) {
- try {
- //do planning
- plan = QueryOptimizer.optimizePlan(command, md, null, capFinder, analysisRecord, null);
-
- } finally {
- if(DEBUG) {
- System.out.println(analysisRecord.getDebugLog());
- }
- }
- return (BatchedUpdatePlan)plan;
- }
- Exception exception = null;
- try {
- //do planning
- QueryOptimizer.optimizePlan(command, md, null, capFinder, analysisRecord, null);
-
- } catch (QueryPlannerException e) {
- exception = e;
- } catch (TeiidComponentException e) {
- exception = e;
- } finally {
- if(DEBUG) {
- System.out.println(analysisRecord.getDebugLog());
- }
- }
- assertNotNull("Expected exception but did not get one.", exception); //$NON-NLS-1$
- return null;
- }
-
- public static CapabilitiesFinder getGenericFinder() {
- return new DefaultCapabilitiesFinder(new FakeCapabilities(true));
- }
-
- private BatchedUpdatePlan helpPlan(String[] sql, QueryMetadataInterface md) throws TeiidComponentException, QueryMetadataException, TeiidProcessingException {
- return helpPlan(sql, md, getGenericFinder(), true);
- }
-
- private BatchedUpdatePlan helpPlan(String[] sql, QueryMetadataInterface md, CapabilitiesFinder capFinder, boolean shouldSucceed) throws TeiidComponentException, QueryMetadataException, TeiidProcessingException {
- Command command = helpGetCommand(sql, md);
-
- if (capFinder == null){
- capFinder = getGenericFinder();
- }
-
- return helpPlanCommand(command, md, capFinder, shouldSucceed);
- }
-
- private void helpAssertIsBatchedPlan(RelationalPlan plan, boolean isBatchedPlan) {
- RelationalNode node = plan.getRootNode();
- if (node instanceof ProjectNode) {
- node = node.getChildren()[0];
- }
- if (isBatchedPlan) {
- assertTrue("Plan should have been a batched", node instanceof BatchedUpdateNode); //$NON-NLS-1$
- } else {
- assertTrue("Plan should not have been batched.", node instanceof AccessNode); //$NON-NLS-1$
- }
- }
-
- private void helpTestPlanner(String[] sql, boolean[] expectedBatching) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
- BatchedUpdatePlan plan = helpPlan(sql, FakeMetadataFactory.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++) {
- helpAssertIsBatchedPlan((RelationalPlan)plans.get(i), expectedBatching[i]);
- }
- }
-
- private void helpTestPlanner(String[] sql, boolean[] expectedBatching, CapabilitiesFinder capFinder) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
- BatchedUpdatePlan plan = helpPlan(sql, FakeMetadataFactory.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++) {
- helpAssertIsBatchedPlan((RelationalPlan)plans.get(i), expectedBatching[i]);
- }
- }
-
- public void testPlannerAllCommandsBatched() throws Exception {
- String[] sql = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
- "INSERT INTO pm1.g2 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
- "DELETE FROM pm1.g1 WHERE e2 > 5000", //$NON-NLS-1$
- "UPDATE pm1.g1 set e2 = -1 WHERE e2 = 4999" //$NON-NLS-1$
- };
- boolean[] expectedBatching = {true};
- helpTestPlanner(sql, expectedBatching);
- }
-
- public void testPlannerNoCommandsBatched() throws Exception {
- String[] sql = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
- "INSERT INTO pm1.g2 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
- "DELETE FROM pm1.g1 WHERE e2 > 5000", //$NON-NLS-1$
- "UPDATE pm1.g1 set e2 = -1 WHERE e2 = 4999" //$NON-NLS-1$
- };
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- finder.addCapabilities("pm1", new FakeCapabilities(false)); //$NON-NLS-1$
- boolean[] expectedBatching = {false, false, false, false};
- helpTestPlanner(sql, expectedBatching, finder);
- }
-
- public void testPlannerSomeCommandsBatched() throws Exception {
- String[] sql = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
- "INSERT INTO pm1.g2 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
- "DELETE FROM pm2.g1 WHERE e2 > 5000", //$NON-NLS-1$
- "INSERT INTO pm2.g1 (e1, e2, e3, e4) values ('5000', 5000, {b'true'}, 5000.0)", //$NON-NLS-1$
- "UPDATE pm2.g1 set e2 = -1 WHERE e2 = 4999", //$NON-NLS-1$
- "DELETE FROM pm1.g2 WHERE e2 = 50" //$NON-NLS-1$
- };
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- finder.addCapabilities("pm1", new FakeCapabilities(false)); //$NON-NLS-1$
- finder.addCapabilities("pm2", new FakeCapabilities(true)); //$NON-NLS-1$
- boolean[] expectedBatching = {false, false, true, false};
- helpTestPlanner(sql, expectedBatching, finder);
- }
-
- private static final class FakeCapabilities implements SourceCapabilities {
- private boolean supportsBatching = false;
- private FakeCapabilities(boolean supportsBatching) {
- this.supportsBatching = supportsBatching;
- }
- public Scope getScope() {return null;}
- public boolean supportsCapability(Capability capability) {
- return !capability.equals(Capability.BATCHED_UPDATES) || supportsBatching;
- }
- public boolean supportsFunction(String functionName) {return false;}
- // since 4.4
- public Object getSourceProperty(Capability propertyName) {return null;}
-
- }
-
- private static final boolean DEBUG = false;
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,230 @@
+/*
+ * 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;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+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.query.analysis.AnalysisRecord;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.QueryOptimizer;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.BatchedUpdatePlan;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.relational.AccessNode;
+import org.teiid.query.processor.relational.BatchedUpdateNode;
+import org.teiid.query.processor.relational.ProjectNode;
+import org.teiid.query.processor.relational.RelationalNode;
+import org.teiid.query.processor.relational.RelationalPlan;
+import org.teiid.query.resolver.QueryResolver;
+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.RealMetadataFactory;
+import org.teiid.query.validator.Validator;
+import org.teiid.query.validator.ValidatorReport;
+
+import junit.framework.TestCase;
+
+
+
+/**
+ * @since 4.2
+ */
+public class TestBatchedUpdatePlanner extends TestCase {
+
+ public TestBatchedUpdatePlanner(String name) {
+ super(name);
+ }
+
+ public static List<Command> helpGetCommands(String[] sql, QueryMetadataInterface md) throws TeiidComponentException, TeiidProcessingException {
+ if(DEBUG) System.out.println("\n####################################\n" + sql); //$NON-NLS-1$
+ List<Command> commands = new ArrayList<Command>(sql.length);
+ for (int i = 0; i < sql.length; i++) {
+ Command command = QueryParser.getQueryParser().parseCommand(sql[i]);
+ QueryResolver.resolveCommand(command, md);
+ ValidatorReport repo = Validator.validate(command, md);
+ Collection failures = new ArrayList();
+ repo.collectInvalidObjects(failures);
+ if (failures.size() > 0){
+ fail("Exception during validation (" + repo); //$NON-NLS-1$
+ }
+
+ command = QueryRewriter.rewrite(command, md, null);
+ commands.add(command);
+ }
+ return commands;
+ }
+
+ private BatchedUpdateCommand helpGetCommand(String[] sql, QueryMetadataInterface md) throws TeiidComponentException, TeiidProcessingException {
+ BatchedUpdateCommand command = new BatchedUpdateCommand(helpGetCommands(sql, md));
+ return command;
+ }
+
+ private BatchedUpdatePlan helpPlanCommand(Command command, QueryMetadataInterface md, CapabilitiesFinder capFinder, boolean shouldSucceed) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ // plan
+ ProcessorPlan plan = null;
+ AnalysisRecord analysisRecord = new AnalysisRecord(false, DEBUG);
+ if (shouldSucceed) {
+ try {
+ //do planning
+ plan = QueryOptimizer.optimizePlan(command, md, null, capFinder, analysisRecord, null);
+
+ } finally {
+ if(DEBUG) {
+ System.out.println(analysisRecord.getDebugLog());
+ }
+ }
+ return (BatchedUpdatePlan)plan;
+ }
+ Exception exception = null;
+ try {
+ //do planning
+ QueryOptimizer.optimizePlan(command, md, null, capFinder, analysisRecord, null);
+
+ } catch (QueryPlannerException e) {
+ exception = e;
+ } catch (TeiidComponentException e) {
+ exception = e;
+ } finally {
+ if(DEBUG) {
+ System.out.println(analysisRecord.getDebugLog());
+ }
+ }
+ assertNotNull("Expected exception but did not get one.", exception); //$NON-NLS-1$
+ return null;
+ }
+
+ public static CapabilitiesFinder getGenericFinder() {
+ return new DefaultCapabilitiesFinder(new FakeCapabilities(true));
+ }
+
+ private BatchedUpdatePlan helpPlan(String[] sql, QueryMetadataInterface md) throws TeiidComponentException, QueryMetadataException, TeiidProcessingException {
+ return helpPlan(sql, md, getGenericFinder(), true);
+ }
+
+ private BatchedUpdatePlan helpPlan(String[] sql, QueryMetadataInterface md, CapabilitiesFinder capFinder, boolean shouldSucceed) throws TeiidComponentException, QueryMetadataException, TeiidProcessingException {
+ Command command = helpGetCommand(sql, md);
+
+ if (capFinder == null){
+ capFinder = getGenericFinder();
+ }
+
+ return helpPlanCommand(command, md, capFinder, shouldSucceed);
+ }
+
+ private void helpAssertIsBatchedPlan(RelationalPlan plan, boolean isBatchedPlan) {
+ RelationalNode node = plan.getRootNode();
+ if (node instanceof ProjectNode) {
+ node = node.getChildren()[0];
+ }
+ if (isBatchedPlan) {
+ assertTrue("Plan should have been a batched", node instanceof BatchedUpdateNode); //$NON-NLS-1$
+ } else {
+ assertTrue("Plan should not have been batched.", node instanceof AccessNode); //$NON-NLS-1$
+ }
+ }
+
+ private void helpTestPlanner(String[] sql, boolean[] expectedBatching) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+ 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++) {
+ helpAssertIsBatchedPlan((RelationalPlan)plans.get(i), expectedBatching[i]);
+ }
+ }
+
+ private void helpTestPlanner(String[] sql, boolean[] expectedBatching, CapabilitiesFinder capFinder) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+ 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++) {
+ helpAssertIsBatchedPlan((RelationalPlan)plans.get(i), expectedBatching[i]);
+ }
+ }
+
+ public void testPlannerAllCommandsBatched() throws Exception {
+ String[] sql = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
+ "INSERT INTO pm1.g2 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
+ "DELETE FROM pm1.g1 WHERE e2 > 5000", //$NON-NLS-1$
+ "UPDATE pm1.g1 set e2 = -1 WHERE e2 = 4999" //$NON-NLS-1$
+ };
+ boolean[] expectedBatching = {true};
+ helpTestPlanner(sql, expectedBatching);
+ }
+
+ public void testPlannerNoCommandsBatched() throws Exception {
+ String[] sql = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
+ "INSERT INTO pm1.g2 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
+ "DELETE FROM pm1.g1 WHERE e2 > 5000", //$NON-NLS-1$
+ "UPDATE pm1.g1 set e2 = -1 WHERE e2 = 4999" //$NON-NLS-1$
+ };
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ finder.addCapabilities("pm1", new FakeCapabilities(false)); //$NON-NLS-1$
+ boolean[] expectedBatching = {false, false, false, false};
+ helpTestPlanner(sql, expectedBatching, finder);
+ }
+
+ public void testPlannerSomeCommandsBatched() throws Exception {
+ String[] sql = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
+ "INSERT INTO pm1.g2 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
+ "DELETE FROM pm2.g1 WHERE e2 > 5000", //$NON-NLS-1$
+ "INSERT INTO pm2.g1 (e1, e2, e3, e4) values ('5000', 5000, {b'true'}, 5000.0)", //$NON-NLS-1$
+ "UPDATE pm2.g1 set e2 = -1 WHERE e2 = 4999", //$NON-NLS-1$
+ "DELETE FROM pm1.g2 WHERE e2 = 50" //$NON-NLS-1$
+ };
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ finder.addCapabilities("pm1", new FakeCapabilities(false)); //$NON-NLS-1$
+ finder.addCapabilities("pm2", new FakeCapabilities(true)); //$NON-NLS-1$
+ boolean[] expectedBatching = {false, false, true, false};
+ helpTestPlanner(sql, expectedBatching, finder);
+ }
+
+ private static final class FakeCapabilities implements SourceCapabilities {
+ private boolean supportsBatching = false;
+ private FakeCapabilities(boolean supportsBatching) {
+ this.supportsBatching = supportsBatching;
+ }
+ public Scope getScope() {return null;}
+ public boolean supportsCapability(Capability capability) {
+ return !capability.equals(Capability.BATCHED_UPDATES) || supportsBatching;
+ }
+ public boolean supportsFunction(String functionName) {return false;}
+ // since 4.4
+ public Object getSourceProperty(Capability propertyName) {return null;}
+
+ }
+
+ private static final boolean DEBUG = false;
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,842 +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.optimizer;
-
-import static org.junit.Assert.*;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.junit.Test;
-import org.teiid.metadata.Column;
-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;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.optimizer.relational.rules.RuleChooseDependent;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.relational.AccessNode;
-import org.teiid.query.processor.relational.DependentAccessNode;
-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.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;
-
- at SuppressWarnings("nls")
-public class TestDependentJoins {
-
- static void checkDependentGroups(ProcessorPlan plan, String[] groups) {
- if(! (plan instanceof RelationalPlan)) {
- return;
- }
-
- // Collect all the group names (uppercase) for all the dependent groups in the plan
- Set<String> depGroups = new HashSet<String>();
- getDependentGroups(((RelationalPlan)plan).getRootNode(), depGroups, true);
-
- // Check that all the expected groups exist in depGroups
- Set<String> expectedGroups = new HashSet<String>();
- for(int i=0; i<groups.length; i++) {
- expectedGroups.add(groups[i].toUpperCase());
- }
-
- assertEquals("Expected groups were not made dependent", expectedGroups, depGroups); //$NON-NLS-1$
- }
-
- static void getDependentGroups(RelationalNode node, Set<String> depGroups, boolean depdenent) {
- if(node instanceof AccessNode) {
- if (node instanceof DependentAccessNode) {
- if (!depdenent) {
- return;
- }
- } else if (depdenent) {
- return;
- }
- AccessNode accessNode = (AccessNode)node;
- Command depCommand = accessNode.getCommand();
- Collection<GroupSymbol> groupSymbols = GroupCollectorVisitor.getGroups(depCommand, true);
- for (GroupSymbol groupSymbol : groupSymbols) {
- depGroups.add(groupSymbol.getName().toUpperCase());
- }
- }
-
- // Recurse through children
- RelationalNode[] children = node.getChildren();
- for(int i=0; i<children.length; i++) {
- if(children[i] != null) {
- getDependentGroups(node.getChildren()[i], depGroups, depdenent);
- }
- }
- }
-
- private void checkNotDependentGroups(ProcessorPlan plan, String[] groups) {
- if(! (plan instanceof RelationalPlan)) {
- return;
- }
-
- // Collect all the group names (uppercase) for all the dependent groups in the plan
- Set<String> notDepGroups = new HashSet<String>();
- getDependentGroups(((RelationalPlan)plan).getRootNode(), notDepGroups, false);
-
- // Check that all the expected groups exist in depGroups
- Set<String> expectedGroups = new HashSet<String>();
- for(int i=0; i<groups.length; i++) {
- expectedGroups.add(groups[i].toUpperCase());
- }
-
- assertEquals("Expected groups were made dependent", expectedGroups, notDepGroups); //$NON-NLS-1$
- }
-
- @Test public void testOptionMakeDep1() throws Exception {
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
- 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$
- 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$
- checkNotDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testOptionMakeDep2() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
- 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$
- 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$
- checkNotDependentGroups(plan, new String[] {"pm2.g1"}); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testDepJoinHintForceLeft() throws Exception {
- ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g1", TestOptimizer.example1(), //$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 pm1.g2 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$
- }
-
- @Test public void testDepJoinHintForceRight() throws Exception {
-
- ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g2", TestOptimizer.example1(), //$NON-NLS-1$
- 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.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$
- }
-
- @Test public void testDepJoinMultiGroupBaseline() throws Exception {
- ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1", TestOptimizer.example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
- "SELECT pm1.g2.e1 FROM pm1.g2", //$NON-NLS-1$
- "SELECT pm1.g3.e1 FROM pm1.g3" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING ); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 3, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkDependentGroups(plan, new String[0]);
- }
-
- @Test public void testDepJoinMultiGroupForceOther() throws Exception {
- ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1 option makedep pm1.g2", TestOptimizer.example1(), //$NON-NLS-1$
- new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", "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.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$
- }
-
- @Test public void testDepJoinHintForceLeft_NotDep() throws Exception {
- ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g1 makenotdep pm1.g2", TestOptimizer.example1(), //$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 pm1.g2 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$
- checkNotDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$
- }
-
- @Test public void testDepJoinHintForceRight_NotDep() throws Exception {
- ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g2 makenotdep pm1.g1", TestOptimizer.example1(), //$NON-NLS-1$
- 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.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$
- checkNotDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$
- }
-
- @Test public void testDepJoinMultiGroupForceOther_NotDep() throws Exception {
- ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1 option makedep pm1.g2 makenotdep pm1.g1, pm1.g3", TestOptimizer.example1(), //$NON-NLS-1$
- new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", "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.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$
- checkNotDependentGroups(plan, new String[] {"pm1.g1", "pm1.g3"}); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * 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$
- 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$
- }
-
- /**
- * Test that access node with unsatisfied access pattern is made dependent
- * (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$
- 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$
- }
-
- /**
- * 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$
- 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$
- }
-
- /**
- * Test that second access pattern of access node is chosen to make
- * 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$
- 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$
- }
-
- /**
- * This case actually tests the dead-tie case - either access node could
- * be made dependent, but merge join is used since no access pattern
- * 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$
- 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]);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * This case actually tests the dead-tie case - either access node could
- * be made dependent, but merge join is used since no access pattern
- * needs to be fulfilled and there is no cost info available for either source
- * (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$
- 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]);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Tests that it is enforced if an access node can't be made dependent
- * 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$
- 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] );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /** Should use dependent join since one access node is "strong" */
- @Test public void testUseMergeJoin1() 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- 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));
-
- 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$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /** Should not use a dependent join since neither access node is "strong" */
- @Test public void testUseMergeJoin2() 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- 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));
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2" }, TestOptimizer.ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /** should have one dependent joins */
- @Test public void testMultiMergeJoin3() throws Exception {
- // Create query
- String sql = "SELECT pm1.g2.e1 FROM pm1.g3, pm1.g2, pm1.g1 WHERE pm1.g2.e1 = pm1.g3.e1 AND pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- 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));
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g2 AS g_0", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testMultiMergeJoin2() throws Exception {
- 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- 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));
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", "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$ //$NON-NLS-3$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Defect 13448
- * should be one merge join and one dependent join
- * Unlike the above tests, here the model pm1 supports ORDER BY.
- */
- @Test public void testMultiMergeJoin5_defect13448() 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.g1.e1 = pm1.g3.e1";//$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- 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));
-
- 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$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testMergeJoinVirtualGroups() throws Exception {
- String sql = "SELECT vm1.g1.e1 FROM vm1.g1, vm1.g2a WHERE vm1.g1.e1 = vm1.g2a.e1";//$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- 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));
-
- 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.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$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testRLMCase2077() throws Exception {
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
- caps.setFunctionSupport("||", true); //$NON-NLS-1$
- 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$
-
- 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$
- metadata,
- null, capFinder,
- new String[] {"SELECT g_0.StringKey FROM BQT1.SmallA AS g_0 WHERE g_0.StringKey IN (<dependent values>)", "SELECT g_0.STRINGKEY, g_0.STRINGNUM, g_0.IntKey FROM BQT2.SmallA AS g_0"}, //$NON-NLS-1$ //$NON-NLS-2$
- TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- }
-
- @Test public void testRLMCase2077_2() throws Exception {
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
- caps.setFunctionSupport("||", true); //$NON-NLS-1$
- 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$
-
- 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$
- metadata,
- null, capFinder,
- new String[] {"SELECT g_0.STRINGKEY, g_0.STRINGNUM, g_0.IntKey FROM BQT2.SmallA AS g_0", "SELECT g_0.StringKey, g_0.StringNum FROM BQT1.SmallA AS g_0 WHERE (g_0.StringKey IN (<dependent values>)) AND (g_0.StringNum IN (<dependent values>))"}, //$NON-NLS-1$ //$NON-NLS-2$
- TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- }
-
- @Test public void testCostingCleanup() throws Exception {
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
- 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");
- fmo.setDistinctValues(1000);
- Column floatnum = (Column)metadata.getElementID("bqt1.smalla.floatnum");
- floatnum.setDistinctValues(800);
-
- ProcessorPlan plan = TestOptimizer.helpPlan(
- "SELECT max(a.stringkey) from bqt1.smalla a, bqt2.smalla a2, bqt1.smalla a1 where a.intnum = a2.intnum and a1.stringnum = a2.stringnum and a.floatnum = a1.floatnum", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT g_1.stringnum AS c_0, g_0.intnum AS c_1, MAX(g_0.stringkey) AS c_2 FROM bqt1.smalla AS g_0, bqt1.smalla AS g_1 WHERE g_0.floatnum = g_1.floatnum GROUP BY g_1.stringnum, g_0.intnum ORDER BY c_0, c_1", "SELECT DISTINCT g_0.stringnum AS c_0, g_0.intnum AS c_1 FROM bqt2.smalla AS g_0 WHERE (g_0.stringnum IN (<dependent values>)) AND (g_0.intnum IN (<dependent values>)) ORDER BY c_0, c_1"},
- TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // 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
- });
-
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,827 @@
+/*
+ * 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;
+
+import static org.junit.Assert.*;
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.junit.Test;
+import org.teiid.metadata.Column;
+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;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.optimizer.relational.rules.RuleChooseDependent;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.relational.AccessNode;
+import org.teiid.query.processor.relational.DependentAccessNode;
+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.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.visitor.GroupCollectorVisitor;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+ at SuppressWarnings("nls")
+public class TestDependentJoins {
+
+ static void checkDependentGroups(ProcessorPlan plan, String[] groups) {
+ if(! (plan instanceof RelationalPlan)) {
+ return;
+ }
+
+ // Collect all the group names (uppercase) for all the dependent groups in the plan
+ Set<String> depGroups = new HashSet<String>();
+ getDependentGroups(((RelationalPlan)plan).getRootNode(), depGroups, true);
+
+ // Check that all the expected groups exist in depGroups
+ Set<String> expectedGroups = new HashSet<String>();
+ for(int i=0; i<groups.length; i++) {
+ expectedGroups.add(groups[i].toUpperCase());
+ }
+
+ assertEquals("Expected groups were not made dependent", expectedGroups, depGroups); //$NON-NLS-1$
+ }
+
+ static void getDependentGroups(RelationalNode node, Set<String> depGroups, boolean depdenent) {
+ if(node instanceof AccessNode) {
+ if (node instanceof DependentAccessNode) {
+ if (!depdenent) {
+ return;
+ }
+ } else if (depdenent) {
+ return;
+ }
+ AccessNode accessNode = (AccessNode)node;
+ Command depCommand = accessNode.getCommand();
+ Collection<GroupSymbol> groupSymbols = GroupCollectorVisitor.getGroups(depCommand, true);
+ for (GroupSymbol groupSymbol : groupSymbols) {
+ depGroups.add(groupSymbol.getName().toUpperCase());
+ }
+ }
+
+ // Recurse through children
+ RelationalNode[] children = node.getChildren();
+ for(int i=0; i<children.length; i++) {
+ if(children[i] != null) {
+ getDependentGroups(node.getChildren()[i], depGroups, depdenent);
+ }
+ }
+ }
+
+ private void checkNotDependentGroups(ProcessorPlan plan, String[] groups) {
+ if(! (plan instanceof RelationalPlan)) {
+ return;
+ }
+
+ // Collect all the group names (uppercase) for all the dependent groups in the plan
+ Set<String> notDepGroups = new HashSet<String>();
+ getDependentGroups(((RelationalPlan)plan).getRootNode(), notDepGroups, false);
+
+ // Check that all the expected groups exist in depGroups
+ Set<String> expectedGroups = new HashSet<String>();
+ for(int i=0; i<groups.length; i++) {
+ expectedGroups.add(groups[i].toUpperCase());
+ }
+
+ assertEquals("Expected groups were made dependent", expectedGroups, notDepGroups); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionMakeDep1() throws Exception {
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ 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", 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$
+ checkNotDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testOptionMakeDep2() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ 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", 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$
+ checkNotDependentGroups(plan, new String[] {"pm2.g1"}); //$NON-NLS-1$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testDepJoinHintForceLeft() throws Exception {
+ ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g1", TestOptimizer.example1(), //$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 pm1.g2 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$
+ }
+
+ @Test public void testDepJoinHintForceRight() throws Exception {
+
+ ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g2", TestOptimizer.example1(), //$NON-NLS-1$
+ 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.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$
+ }
+
+ @Test public void testDepJoinMultiGroupBaseline() throws Exception {
+ ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1", TestOptimizer.example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
+ "SELECT pm1.g2.e1 FROM pm1.g2", //$NON-NLS-1$
+ "SELECT pm1.g3.e1 FROM pm1.g3" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING ); //$NON-NLS-1$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 3, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkDependentGroups(plan, new String[0]);
+ }
+
+ @Test public void testDepJoinMultiGroupForceOther() throws Exception {
+ ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1 option makedep pm1.g2", TestOptimizer.example1(), //$NON-NLS-1$
+ new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", "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.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$
+ }
+
+ @Test public void testDepJoinHintForceLeft_NotDep() throws Exception {
+ ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g1 makenotdep pm1.g2", TestOptimizer.example1(), //$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 pm1.g2 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$
+ checkNotDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$
+ }
+
+ @Test public void testDepJoinHintForceRight_NotDep() throws Exception {
+ ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g2 makenotdep pm1.g1", TestOptimizer.example1(), //$NON-NLS-1$
+ 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.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$
+ checkNotDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$
+ }
+
+ @Test public void testDepJoinMultiGroupForceOther_NotDep() throws Exception {
+ ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1 option makedep pm1.g2 makenotdep pm1.g1, pm1.g3", TestOptimizer.example1(), //$NON-NLS-1$
+ new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", "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.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$
+ checkNotDependentGroups(plan, new String[] {"pm1.g1", "pm1.g3"}); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * 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", 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$
+ }
+
+ /**
+ * Test that access node with unsatisfied access pattern is made dependent
+ * (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", 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$
+ }
+
+ /**
+ * 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", 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$
+ }
+
+ /**
+ * Test that second access pattern of access node is chosen to make
+ * 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", 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$
+ }
+
+ /**
+ * This case actually tests the dead-tie case - either access node could
+ * be made dependent, but merge join is used since no access pattern
+ * 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", 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]);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * This case actually tests the dead-tie case - either access node could
+ * be made dependent, but merge join is used since no access pattern
+ * needs to be fulfilled and there is no cost info available for either source
+ * (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'", 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]);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Tests that it is enforced if an access node can't be made dependent
+ * 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", 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] );
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /** Should use dependent join since one access node is "strong" */
+ @Test public void testUseMergeJoin1() 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$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(10));
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-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$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /** Should not use a dependent join since neither access node is "strong" */
+ @Test public void testUseMergeJoin2() 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$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-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 pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2" }, TestOptimizer.ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /** should have one dependent joins */
+ @Test public void testMultiMergeJoin3() throws Exception {
+ // Create query
+ String sql = "SELECT pm1.g2.e1 FROM pm1.g3, pm1.g2, pm1.g1 WHERE pm1.g2.e1 = pm1.g3.e1 AND pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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,
+ new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g2 AS g_0", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testMultiMergeJoin2() throws Exception {
+ 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$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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 FROM pm1.g3 AS g_0", "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$ //$NON-NLS-3$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Defect 13448
+ * should be one merge join and one dependent join
+ * Unlike the above tests, here the model pm1 supports ORDER BY.
+ */
+ @Test public void testMultiMergeJoin5_defect13448() 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.g1.e1 = pm1.g3.e1";//$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testMergeJoinVirtualGroups() throws Exception {
+ String sql = "SELECT vm1.g1.e1 FROM vm1.g1, vm1.g2a WHERE vm1.g1.e1 = vm1.g2a.e1";//$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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,
+ 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.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$
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testRLMCase2077() throws Exception {
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ caps.setFunctionSupport("||", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT g_0.StringKey FROM BQT1.SmallA AS g_0 WHERE g_0.StringKey IN (<dependent values>)", "SELECT g_0.STRINGKEY, g_0.STRINGNUM, g_0.IntKey FROM BQT2.SmallA AS g_0"}, //$NON-NLS-1$ //$NON-NLS-2$
+ TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ }
+
+ @Test public void testRLMCase2077_2() throws Exception {
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ caps.setFunctionSupport("||", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT g_0.STRINGKEY, g_0.STRINGNUM, g_0.IntKey FROM BQT2.SmallA AS g_0", "SELECT g_0.StringKey, g_0.StringNum FROM BQT1.SmallA AS g_0 WHERE (g_0.StringKey IN (<dependent values>)) AND (g_0.StringNum IN (<dependent values>))"}, //$NON-NLS-1$ //$NON-NLS-2$
+ TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ }
+
+ @Test public void testCostingCleanup() throws Exception {
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ TransformationMetadata metadata = RealMetadataFactory.exampleBQT();
+ RealMetadataFactory.setCardinality("bqt1.smalla", 1000, metadata); //$NON-NLS-1$
+ RealMetadataFactory.setCardinality("bqt2.smalla", 10000, metadata); //$NON-NLS-1$
+ Column fmo = (Column)metadata.getElementID("bqt1.smalla.intnum");
+ fmo.setDistinctValues(1000);
+ Column floatnum = (Column)metadata.getElementID("bqt1.smalla.floatnum");
+ floatnum.setDistinctValues(800);
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(
+ "SELECT max(a.stringkey) from bqt1.smalla a, bqt2.smalla a2, bqt1.smalla a1 where a.intnum = a2.intnum and a1.stringnum = a2.stringnum and a.floatnum = a1.floatnum", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT g_1.stringnum AS c_0, g_0.intnum AS c_1, MAX(g_0.stringkey) AS c_2 FROM bqt1.smalla AS g_0, bqt1.smalla AS g_1 WHERE g_0.floatnum = g_1.floatnum GROUP BY g_1.stringnum, g_0.intnum ORDER BY c_0, c_1", "SELECT DISTINCT g_0.stringnum AS c_0, g_0.intnum AS c_1 FROM bqt2.smalla AS g_0 WHERE (g_0.stringnum IN (<dependent values>)) AND (g_0.intnum IN (<dependent values>)) ORDER BY c_0, c_1"},
+ TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // 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
+ });
+
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,453 +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.optimizer;
-
-import org.junit.Test;
-import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
-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.unittest.FakeMetadataFactory;
-
-
-/**
- * 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.
- */
-public class TestExpressionsInGroupBy {
-
- @Test public void testCase1565() throws Exception {
- // Create query
- String sql = "SELECT x, COUNT(*) FROM (SELECT convert(TimestampValue, date) AS x FROM bqt1.smalla) as y GROUP BY x"; //$NON-NLS-1$
-
- // Create capabilities
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),
- null, capFinder,
- new String[] { "SELECT convert(TimestampValue, date), COUNT(*) FROM bqt1.smalla GROUP BY convert(TimestampValue, date)" }, //$NON-NLS-1$
- true);
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- // Merge across multiple virtual groups - should be same outcome as testCase1565
- @Test public void testCase1565_2() throws Exception {
- // Create query
- 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$
-
- // Create capabilities
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),
- null, capFinder,
- new String[] { "SELECT convert(TimestampValue, date), COUNT(*) FROM bqt1.smalla GROUP BY convert(TimestampValue, date)" }, //$NON-NLS-1$
- true);
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- // Merge across multiple virtual groups above the physical
- @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(),
- null, TestOptimizer.getGenericFinder(),
- new String[] { "SELECT TimestampValue FROM bqt1.smalla" }, //$NON-NLS-1$
- true);
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // 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
- 0 // UnionAll
- });
-
- }
-
- // Test what happens when not all the functions in the virtual SELECT can be pushed
- @Test public void testCase1565_4() throws Exception {
- // Create query
- String sql = "SELECT x, y FROM (SELECT convert(TimestampValue, date) as x, length(stringkey) as y from bqt1.smalla) as z GROUP BY x, y"; //$NON-NLS-1$
-
- // Create capabilities
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),
- null, capFinder,
- new String[] { "SELECT TimestampValue, stringkey FROM bqt1.smalla" }, //$NON-NLS-1$
- true);
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // 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
- 0 // UnionAll
- });
-
- }
-
- // Test nested functions
- @Test public void testCase1565_5() throws Exception {
- // Create query
- String sql = "SELECT x, COUNT(*) FROM (SELECT convert(intkey + 5, string) AS x FROM bqt1.smalla) as y GROUP BY x"; //$NON-NLS-1$
-
- // Create capabilities
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),
- null, capFinder,
- new String[] { "SELECT intkey FROM bqt1.smalla" }, //$NON-NLS-1$
- true);
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // 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
- 0 // UnionAll
- });
-
- }
-
- // 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$
- new String[] { "SELECT IntKey FROM BQT1.SmallA" }); //$NON-NLS-1$
-
- TestOptimizer.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
- });
- }
-
- /**
- * Without inline view support 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$
- "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.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(),
- 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$
- TestOptimizer.SHOULD_SUCCEED );
-
- TestOptimizer.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
- });
- }
-
- /**
- * 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.
- *
- * @since 4.2
- */
- @Test public void testFunctionInGroupByCantPush() {
- 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_AGGREGATES_SUM, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_CASE, false);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, false);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql,
- FakeMetadataFactory.exampleBQTCached(),
- null, capFinder,
- new String[] {"SELECT IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$
- TestOptimizer.SHOULD_SUCCEED );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // 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
- 0 // UnionAll
- });
- }
-
- /**
- * 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.
- *
- * @since 4.2
- */
- @Test public void testFunctionInGroupByHavingCantPush() {
- 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$
- "HAVING case when IntKey>=5000 then '5000 +' else '0-999' end = '5000 +'"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_CASE, false);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, false);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql,
- FakeMetadataFactory.exampleBQTCached(),
- null, capFinder,
- new String[] {"SELECT IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$
- TestOptimizer.SHOULD_SUCCEED );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
- /**
- * 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.
- *
- * @since 4.2
- */
- @Test public void testFunctionInGroupByCantPushRewritten() {
- String sql = "SELECT SUM(IntKey), c FROM (SELECT IntKey, case when IntKey>=5000 then '5000 +' else '0-999' end AS c FROM BQT1.SmallA) AS temp GROUP BY c"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_CASE, false);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, false);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql,
- FakeMetadataFactory.exampleBQTCached(),
- null, capFinder,
- new String[] {"SELECT IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$
- TestOptimizer.SHOULD_SUCCEED );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // 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
- 0 // UnionAll
- });
- }
-
- @Test public void testFunctionOfAggregateCantPush2() {
- String sql = "SELECT SUM(length(StringKey || 'x')) + 1 AS x FROM BQT1.SmallA GROUP BY StringKey || 'x' HAVING space(MAX(length((StringKey || 'x') || 'y'))) = ' '"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql,
- FakeMetadataFactory.exampleBQTCached(),
- null, capFinder,
- new String[] {"SELECT StringKey FROM BQT1.SmallA"}, //$NON-NLS-1$
- TestOptimizer.SHOULD_SUCCEED );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
-
- @Test public void testDontPushGroupByUnsupportedFunction() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = TestOptimizer.helpPlan(
- "SELECT e2 as x FROM pm1.g1 GROUP BY upper(e1), e2", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}, //$NON-NLS-1$
- ComparisonMode.EXACT_COMMAND_STRING );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // 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
- 0 // UnionAll
- });
-
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,453 @@
+/*
+ * 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;
+
+import org.junit.Test;
+import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
+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.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.
+ */
+public class TestExpressionsInGroupBy {
+
+ @Test public void testCase1565() throws Exception {
+ // Create query
+ String sql = "SELECT x, COUNT(*) FROM (SELECT convert(TimestampValue, date) AS x FROM bqt1.smalla) as y GROUP BY x"; //$NON-NLS-1$
+
+ // Create capabilities
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ // Plan query
+ 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$
+ true);
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ // Merge across multiple virtual groups - should be same outcome as testCase1565
+ @Test public void testCase1565_2() throws Exception {
+ // Create query
+ 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$
+
+ // Create capabilities
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ // Plan query
+ 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$
+ true);
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ // Merge across multiple virtual groups above the physical
+ @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, RealMetadataFactory.exampleBQTCached(),
+ null, TestOptimizer.getGenericFinder(),
+ new String[] { "SELECT TimestampValue FROM bqt1.smalla" }, //$NON-NLS-1$
+ true);
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // 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
+ 0 // UnionAll
+ });
+
+ }
+
+ // Test what happens when not all the functions in the virtual SELECT can be pushed
+ @Test public void testCase1565_4() throws Exception {
+ // Create query
+ String sql = "SELECT x, y FROM (SELECT convert(TimestampValue, date) as x, length(stringkey) as y from bqt1.smalla) as z GROUP BY x, y"; //$NON-NLS-1$
+
+ // Create capabilities
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+
+ // Plan query
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] { "SELECT TimestampValue, stringkey FROM bqt1.smalla" }, //$NON-NLS-1$
+ true);
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // 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
+ 0 // UnionAll
+ });
+
+ }
+
+ // Test nested functions
+ @Test public void testCase1565_5() throws Exception {
+ // Create query
+ String sql = "SELECT x, COUNT(*) FROM (SELECT convert(intkey + 5, string) AS x FROM bqt1.smalla) as y GROUP BY x"; //$NON-NLS-1$
+
+ // Create capabilities
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ // Plan query
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] { "SELECT intkey FROM bqt1.smalla" }, //$NON-NLS-1$
+ true);
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // 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
+ 0 // UnionAll
+ });
+
+ }
+
+ // 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", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+ new String[] { "SELECT IntKey FROM BQT1.SmallA" }); //$NON-NLS-1$
+
+ TestOptimizer.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
+ });
+ }
+
+ /**
+ * Without inline view support 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$
+ "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.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 CASE WHEN BQT1.SmallA.IntKey >= 5000 THEN '5000 +' ELSE '0-999' END, BQT1.SmallA.IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$
+ TestOptimizer.SHOULD_SUCCEED );
+
+ TestOptimizer.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
+ });
+ }
+
+ /**
+ * 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.
+ *
+ * @since 4.2
+ */
+ @Test public void testFunctionInGroupByCantPush() {
+ 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_AGGREGATES_SUM, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_CASE, false);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, false);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql,
+ RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] {"SELECT IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$
+ TestOptimizer.SHOULD_SUCCEED );
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // 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
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * 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.
+ *
+ * @since 4.2
+ */
+ @Test public void testFunctionInGroupByHavingCantPush() {
+ 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$
+ "HAVING case when IntKey>=5000 then '5000 +' else '0-999' end = '5000 +'"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_CASE, false);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, false);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql,
+ RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] {"SELECT IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$
+ TestOptimizer.SHOULD_SUCCEED );
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+ /**
+ * 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.
+ *
+ * @since 4.2
+ */
+ @Test public void testFunctionInGroupByCantPushRewritten() {
+ String sql = "SELECT SUM(IntKey), c FROM (SELECT IntKey, case when IntKey>=5000 then '5000 +' else '0-999' end AS c FROM BQT1.SmallA) AS temp GROUP BY c"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_CASE, false);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, false);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql,
+ RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] {"SELECT IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$
+ TestOptimizer.SHOULD_SUCCEED );
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // 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
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testFunctionOfAggregateCantPush2() {
+ String sql = "SELECT SUM(length(StringKey || 'x')) + 1 AS x FROM BQT1.SmallA GROUP BY StringKey || 'x' HAVING space(MAX(length((StringKey || 'x') || 'y'))) = ' '"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql,
+ RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] {"SELECT StringKey FROM BQT1.SmallA"}, //$NON-NLS-1$
+ TestOptimizer.SHOULD_SUCCEED );
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+
+ @Test public void testDontPushGroupByUnsupportedFunction() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(
+ "SELECT e2 as x FROM pm1.g1 GROUP BY upper(e1), e2", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}, //$NON-NLS-1$
+ ComparisonMode.EXACT_COMMAND_STRING );
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // 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
+ 0 // UnionAll
+ });
+
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,303 +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.optimizer;
-
-import static org.teiid.query.optimizer.TestOptimizer.*;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.junit.Test;
-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.FakeCapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
-
-public class TestInlineView {
-
- public static FakeCapabilitiesFinder getInliveViewCapabilitiesFinder() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- caps.setFunctionSupport("case", true); //$NON-NLS-1$
- caps.setFunctionSupport("+", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- return capFinder;
- }
-
- @Test public void testANSIJoinInlineView() throws Exception {
- runTest(createANSIJoinInlineView());
- }
-
- @Test public void testInlineView() throws Exception {
- runTest(createInlineView());
- }
-
- @Test public void testInlineViewWithDistinctAndOrderBy() throws Exception {
- runTest(createInlineViewWithDistinctAndOrderBy());
- }
-
- @Test public void testInlineViewOfVirtual() throws Exception{
- runTest(createInlineViewOfVirtual());
- }
-
- @Test public void testInlineViewWithOuterOrderAndGroup() throws Exception {
- runTest(createInlineViewWithOuterOrderAndGroup());
- }
-
- @Test public void testInlineViewsInUnions() throws Exception {
- runTest(crateInlineViewsInUnions());
- }
-
- @Test public void testUnionInInlineView() throws Exception{
- runTest(createUnionInInlineView());
- }
-
- public static InlineViewCase createANSIJoinInlineView() 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"; //$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);
-
- Set<String> sourceQueries = new HashSet<String>();
- sourceQueries.add("oracle"); //$NON-NLS-1$
- sourceQueries.add("db2"); //$NON-NLS-1$
- sourceQueries.add("sybase"); //$NON-NLS-1$
- sourceQueries.add("sqlserver"); //$NON-NLS-1$
- sourceQueries.add("mysql"); //$NON-NLS-1$
- sourceQueries.add("postgres"); //$NON-NLS-1$
- return new InlineViewCase("testANSIJoinInlineView", userQuery, optimizedQuery, //$NON-NLS-1$
- sourceQueries, expectedResults);
-
- }
-
- public static InlineViewCase createInlineView() throws Exception {
- String userQuery = "select bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa from (select count(bqt1.smalla.intkey) as aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bqt1.smalla.intkey from bqt1.smalla group by bqt1.smalla.intkey) bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, bqt1.smallb " + //$NON-NLS-1$
- "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);
-
- Set<String> sourceQueries = new HashSet<String>();
- sourceQueries.add("oracle"); //$NON-NLS-1$
- sourceQueries.add("db2"); //$NON-NLS-1$
- sourceQueries.add("sybase"); //$NON-NLS-1$
- sourceQueries.add("sqlserver"); //$NON-NLS-1$
- sourceQueries.add("mysql"); //$NON-NLS-1$
- sourceQueries.add("postgres"); //$NON-NLS-1$
- return new InlineViewCase("testInlineView", userQuery, optimizedQuery, //$NON-NLS-1$
- sourceQueries, expectedResults);
- }
-
- 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$
-
- List expectedResults = new ArrayList();
- List row1 = new ArrayList();
- row1.add(new Integer(1));
- expectedResults.add(row1);
-
- Set<String> sourceQueries = new HashSet<String>();
- sourceQueries.add("oracle"); //$NON-NLS-1$
- sourceQueries.add("db2"); //$NON-NLS-1$
- sourceQueries.add("sybase"); //$NON-NLS-1$
- sourceQueries.add("sqlserver"); //$NON-NLS-1$
- sourceQueries.add("mysql"); //$NON-NLS-1$
- sourceQueries.add("postgres"); //$NON-NLS-1$
- return new InlineViewCase("testInlineViewWithDistinctAndOrderBy", userQuery, optimizedQuery, //$NON-NLS-1$
- sourceQueries, expectedResults);
-
- }
-
- public static InlineViewCase createInlineViewOfVirtual() throws Exception{
- 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();
-
- Set<String> sourceQueries = new HashSet<String>();
- sourceQueries.add("oracle"); //$NON-NLS-1$
- sourceQueries.add("db2"); //$NON-NLS-1$
- sourceQueries.add("sybase"); //$NON-NLS-1$
- sourceQueries.add("sqlserver"); //$NON-NLS-1$
- sourceQueries.add("mysql"); //$NON-NLS-1$
- sourceQueries.add("postgres"); //$NON-NLS-1$
- return new InlineViewCase("testInlineViewOfVirtual", userQuery, optimizedQuery, //$NON-NLS-1$
- sourceQueries, expectedResults);
- }
-
- 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$
-
- List expectedResults = new ArrayList();
- List row1 = new ArrayList();
- row1.add(new Integer(1));
- expectedResults.add(row1);
-
- Set<String> sourceQueries = new HashSet<String>();
- sourceQueries.add("oracle"); //$NON-NLS-1$
- sourceQueries.add("db2"); //$NON-NLS-1$
- sourceQueries.add("sybase"); //$NON-NLS-1$
- sourceQueries.add("sqlserver"); //$NON-NLS-1$
- sourceQueries.add("mysql"); //$NON-NLS-1$
- sourceQueries.add("postgres"); //$NON-NLS-1$
- return new InlineViewCase("testInlineViewWithOuterOrderAndGroup", userQuery, optimizedQuery, //$NON-NLS-1$
- sourceQueries, expectedResults);
- }
-
- 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$
-
- 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);
-
- Set<String> sourceQueries = new HashSet<String>();
- sourceQueries.add("oracle"); //$NON-NLS-1$
- sourceQueries.add("db2"); //$NON-NLS-1$
- sourceQueries.add("sybase"); //$NON-NLS-1$
- sourceQueries.add("sqlserver"); //$NON-NLS-1$
- sourceQueries.add("mysql"); //$NON-NLS-1$
- sourceQueries.add("postgres"); //$NON-NLS-1$
- return new InlineViewCase("testInlineViewsInUnions", userQuery, optimizedQuery, //$NON-NLS-1$
- sourceQueries, expectedResults);
-
- }
-
- 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$
-
- 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);
-
- Set<String> sourceQueries = new HashSet<String>();
- sourceQueries.add("oracle"); //$NON-NLS-1$
- /*
- * fails in db2 since the intkey column is in the database as a decimal
- */
- //sourceQueries.add("db2"); //$NON-NLS-1$
- sourceQueries.add("sybase"); //$NON-NLS-1$
- sourceQueries.add("sqlserver"); //$NON-NLS-1$
- sourceQueries.add("mysql"); //$NON-NLS-1$
- sourceQueries.add("postgres"); //$NON-NLS-1$
- return new InlineViewCase("testUnionInInlineView", userQuery, optimizedQuery, //$NON-NLS-1$
- sourceQueries, expectedResults);
-
- }
-
- protected void runTest(InlineViewCase testCase) throws Exception {
- FakeCapabilitiesFinder capFinder = getInliveViewCapabilitiesFinder();
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = TestOptimizer.helpPlan(testCase.userQuery, metadata, null, capFinder, new String[] {testCase.optimizedQuery}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testAliasCreationWithInlineView() {
- FakeCapabilitiesFinder capFinder = getInliveViewCapabilitiesFinder();
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testAliasPreservationWithInlineView() {
- FakeCapabilitiesFinder capFinder = getInliveViewCapabilitiesFinder();
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * Order by's will be added to the atomic queries
- */
- @Test public void testCrossSourceInlineView() throws Exception {
- FakeCapabilitiesFinder capFinder = getInliveViewCapabilitiesFinder();
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
- "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 bqt1.smalla AS g_0 GROUP BY g_0.intkey HAVING COUNT(g_0.intkey) = 1) AS v_0 ORDER BY c_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,303 @@
+/*
+ * 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;
+
+import static org.teiid.query.optimizer.TestOptimizer.*;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Test;
+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.FakeCapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+
+public class TestInlineView {
+
+ public static FakeCapabilitiesFinder getInliveViewCapabilitiesFinder() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ caps.setFunctionSupport("case", true); //$NON-NLS-1$
+ caps.setFunctionSupport("+", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ return capFinder;
+ }
+
+ @Test public void testANSIJoinInlineView() throws Exception {
+ runTest(createANSIJoinInlineView());
+ }
+
+ @Test public void testInlineView() throws Exception {
+ runTest(createInlineView());
+ }
+
+ @Test public void testInlineViewWithDistinctAndOrderBy() throws Exception {
+ runTest(createInlineViewWithDistinctAndOrderBy());
+ }
+
+ @Test public void testInlineViewOfVirtual() throws Exception{
+ runTest(createInlineViewOfVirtual());
+ }
+
+ @Test public void testInlineViewWithOuterOrderAndGroup() throws Exception {
+ runTest(createInlineViewWithOuterOrderAndGroup());
+ }
+
+ @Test public void testInlineViewsInUnions() throws Exception {
+ runTest(crateInlineViewsInUnions());
+ }
+
+ @Test public void testUnionInInlineView() throws Exception{
+ runTest(createUnionInInlineView());
+ }
+
+ public static InlineViewCase createANSIJoinInlineView() 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"; //$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);
+
+ Set<String> sourceQueries = new HashSet<String>();
+ sourceQueries.add("oracle"); //$NON-NLS-1$
+ sourceQueries.add("db2"); //$NON-NLS-1$
+ sourceQueries.add("sybase"); //$NON-NLS-1$
+ sourceQueries.add("sqlserver"); //$NON-NLS-1$
+ sourceQueries.add("mysql"); //$NON-NLS-1$
+ sourceQueries.add("postgres"); //$NON-NLS-1$
+ return new InlineViewCase("testANSIJoinInlineView", userQuery, optimizedQuery, //$NON-NLS-1$
+ sourceQueries, expectedResults);
+
+ }
+
+ public static InlineViewCase createInlineView() throws Exception {
+ String userQuery = "select bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa from (select count(bqt1.smalla.intkey) as aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bqt1.smalla.intkey from bqt1.smalla group by bqt1.smalla.intkey) bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, bqt1.smallb " + //$NON-NLS-1$
+ "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);
+
+ Set<String> sourceQueries = new HashSet<String>();
+ sourceQueries.add("oracle"); //$NON-NLS-1$
+ sourceQueries.add("db2"); //$NON-NLS-1$
+ sourceQueries.add("sybase"); //$NON-NLS-1$
+ sourceQueries.add("sqlserver"); //$NON-NLS-1$
+ sourceQueries.add("mysql"); //$NON-NLS-1$
+ sourceQueries.add("postgres"); //$NON-NLS-1$
+ return new InlineViewCase("testInlineView", userQuery, optimizedQuery, //$NON-NLS-1$
+ sourceQueries, expectedResults);
+ }
+
+ 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$
+
+ List expectedResults = new ArrayList();
+ List row1 = new ArrayList();
+ row1.add(new Integer(1));
+ expectedResults.add(row1);
+
+ Set<String> sourceQueries = new HashSet<String>();
+ sourceQueries.add("oracle"); //$NON-NLS-1$
+ sourceQueries.add("db2"); //$NON-NLS-1$
+ sourceQueries.add("sybase"); //$NON-NLS-1$
+ sourceQueries.add("sqlserver"); //$NON-NLS-1$
+ sourceQueries.add("mysql"); //$NON-NLS-1$
+ sourceQueries.add("postgres"); //$NON-NLS-1$
+ return new InlineViewCase("testInlineViewWithDistinctAndOrderBy", userQuery, optimizedQuery, //$NON-NLS-1$
+ sourceQueries, expectedResults);
+
+ }
+
+ public static InlineViewCase createInlineViewOfVirtual() throws Exception{
+ 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();
+
+ Set<String> sourceQueries = new HashSet<String>();
+ sourceQueries.add("oracle"); //$NON-NLS-1$
+ sourceQueries.add("db2"); //$NON-NLS-1$
+ sourceQueries.add("sybase"); //$NON-NLS-1$
+ sourceQueries.add("sqlserver"); //$NON-NLS-1$
+ sourceQueries.add("mysql"); //$NON-NLS-1$
+ sourceQueries.add("postgres"); //$NON-NLS-1$
+ return new InlineViewCase("testInlineViewOfVirtual", userQuery, optimizedQuery, //$NON-NLS-1$
+ sourceQueries, expectedResults);
+ }
+
+ 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$
+
+ List expectedResults = new ArrayList();
+ List row1 = new ArrayList();
+ row1.add(new Integer(1));
+ expectedResults.add(row1);
+
+ Set<String> sourceQueries = new HashSet<String>();
+ sourceQueries.add("oracle"); //$NON-NLS-1$
+ sourceQueries.add("db2"); //$NON-NLS-1$
+ sourceQueries.add("sybase"); //$NON-NLS-1$
+ sourceQueries.add("sqlserver"); //$NON-NLS-1$
+ sourceQueries.add("mysql"); //$NON-NLS-1$
+ sourceQueries.add("postgres"); //$NON-NLS-1$
+ return new InlineViewCase("testInlineViewWithOuterOrderAndGroup", userQuery, optimizedQuery, //$NON-NLS-1$
+ sourceQueries, expectedResults);
+ }
+
+ 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$
+
+ 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);
+
+ Set<String> sourceQueries = new HashSet<String>();
+ sourceQueries.add("oracle"); //$NON-NLS-1$
+ sourceQueries.add("db2"); //$NON-NLS-1$
+ sourceQueries.add("sybase"); //$NON-NLS-1$
+ sourceQueries.add("sqlserver"); //$NON-NLS-1$
+ sourceQueries.add("mysql"); //$NON-NLS-1$
+ sourceQueries.add("postgres"); //$NON-NLS-1$
+ return new InlineViewCase("testInlineViewsInUnions", userQuery, optimizedQuery, //$NON-NLS-1$
+ sourceQueries, expectedResults);
+
+ }
+
+ 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$
+
+ 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);
+
+ Set<String> sourceQueries = new HashSet<String>();
+ sourceQueries.add("oracle"); //$NON-NLS-1$
+ /*
+ * fails in db2 since the intkey column is in the database as a decimal
+ */
+ //sourceQueries.add("db2"); //$NON-NLS-1$
+ sourceQueries.add("sybase"); //$NON-NLS-1$
+ sourceQueries.add("sqlserver"); //$NON-NLS-1$
+ sourceQueries.add("mysql"); //$NON-NLS-1$
+ sourceQueries.add("postgres"); //$NON-NLS-1$
+ return new InlineViewCase("testUnionInInlineView", userQuery, optimizedQuery, //$NON-NLS-1$
+ sourceQueries, expectedResults);
+
+ }
+
+ protected void runTest(InlineViewCase testCase) throws Exception {
+ FakeCapabilitiesFinder capFinder = getInliveViewCapabilitiesFinder();
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(testCase.userQuery, metadata, null, capFinder, new String[] {testCase.optimizedQuery}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testAliasCreationWithInlineView() {
+ FakeCapabilitiesFinder capFinder = getInliveViewCapabilitiesFinder();
+ 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$
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testAliasPreservationWithInlineView() {
+ FakeCapabilitiesFinder capFinder = getInliveViewCapabilitiesFinder();
+ 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$
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /**
+ * Order by's will be added to the atomic queries
+ */
+ @Test public void testCrossSourceInlineView() throws Exception {
+ FakeCapabilitiesFinder capFinder = getInliveViewCapabilitiesFinder();
+ 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$
+ "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 bqt1.smalla AS g_0 GROUP BY g_0.intkey HAVING COUNT(g_0.intkey) = 1) AS v_0 ORDER BY c_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1031 +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.optimizer;
-
-import static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.List;
-
-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.core.TeiidComponentException;
-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.FakeCapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.optimizer.relational.rules.JoinUtil;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.resolver.util.ResolverVisitor;
-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.translator.SourceSystemFunctions;
-
- at SuppressWarnings("nls")
-public class TestJoinOptimization {
-
- /**
- * Single group criteria should get pushed and be eligible for copy criteria
- */
- @Test public void testInnerJoinPushAndCopyNonJoinCriteria() {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Single group criteria should get pushed when it is on the inner side
- */
- @Test public void testOuterJoinPushNonJoinCriteria() {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Single group criteria should not be pushed when it is on the outer side
- */
- @Test public void testOuterJoinPushNonJoinCriteriaA() {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testOuterJoinPushNonJoinCriteria_Case5547() {
- String sql = "select bqt1.smalla.intkey from bqt1.smalla left outer join bqt2.smalla on (1=1)"; //$NON-NLS-1$
- String BQT1 = "BQT1"; //$NON-NLS-1$
- String BQT2 = "BQT2"; //$NON-NLS-1$
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
-
- // === Must set the ORDER BY prop on the capabilities object to TRUE
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- capFinder.addCapabilities(BQT1, caps);
- capFinder.addCapabilities(BQT2, caps);
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql,
- metadata,
- null,
- capFinder,
- new String[] {"SELECT bqt1.smalla.intkey FROM bqt1.smalla", "SELECT 1 FROM bqt2.smalla"}, true ); //$NON-NLS-1$ //$NON-NLS-2$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- }
-
-
- /**
- * Single group criteria should not be pushed when it is used in a full outer join
- * Note that the join has also degraded into a cross join rather than an outer join
- */
- @Test public void testFullOuterJoinPushNonJoinCriteria() {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Copy criteria should still work here even though the join criteria has an implicit type conversion because
- * the equality operation on the select criteria can be used.
- */
- @Test public void testCopyCriteriaWithFunction1() {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Copy criteria should not work here as the join criteria has an implicit convert and the where criteria is a non-equality predicate
- */
- @Test public void testCopyCriteriaWithFunction2() {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * The intkey criteria should not be copied above to bqt1.smalla since the criteria is coming from the inner side in the join below
- */
- @Test public void testInvalidCopyCriteria() {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 3, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /*
- * Note that the criteria does not get copied to the outer side.
- */
- @Test public void testCopyCriteriaFromInnerSide() throws Exception {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Check to ensure that the full outer join does not get merged since the where criteria cannot be moved
- */
- @Test public void testFullOuterJoinPreservation() {
- 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(),
- 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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Same as above but with a 0 group criteria
- */
- @Test public void testFullOuterJoinPreservation1() {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Same as above but with a left outer join
- */
- @Test public void testOuterJoinPreservation() {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testCopyCriteriaCreatesFalseCriteria() {
- 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[] {});
-
- TestOptimizer.checkNodeTypes(plan, TestRuleRaiseNull.FULLY_NULL);
- }
-
- @Test public void testPushNonJoinCriteriaWithFalse() {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testPushMultiGroupJoinCriteria() throws Exception {
- String sql = "select bqt1.smalla.intkey, bqt1.smallb.intkey from bqt1.smalla right outer join (bqt1.smallb cross join (bqt1.mediuma cross join bqt1.mediumb)) on bqt1.smalla.stringkey = bqt1.smallb.stringkey" //$NON-NLS-1$
- +" where bqt1.smallb.intkey + bqt1.mediuma.intkey + bqt1.mediumb.intkey = 1"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setFunctionSupport("+", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.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);
- }
-
- /**
- * Since the multigroup criteria spans the inner side, it should not be pushed.
- */
- @Test public void testPushMultiGroupJoinCriteria1() {
- String sql = "select bqt1.smalla.intkey, bqt1.smallb.intkey from bqt1.smalla right outer join (bqt1.smallb cross join (bqt1.mediuma cross join bqt1.mediumb)) on bqt1.smalla.stringkey = bqt1.smallb.stringkey" //$NON-NLS-1$
- +" where bqt1.smalla.intkey + bqt1.mediuma.intkey + bqt1.mediumb.intkey is null"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setFunctionSupport("+", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.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);
- }
-
- /**
- * Since the multigroup criteria is not null dependent, it should get pushed.
- */
- @Test public void testPushMultiGroupJoinCriteria2() {
- String sql = "select bqt1.smalla.intkey, bqt1.smallb.intkey from bqt1.smalla right outer join (bqt1.smallb cross join (bqt1.mediuma cross join bqt1.mediumb)) on bqt1.smalla.stringkey = bqt1.smallb.stringkey" //$NON-NLS-1$
- +" where bqt1.smalla.intkey + bqt1.mediuma.intkey + bqt1.mediumb.intkey = 1"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setFunctionSupport("+", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.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);
- }
-
-
- /**
- * Having criteria should not be considered as regular criteria (unless it contains no aggregate expressions).
- */
- @Test public void testHavingCriteriaNotUsedAsJoinCriteria() {
- String sql = "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"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_HAVING, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.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);
- }
-
- /**
- * Ensure that subqueries not initially pushable to the source still get replaced
- */
- @Test public void testSubqueryReplacement() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testRulePushNonJoinCriteriaPreservesOuterJoin() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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,
- new String[]{"SELECT g_1.intkey FROM bqt1.smalla AS g_0 LEFT OUTER JOIN bqt1.smallb AS g_1 ON 1 = 1"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testOuterToInnerJoinConversion() {
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
- }
-
- //same as above, but with a right outer join
- @Test public void testOuterToInnerJoinConversion1() {
- QueryMetadataInterface metadata = FakeMetadataFactory.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();
- 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();
- 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$
- }
-
- /**
- * non-dependent criteria on each side of a full outer creates an inner join
- */
- @Test public void testOuterToInnerJoinConversion4() {
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
- }
-
- /**
- * Since concat2 is null dependent the join will not be changed
- */
- @Test public void testOuterToInnerJoinConversionNullDependent() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setFunctionSupport("concat2", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
- }
-
- @Test public void testInlineViewToHaving() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_HAVING, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- 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,
- 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);
- }
-
- /**
- * <p>In RuleBreakMultiJoin terminology:
- * If any of the regions contains a group with any unsatisfied access patterns, one
- * of those access patterns could be satisfied by arranging for a dependent join,
- * provided that group has join criteria which covers the column(s) in an access
- * pattern, and which joins the group to group(s) in other region(s). The task, then,
- * is to ensure that an ordering isn't picked which makes such a dependent join
- * impossible.</p>
- *
- * <p>A physical group can have zero or more access patterns; each access pattern can have one
- * or more columns. So a group could implicitly be dependent on one or more other physical
- * groups in one or more other regions. A table can be used to illustrate the potential
- * complexity of access patterns:
- * <pre>
- * Region with | Target
- * Access Patterns| Regions
- * -------------------------
- * Reg3 | Reg1, Reg2
- * Reg3 | Reg4
- * Reg1 | Reg2
- * Reg4 | Reg3
- * </pre></p>
- *
- * This tests now passes with RulePlanJoins
- */
- @Test public void testPathologicalAccessPatternCaseCase2976Defect19018() throws Exception{
- FakeMetadataFacade metadata = FakeMetadataFactory.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);
-
- 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$
- "pm1.g1.e1 = pm4.g1.e1 AND pm2.g1.e2 = pm4.g1.e2 AND pm1.g1.e4 = pm2.g1.e4 " +//$NON-NLS-1$
- "AND pm4.g1.e4 = 3.2";//$NON-NLS-1$
-
- String[] expected = new String[] {"SELECT g_0.e4 AS c_0, g_0.e1 AS c_1 FROM pm1.g1 AS g_0 ORDER BY c_0", //$NON-NLS-1$
- "SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm4.g1 AS g_0 WHERE (g_0.e4 = 3.2) AND (g_0.e1 IN (<dependent values>)) AND (g_0.e2 IN (<dependent values>)) ORDER BY c_0, c_1", //$NON-NLS-1$
- "SELECT g_0.e4 AS c_0, g_0.e2 AS c_1, g_0.e1 AS c_2 FROM pm2.g1 AS g_0 ORDER BY c_0",//$NON-NLS-1$
- };
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, expected, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * non-null dependent criteria should get pushed down
- */
- @Test public void testPushMultiGroupCriteriaOuterJoin() {
- String sql = "select m.intkey, m.intnum, s.intkey, s.intnum from BQT2.mediuma m left outer join BQT2.smalla s on m.intkey = s.intkey where not (m.intkey + s.intnum = 26)"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport("+", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.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$
- TestOptimizer.SHOULD_SUCCEED);
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
-
- }
-
- /**
- * Assumes that pm1.g1 is the only inner group
- */
- private void helpTestNullDependentVisitor(String critSQL,
- boolean dependent) throws QueryParserException,
- QueryResolverException,
- QueryMetadataException,
- TeiidComponentException {
- List<GroupSymbol> innerGroups = new ArrayList<GroupSymbol>();
- innerGroups.add(new GroupSymbol("pm1.g1")); //$NON-NLS-1$
-
- Criteria crit = QueryParser.getQueryParser().parseCriteria(critSQL);
-
- QueryResolver.resolveCriteria(crit, FakeMetadataFactory.example1Cached());
-
- assertEquals(dependent, JoinUtil.isNullDependent(FakeMetadataFactory.example1Cached(), innerGroups, crit));
- }
-
- private void helpTestNullDependent(String expressionSQL,
- boolean dependent) throws QueryParserException,
- QueryResolverException,
- QueryMetadataException,
- TeiidComponentException {
- List<GroupSymbol> innerGroups = new ArrayList<GroupSymbol>();
- innerGroups.add(new GroupSymbol("pm1.g1")); //$NON-NLS-1$
-
- Expression expr = QueryParser.getQueryParser().parseExpression(expressionSQL);
-
- ResolverVisitor.resolveLanguageObject(expr, FakeMetadataFactory.example1Cached());
-
- assertEquals(dependent, JoinUtil.isNullDependent(FakeMetadataFactory.example1Cached(), innerGroups, expr));
- }
-
- @Test public void testNullDependentVisitor() throws Exception {
- helpTestNullDependentVisitor("nvl(pm1.g1.e1, 1) = 1", true); //$NON-NLS-1$
- }
-
- @Test public void testNullDependentVisitor1() throws Exception {
- helpTestNullDependentVisitor("ifnull(pm1.g1.e1, 1) = 1", true); //$NON-NLS-1$
- }
-
- @Test public void testNullDependentVisitor2() throws Exception {
- helpTestNullDependentVisitor("rand(pm1.g1.e2) = 1", true); //$NON-NLS-1$
- }
-
- @Test public void testNullDependentVisitor3() throws Exception {
- helpTestNullDependentVisitor("concat2(pm1.g1.e1, pm1.g1.e2) = '1'", false); //$NON-NLS-1$
- }
-
- @Test public void testNullDependentVisitor4() throws Exception {
- helpTestNullDependentVisitor("nvl(pm1.g2.e1, 1) = 1", true); //$NON-NLS-1$
- }
-
- @Test public void testNullDependentVisitor5() throws Exception {
- helpTestNullDependentVisitor("pm1.g1.e1 is null", true); //$NON-NLS-1$
- }
-
- @Test public void testNullDependentVisitor6() throws Exception {
- helpTestNullDependentVisitor("pm1.g1.e1 is not null", false); //$NON-NLS-1$
- }
-
- @Test public void testNullDependentVisitor7() throws Exception {
- helpTestNullDependentVisitor("pm1.g2.e1 is not null", true); //$NON-NLS-1$
- }
-
- //this is an important test, the or causes this criteria to be null dependent
- @Test public void testNullDependentVisitor8() throws Exception {
- helpTestNullDependentVisitor("pm1.g1.e1 = 1 or pm1.g2.e1 = 1", true); //$NON-NLS-1$
- }
-
- @Test public void testNullDependentVisitor9() throws Exception {
- helpTestNullDependentVisitor("pm1.g1.e1 = 1 or pm1.g1.e2 = 2", false); //$NON-NLS-1$
- }
-
- @Test public void testNullDependentVisitor10() throws Exception {
- helpTestNullDependentVisitor("pm1.g1.e1 in (1, pm1.g2.e1)", false); //$NON-NLS-1$
- }
-
- @Test public void testNullDependentVisitor11() throws Exception {
- helpTestNullDependentVisitor("pm1.g2.e1 in (1, pm1.g1.e1)", true); //$NON-NLS-1$
- }
-
- @Test public void testIsNullDependent() throws Exception {
- helpTestNullDependent("pm1.g1.e2 + 1", false); //$NON-NLS-1$
- }
-
- @Test public void testIsNullDependent1() throws Exception {
- helpTestNullDependent("pm1.g2.e2 + 1", true); //$NON-NLS-1$
- }
-
- /**
- * The criteria will still get pushed to appropriate location, and
- * the other side of the join will be removed
- */
- @Test public void testCriteriaPushedWithUnionJoin() throws Exception {
- String sql = "select * from pm1.g1 union join pm1.g2 where g1.e1 = 1"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.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$
- TestOptimizer.SHOULD_SUCCEED);
-
- TestOptimizer.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
- });
-
- }
-
- /**
- * union joins allow RuleRemoveVirtual to still take effect
- */
- @Test public void testCriteriaPushedWithUnionJoin1() throws Exception {
- String sql = "select vm1.g1.e1 from vm1.g1 union join vm1.g2 where g2.e1 = 1"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
- null, capFinder,
- new String[] {
- "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 = '1') AND (g_1.e1 = '1')" }, //$NON-NLS-1$
- ComparisonMode.EXACT_COMMAND_STRING);
-
- TestOptimizer.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
- });
-
- }
-
- /**
- * null-dependent expressions should prevent merging of virtual layers
- */
- @Test public void testNullDependentPreventsMerge() throws Exception {
- String sql = "select x from pm1.g1 left outer join (select nvl(e2, 1) x from pm1.g2) y on e2 = x"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- caps.setFunctionSupport(SourceSystemFunctions.IFNULL, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
- null, capFinder,
- new String[] {
- "SELECT v_0.c_0 FROM pm1.g1 AS g_0 LEFT OUTER JOIN (SELECT ifnull(g_1.e2, 1) AS c_0 FROM pm1.g2 AS g_1) AS v_0 ON g_0.e2 = v_0.c_0" }, //$NON-NLS-1$
- TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
-
- }
-
- /**
- * RuleCopyCriteria will remove the first join criteria and the source doesn't support the * function. However we still
- * want the join to be pushed since it originally contained proper criteria.
- */
- @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();
-
- 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$
-
- TestOptimizer.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 for Case 836073:
- */
- @Test public void testForCase836073_1() {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testForCase836073_2() {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Note that we don't allow pushdown here because the criteria placement matters
- */
- @Test public void testForCase836073_3() {
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testTransitiveJoinCondition() {
- 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[] {
- "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"});
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1030 @@
+/*
+ * 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;
+
+import static org.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.List;
+
+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.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;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.optimizer.relational.rules.JoinUtil;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.resolver.util.ResolverVisitor;
+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.RealMetadataFactory;
+import org.teiid.translator.SourceSystemFunctions;
+
+ at SuppressWarnings("nls")
+public class TestJoinOptimization {
+
+ /**
+ * Single group criteria should get pushed and be eligible for copy criteria
+ */
+ @Test public void testInnerJoinPushAndCopyNonJoinCriteria() {
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Single group criteria should get pushed when it is on the inner side
+ */
+ @Test public void testOuterJoinPushNonJoinCriteria() {
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Single group criteria should not be pushed when it is on the outer side
+ */
+ @Test public void testOuterJoinPushNonJoinCriteriaA() {
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testOuterJoinPushNonJoinCriteria_Case5547() {
+ String sql = "select bqt1.smalla.intkey from bqt1.smalla left outer join bqt2.smalla on (1=1)"; //$NON-NLS-1$
+ String BQT1 = "BQT1"; //$NON-NLS-1$
+ String BQT2 = "BQT2"; //$NON-NLS-1$
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+
+ // === Must set the ORDER BY prop on the capabilities object to TRUE
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities(BQT1, caps);
+ capFinder.addCapabilities(BQT2, caps);
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ // Plan query
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql,
+ metadata,
+ null,
+ capFinder,
+ new String[] {"SELECT bqt1.smalla.intkey FROM bqt1.smalla", "SELECT 1 FROM bqt2.smalla"}, true ); //$NON-NLS-1$ //$NON-NLS-2$
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ }
+
+
+ /**
+ * Single group criteria should not be pushed when it is used in a full outer join
+ * Note that the join has also degraded into a cross join rather than an outer join
+ */
+ @Test public void testFullOuterJoinPushNonJoinCriteria() {
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Copy criteria should still work here even though the join criteria has an implicit type conversion because
+ * the equality operation on the select criteria can be used.
+ */
+ @Test public void testCopyCriteriaWithFunction1() {
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Copy criteria should not work here as the join criteria has an implicit convert and the where criteria is a non-equality predicate
+ */
+ @Test public void testCopyCriteriaWithFunction2() {
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * The intkey criteria should not be copied above to bqt1.smalla since the criteria is coming from the inner side in the join below
+ */
+ @Test public void testInvalidCopyCriteria() {
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /*
+ * Note that the criteria does not get copied to the outer side.
+ */
+ @Test public void testCopyCriteriaFromInnerSide() throws Exception {
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Check to ensure that the full outer join does not get merged since the where criteria cannot be moved
+ */
+ @Test public void testFullOuterJoinPreservation() {
+ 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, 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Same as above but with a 0 group criteria
+ */
+ @Test public void testFullOuterJoinPreservation1() {
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Same as above but with a left outer join
+ */
+ @Test public void testOuterJoinPreservation() {
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testCopyCriteriaCreatesFalseCriteria() {
+ 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, RealMetadataFactory.exampleBQTCached(), new String[] {});
+
+ TestOptimizer.checkNodeTypes(plan, TestRuleRaiseNull.FULLY_NULL);
+ }
+
+ @Test public void testPushNonJoinCriteriaWithFalse() {
+ 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, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT bqt1.smalla.intkey FROM bqt1.smalla"}); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushMultiGroupJoinCriteria() throws Exception {
+ String sql = "select bqt1.smalla.intkey, bqt1.smallb.intkey from bqt1.smalla right outer join (bqt1.smallb cross join (bqt1.mediuma cross join bqt1.mediumb)) on bqt1.smalla.stringkey = bqt1.smallb.stringkey" //$NON-NLS-1$
+ +" where bqt1.smallb.intkey + bqt1.mediuma.intkey + bqt1.mediumb.intkey = 1"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setFunctionSupport("+", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ // Plan query
+ 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);
+ }
+
+ /**
+ * Since the multigroup criteria spans the inner side, it should not be pushed.
+ */
+ @Test public void testPushMultiGroupJoinCriteria1() {
+ String sql = "select bqt1.smalla.intkey, bqt1.smallb.intkey from bqt1.smalla right outer join (bqt1.smallb cross join (bqt1.mediuma cross join bqt1.mediumb)) on bqt1.smalla.stringkey = bqt1.smallb.stringkey" //$NON-NLS-1$
+ +" where bqt1.smalla.intkey + bqt1.mediuma.intkey + bqt1.mediumb.intkey is null"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setFunctionSupport("+", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ // Plan query
+ 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);
+ }
+
+ /**
+ * Since the multigroup criteria is not null dependent, it should get pushed.
+ */
+ @Test public void testPushMultiGroupJoinCriteria2() {
+ String sql = "select bqt1.smalla.intkey, bqt1.smallb.intkey from bqt1.smalla right outer join (bqt1.smallb cross join (bqt1.mediuma cross join bqt1.mediumb)) on bqt1.smalla.stringkey = bqt1.smallb.stringkey" //$NON-NLS-1$
+ +" where bqt1.smalla.intkey + bqt1.mediuma.intkey + bqt1.mediumb.intkey = 1"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setFunctionSupport("+", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ // Plan query
+ 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);
+ }
+
+
+ /**
+ * Having criteria should not be considered as regular criteria (unless it contains no aggregate expressions).
+ */
+ @Test public void testHavingCriteriaNotUsedAsJoinCriteria() {
+ String sql = "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"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_HAVING, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ // Plan query
+ 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);
+ }
+
+ /**
+ * Ensure that subqueries not initially pushable to the source still get replaced
+ */
+ @Test public void testSubqueryReplacement() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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$
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testRulePushNonJoinCriteriaPreservesOuterJoin() throws Exception {
+ 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,
+ new String[]{"SELECT g_1.intkey FROM bqt1.smalla AS g_0 LEFT OUTER JOIN bqt1.smallb AS g_1 ON 1 = 1"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testOuterToInnerJoinConversion() {
+ 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$
+ }
+
+ //same as above, but with a right outer join
+ @Test public void testOuterToInnerJoinConversion1() {
+ 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 = 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 = 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$
+ }
+
+ /**
+ * non-dependent criteria on each side of a full outer creates an inner join
+ */
+ @Test public void testOuterToInnerJoinConversion4() {
+ 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$
+ }
+
+ /**
+ * Since concat2 is null dependent the join will not be changed
+ */
+ @Test public void testOuterToInnerJoinConversionNullDependent() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setFunctionSupport("concat2", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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$
+ }
+
+ @Test public void testInlineViewToHaving() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_HAVING, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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, 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);
+ }
+
+ /**
+ * <p>In RuleBreakMultiJoin terminology:
+ * If any of the regions contains a group with any unsatisfied access patterns, one
+ * of those access patterns could be satisfied by arranging for a dependent join,
+ * provided that group has join criteria which covers the column(s) in an access
+ * pattern, and which joins the group to group(s) in other region(s). The task, then,
+ * is to ensure that an ordering isn't picked which makes such a dependent join
+ * impossible.</p>
+ *
+ * <p>A physical group can have zero or more access patterns; each access pattern can have one
+ * or more columns. So a group could implicitly be dependent on one or more other physical
+ * groups in one or more other regions. A table can be used to illustrate the potential
+ * complexity of access patterns:
+ * <pre>
+ * Region with | Target
+ * Access Patterns| Regions
+ * -------------------------
+ * Reg3 | Reg1, Reg2
+ * Reg3 | Reg4
+ * Reg1 | Reg2
+ * Reg4 | Reg3
+ * </pre></p>
+ *
+ * This tests now passes with RulePlanJoins
+ */
+ @Test public void testPathologicalAccessPatternCaseCase2976Defect19018() throws Exception{
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ // add single access pattern to pm1.g4 containing elements e1, e2, and e3
+ 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$
+ "pm1.g1.e1 = pm4.g1.e1 AND pm2.g1.e2 = pm4.g1.e2 AND pm1.g1.e4 = pm2.g1.e4 " +//$NON-NLS-1$
+ "AND pm4.g1.e4 = 3.2";//$NON-NLS-1$
+
+ String[] expected = new String[] {"SELECT g_0.e4 AS c_0, g_0.e1 AS c_1 FROM pm1.g1 AS g_0 ORDER BY c_0", //$NON-NLS-1$
+ "SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm4.g1 AS g_0 WHERE (g_0.e4 = 3.2) AND (g_0.e1 IN (<dependent values>)) AND (g_0.e2 IN (<dependent values>)) ORDER BY c_0, c_1", //$NON-NLS-1$
+ "SELECT g_0.e4 AS c_0, g_0.e2 AS c_1, g_0.e1 AS c_2 FROM pm2.g1 AS g_0 ORDER BY c_0",//$NON-NLS-1$
+ };
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, expected, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * non-null dependent criteria should get pushed down
+ */
+ @Test public void testPushMultiGroupCriteriaOuterJoin() {
+ String sql = "select m.intkey, m.intnum, s.intkey, s.intnum from BQT2.mediuma m left outer join BQT2.smalla s on m.intkey = s.intkey where not (m.intkey + s.intnum = 26)"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport("+", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ 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$
+ TestOptimizer.SHOULD_SUCCEED);
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+
+ }
+
+ /**
+ * Assumes that pm1.g1 is the only inner group
+ */
+ private void helpTestNullDependentVisitor(String critSQL,
+ boolean dependent) throws QueryParserException,
+ QueryResolverException,
+ QueryMetadataException,
+ TeiidComponentException {
+ List<GroupSymbol> innerGroups = new ArrayList<GroupSymbol>();
+ innerGroups.add(new GroupSymbol("pm1.g1")); //$NON-NLS-1$
+
+ Criteria crit = QueryParser.getQueryParser().parseCriteria(critSQL);
+
+ QueryResolver.resolveCriteria(crit, RealMetadataFactory.example1Cached());
+
+ assertEquals(dependent, JoinUtil.isNullDependent(RealMetadataFactory.example1Cached(), innerGroups, crit));
+ }
+
+ private void helpTestNullDependent(String expressionSQL,
+ boolean dependent) throws QueryParserException,
+ QueryResolverException,
+ QueryMetadataException,
+ TeiidComponentException {
+ List<GroupSymbol> innerGroups = new ArrayList<GroupSymbol>();
+ innerGroups.add(new GroupSymbol("pm1.g1")); //$NON-NLS-1$
+
+ Expression expr = QueryParser.getQueryParser().parseExpression(expressionSQL);
+
+ ResolverVisitor.resolveLanguageObject(expr, RealMetadataFactory.example1Cached());
+
+ assertEquals(dependent, JoinUtil.isNullDependent(RealMetadataFactory.example1Cached(), innerGroups, expr));
+ }
+
+ @Test public void testNullDependentVisitor() throws Exception {
+ helpTestNullDependentVisitor("nvl(pm1.g1.e1, 1) = 1", true); //$NON-NLS-1$
+ }
+
+ @Test public void testNullDependentVisitor1() throws Exception {
+ helpTestNullDependentVisitor("ifnull(pm1.g1.e1, 1) = 1", true); //$NON-NLS-1$
+ }
+
+ @Test public void testNullDependentVisitor2() throws Exception {
+ helpTestNullDependentVisitor("rand(pm1.g1.e2) = 1", true); //$NON-NLS-1$
+ }
+
+ @Test public void testNullDependentVisitor3() throws Exception {
+ helpTestNullDependentVisitor("concat2(pm1.g1.e1, pm1.g1.e2) = '1'", false); //$NON-NLS-1$
+ }
+
+ @Test public void testNullDependentVisitor4() throws Exception {
+ helpTestNullDependentVisitor("nvl(pm1.g2.e1, 1) = 1", true); //$NON-NLS-1$
+ }
+
+ @Test public void testNullDependentVisitor5() throws Exception {
+ helpTestNullDependentVisitor("pm1.g1.e1 is null", true); //$NON-NLS-1$
+ }
+
+ @Test public void testNullDependentVisitor6() throws Exception {
+ helpTestNullDependentVisitor("pm1.g1.e1 is not null", false); //$NON-NLS-1$
+ }
+
+ @Test public void testNullDependentVisitor7() throws Exception {
+ helpTestNullDependentVisitor("pm1.g2.e1 is not null", true); //$NON-NLS-1$
+ }
+
+ //this is an important test, the or causes this criteria to be null dependent
+ @Test public void testNullDependentVisitor8() throws Exception {
+ helpTestNullDependentVisitor("pm1.g1.e1 = 1 or pm1.g2.e1 = 1", true); //$NON-NLS-1$
+ }
+
+ @Test public void testNullDependentVisitor9() throws Exception {
+ helpTestNullDependentVisitor("pm1.g1.e1 = 1 or pm1.g1.e2 = 2", false); //$NON-NLS-1$
+ }
+
+ @Test public void testNullDependentVisitor10() throws Exception {
+ helpTestNullDependentVisitor("pm1.g1.e1 in (1, pm1.g2.e1)", false); //$NON-NLS-1$
+ }
+
+ @Test public void testNullDependentVisitor11() throws Exception {
+ helpTestNullDependentVisitor("pm1.g2.e1 in (1, pm1.g1.e1)", true); //$NON-NLS-1$
+ }
+
+ @Test public void testIsNullDependent() throws Exception {
+ helpTestNullDependent("pm1.g1.e2 + 1", false); //$NON-NLS-1$
+ }
+
+ @Test public void testIsNullDependent1() throws Exception {
+ helpTestNullDependent("pm1.g2.e2 + 1", true); //$NON-NLS-1$
+ }
+
+ /**
+ * The criteria will still get pushed to appropriate location, and
+ * the other side of the join will be removed
+ */
+ @Test public void testCriteriaPushedWithUnionJoin() throws Exception {
+ String sql = "select * from pm1.g1 union join pm1.g2 where g1.e1 = 1"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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$
+ TestOptimizer.SHOULD_SUCCEED);
+
+ TestOptimizer.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
+ });
+
+ }
+
+ /**
+ * union joins allow RuleRemoveVirtual to still take effect
+ */
+ @Test public void testCriteriaPushedWithUnionJoin1() throws Exception {
+ String sql = "select vm1.g1.e1 from vm1.g1 union join vm1.g2 where g2.e1 = 1"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
+ null, capFinder,
+ new String[] {
+ "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 = '1') AND (g_1.e1 = '1')" }, //$NON-NLS-1$
+ ComparisonMode.EXACT_COMMAND_STRING);
+
+ TestOptimizer.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
+ });
+
+ }
+
+ /**
+ * null-dependent expressions should prevent merging of virtual layers
+ */
+ @Test public void testNullDependentPreventsMerge() throws Exception {
+ String sql = "select x from pm1.g1 left outer join (select nvl(e2, 1) x from pm1.g2) y on e2 = x"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ caps.setFunctionSupport(SourceSystemFunctions.IFNULL, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
+ null, capFinder,
+ new String[] {
+ "SELECT v_0.c_0 FROM pm1.g1 AS g_0 LEFT OUTER JOIN (SELECT ifnull(g_1.e2, 1) AS c_0 FROM pm1.g2 AS g_1) AS v_0 ON g_0.e2 = v_0.c_0" }, //$NON-NLS-1$
+ TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+
+ }
+
+ /**
+ * RuleCopyCriteria will remove the first join criteria and the source doesn't support the * function. However we still
+ * want the join to be pushed since it originally contained proper criteria.
+ */
+ @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$
+
+ 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$
+
+ TestOptimizer.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 for Case 836073:
+ */
+ @Test public void testForCase836073_1() {
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testForCase836073_2() {
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Note that we don't allow pushdown here because the criteria placement matters
+ */
+ @Test public void testForCase836073_3() {
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testTransitiveJoinCondition() {
+ 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, 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"});
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,156 +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.optimizer;
-
-import org.junit.Test;
-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.translator.ExecutionFactory.SupportedJoinCriteria;
-
-
-public class TestJoinPushdownRestrictions {
-
- @Test public void testThetaRestriction() throws Exception {
- String sql = "select pm1.g1.e2, pm1.g2.e2 from pm1.g1 inner join pm1.g2 on (pm1.g1.e2 + pm1.g2.e2 = 5)"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.THETA);
- caps.setFunctionSupport("+", true); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- TestOptimizer.helpPlan(sql, FakeMetadataFactory.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(),
- 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$
- }
-
- @Test public void testEquiRestriction() throws Exception {
- String sql = "select pm1.g1.e2, pm1.g2.e2 from pm1.g1 inner join pm1.g2 on (pm1.g1.e2 < pm1.g2.e2)"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.EQUI);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- TestOptimizer.helpPlan(sql, FakeMetadataFactory.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(),
- 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$
- }
-
- @Test public void testKeyRestriction() throws Exception {
- String sql = "select pm1.g1.e2, pm1.g2.e2 from pm1.g1 inner join pm1.g2 on (pm1.g1.e2 = pm1.g2.e2)"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.KEY);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- TestOptimizer.helpPlan(sql, FakeMetadataFactory.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(),
- 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$
- }
-
- @Test public void testKeyRestriction1() throws Exception {
- String sql = "select a.e1, b.e1 from pm4.g1 a inner join pm4.g2 b on (a.e1 = b.e1 and a.e2 = b.e2) left outer join pm4.g1 c on (c.e1 = b.e1 and c.e2 = b.e2)"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.KEY);
- capFinder.addCapabilities("pm4", caps); //$NON-NLS-1$
-
- TestOptimizer.helpPlan(sql, FakeMetadataFactory.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$
- }
-
- @Test public void testKeyPasses() throws Exception {
- String sql = "select a.e1, b.e1 from pm4.g1 a, pm4.g2 b where a.e1 = b.e1 and a.e2 = b.e2"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.KEY);
- capFinder.addCapabilities("pm4", caps); //$NON-NLS-1$
-
- TestOptimizer.helpPlan(sql, FakeMetadataFactory.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$
- }
-
- @Test public void testCrossJoinWithRestriction() throws Exception {
- String sql = "select pm1.g1.e2, pm1.g2.e2 from pm1.g1, pm1.g2"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.THETA);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- TestOptimizer.helpPlan(sql, FakeMetadataFactory.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$
- }
-
- @Test public void testOuterRestriction() throws Exception {
- String sql = "select pm1.g1.e2, pm1.g2.e2 from pm1.g1 inner join pm1.g2 on (pm1.g1.e2 + pm1.g2.e2 = 5)"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, false);
- caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.ANY);
- caps.setFunctionSupport("+", true); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- TestOptimizer.helpPlan(sql, FakeMetadataFactory.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$
- }
-
- @Test public void testCriteriaRestrictionWithNonJoinCriteria() throws Exception {
- String sql = "select pm1.g1.e2, pm1.g2.e2 from pm1.g1 left outer join pm1.g2 on (pm1.g1.e2 = pm1.g2.e2 and pm1.g2.e1 = 'hello')"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.THETA);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- TestOptimizer.helpPlan(sql, FakeMetadataFactory.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$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,156 @@
+/*
+ * 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;
+
+import org.junit.Test;
+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.RealMetadataFactory;
+import org.teiid.translator.ExecutionFactory.SupportedJoinCriteria;
+
+
+public class TestJoinPushdownRestrictions {
+
+ @Test public void testThetaRestriction() throws Exception {
+ String sql = "select pm1.g1.e2, pm1.g2.e2 from pm1.g1 inner join pm1.g2 on (pm1.g1.e2 + pm1.g2.e2 = 5)"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.THETA);
+ caps.setFunctionSupport("+", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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, 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$
+ }
+
+ @Test public void testEquiRestriction() throws Exception {
+ String sql = "select pm1.g1.e2, pm1.g2.e2 from pm1.g1 inner join pm1.g2 on (pm1.g1.e2 < pm1.g2.e2)"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.EQUI);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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, 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$
+ }
+
+ @Test public void testKeyRestriction() throws Exception {
+ String sql = "select pm1.g1.e2, pm1.g2.e2 from pm1.g1 inner join pm1.g2 on (pm1.g1.e2 = pm1.g2.e2)"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.KEY);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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, 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$
+ }
+
+ @Test public void testKeyRestriction1() throws Exception {
+ String sql = "select a.e1, b.e1 from pm4.g1 a inner join pm4.g2 b on (a.e1 = b.e1 and a.e2 = b.e2) left outer join pm4.g1 c on (c.e1 = b.e1 and c.e2 = b.e2)"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.KEY);
+ capFinder.addCapabilities("pm4", caps); //$NON-NLS-1$
+
+ 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$
+ }
+
+ @Test public void testKeyPasses() throws Exception {
+ String sql = "select a.e1, b.e1 from pm4.g1 a, pm4.g2 b where a.e1 = b.e1 and a.e2 = b.e2"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.KEY);
+ capFinder.addCapabilities("pm4", caps); //$NON-NLS-1$
+
+ 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$
+ }
+
+ @Test public void testCrossJoinWithRestriction() throws Exception {
+ String sql = "select pm1.g1.e2, pm1.g2.e2 from pm1.g1, pm1.g2"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.THETA);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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$
+ }
+
+ @Test public void testOuterRestriction() throws Exception {
+ String sql = "select pm1.g1.e2, pm1.g2.e2 from pm1.g1 inner join pm1.g2 on (pm1.g1.e2 + pm1.g2.e2 = 5)"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, false);
+ caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.ANY);
+ caps.setFunctionSupport("+", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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$
+ }
+
+ @Test public void testCriteriaRestrictionWithNonJoinCriteria() throws Exception {
+ String sql = "select pm1.g1.e2, pm1.g2.e2 from pm1.g1 left outer join pm1.g2 on (pm1.g1.e2 = pm1.g2.e2 and pm1.g2.e1 = 'hello')"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.THETA);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,921 +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.optimizer;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.optimizer.TestOptimizer.DependentProjectNode;
-import org.teiid.query.optimizer.TestOptimizer.DependentSelectNode;
-import org.teiid.query.optimizer.TestOptimizer.DupRemoveNode;
-import org.teiid.query.optimizer.TestOptimizer.DupRemoveSortNode;
-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.FakeDataManager;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.TestProcessor;
-import org.teiid.query.processor.relational.AccessNode;
-import org.teiid.query.processor.relational.DependentAccessNode;
-import org.teiid.query.processor.relational.GroupingNode;
-import org.teiid.query.processor.relational.LimitNode;
-import org.teiid.query.processor.relational.MergeJoinStrategy;
-import org.teiid.query.processor.relational.NestedLoopJoinStrategy;
-import org.teiid.query.processor.relational.NullNode;
-import org.teiid.query.processor.relational.PlanExecutionNode;
-import org.teiid.query.processor.relational.ProjectNode;
-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 junit.framework.TestCase;
-
- at SuppressWarnings("nls")
-public class TestLimit extends TestCase {
-
- private static final int[] FULL_PUSHDOWN = new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- };
-
- public static final Class<?>[] NODE_TYPES = new Class[] {
- AccessNode.class,
- DependentAccessNode.class,
- DependentSelectNode.class,
- DependentProjectNode.class,
- DupRemoveNode.class,
- GroupingNode.class,
- LimitNode.class,
- NestedLoopJoinStrategy.class,
- MergeJoinStrategy.class,
- NullNode.class,
- PlanExecutionNode.class,
- ProjectNode.class,
- SelectNode.class,
- SortNode.class,
- UnionAllNode.class
- };
-
- public TestLimit(String name) {
- super(name);
- }
-
- private static FakeMetadataFacade exampleMetadata() {
- // Create models
- FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
- FakeMetadataObject vm1 = FakeMetadataFactory.createVirtualModel("vm1"); //$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$
-
- // Create physical elements
- 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 });
- List pm1g2e = FakeMetadataFactory.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,
- 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,
- 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,
- 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,
- 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$
-
- // Create virtual elements
- List vm1g1e = FakeMetadataFactory.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$
-
- // Create virtual elements
- List vm1g2e = FakeMetadataFactory.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);
- }
- public void testLimit() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM pm1.g1 limit 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
-
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
- }
-
- public void testLimitPushdown() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM pm1.g1 limit 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
- }
-
- public void testLimitWithOffset() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM pm1.g1 limit 50, 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
- }
-
- public void testPushedLimitWithOffset() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM pm1.g1 limit 50, 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
- }
-
- public void testLimitWithOffsetFullyPushed() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.ROW_OFFSET, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM pm1.g1 limit 50, 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
- }
-
- public void testSort() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM pm1.g1 order by e1 limit 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 1, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
- }
-
- public void testSortPushed() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- // pm3 model supports order by
- capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM pm3.g1 order by e1 limit 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
- }
-
- public void testSortPushedWithLimit() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- // pm3 model supports order by
- capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM pm3.g1 order by e1 limit 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
- }
-
- public void testSortUnderLimitNotRemoved() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- // pm3 model supports order by
- capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM (SELECT * FROM pm3.g1 order by e1 limit 100) AS V1 ORDER BY v1.e2";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 2, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
- }
-
- //TODO: there is a redundent project node here
- public void testSortAboveLimitNotPushed() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM vm1.g2 order by e1";//$NON-NLS-1$
- 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, exampleMetadata(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 1, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
- }
-
- public void testLimitNotPushedWithUnion() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- // pm1 model supports order by
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM pm1.g1 UNION SELECT * FROM PM1.g2 LIMIT 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- }, NODE_TYPES);
- }
-
- public void testLimitNotPushedWithDupRemove() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- // pm1 model supports order by
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT distinct * FROM pm1.g1 LIMIT 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
- }
-
- public void testLimitPushedWithUnionAll() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- // pm1 model supports order by
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM pm1.g1 UNION ALL SELECT * FROM PM1.g2 LIMIT 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- }, NODE_TYPES);
- }
-
- public void testLimitWithOffsetPushedWithUnion() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.ROW_OFFSET, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- // pm1 model supports order by
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM pm1.g1 UNION ALL SELECT * FROM PM1.g2 LIMIT 50, 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- }, NODE_TYPES);
- }
-
- public void testLimitNotPushedWithUnionOrderBy() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- // pm1 model supports order by
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM pm1.g1 UNION SELECT * FROM PM1.g2 ORDER BY e1 LIMIT 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- }, NODE_TYPES);
- TestOptimizer.checkNodeTypes(plan, new int[] {1}, new Class[]{DupRemoveSortNode.class});
- }
-
- public void testCombinedLimits() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- // pm1 model supports order by
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT * from (SELECT pm1.g1.e1 FROM pm1.g1 LIMIT 10, 100) x LIMIT 20, 75";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
- }
-
- public void testCombinedLimitsWithOffset() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.ROW_OFFSET, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- // pm1 model supports order by
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "SELECT * from (SELECT pm1.g1.e1 FROM pm1.g1 LIMIT 10, 100) x LIMIT 40, 75";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
-
- TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
- }
-
- public void testInlineView() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- //caps.setCapabilitySupport(SourceCapabilities.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- // pm3 model supports order by
- capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM (SELECT * FROM pm3.g1) as v1 limit 100";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
- }
-
- /**
- * This turns out to be an important test for LIMIT: there are several nodes
- * (e.g. grouping, inline views, aggregates, sorting, joins, etc) that should not be pushed
- * down (because they change row order or row count) if there is already a limit node in that plan branch,
- * which can only be placed above LIMIT with an inline view. This test acts as a gatekeeper for avoiding
- * several of those pushdowns.
- *
- * @since 4.3
- */
- public void testInlineViewAboveLimitNotMerged() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- // pm3 model supports order by
- capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM (SELECT * FROM pm3.g1 limit 100) as v1 order by e1";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * since there is no order by with the nested limit, the criteria can be pushed through
- *
- */
- public void testCriteriaPushedUnderLimit() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- // pm3 model supports order by
- capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
-
- String sql = "SELECT * FROM (SELECT * FROM pm3.g1 limit 100) as v1 where v1.e1 = 1";//$NON-NLS-1$
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
- }
-
- public void testInlineViewJoin() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 1, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
-
- //test to ensure that the unnecessary inline view removal is done properly
- FakeDataManager fdm = new FakeDataManager();
- TestProcessor.sampleData1(fdm);
- TestProcessor.helpProcess(plan, fdm, new List[] {
- Arrays.asList("a"), //$NON-NLS-1$
- Arrays.asList("a"), //$NON-NLS-1$
- Arrays.asList("a"), //$NON-NLS-1$
- Arrays.asList("a"), //$NON-NLS-1$
- Arrays.asList("a"), //$NON-NLS-1$
- });
- }
-
- public void testDontPushSelectWithOrderedLimit() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
- }
-
- public void testDontPushSelectWithOrderedLimit1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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(),
- null, capFinder, expectedSql, true);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
- }
-
- public void testLimitWithNoAccessNode() {
- String sql = "select 1 limit 1";//$NON-NLS-1$
- String[] expectedSql = new String[] {};
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), expectedSql);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 0, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
- }
-
- /**
- * Note here that the criteria made it to the having clause
- */
- 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();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_HAVING, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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);
-
- TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
- }
-
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Limit
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- }, NODE_TYPES);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,901 @@
+/*
+ * 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;
+
+import java.util.Arrays;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+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;
+import org.teiid.query.optimizer.TestOptimizer.DupRemoveSortNode;
+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.FakeDataManager;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.TestProcessor;
+import org.teiid.query.processor.relational.AccessNode;
+import org.teiid.query.processor.relational.DependentAccessNode;
+import org.teiid.query.processor.relational.GroupingNode;
+import org.teiid.query.processor.relational.LimitNode;
+import org.teiid.query.processor.relational.MergeJoinStrategy;
+import org.teiid.query.processor.relational.NestedLoopJoinStrategy;
+import org.teiid.query.processor.relational.NullNode;
+import org.teiid.query.processor.relational.PlanExecutionNode;
+import org.teiid.query.processor.relational.ProjectNode;
+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.RealMetadataFactory;
+
+ at SuppressWarnings("nls")
+public class TestLimit extends TestCase {
+
+ private static final int[] FULL_PUSHDOWN = new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ };
+
+ public static final Class<?>[] NODE_TYPES = new Class[] {
+ AccessNode.class,
+ DependentAccessNode.class,
+ DependentSelectNode.class,
+ DependentProjectNode.class,
+ DupRemoveNode.class,
+ GroupingNode.class,
+ LimitNode.class,
+ NestedLoopJoinStrategy.class,
+ MergeJoinStrategy.class,
+ NullNode.class,
+ PlanExecutionNode.class,
+ ProjectNode.class,
+ SelectNode.class,
+ SortNode.class,
+ UnionAllNode.class
+ };
+
+ public TestLimit(String name) {
+ super(name);
+ }
+
+ private static TransformationMetadata exampleMetadata() {
+ 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$
+ 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
+ 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 });
+ 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 });
+ 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<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 });
+ 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 });
+ 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$
+ Table vm1g1 = RealMetadataFactory.createVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
+
+ // Create virtual elements
+ 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$
+ Table vm1g2 = RealMetadataFactory.createVirtualGroup("g2", vm1, vm1g2n1); //$NON-NLS-1$
+
+ // Create virtual elements
+ 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 });
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "example");
+ }
+ public void testLimit() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM pm1.g1 limit 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ public void testLimitPushdown() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM pm1.g1 limit 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
+ }
+
+ public void testLimitWithOffset() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM pm1.g1 limit 50, 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ public void testPushedLimitWithOffset() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM pm1.g1 limit 50, 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ public void testLimitWithOffsetFullyPushed() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.ROW_OFFSET, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM pm1.g1 limit 50, 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
+ }
+
+ public void testSort() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM pm1.g1 order by e1 limit 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 1, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ public void testSortPushed() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ // pm3 model supports order by
+ capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM pm3.g1 order by e1 limit 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ public void testSortPushedWithLimit() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ // pm3 model supports order by
+ capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM pm3.g1 order by e1 limit 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
+ }
+
+ public void testSortUnderLimitNotRemoved() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ // pm3 model supports order by
+ capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM (SELECT * FROM pm3.g1 order by e1 limit 100) AS V1 ORDER BY v1.e2";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 2, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ //TODO: there is a redundent project node here
+ public void testSortAboveLimitNotPushed() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM vm1.g2 order by e1";//$NON-NLS-1$
+ 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, exampleMetadata(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 1, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ public void testLimitNotPushedWithUnion() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ // pm1 model supports order by
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM pm1.g1 UNION SELECT * FROM PM1.g2 LIMIT 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ public void testLimitNotPushedWithDupRemove() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ // pm1 model supports order by
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT distinct * FROM pm1.g1 LIMIT 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ public void testLimitPushedWithUnionAll() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ // pm1 model supports order by
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM pm1.g1 UNION ALL SELECT * FROM PM1.g2 LIMIT 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ public void testLimitWithOffsetPushedWithUnion() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.ROW_OFFSET, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ // pm1 model supports order by
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM pm1.g1 UNION ALL SELECT * FROM PM1.g2 LIMIT 50, 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ public void testLimitNotPushedWithUnionOrderBy() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ // pm1 model supports order by
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM pm1.g1 UNION SELECT * FROM PM1.g2 ORDER BY e1 LIMIT 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ }, NODE_TYPES);
+ TestOptimizer.checkNodeTypes(plan, new int[] {1}, new Class[]{DupRemoveSortNode.class});
+ }
+
+ public void testCombinedLimits() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ // pm1 model supports order by
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * from (SELECT pm1.g1.e1 FROM pm1.g1 LIMIT 10, 100) x LIMIT 20, 75";//$NON-NLS-1$
+ String[] expectedSql = new String[] {
+ "SELECT pm1.g1.e1 AS c_0 FROM pm1.g1 LIMIT 105" //$NON-NLS-1$
+ };
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ public void testCombinedLimitsWithOffset() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.ROW_OFFSET, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ // pm1 model supports order by
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * from (SELECT pm1.g1.e1 FROM pm1.g1 LIMIT 10, 100) x LIMIT 40, 75";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
+
+ TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
+ }
+
+ public void testInlineView() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ //caps.setCapabilitySupport(SourceCapabilities.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ // pm3 model supports order by
+ capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM (SELECT * FROM pm3.g1) as v1 limit 100";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
+ }
+
+ /**
+ * This turns out to be an important test for LIMIT: there are several nodes
+ * (e.g. grouping, inline views, aggregates, sorting, joins, etc) that should not be pushed
+ * down (because they change row order or row count) if there is already a limit node in that plan branch,
+ * which can only be placed above LIMIT with an inline view. This test acts as a gatekeeper for avoiding
+ * several of those pushdowns.
+ *
+ * @since 4.3
+ */
+ public void testInlineViewAboveLimitNotMerged() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ // pm3 model supports order by
+ capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM (SELECT * FROM pm3.g1 limit 100) as v1 order by e1";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ /**
+ * since there is no order by with the nested limit, the criteria can be pushed through
+ *
+ */
+ public void testCriteriaPushedUnderLimit() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ // pm3 model supports order by
+ capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
+
+ String sql = "SELECT * FROM (SELECT * FROM pm3.g1 limit 100) as v1 where v1.e1 = 1";//$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
+ }
+
+ public void testInlineViewJoin() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 1, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+
+ //test to ensure that the unnecessary inline view removal is done properly
+ FakeDataManager fdm = new FakeDataManager();
+ TestProcessor.sampleData1(fdm);
+ TestProcessor.helpProcess(plan, fdm, new List[] {
+ Arrays.asList("a"), //$NON-NLS-1$
+ Arrays.asList("a"), //$NON-NLS-1$
+ Arrays.asList("a"), //$NON-NLS-1$
+ Arrays.asList("a"), //$NON-NLS-1$
+ Arrays.asList("a"), //$NON-NLS-1$
+ });
+ }
+
+ public void testDontPushSelectWithOrderedLimit() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ public void testDontPushSelectWithOrderedLimit1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ public void testLimitWithNoAccessNode() {
+ String sql = "select 1 limit 1";//$NON-NLS-1$
+ String[] expectedSql = new String[] {};
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), expectedSql);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 0, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+ }
+
+ /**
+ * Note here that the criteria made it to the having clause
+ */
+ 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();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_HAVING, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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, RealMetadataFactory.example1Cached(), null, capFinder, expectedSql, true);
+
+ TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
+ }
+
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Limit
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ }, NODE_TYPES);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,6715 +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.optimizer;
-
-import static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryPlannerException;
-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.DataTypeManager;
-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.optimizer.capabilities.BasicSourceCapabilities;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-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.optimizer.relational.AliasGenerator;
-import org.teiid.query.optimizer.relational.rules.CapabilitiesUtil;
-import org.teiid.query.optimizer.relational.rules.RuleChooseDependent;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.relational.AccessNode;
-import org.teiid.query.processor.relational.DependentAccessNode;
-import org.teiid.query.processor.relational.EnhancedSortMergeJoinStrategy;
-import org.teiid.query.processor.relational.GroupingNode;
-import org.teiid.query.processor.relational.JoinNode;
-import org.teiid.query.processor.relational.JoinStrategy;
-import org.teiid.query.processor.relational.MergeJoinStrategy;
-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.PlanExecutionNode;
-import org.teiid.query.processor.relational.ProjectIntoNode;
-import org.teiid.query.processor.relational.ProjectNode;
-import org.teiid.query.processor.relational.RelationalNode;
-import org.teiid.query.processor.relational.RelationalPlan;
-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.processor.relational.SortUtility.Mode;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.resolver.TestResolver;
-import org.teiid.query.rewriter.QueryRewriter;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.JoinType;
-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.util.CommandContext;
-import org.teiid.query.validator.Validator;
-import org.teiid.query.validator.ValidatorReport;
-import org.teiid.translator.SourceSystemFunctions;
-
- at SuppressWarnings({"nls", "unchecked"})
-public class TestOptimizer {
-
- public interface DependentJoin {}
- public interface DependentSelectNode {}
- public interface SemiJoin {}
- public interface AntiSemiJoin {}
- public interface DependentProjectNode {}
- public interface DupRemoveNode {}
- public interface DupRemoveSortNode {}
-
- public static final int[] FULL_PUSHDOWN = new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- };
-
- public enum ComparisonMode { EXACT_COMMAND_STRING, CORRECTED_COMMAND_STRING, FAILED_PLANNING }
-
- public static final boolean SHOULD_SUCCEED = true;
- public static final boolean SHOULD_FAIL = false;
-
- // ################################## TEST HELPERS ################################
-
- public static BasicSourceCapabilities getTypicalCapabilities() {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.CRITERIA_BETWEEN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
- caps.setCapabilitySupport(Capability.CRITERIA_LIKE_ESCAPE, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_ISNULL, true);
- caps.setCapabilitySupport(Capability.CRITERIA_OR, true);
- caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY_UNRELATED, true);
-
- // set typical max set size
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
- return caps;
- }
-
- public static CapabilitiesFinder getGenericFinder(boolean supportsJoins) {
- final BasicSourceCapabilities caps = getTypicalCapabilities();
- if (!supportsJoins) {
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, false);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
- }
- return new DefaultCapabilitiesFinder(caps);
- }
-
- public static CapabilitiesFinder getGenericFinder() {
- return getGenericFinder(true);
- }
-
- public static ProcessorPlan helpPlan(String sql, QueryMetadataInterface md, String[] expectedAtomic) {
- return helpPlan(sql, md, null, getGenericFinder(), expectedAtomic, SHOULD_SUCCEED);
- }
-
- public static ProcessorPlan helpPlan(String sql,
- QueryMetadataInterface md, String[] expected,
- CapabilitiesFinder capFinder,
- ComparisonMode mode) throws TeiidComponentException, TeiidProcessingException {
- return helpPlan(sql, md, null, capFinder, expected, mode);
- }
-
- public static ProcessorPlan helpPlan(String sql, QueryMetadataInterface md, String[] expectedAtomic, ComparisonMode mode) throws TeiidComponentException, TeiidProcessingException {
- return helpPlan(sql, md, null, getGenericFinder(), expectedAtomic, mode);
- }
-
- public static ProcessorPlan helpPlan(String sql, QueryMetadataInterface md, List bindings, CapabilitiesFinder capFinder, String[] expectedAtomic, boolean shouldSucceed) {
- Command command;
- try {
- command = helpGetCommand(sql, md, bindings);
- } catch (TeiidException err) {
- throw new TeiidRuntimeException(err);
- }
-
- return helpPlanCommand(command, md, capFinder, null, expectedAtomic, shouldSucceed ? ComparisonMode.CORRECTED_COMMAND_STRING : ComparisonMode.FAILED_PLANNING);
- }
-
- public static ProcessorPlan helpPlan(String sql, QueryMetadataInterface md, List bindings, CapabilitiesFinder capFinder, String[] expectedAtomic, ComparisonMode mode) throws TeiidComponentException, TeiidProcessingException {
- Command command = helpGetCommand(sql, md, bindings);
-
- return helpPlanCommand(command, md, capFinder, null, expectedAtomic, mode);
- }
-
-
- public static Command helpGetCommand(String sql, QueryMetadataInterface md, List bindings) throws TeiidComponentException, TeiidProcessingException {
- if(DEBUG) System.out.println("\n####################################\n" + sql); //$NON-NLS-1$
- Command command = null;
- if (bindings != null && !bindings.isEmpty()) {
- command = TestResolver.helpResolveWithBindings(sql, md, bindings);
- } else {
- command = QueryParser.getQueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(command, md);
- }
-
- ValidatorReport repo = Validator.validate(command, md);
-
- Collection failures = new ArrayList();
- repo.collectInvalidObjects(failures);
- if (failures.size() > 0){
- fail("Exception during validation (" + repo); //$NON-NLS-1$
- }
-
- // rewrite
- command = QueryRewriter.rewrite(command, md, new CommandContext());
-
- return command;
- }
-
- public static ProcessorPlan helpPlanCommand(Command command, QueryMetadataInterface md, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord, String[] expectedAtomic, ComparisonMode mode) {
- if (capFinder == null){
- capFinder = getGenericFinder();
- }
-
- // Collect atomic queries
- ProcessorPlan plan = getPlan(command, md, capFinder, analysisRecord, mode != ComparisonMode.FAILED_PLANNING, new CommandContext());
-
- if (mode == ComparisonMode.CORRECTED_COMMAND_STRING) {
- checkAtomicQueries(expectedAtomic, plan, md, capFinder);
- } else if (mode == ComparisonMode.EXACT_COMMAND_STRING) {
- checkAtomicQueries(expectedAtomic, plan);
- }
-
- return plan;
- }
-
- public static void checkAtomicQueries(String[] expectedAtomic,
- ProcessorPlan plan) {
- Set<String> actualQueries = getAtomicQueries(plan);
-
- if (actualQueries.size() != 1 || expectedAtomic.length != 1) {
- // Compare atomic queries
- HashSet<String> expectedQueries = new HashSet<String>(Arrays.asList(expectedAtomic));
- assertEquals("Did not get expected atomic queries: ", expectedQueries, actualQueries); //$NON-NLS-1$
- } else {
- assertEquals("Did not get expected atomic query: ", expectedAtomic[0], actualQueries.iterator().next()); //$NON-NLS-1$
- }
- }
-
- public static void checkAtomicQueries(String[] expectedAtomic,
- ProcessorPlan plan, QueryMetadataInterface md, CapabilitiesFinder capFinder) {
- Set actualQueries = getAtomicQueries(plan);
-
- HashSet<String> expectedQueries = new HashSet<String>();
-
- // Compare atomic queries
- for (int i = 0; i < expectedAtomic.length; i++) {
- final String sql = expectedAtomic[i];
- Command command;
- try {
- command = helpGetCommand(sql, md, null);
- Collection groups = GroupCollectorVisitor.getGroupsIgnoreInlineViews(command, false);
- final GroupSymbol symbol = (GroupSymbol)groups.iterator().next();
- Object modelId = md.getModelID(symbol.getMetadataID());
- boolean supportsGroupAliases = CapabilitiesUtil.supportsGroupAliases(modelId, md, capFinder);
- boolean supportsProjection = CapabilitiesUtil.supports(Capability.QUERY_SELECT_EXPRESSION, modelId, md, capFinder);
- command.acceptVisitor(new AliasGenerator(supportsGroupAliases, !supportsProjection));
- expectedQueries.add(command.toString());
- } catch (Exception err) {
- throw new RuntimeException(err);
- }
- }
-
- assertEquals("Did not get expected atomic queries: ", expectedQueries, actualQueries); //$NON-NLS-1$
- }
-
- public static ProcessorPlan getPlan(Command command, QueryMetadataInterface md, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord, boolean shouldSucceed, CommandContext cc) {
- ProcessorPlan plan = null;
- if (analysisRecord == null) {
- analysisRecord = new AnalysisRecord(false, DEBUG);
- }
- Exception exception = null;
- try {
- //do planning
- plan = QueryOptimizer.optimizePlan(command, md, null, capFinder, analysisRecord, cc);
- } catch (QueryPlannerException e) {
- exception = e;
- } catch (TeiidComponentException e) {
- exception = e;
- } catch (Throwable e) {
- throw new TeiidRuntimeException(e);
- } finally {
- if(DEBUG) {
- System.out.println(analysisRecord.getDebugLog());
- }
- }
- if (!shouldSucceed) {
- assertNotNull("Expected exception but did not get one.", exception); //$NON-NLS-1$
- return null;
- }
- if (plan == null) {
- throw new TeiidRuntimeException(exception);
- }
- assertNotNull("Output elements are null", plan.getOutputElements()); //$NON-NLS-1$
- if(DEBUG) System.out.println("\n" + plan); //$NON-NLS-1$
- return plan;
- }
-
- public static Set<String> getAtomicQueries(ProcessorPlan plan) {
- Set<Command> atomicQueries = new HashSet<Command>();
- if(plan instanceof RelationalPlan) {
- getAtomicCommands( ((RelationalPlan)plan).getRootNode(), atomicQueries );
- }
-
- Set<String> stringQueries = new HashSet<String>();
-
- for (Command command : atomicQueries) {
- stringQueries.add(command.toString());
- }
-
- return stringQueries;
- }
-
- private static void getAtomicCommands(RelationalNode node, Set<Command> atomicQueries) {
- if(node instanceof AccessNode) {
- AccessNode accessNode = (AccessNode) node;
- atomicQueries.add( accessNode.getCommand());
- }
-
- // Recurse through children
- RelationalNode[] children = node.getChildren();
- for(int i=0; i<children.length; i++) {
- if(children[i] != null) {
- getAtomicCommands(children[i], atomicQueries);
- } else {
- break;
- }
- }
- }
-
- // Counts are (mostly) alphabetical:
- // Access, DependentAccess, DependentSelect, DependentProject, DupRemove, Grouping, NestedLoopJoinStrategy, Null, PlanExecution, Project, Select, Sort, UnionAll
- private static final Class[] COUNT_TYPES = new Class[] {
- AccessNode.class,
- DependentAccessNode.class,
- DependentSelectNode.class,
- DependentProjectNode.class,
- DupRemoveNode.class,
- GroupingNode.class,
- NestedLoopJoinStrategy.class,
- MergeJoinStrategy.class,
- NullNode.class,
- PlanExecutionNode.class,
- ProjectNode.class,
- SelectNode.class,
- SortNode.class,
- UnionAllNode.class
- };
-
- public static void checkNodeTypes(ProcessorPlan root, int[] expectedCounts) {
- checkNodeTypes(root, expectedCounts, COUNT_TYPES);
- }
-
- public static void checkNodeTypes(ProcessorPlan root, int[] expectedCounts, Class[] types) {
- if(! (root instanceof RelationalPlan)) {
- return;
- }
-
- int[] actualCounts = new int[types.length];
- collectCounts(((RelationalPlan)root).getRootNode(), actualCounts, types);
-
- for(int i=0; i<expectedCounts.length; i++) {
- assertEquals("Did not find the correct number of nodes for type " + types[i], //$NON-NLS-1$
- expectedCounts[i], actualCounts[i]);
- }
- }
-
- /**
- * Method collectCounts.
- * @param relationalNode
- * @return int[]
- */
- static void collectCounts(RelationalNode relationalNode, int[] counts, Class<?>[] types) {
- Class<?> nodeType = relationalNode.getClass();
- if(nodeType.equals(JoinNode.class)) {
- JoinStrategy strategy = ((JoinNode)relationalNode).getJoinStrategy();
- if (((JoinNode)relationalNode).getJoinType().equals(JoinType.JOIN_SEMI)) {
- updateCounts(SemiJoin.class, counts, types);
- } else if (((JoinNode)relationalNode).getJoinType().equals(JoinType.JOIN_ANTI_SEMI)) {
- updateCounts(AntiSemiJoin.class, counts, types);
- }
- if (strategy instanceof NestedLoopJoinStrategy) {
- updateCounts(NestedLoopJoinStrategy.class, counts, types);
- } else if (strategy instanceof MergeJoinStrategy) {
- updateCounts(MergeJoinStrategy.class, counts, types);
- if (strategy instanceof EnhancedSortMergeJoinStrategy) {
- updateCounts(EnhancedSortMergeJoinStrategy.class, counts, types);
- }
- } else if (strategy instanceof NestedTableJoinStrategy) {
- updateCounts(NestedTableJoinStrategy.class, counts, types);
- }
- if (((JoinNode)relationalNode).isDependent()) {
- updateCounts(DependentJoin.class, counts, types);
- }
- }else if (nodeType.equals(ProjectNode.class)){
- if (ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(((ProjectNode)relationalNode).getSelectSymbols()).isEmpty()) {
- updateCounts(ProjectNode.class, counts, types);
- } else {
- updateCounts(DependentProjectNode.class, counts, types);
- }
- }else if (nodeType.equals(SelectNode.class)){
- if (ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(((SelectNode)relationalNode).getCriteria()).isEmpty()) {
- updateCounts(SelectNode.class, counts, types);
- } else {
- updateCounts(DependentSelectNode.class, counts, types);
- }
- } else if (nodeType.equals(SortNode.class)) {
- Mode mode = ((SortNode)relationalNode).getMode();
- switch(mode) {
- case DUP_REMOVE:
- updateCounts(DupRemoveNode.class, counts, types);
- break;
- case DUP_REMOVE_SORT:
- updateCounts(DupRemoveSortNode.class, counts, types);
- break;
- case SORT:
- updateCounts(SortNode.class, counts, types);
- break;
- }
- } else {
- updateCounts(nodeType, counts, types);
- }
-
- RelationalNode[] children = relationalNode.getChildren();
- for(int i=0; i<children.length; i++) {
- if(children[i] != null) {
- collectCounts(children[i], counts, types);
- } else {
- break;
- }
- }
- }
-
- private static void updateCounts(Class nodeClass, int[] counts, Class[] types) {
- for(int i=0; i<types.length; i++) {
- if(types[i].equals(nodeClass)) {
- counts[i] = counts[i] + 1;
- return;
- }
- }
- }
-
- public static void checkDependentJoinCount(ProcessorPlan plan, int expectedCount) {
- checkNodeTypes(plan, new int[] {expectedCount}, new Class[] {DependentJoin.class});
- }
-
- public static FakeMetadataFacade example1() {
- // 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$
-
- // 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$
-
- // Create physical elements
- 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 });
- List pm1g2e = FakeMetadataFactory.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,
- 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,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING });
- List pm1g5e = FakeMetadataFactory.createElements(pm1g5,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING });
- List pm1g6e = FakeMetadataFactory.createElements(pm1g6,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING });
- List pm1g7e = FakeMetadataFactory.createElements(pm1g7,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING });
- List pm1g8e = FakeMetadataFactory.createElements(pm1g8,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING });
- List pm2g1e = FakeMetadataFactory.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,
- 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,
- 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$
-
- 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$
-
- //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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- // Create virtual elements
- List vm1g1e = FakeMetadataFactory.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,
- 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,
- 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,
- 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,
- new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
- List vm1g5e = FakeMetadataFactory.createElements(vm1g5,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING});
- List vm1g6e = FakeMetadataFactory.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,
- new String[] { "e1", "e2"}, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
- List vm1u1e = FakeMetadataFactory.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,
- 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,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING });
- List vm1u4e = FakeMetadataFactory.createElements(vm1u4,
- new String[] { "v1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING });
- List vm1u5e = FakeMetadataFactory.createElements(vm1u5,
- new String[] { "v1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING });
- List vm1u6e = FakeMetadataFactory.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,
- new String[] { "const", "e1" }, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
- List vm1u8e = FakeMetadataFactory.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,
- new String[] { "a", "b" }, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
- List vm1a1e = FakeMetadataFactory.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,
- new String[] { "e1", "sum_e2" }, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.LONG });
- List vm1a3e = FakeMetadataFactory.createElements(vm1a3,
- new String[] { "sum_e2" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.LONG });
- List vm1a4e = FakeMetadataFactory.createElements(vm1a4,
- new String[] { "count" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.INTEGER });
- List vm1a5e = FakeMetadataFactory.createElements(vm1a5,
- new String[] { "count" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.INTEGER });
- List vm1a6e = FakeMetadataFactory.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);
- }
-
- // ################################## ACTUAL TESTS ################################
-
- /**
- * Test defect 8096 - query a virtual group with subquery of another virtual group
- */
- @Test public void testVirtualSubqueryINClause_8096() {
- helpPlan("SELECT * FROM vm1.sub1", example1(), //$NON-NLS-1$
- new String[] {"SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1"} ); //$NON-NLS-1$
- }
-
- @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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- new String[] { "UPDATE pm1.g1 SET pm1.g1.e1 = 'MyString', pm1.g1.e2 = 1 WHERE pm1.g1.e3 = TRUE"} ); //$NON-NLS-1$
- }
-
- @Test public void testUpdate2() throws Exception {
- 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$
- 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$
- }
-
- @Test public void testDelete() throws Exception {
- 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$
- new String[] { "DELETE FROM pm1.g1 WHERE pm1.g1.e1 = convert(pm1.g1.e2, string)"}, dcf, ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
- }
-
- // ############################# TESTS ON EXAMPLE 1 ############################
-
- @Test public void testCopyInAcrossJoin() throws Exception {
- ProcessorPlan plan = helpPlan("select pm1.g1.e1, pm2.g2.e1 from pm1.g1, pm2.g2 where pm1.g1.e1=pm2.g2.e1 and pm1.g1.e1 IN ('a', 'b')", example1(), //$NON-NLS-1$
- new String[] { "SELECT g_0.e1 AS c_0 FROM pm2.g2 AS g_0 WHERE g_0.e1 IN ('a', 'b') ORDER BY c_0", //$NON-NLS-1$
- "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 WHERE g_0.e1 IN ('a', 'b') ORDER BY c_0" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testCopyMatchAcrossJoin() throws Exception {
- helpPlan("select pm1.g1.e1, pm2.g2.e1 from pm1.g1, pm2.g2 where pm1.g1.e1=pm2.g2.e1 and pm1.g1.e1 LIKE '%1'", example1(), //$NON-NLS-1$
- new String[] { "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 WHERE g_0.e1 LIKE '%1' ORDER BY c_0", //$NON-NLS-1$
- "SELECT g_0.e1 AS c_0 FROM pm2.g2 AS g_0 WHERE g_0.e1 LIKE '%1' ORDER BY c_0" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
- }
-
- @Test public void testCopyOrAcrossJoin() throws Exception {
- helpPlan("select pm1.g1.e1, pm1.g2.e1 from pm1.g1, pm1.g2 where pm1.g1.e1=pm1.g2.e1 and (pm1.g1.e1 = 'abc' OR pm1.g1.e1 = 'def')", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 WHERE (pm1.g1.e1 = 'abc') OR (pm1.g1.e1 = 'def')", //$NON-NLS-1$
- "SELECT pm1.g2.e1 FROM pm1.g2 WHERE (pm1.g2.e1 = 'abc') OR (pm1.g2.e1 = 'def')" }, getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$
- }
-
- @Test public void testCopyMultiElementCritAcrossJoin() throws Exception {
- helpPlan("select pm1.g1.e1, pm1.g2.e1 from pm1.g1, pm1.g2 where pm1.g1.e1=pm1.g2.e1 and pm1.g1.e2=pm1.g2.e2 and (pm1.g1.e1 = 'abc' OR pm1.g1.e2 = 5)", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g2.e1, pm1.g2.e2 FROM pm1.g2 WHERE (pm1.g2.e1 = 'abc') OR (pm1.g2.e2 = 5)", "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 WHERE (pm1.g1.e1 = 'abc') OR (pm1.g1.e2 = 5)" }, getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCantCopyAcrossJoin1() throws Exception {
- helpPlan("select pm1.g1.e1, pm1.g2.e1 from pm1.g1, pm1.g2 where pm1.g1.e1=pm1.g2.e1 and concat(pm1.g1.e1, pm1.g1.e2) = 'abc'", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1", //$NON-NLS-1$
- "SELECT pm1.g2.e1 FROM pm1.g2" }, getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$
- }
-
- @Test public void testCantCopyAcrossJoin2() throws Exception {
- helpPlan("select pm1.g1.e1, pm1.g2.e1 from pm1.g1, pm1.g2 where pm1.g1.e1=pm1.g2.e1 and (pm1.g1.e1 = 'abc' OR pm1.g1.e2 = 5)", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 WHERE (pm1.g1.e1 = 'abc') OR (pm1.g1.e2 = 5)", //$NON-NLS-1$
- "SELECT pm1.g2.e1 FROM pm1.g2" }, getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$
- }
-
- @Test public void testPushingCriteriaThroughFrame1() {
- helpPlan("select * from vm1.g1, vm1.g2 where vm1.g1.e1='abc' and vm1.g1.e1=vm1.g2.e1", example1(), //$NON-NLS-1$
- new String[] { "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$
- "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'" } ); //$NON-NLS-1$
- }
-
- @Test public void testPushingCriteriaThroughFrame2() throws Exception {
- helpPlan("select * from vm1.g1, vm1.g3 where vm1.g1.e1='abc' and vm1.g1.e1=vm1.g3.e1", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2 WHERE pm1.g2.e1 = 'abc'", //$NON-NLS-1$
- "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'" }, getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING ); //$NON-NLS-1$
- }
-
- @Test public void testPushingCriteriaThroughFrame3() {
- helpPlan("select * from vm1.g1, vm1.g2, vm1.g1 as a where vm1.g1.e1='abc' and vm1.g1.e1=vm1.g2.e1 and vm1.g1.e1=a.e1", example1(), //$NON-NLS-1$
- new String[] { "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$
- "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'", //$NON-NLS-1$
- "SELECT g1__2.e1, g1__2.e2, g1__2.e3, g1__2.e4 FROM pm1.g1 AS g1__2 WHERE g1__2.e1 = 'abc'" } ); //$NON-NLS-1$
- }
-
- @Test public void testPushingCriteriaThroughUnion1() {
- helpPlan("select e1 from vm1.u1 where e1='abc'", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g3.e1, pm1.g3.e2, pm1.g3.e3, pm1.g3.e4 FROM pm1.g3 WHERE pm1.g3.e1 = 'abc'", //$NON-NLS-1$
- "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2 WHERE pm1.g2.e1 = 'abc'", //$NON-NLS-1$
- "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'" } ); //$NON-NLS-1$
- }
-
- @Test public void testPushingCriteriaThroughUnion2() {
- helpPlan("select e1 from vm1.u2 where e1='abc'", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2 WHERE pm1.g2.e1 = 'abc'", //$NON-NLS-1$
- "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'" } ); //$NON-NLS-1$
- }
-
- @Test public void testPushingCriteriaThroughUnion3() {
- helpPlan("select e1 from vm1.u1 where e1='abc' and e2=5", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g3.e1, pm1.g3.e2, pm1.g3.e3, pm1.g3.e4 FROM pm1.g3 WHERE (pm1.g3.e1 = 'abc') AND (pm1.g3.e2 = 5)", //$NON-NLS-1$
- "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2 WHERE (pm1.g2.e1 = 'abc') AND (pm1.g2.e2 = 5)", //$NON-NLS-1$
- "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE (pm1.g1.e1 = 'abc') AND (pm1.g1.e2 = 5)" } ); //$NON-NLS-1$
- }
-
- @Test public void testPushingCriteriaThroughUnion4() {
- helpPlan("select e1 from vm1.u1 where e1='abc' or e2=5", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g3.e1, pm1.g3.e2, pm1.g3.e3, pm1.g3.e4 FROM pm1.g3 WHERE (pm1.g3.e1 = 'abc') OR (pm1.g3.e2 = 5)", //$NON-NLS-1$
- "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE (pm1.g1.e1 = 'abc') OR (pm1.g1.e2 = 5)", //$NON-NLS-1$
- "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2 WHERE (pm1.g2.e1 = 'abc') OR (pm1.g2.e2 = 5)" } ); //$NON-NLS-1$
- }
-
- // expression in a subquery of the union
- @Test public void testPushingCriteriaThroughUnion5() {
- helpPlan("select e1 from vm1.u3 where e1='abc'", example1(), //$NON-NLS-1$
- new String[] { "SELECT DISTINCT e1 FROM pm1.g1 WHERE e1 = 'abc'" } ); //$NON-NLS-1$
- }
-
- /** defect #4956 */
- @Test public void testPushCriteriaThroughUnion6() {
- helpPlan("select v1 from vm1.u4 where vm1.u4.v1='x'", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1 FROM pm1.g1", //$NON-NLS-1$
- "SELECT e1 FROM pm1.g2 WHERE e1 = 'x'" } ); //$NON-NLS-1$
- }
-
- @Test public void testPushCriteriaThroughUnion7() {
- helpPlan("select v1 from vm1.u5 where vm1.u5.v1='x'", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1 FROM pm1.g1", //$NON-NLS-1$
- "SELECT e1 FROM pm1.g2" } ); //$NON-NLS-1$
- }
-
- @Test public void testPushCriteriaThroughUnion8() {
- helpPlan("select v1 from vm1.u5 where length(v1) > 0", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1 FROM pm1.g1", //$NON-NLS-1$
- "SELECT e1 FROM pm1.g2" } ); //$NON-NLS-1$
- }
-
- @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$
- }
-
- @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$
- }
-
- /** defect #4997 */
- @Test public void testCountStarNoRows() {
- ProcessorPlan plan = helpPlan("select count(*) from vm1.u4", example1(), //$NON-NLS-1$
- new String[] { "SELECT 1 FROM pm1.g2", //$NON-NLS-1$
- "SELECT 1 FROM pm1.g1" } ); //$NON-NLS-1$
- 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 testPushingCriteriaWithCopy() {
- ProcessorPlan plan = helpPlan("select vm1.u1.e1 from vm1.u1, pm1.g1 where vm1.u1.e1='abc' and vm1.u1.e1=pm1.g1.e1", example1(), //$NON-NLS-1$
- new String[] { "SELECT 1 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'", //$NON-NLS-1$
- "SELECT pm1.g3.e1, pm1.g3.e2, pm1.g3.e3, pm1.g3.e4 FROM pm1.g3 WHERE pm1.g3.e1 = 'abc'", //$NON-NLS-1$
- "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2 WHERE pm1.g2.e1 = 'abc'", //$NON-NLS-1$
- "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'" } ); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 4, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 1, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 2 // UnionAll
- });
- }
-
- @Test public void testVirtualGroupWithAliasedElement() {
- helpPlan("select elem FROM vm1.u6 where elem='abc' and const='xyz'", example1(), //$NON-NLS-1$
- new String[] { "SELECT x1.e1 FROM pm1.g1 AS x1 WHERE x1.e1 = 'abc'" } ); //$NON-NLS-1$
- }
-
- @Test public void testPushThroughGroup1() {
- helpPlan("select * FROM vm1.a1 WHERE e1 = 'x'", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1, e2 FROM pm1.g1 WHERE e1 = 'x'" } ); //$NON-NLS-1$
- }
-
- @Test public void testPushThroughGroup2() {
- helpPlan("select * FROM vm1.a2 WHERE e1 = 'x'", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1, e2 FROM pm1.g1 WHERE e1 = 'x'" } ); //$NON-NLS-1$
- }
-
- @Test public void testPushThroughGroup3() {
- helpPlan("select * FROM vm1.a3 WHERE sum_e2 > 0", example1(), //$NON-NLS-1$
- new String[] { "SELECT e2 FROM pm1.g1" } ); //$NON-NLS-1$
- }
-
- @Test public void testPushMultiGroupCriteria() {
- ProcessorPlan plan = 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)", example1(), //$NON-NLS-1$
- new String[] { "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))" } ); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testSimpleCrossJoin1() throws Exception {
- helpPlan("select pm1.g1.e1 FROM pm1.g1, pm1.g2", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
- "SELECT pm1.g2.e1 FROM pm1.g2" }, new DefaultCapabilitiesFinder(), ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
- }
-
- @Test public void testSimpleCrossJoin2() {
- helpPlan("select pm2.g1.e1 FROM pm2.g1, pm2.g2", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm2.g1.e1 FROM pm2.g1, pm2.g2"} ); //$NON-NLS-1$
-
- }
-
- @Test public void testSimpleCrossJoin3() {
- helpPlan("select pm2.g1.e1 FROM pm2.g1 CROSS JOIN pm2.g2", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm2.g1.e1 FROM pm2.g1, pm2.g2"} ); //$NON-NLS-1$
-
- }
-
- @Test public void testMultiSourceCrossJoin() throws Exception {
- helpPlan("select pm1.g1.e1 FROM pm1.g1, pm1.g2, pm1.g3", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
- "SELECT pm1.g2.e1 FROM pm1.g2", //$NON-NLS-1$
- "SELECT pm1.g3.e1 FROM pm1.g3" }, new DefaultCapabilitiesFinder(), ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
- }
-
- @Test public void testSingleSourceCrossJoin() {
- helpPlan("select pm2.g1.e1 FROM pm2.g1, pm2.g2, pm2.g3", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm2.g1.e1 FROM pm2.g1, pm2.g2, pm2.g3"} ); //$NON-NLS-1$
- }
-
- @Test public void testSelfJoins() {
- helpPlan("select pm2.g1.e1 FROM pm2.g1 JOIN pm2.g1 AS x ON pm2.g1.e1=x.e1", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm2.g1.e1 FROM pm2.g1 order by e1", //$NON-NLS-1$
- "SELECT x.e1 FROM pm2.g1 AS x order by e1" } ); //$NON-NLS-1$
- }
-
- @Test public void testDefect5282_1() {
- helpPlan("select * FROM vm1.a4 WHERE vm1.a4.count > 0", example1(), //$NON-NLS-1$
- new String[] { "SELECT 1 FROM pm1.g1" } ); //$NON-NLS-1$
- }
-
- @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$
- }
-
- @Test public void testDefect5282_3() {
- helpPlan("select * FROM vm1.a5 WHERE vm1.a5.count > 0", example1(), //$NON-NLS-1$
- new String[] { "SELECT 1 FROM pm1.g1" } ); //$NON-NLS-1$
- }
-
- @Test public void testDepJoinHintBaseline() throws Exception {
- ProcessorPlan plan = helpPlan("select * FROM vm1.g4", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
- "SELECT pm1.g2.e1 FROM pm1.g2" }, new DefaultCapabilitiesFinder(), ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @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$
- }
-
- @Test public void testDefect6425_2() {
- helpPlan("select count(*) from vm1.u9", example1(), //$NON-NLS-1$
- new String[] { "SELECT 1 FROM pm1.g1", //$NON-NLS-1$
- "SELECT 1 FROM pm1.g2" } ); //$NON-NLS-1$
- }
-
- @Test public void testPushMatchCritWithReference() throws Exception {
- List bindings = new ArrayList();
- bindings.add("pm1.g2.e1"); //$NON-NLS-1$
- helpPlan("select e1 FROM pm1.g1 WHERE e1 LIKE ?", example1(), bindings, null, //$NON-NLS-1$
- new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 LIKE PM1.G2.e1" }, ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
- }
-
- @Test public void testDefect6517() {
- helpPlan("select count(*) from vm1.g5", example1(), //$NON-NLS-1$
- new String[] { "SELECT DISTINCT pm1.g1.e1 FROM pm1.g1" }); //$NON-NLS-1$
- }
-
- @Test public void testDefect5283() {
- helpPlan("select * from vm1.a6", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1", //$NON-NLS-1$
- "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2" } ); //$NON-NLS-1$
- }
-
- @Test public void testManyJoinsOverThreshold() throws Exception {
- long begin = System.currentTimeMillis();
- helpPlan("SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2, pm1.g3, pm1.g4, pm1.g5, pm1.g6, pm1.g7, pm1.g8, pm1.g1 AS x, pm1.g2 AS y WHERE pm1.g1.e1 = pm1.g2.e1 AND pm1.g2.e1 = pm1.g3.e1 AND pm1.g3.e1 = pm1.g4.e1 AND pm1.g4.e1 = pm1.g5.e1 AND pm1.g5.e1=pm1.g6.e1 AND pm1.g6.e1=pm1.g7.e1 AND pm1.g7.e1=pm1.g8.e1", //$NON-NLS-1$
- example1(),
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
- "SELECT pm1.g2.e1 FROM pm1.g2", //$NON-NLS-1$
- "SELECT pm1.g3.e1 FROM pm1.g3", //$NON-NLS-1$
- "SELECT pm1.g4.e1 FROM pm1.g4", //$NON-NLS-1$
- "SELECT pm1.g5.e1 FROM pm1.g5", //$NON-NLS-1$
- "SELECT pm1.g6.e1 FROM pm1.g6", //$NON-NLS-1$
- "SELECT pm1.g7.e1 FROM pm1.g7", //$NON-NLS-1$
- "SELECT pm1.g8.e1 FROM pm1.g8", //$NON-NLS-1$
- "SELECT x.e1 FROM pm1.g1 AS x", //$NON-NLS-1$
- "SELECT y.e1 FROM pm1.g2 AS y" }, new DefaultCapabilitiesFinder(), ComparisonMode.CORRECTED_COMMAND_STRING ); //$NON-NLS-1$
-
- long elapsed = System.currentTimeMillis() - begin;
- assertTrue("Did not plan many join query in reasonable time frame: " + elapsed + " ms", elapsed < 4000); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testAggregateWithoutGroupBy() {
- ProcessorPlan plan = helpPlan("select count(e2) from pm1.g1", example1(), //$NON-NLS-1$
- new String[] { "SELECT e2 FROM pm1.g1" } ); //$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
- });
- }
-
- @Test public void testHavingWithoutGroupBy() {
- ProcessorPlan plan = helpPlan("select count(e2) from pm1.g1 HAVING count(e2) > 0", example1(), //$NON-NLS-1$
- new String[] { "SELECT e2 FROM pm1.g1" } ); //$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
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testHavingAndGroupBy() {
- ProcessorPlan plan = helpPlan("select e1, count(e2) from pm1.g1 group by e1 having count(e2) > 0 and sum(e2) > 0", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1, e2 FROM pm1.g1" } ); //$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
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testAllJoinsInSingleClause() throws Exception {
- ProcessorPlan plan = helpPlan("select pm1.g1.e1 FROM pm1.g1 join (pm1.g2 right outer join pm1.g3 on pm1.g2.e1=pm1.g3.e1) on pm1.g1.e1=pm1.g3.e1", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
- "SELECT pm1.g2.e1 FROM pm1.g2", //$NON-NLS-1$
- "SELECT pm1.g3.e1 FROM pm1.g3" }, new DefaultCapabilitiesFinder(), ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 3, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testSelectCountStarFalseCriteria() {
- ProcessorPlan plan = helpPlan("Select count(*) from pm1.g1 where 1=0", example1(), //$NON-NLS-1$
- new String[] { });
- checkNodeTypes(plan, new int[] {
- 0, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 1, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testSubquery1() {
- ProcessorPlan plan = helpPlan("Select e1 from (select e1 FROM pm1.g1) AS x", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testSubquery2() {
- ProcessorPlan plan = helpPlan("Select e1, a from (select e1 FROM pm1.g1) AS x, (select e1 as a FROM pm1.g2) AS y WHERE x.e1=y.a", example1(), //$NON-NLS-1$
- new String[] { "SELECT g_0.e1, g_1.e1 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 testSubquery3() {
- ProcessorPlan plan = helpPlan("Select e1 from (select e1 FROM pm1.g1) AS x WHERE x.e1 = 'a'", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 = 'a'" }); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testSubquery4() {
- ProcessorPlan plan = helpPlan("Select e1 from (select e1 FROM pm1.g1 WHERE e1 = 'a') AS x", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 = 'a'" }); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testSubqueryInClause1() {
- ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select e1 FROM pm2.g1)", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // 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 testCompareSubquery1() {
- ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 < ALL (select e1 FROM pm2.g1)", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // 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 testCompareSubquery3() {
- ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 >= all (select e1 FROM pm2.g1)", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // 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 testExistsSubquery1() {
- ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where exists (select e1 FROM pm2.g1)", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // 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 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$
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1" }, new DefaultCapabilitiesFinder(), ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testPushDistinct() {
- ProcessorPlan plan = helpPlan("select distinct e1 from pm3.g1", FakeMetadataFactory.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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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);
- }
-
- /**
- * Defect #7819
- */
- @Test public void testPushDistinctWithExpressions() {
- ProcessorPlan plan = helpPlan("SELECT DISTINCT * FROM vm1.g15", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
- new String[] { "SELECT e1, e2 FROM pm3.g1" }); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @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$
- new String[] { "SELECT IntKey, LongNum FROM BQT2.SmallA order by intkey" }); //$NON-NLS-1$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /** 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$
- new String[] { "SELECT pm3.g1.e1 FROM pm3.g1 ORDER BY pm3.g1.e1"}); //$NON-NLS-1$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /** 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$
- 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$
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 1, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Tests that user's order by gets pushed to the source, but query
- * 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$
- new String[] { "SELECT pm3.g1.e1, pm3.g1.e2 FROM pm3.g1 ORDER BY pm3.g1.e2"}); //$NON-NLS-1$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * 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$
- new String[] { "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 order by e2"}); //$NON-NLS-1$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * Tests that a user's order by does not get pushed to the source
- * 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$
- 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$
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 1, // Sort
- 1 // UnionAll
- });
- }
-
- /** Tests outer join defect #7945 - see also defect #10050*/
- @Test public void testOuterJoinDefect7945() {
- ProcessorPlan plan = helpPlan(
- "SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey, BQT3.MediumB.IntKey AS MediumC_IntKey " + //$NON-NLS-1$
- "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(),
- 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$
- "SELECT BQT2.MediumB.IntKey FROM BQT2.MediumB WHERE BQT2.MediumB.IntKey < 1500 order by intkey" }); //$NON-NLS-1$
-
- checkNodeTypes(plan, new int[] {
- 3, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /** Tests outer join defect #7945 */
- @Test public void testFunctionSimplification1() {
- ProcessorPlan plan = helpPlan(
- "SELECT x FROM vm1.g18 WHERE x = 92.0", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- new String[] {
- "SELECT e4 FROM pm1.g1 WHERE e4 = 0.92" }); //$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 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(),
- 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 );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @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(),
- 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$
- "SELECT c.e1 FROM pm2.g1 AS c"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 3, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testPushSelfJoin1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT a.e1, b.e2 FROM pm1.g1 a, pm1.g1 b WHERE a.e1 = b.e1", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT a.e1, b.e2 FROM pm1.g1 AS a, pm1.g1 AS b WHERE a.e1 = b.e1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushSelfJoin2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- metadata,
- null, capFinder,
- new String[] {"SELECT a.e1, a.e2, b.e2 FROM pm1.g1 AS a, pm1.g1 AS b WHERE a.e1 = b.e1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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 testPushOuterJoin1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- metadata,
- null, capFinder,
- new String[] {"SELECT pm1.g1.e1 FROM pm1.g2 LEFT OUTER JOIN pm1.g1 ON pm1.g1.e1 = pm1.g2.e1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushOuterJoin2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- metadata,
- null, capFinder,
- new String[] {"SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2"}, //$NON-NLS-1$ //$NON-NLS-2$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- // With join expression that can't be pushed
- @Test public void testPushOuterJoin3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- metadata,
- null, capFinder,
- new String[] {"SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2"}, //$NON-NLS-1$ //$NON-NLS-2$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- }
-
- @Test public void testPushGroupBy1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "SELECT e1, e2 as x FROM pm1.g1 GROUP BY e1, e2", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT e1, e2 FROM pm1.g1 GROUP BY e1, e2"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
-
- }
-
- @Test public void testPushGroupBy2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "SELECT e1, max(e2) as x FROM pm1.g1 GROUP BY e1", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT e1, MAX(e2) FROM pm1.g1 GROUP BY e1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
-
- }
-
- @Test public void testPushGroupBy3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "SELECT e1, e2 as x FROM pm1.g1 GROUP BY e1, e2", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT e1, e2 FROM pm1.g1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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
- });
-
- }
-
- @Test public void testPushGroupBy4() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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(),
- null, capFinder,
- new String[] {"SELECT MAX(e2) FROM pm1.g1 GROUP BY e1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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 testPushHaving1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "SELECT e1 FROM pm1.g1 GROUP BY e1 HAVING MAX(e1) = 'zzz'", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT e1 FROM pm1.g1 GROUP BY e1 HAVING MAX(e1) = 'zzz'"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushHaving2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "SELECT e1 FROM pm1.g1 GROUP BY e1 HAVING MAX(e1) = 'zzz'", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testPushHaving3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "SELECT e1 FROM pm1.g1 GROUP BY e1 HAVING MAX(e1) = 'zzz'", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testPushAggregate1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "SELECT MAX(e1) FROM pm1.g1", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT MAX(e1) FROM pm1.g1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushAggregate2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "SELECT MAX(e1) FROM pm1.g1 GROUP BY e1", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT MAX(e1) FROM pm1.g1 GROUP BY e1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushAggregate3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushAggregate4() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2 HAVING COUNT(e1) > 0", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2 HAVING COUNT(e1) > 0"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * Can't push aggs due to not being able to push COUNT in the HAVING clause.
- */
- @Test public void testPushAggregate5() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2 HAVING COUNT(e1) > 0", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT e2, e1 FROM pm1.g1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Can't push aggs due to not being able to push function inside the aggregate
- */
- @Test public void testPushAggregate6() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "SELECT COUNT(length(e1)) FROM pm1.g1", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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
- });
- }
-
- /**
- * Can't push aggs due to not being able to push function inside having
- */
- @Test public void testPushAggregate7() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "SELECT COUNT(*) FROM pm1.g1 GROUP BY e1 HAVING length(e1) > 0", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, capFinder,
- new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * BQT query that is failing
- */
- @Test public void testPushAggregate8() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- String sqlIn =
- "SELECT intkey FROM bqt1.smalla AS sa WHERE (sa.intkey = 46) AND " + //$NON-NLS-1$
- "(sa.stringkey IN (46)) AND (sa.datevalue = (" + //$NON-NLS-1$
- "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$
-
- ProcessorPlan plan = helpPlan(sqlIn,
- FakeMetadataFactory.exampleBQTCached(),
- null, capFinder,
- new String[] {sqlOut},
- ComparisonMode.EXACT_COMMAND_STRING );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testQueryManyJoin() throws Exception {
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushSelectDistinct() {
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushFunctionInCriteria1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT e1 FROM pm1.g1 WHERE upper(e1) = 'X'", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT e1 FROM pm1.g1 WHERE ucase(e1) = 'X'"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushFunctionInSelect1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
- caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT lower(e1) FROM pm1.g1 WHERE upper(e1) = 'X'", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT lower(e1) FROM pm1.g1 WHERE ucase(e1) = 'X'"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushFunctionInSelect2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
- caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT lower(e1), upper(e1), e2 FROM pm1.g1 WHERE upper(e1) = 'X'", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT lower(e1), upper(e1), e2 FROM pm1.g1 WHERE ucase(e1) = 'X'"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushFunctionInSelect3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
- caps.setFunctionSupport(SourceSystemFunctions.LCASE, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT lower(e1), upper(e1) FROM pm1.g1 WHERE upper(e1) = 'X'", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT e1 FROM pm1.g1 WHERE ucase(e1) = 'X'"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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 testPushFunctionInSelect4() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
- caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- metadata,
- null, capFinder,
- new String[] {"SELECT lcase(e1) FROM pm1.g1 WHERE ucase(e1) = 'X'"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushFunctionInSelect5() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
- caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- metadata,
- null, capFinder,
- new String[] {"SELECT ucase(e1), e1, lcase(e1) FROM pm1.g1 WHERE ucase(e1) = 'X'"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushFunctionInSelect6_defect_10081() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setFunctionSupport("upper", true); //$NON-NLS-1$
- caps.setFunctionSupport("lower", false); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT upper(lower(e1)) FROM pm1.g1", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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 testPushFunctionInSelectWithOrderBy1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
- caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT e1, lower(e1) FROM pm1.g1 WHERE upper(e1) = 'X' ORDER BY e1", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT e1, lcase(e1) FROM pm1.g1 WHERE ucase(e1) = 'X' ORDER BY e1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /** defect 13336 */
- @Test public void testPushFunctionInSelectWithOrderBy1a() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
- caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT e1, lower(e1) AS x FROM pm1.g1 WHERE upper(e1) = 'X' ORDER BY x", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT e1, lcase(e1) AS x FROM pm1.g1 WHERE ucase(e1) = 'X' ORDER BY x"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /** defect 13336 */
- @Test public void testPushFunctionInSelectWithOrderBy2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
- caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- metadata,
- null, capFinder,
- new String[] {"SELECT e1, lcase(e1) AS EXPR FROM pm1.g1 WHERE ucase(e1) = 'X' ORDER BY EXPR"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushFunctionInJoin1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- metadata,
- null, capFinder,
- new String[] {"SELECT pm1.g1.e1, pm1.g2.e3 FROM pm1.g1, pm1.g2 WHERE (pm1.g1.e1 = convert(pm1.g2.e2, string)) AND (ucase(pm1.g1.e1) = 'X') AND (ucase(convert(pm1.g2.e2, string)) = 'X')"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushFunctionInJoin2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- metadata,
- null, capFinder,
- new String[] {"SELECT pm1.g1.e1, pm1.g2.e3 FROM pm1.g1, pm1.g2 WHERE (pm1.g1.e1 = convert(pm1.g2.e2, string)) AND (ucase(pm1.g1.e1) = 'X') AND (ucase(convert(pm1.g2.e2, string)) = 'X')", //$NON-NLS-1$
- "SELECT pm1.g3.e1 FROM pm1.g3"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testPushFunctionInJoin3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- metadata,
- null, capFinder,
- new String[] {"SELECT pm1.g1.e1, pm1.g2.e3 FROM pm1.g1, pm1.g2 WHERE (pm1.g1.e1 = convert(pm1.g2.e2, string)) AND (ucase(pm1.g1.e1) = 'X') AND (ucase(convert(pm1.g2.e2, string)) = 'X')", //$NON-NLS-1$
- "SELECT e1 FROM pm1.g3"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testUnionOverFunctions() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT StringCol AS E " + //$NON-NLS-1$
- "FROM (SELECT CONVERT(BQT1.SmallA.IntNum, string) AS StringCol, BQT1.SmallA.IntNum AS IntCol FROM BQT1.SmallA " + //$NON-NLS-1$
- "UNION ALL SELECT BQT1.SmallB.StringNum, CONVERT(BQT1.SmallB.StringNum, integer) FROM BQT1.SmallB) AS x", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT CONVERT(BQT1.SmallA.IntNum, string) FROM BQT1.SmallA", //$NON-NLS-1$
- "SELECT BQT1.SmallB.StringNum FROM BQT1.SmallB"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- @Test public void testDefect9827() {
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
-
- 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
- 1, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * This tests that a criteria with no elements is not pushed down,
- * but instead is cleaned up properly later
- * See defect 9865
- */
- @Test public void testCrossJoinNoElementCriteriaOptimization2() {
- ProcessorPlan plan = helpPlan("select Y.e1, Y.e2 FROM vm1.g1 X, vm1.g1 Y where {b'true'} = {b'true'}", example1(), //$NON-NLS-1$
- new String[]{"SELECT 1 FROM pm1.g1 AS g1__1", "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}); //$NON-NLS-1$ //$NON-NLS-2$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * <p>This tests that a SELECT node with no groups is not pushed down without the capability to have a subquery in the where clause.
- */
- @Test public void testCrossJoinNoElementCriteriaOptimization3() {
- ProcessorPlan plan = helpPlan("select Y.e1, Y.e2 FROM vm1.g1 X, vm1.g1 Y where {b'true'} in (select e3 FROM vm1.g1)", example1(), //$NON-NLS-1$
- new String[]{"SELECT 1 FROM pm1.g1 AS g1__1", "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}); //$NON-NLS-1$ //$NON-NLS-2$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * <p>This tests that a SELECT node with no groups is pushed down.
- */
- @Test public void testCrossJoinNoElementCriteriaOptimization4() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan("select Y.e1, Y.e2 FROM vm1.g1 X, vm1.g1 Y where {b'true'} in (select e3 FROM vm1.g1)", example1(), null, capFinder, //$NON-NLS-1$
- new String[]{"SELECT 1 FROM pm1.g1 AS g1__1 WHERE TRUE IN (SELECT pm1.g1.e3 FROM pm1.g1)", "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}, true); //$NON-NLS-1$ //$NON-NLS-2$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Criteria should be copied across this join
- */
- @Test public void testCopyCriteriaWithOuterJoin_defect10050(){
-
- ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1 left outer join pm2.g2 on pm2.g1.e1=pm2.g2.e1 where pm2.g1.e1 IN ('a', 'b')", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm2.g1.e1, pm2.g2.e1 FROM pm2.g1 LEFT OUTER JOIN pm2.g2 ON pm2.g1.e1 = pm2.g2.e1 AND pm2.g2.e1 IN ('a', 'b') WHERE pm2.g1.e1 IN ('a', 'b')" }); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * Criteria should be copied across this join
- */
- @Test public void testCopyCriteriaWithOuterJoin2_defect10050(){
-
- ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1 left outer join pm2.g2 on pm2.g1.e1=pm2.g2.e1 and pm2.g1.e2=pm2.g2.e2 where pm2.g1.e1 = 'a' and pm2.g1.e2 = 1", example1(), //$NON-NLS-1$
- new String[] { "SELECT g_0.e1, g_1.e1 FROM pm2.g1 AS g_0 LEFT OUTER JOIN pm2.g2 AS g_1 ON g_0.e1 = g_1.e1 AND g_0.e2 = g_1.e2 AND g_1.e1 = 'a' AND g_1.e2 = 1 WHERE (g_0.e1 = 'a') AND (g_0.e2 = 1)" }); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * See also case 2912.
- */
- @Test public void testCopyCriteriaWithOuterJoin5_defect10050(){
-
- ProcessorPlan plan = helpPlan(
- "select pm2.g1.e1, pm2.g2.e1, pm2.g3.e1 from ( (pm2.g1 right outer join pm2.g2 on pm2.g1.e1=pm2.g2.e1) right outer join pm2.g3 on pm2.g2.e1=pm2.g3.e1) where pm2.g3.e1 = 'a'", example1(), //$NON-NLS-1$
- new String[] { "SELECT g_2.e1, g_1.e1, g_0.e1 FROM pm2.g3 AS g_0 LEFT OUTER JOIN (pm2.g2 AS g_1 LEFT OUTER JOIN pm2.g1 AS g_2 ON g_2.e1 = g_1.e1 AND g_2.e1 = 'a') ON g_1.e1 = g_0.e1 AND g_1.e1 = 'a' WHERE g_0.e1 = 'a'" }); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- *
- */
- @Test public void testCopyCriteriaWithOuterJoin6_defect10050(){
-
- ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1 left outer join pm2.g2 on pm2.g2.e1=pm2.g1.e1 where pm2.g1.e1 IN ('a', 'b')", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm2.g1.e1, pm2.g2.e1 FROM pm2.g1 LEFT OUTER JOIN pm2.g2 ON pm2.g2.e1 = pm2.g1.e1 AND pm2.g2.e1 IN ('a', 'b') WHERE pm2.g1.e1 IN ('a', 'b')" }); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * Same as previous test, only right outer join
- */
- @Test public void testCopyCriteriaWithOuterJoin7_defect10050(){
-
- ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1 right outer join pm2.g2 on pm2.g2.e1=pm2.g1.e1 where pm2.g2.e1 IN ('a', 'b')", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm2.g1.e1, pm2.g2.e1 FROM pm2.g2 LEFT OUTER JOIN pm2.g1 ON pm2.g2.e1 = pm2.g1.e1 AND pm2.g1.e1 IN ('a', 'b') WHERE pm2.g2.e1 IN ('a', 'b')" }); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testCleanCriteria(){
-
- ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1, pm2.g2 where pm2.g1.e1=pm2.g2.e1 and pm2.g1.e2 IN (1, 2)", example1(), //$NON-NLS-1$
- new String[] { "SELECT pm2.g1.e1, pm2.g2.e1 FROM pm2.g1, pm2.g2 WHERE (pm2.g1.e1 = pm2.g2.e1) AND (pm2.g1.e2 IN (1, 2))" }); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testCleanCriteria2(){
-
- ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1, pm2.g2 where pm2.g1.e1=pm2.g2.e1 and pm2.g1.e1 = 'a'", example1(), //$NON-NLS-1$
- new String[] { "SELECT g_0.e1, g_1.e1 FROM pm2.g1 AS g_0, pm2.g2 AS g_1 WHERE (g_0.e1 = g_1.e1) AND (g_0.e1 = 'a') AND (g_1.e1 = 'a')" }); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testCleanCriteria3(){
-
- ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1 inner join pm2.g2 on pm2.g1.e1=pm2.g2.e1 where pm2.g1.e1 = 'a'", example1(), //$NON-NLS-1$
- new String[] { "SELECT g_0.e1, g_1.e1 FROM pm2.g1 AS g_0, pm2.g2 AS g_1 WHERE (g_0.e1 = g_1.e1) AND (g_0.e1 = 'a') AND (g_1.e1 = 'a')" }); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
-
- @Test public void testPushSubqueryInWhereClause1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select e1 FROM pm1.g2)", example1(), //$NON-NLS-1$
- null, capFinder,
- new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 IN (SELECT e1 FROM pm1.g2)"}, SHOULD_SUCCEED ); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushSubqueryInWhereClause2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select max(e1) FROM pm1.g2)", example1(), //$NON-NLS-1$
- null, capFinder,
- new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 IN (SELECT MAX(e1) FROM pm1.g2)" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * Check that subquery is pushed if the subquery selects a function that is pushed
- */
- @Test public void testPushSubqueryInWhereClause3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setFunctionSupport("ltrim", true); //$NON-NLS-1$
- 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$
- 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);
- }
-
- /**
- * Check that subquery is pushed if the subquery selects an aliased function that is pushed
- */
- @Test public void testPushSubqueryInWhereClause4() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setFunctionSupport("ltrim", true); //$NON-NLS-1$
- 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$
- 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);
- }
-
- /** Case 1456, defect 10492*/
- @Test public void testAliasingDefect1(){
- // Create query
- String sql = "SELECT e1 FROM vm1.g1 X WHERE e2 = (SELECT MAX(e2) FROM vm1.g1 Y WHERE X.e1 = Y.e1)";//$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.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);
- }
-
- /** Case 1456, defect 10492*/
- @Test public void testAliasingDefect2(){
- // Create query
- String sql = "SELECT X.e1 FROM vm1.g1 X, vm1.g1 Z WHERE X.e2 = (SELECT MAX(e2) FROM vm1.g1 Y WHERE X.e1 = Y.e1 AND Y.e2 = Z.e2) AND X.e1 = Z.e1";//$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT g1__1.e1 FROM pm1.g1 AS g1__1, pm1.g1 AS g1__2 WHERE (g1__1.e2 = (SELECT MAX(pm1.g1.e2) FROM pm1.g1 WHERE (pm1.g1.e1 = g1__1.e1) AND (pm1.g1.e2 = g1__2.e2))) AND (g1__1.e1 = g1__2.e1)" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /** Case 1456, defect 10492*/
- @Test public void testAliasingDefect3() throws Exception {
- // Create query
- String sql = "SELECT X.e1 FROM pm1.g2, vm1.g1 X WHERE X.e2 = ALL (SELECT MAX(e2) FROM vm1.g1 Y WHERE X.e1 = Y.e1) AND X.e1 = pm1.g2.e1";//$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT g_1.e1 FROM pm1.g2 AS g_0, pm1.g1 AS g_1 WHERE (g_1.e1 = g_0.e1) AND (g_1.e2 = ALL (SELECT MAX(g_2.e2) FROM pm1.g1 AS g_2 WHERE g_2.e1 = g_1.e1))" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /** Should use merge join since neither access node is "strong" - order by's pushed to source */
- @Test public void testUseMergeJoin3(){
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- 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));
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY pm1.g1.e1", "SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY pm1.g2.e1" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /** Model supports order by, should be pushed to the source */
- @Test public void testUseMergeJoin4(){
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- 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));
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY pm1.g1.e1", "SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY pm1.g2.e1" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /** Should use merge join, since costs are not known, neither access node is "strong" */
- @Test public void testUseMergeJoin5_CostsNotKnown(){
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /** one side of join supports order by, the other doesn't*/
- @Test public void testUseMergeJoin7(){
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g2 WHERE pm1.g1.e1 = pm2.g2.e1";//$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- caps = new BasicSourceCapabilities();
- 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));
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY pm1.g1.e1", "SELECT pm2.g2.e1 FROM pm2.g2" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /** reverse of testUseMergeJoin7 */
- @Test public void testUseMergeJoin7a(){
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g2 WHERE pm1.g1.e1 = pm2.g2.e1";//$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- 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));
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm2.g2.e1 FROM pm2.g2 ORDER BY pm2.g2.e1" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /** function on one side of join should prevent order by from being pushed down*/
- @Test public void testUseMergeJoin8(){
- // 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- 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));
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm2.g2.e1 FROM pm2.g2 ORDER BY pm2.g2.e1" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /** Model supports order by, functions in join criteria */
- @Test public void testUseMergeJoin9(){
- // 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- 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));
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 3, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /** should be one dependent join */
- @Test public void testMultiMergeJoin1(){
- // 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- 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));
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2", "SELECT pm1.g3.e1 FROM pm1.g3" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- checkNodeTypes(plan, new int[] {
- 3, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testLargeSetCriteria() {
- // Create query
- String sql = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA INNER JOIN BQT2.SmallB ON BQT1.SmallA.IntKey = BQT2.SmallB.IntKey WHERE BQT1.SmallA.IntKey IN (1,2,3,4,5)"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.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$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 2, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testMergeJoin_defect11236(){
- // Create query
- String sql = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA, BQT1.SmallB WHERE BQT1.SmallA.IntKey = (BQT1.SmallB.IntKey + 1)"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT BQT1.SmallB.IntKey FROM BQT1.SmallB", //$NON-NLS-1$
- "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA ORDER BY BQT1.SmallA.IntKey" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testNoFrom() {
- ProcessorPlan plan = helpPlan("SELECT 1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
- new String[] {} );
-
- checkNodeTypes(plan, new int[] {
- 0, // 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 testINCriteria_defect10718(){
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- 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));
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY pm1.g1.e1", "SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY pm1.g2.e1"}, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testDefect10711(){
- ProcessorPlan plan = helpPlan("SELECT * from vm1.g1a as X", FakeMetadataFactory.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);
-
- }
-
- // 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$
- new String[] { "SELECT IntKey FROM BQT1.SmallA" }); //$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
- });
- }
-
- /** 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$
- new String[] { "SELECT e1 FROM pm1.g2 WHERE LOOKUP('pm1.g1', 'e1', 'e2', 1) IS NULL" }); //$NON-NLS-1$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
-
- }
-
- /** 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$
- 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[] {
- 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
- });
-
- }
-
- /** 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$
- new String[] { "SELECT e1, LOOKUP('pm1.g1','e1', 'e2', 1) FROM pm1.g2" }); //$NON-NLS-1$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- // 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$
- 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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- // 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$
- 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$
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- // 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$
- 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$
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- @Test public void testCountStarOverSelectDistinct() {
- ProcessorPlan plan = helpPlan("SELECT COUNT(*) FROM (SELECT DISTINCT IntNum, Intkey FROM bqt1.smalla) AS x", FakeMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
- new String[] {
- "SELECT DISTINCT IntNum, Intkey FROM bqt1.smalla" }); //$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
- });
- }
-
- //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$
- new String[] { "SELECT e2 FROM pm1.g1" } ); //$NON-NLS-1$
-
- checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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(),
- 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$
-
- 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 void helpTestUnionPushdown(boolean queryHasOrderBy, boolean hasUnionCapability, boolean hasUnionOrderByCapability) {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, hasUnionCapability);
- caps.setCapabilitySupport((Capability.QUERY_ORDERBY), hasUnionOrderByCapability);
- caps.setCapabilitySupport((Capability.QUERY_SET_ORDER_BY), hasUnionOrderByCapability);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- String sqlUnion = "SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB";//$NON-NLS-1$
- String sqlOrderBy = sqlUnion + " ORDER BY IntKey"; //$NON-NLS-1$
- String sql = null;
- if(queryHasOrderBy) {
- sql = sqlOrderBy;
- } else {
- sql = sqlUnion;
- }
-
- String[] expectedSql = null;
- if(hasUnionCapability) {
- if(queryHasOrderBy && hasUnionOrderByCapability) {
- expectedSql = new String[] {sqlOrderBy };
- } else {
- expectedSql = new String[] {sqlUnion };
- }
- } else {
- expectedSql = new String[] { "SELECT IntKey FROM BQT1.SmallA", "SELECT IntKey FROM BQT1.SmallB" }; //$NON-NLS-1$//$NON-NLS-2$
- }
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder, expectedSql, SHOULD_SUCCEED);
-
- int accessCount = hasUnionCapability ? 1 : 2;
- int projectCount = 0;
- int sortCount = 0;
- if(queryHasOrderBy && ! (hasUnionCapability && hasUnionOrderByCapability)) {
- sortCount = 1;
- }
- int unionCount = hasUnionCapability ? 0 : 1;
-
-
-
- checkNodeTypes(plan, new int[] {
- accessCount, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- projectCount, // Project
- 0, // Select
- sortCount, // Sort
- unionCount // UnionAll
- });
- }
-
- /**
- * Query has union but no order by and no capabilities.
- */
- @Test public void testUnionPushdown1() {
- helpTestUnionPushdown(false, false, false);
- }
-
- /**
- * Query has union but no order by and only union capability.
- */
- @Test public void testUnionPushdown2() {
- helpTestUnionPushdown(false, true, false);
- }
-
- /**
- * Query has union with order by and no capabilities.
- */
- @Test public void testUnionPushdown3() {
- helpTestUnionPushdown(true, false, false);
- }
-
- /**
- * Query has union with order by and just union capability.
- */
- @Test public void testUnionPushdown4() {
- helpTestUnionPushdown(true, true, false);
- }
-
- /**
- * Query has union with order by and both capabilities.
- */
- @Test public void testUnionPushdown5() {
- helpTestUnionPushdown(true, true, true);
- }
-
- @Test public void testUnionPushdownWithSelectNoFrom() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- 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$
- null, capFinder, new String[] {}, SHOULD_SUCCEED);
-
- checkNodeTypes(plan, new int[] {
- 0, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- @Test public void testUnionPushdownWithSelectNoFromFirstBranch() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- 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$
- null, capFinder, new String[] {"SELECT IntKey FROM BQT1.SmallA"}, SHOULD_SUCCEED); //$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
- 1 // UnionAll
- });
- }
-
- @Test public void testUnionPushdownWithSelectNoFromSecondBranch() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- 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$
- null, capFinder, new String[] {"SELECT IntKey FROM BQT1.SmallA"}, SHOULD_SUCCEED); //$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
- 1 // UnionAll
- });
- }
-
- @Test public void testUnionPushdownMultipleBranches() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- 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$
- 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);
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testUnionPushdownMultipleBranchesMixedModels1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
- 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$
- 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);
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- @Test public void testUnionPushdownMultipleBranchesNoDupRemoval() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- 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$
- 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);
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testAggregateOverUnionPushdown() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- 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$
- null, capFinder,
- new String[] {"SELECT IntKey FROM BQT1.SmallA UNION SELECT IntKey FROM BQT1.SmallB"}, //$NON-NLS-1$
- SHOULD_SUCCEED);
-
- 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
- });
- }
-
- @Test public void testUnionPushdownWithFunctionsAndAliases() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
- 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$
- 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);
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testUnionPushdownWithInternalOrderBy() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
- 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$
- null, capFinder,
- new String[] {"SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB"}, //$NON-NLS-1$
- SHOULD_SUCCEED);
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testUnionPushdownWithInternalDistinct() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = helpPlan("SELECT DISTINCT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB", metadata, //$NON-NLS-1$
- null, capFinder,
- new String[] {"SELECT DISTINCT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB"}, //$NON-NLS-1$
- SHOULD_SUCCEED);
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testUnionNoAllPushdownInInlineView() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
- 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$
- 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);
-
- 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 testUnionAllPushdownInInlineView() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
- 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$
- null, capFinder,
- new String[] {"SELECT StringKey AS x FROM BQT1.SmallA UNION ALL SELECT StringKey FROM BQT1.SmallB"}, //$NON-NLS-1$
- SHOULD_SUCCEED);
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testUnionAllPushdownVirtualGroup() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
- 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$
- null, capFinder,
- new String[] {"SELECT e1 FROM pm1.g1 UNION ALL SELECT convert(e2, string) FROM pm1.g2"}, //$NON-NLS-1$
- SHOULD_SUCCEED);
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testUnionAllPushdownVirtualGroup2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- 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$
- 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);
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testUnionAllPushdownVirtualGroup3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
- 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(),
- null, capFinder,
- new String[] {"SELECT intkey FROM BQT1.SmallA", "SELECT IntNum FROM bqt1.smalla"}, //$NON-NLS-1$ //$NON-NLS-2$
- SHOULD_SUCCEED);
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- // Allow pushing literals
- @Test public void testUnionAllPushdownVirtualGroup4() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- 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(),
- null, capFinder,
- new String[] {"SELECT intkey, 5 FROM BQT1.SmallA UNION ALL SELECT IntNum, 10 FROM bqt1.smalla"}, //$NON-NLS-1$
- SHOULD_SUCCEED);
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushCaseInSelect() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_CASE, true);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT CASE WHEN e1 = 'a' THEN 10 ELSE 0 END FROM pm1.g1", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT CASE WHEN e1 = 'a' THEN 10 ELSE 0 END FROM pm1.g1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testCantPushCaseInSelectWithFunction() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_CASE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT CASE e1 WHEN 'a' THEN 10 ELSE (e2+0) END FROM pm1.g1", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT e1, e2 FROM pm1.g1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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 testPushSearchedCaseInSelect() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT CASE WHEN e1 = 'a' THEN 10 ELSE 0 END FROM pm1.g1", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT CASE WHEN e1 = 'a' THEN 10 ELSE 0 END FROM pm1.g1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testCantPushSearchedCaseInSelectWithFunction() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT CASE WHEN e1 = 'a' THEN 10 ELSE (e2+0) END FROM pm1.g1", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT e1, e2 FROM pm1.g1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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 testPushdownFunctionNotEvaluated() {
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
- 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);
-
-
- ProcessorPlan plan = helpPlan(
- "SELECT e1 FROM pm1.g1 WHERE xyz() > 0", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT e1 FROM pm1.g1 WHERE xyz() > 0"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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$
- new String[] { });
-
- checkNodeTypes(plan, new int[] {
- 0, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /** defect 14510 */
- @Test public void testDefect14510LookupFunction() throws Exception {
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- 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$
-
- 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$
- metadata,
- null, capFinder,
- new String[] {"SELECT g_1.StringKey, g_0.IntKey FROM BQT1.SmallA AS g_0, BQT1.SmallB AS g_1 WHERE g_0.IntKey = 1"}, //$NON-NLS-1$ //$NON-NLS-2$
- SHOULD_SUCCEED );
-
- 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
- });
- }
-
- /** defect 14510 */
- @Test public void testDefect14510LookupFunction2() throws Exception {
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- 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$
-
- 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$
- metadata,
- null, capFinder,
- new String[] {"SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA", "SELECT BQT1.MediumB.StringKey, BQT1.MediumB.IntKey FROM BQT1.MediumB"}, //$NON-NLS-1$ //$NON-NLS-2$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /** defect 14510 */
- @Test public void testDefect14510LookupFunction3() throws Exception {
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- 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$
-
- 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$
- metadata,
- null, capFinder,
- new String[] {"SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA", "SELECT BQT1.MediumB.StringKey, BQT1.MediumB.IntKey FROM BQT1.MediumB"}, //$NON-NLS-1$ //$NON-NLS-2$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testCase2125() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, false);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- String sql = "SELECT OD.IntKEy, P.IntKEy, O.IntKey " + //$NON-NLS-1$
- "FROM (bqt1.smalla AS OD INNER JOIN bqt1.smallb AS P ON OD.StringKey = P.StringKey) " + //$NON-NLS-1$
- "INNER JOIN bqt1.mediuma AS O ON O.IntKey = OD.IntKey " + //$NON-NLS-1$
- "WHERE (OD.IntNum > (SELECT SUM(IntNum) FROM bqt1.smalla)) AND " + //$NON-NLS-1$
- "(P.longnum > (SELECT AVG(LongNum) FROM bqt1.smallb WHERE bqt1.smallb.datevalue = O.datevalue))"; //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- FakeMetadataFactory.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 );
-
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // 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 testPushdownLiteralInSelectUnderAggregate() {
- String sql = "SELECT COUNT(*) FROM (SELECT '' AS y, a.IntKey FROM BQT1.SmallA a union all select '', b.intkey from bqt1.smallb b) AS x"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- FakeMetadataFactory.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 );
-
- 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
- });
- }
-
- @Test public void testPushdownLiteralInSelectUnderAggregate2() {
- String sql = "SELECT SUM(z) FROM (SELECT '' AS y, a.IntKey as z FROM BQT1.SmallA a union all select b.stringkey, 0 from bqt1.smallb b) AS x group by z"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- FakeMetadataFactory.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 );
-
- 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
- });
- }
-
- @Test public void testPushdownLiteralInSelectUnderAggregate3() {
- String sql = "SELECT code, SUM(ID) FROM (SELECT IntKey AS ID, '' AS Code FROM BQT1.SmallA union all select intkey, stringkey from bqt1.smallb b) AS x group by code"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- FakeMetadataFactory.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 );
-
- 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
- });
- }
-
- @Test public void testPushdownLiteralInSelectWithOrderBy() {
- String sql = "SELECT 1, concat('a', 'b' ) AS X FROM BQT1.SmallA where intkey = 0 " + //$NON-NLS-1$
- "UNION ALL " + //$NON-NLS-1$
- "select 2, 'Hello2' from BQT1.SmallA where intkey = 1 order by X desc"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- FakeMetadataFactory.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 );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testUpdateWithElement() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setFunctionSupport(SourceSystemFunctions.ADD_OP, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- String sql = "UPDATE BQT1.SmallA SET IntKey = IntKey + 1"; //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- FakeMetadataFactory.exampleBQTCached(),
- null, capFinder,
- new String[] {"UPDATE BQT1.SmallA SET IntKey = (IntKey + 1)"}, //$NON-NLS-1$
- ComparisonMode.EXACT_COMMAND_STRING );
-
- checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testCase2187() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {"SELECT a.IntKey FROM ((bqt1.smalla AS a LEFT OUTER JOIN bqt1.smallb AS b ON a.intkey = b.intkey) CROSS JOIN bqt1.smalla AS x) FULL OUTER JOIN bqt1.smallb AS c ON a.IntKey = c.intkey"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testMultiUnionMergeVirtual() throws Exception {
- String sql = "SELECT * FROM " + //$NON-NLS-1$
- "(SELECT IntKey, 'a' AS s FROM (SELECT intkey, stringkey from BQT1.SmallA) as a union all " + //$NON-NLS-1$
- "select IntKey, 'b' FROM (SELECT intkey, stringkey from BQT1.SmallA) as b union all " + //$NON-NLS-1$
- "select IntKey, 'c' FROM (SELECT intkey, stringkey from BQT1.SmallA) as c " + //$NON-NLS-1$
- ") AS x"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- FakeMetadataFactory.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 );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testDefect16848_groupAliasNotSupported_1() {
- String sql = "SELECT sa.intkey, sa.objectvalue FROM bqt1.smalla AS sa WHERE (sa.intkey = 46) AND (sa.stringkey IN (46)) AND (sa.datevalue = (SELECT MAX(sb.datevalue) FROM bqt1.smalla AS sb WHERE (sb.intkey = sa.intkey) AND (sa.stringkey = sb.stringkey) ))"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- RelationalPlan plan = (RelationalPlan)helpPlan(sql,
- FakeMetadataFactory.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 );
-
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- ProcessorPlan subplan = ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(((SelectNode)plan.getRootNode().getChildren()[0]).getCriteria()).get(0).getCommand().getProcessorPlan();
-
- // Collect atomic queries
- Set<String> actualQueries = getAtomicQueries(subplan);
-
- // Compare atomic queries
- HashSet<String> expectedQueries = new HashSet<String>(Arrays.asList(new String[] { "SELECT bqt1.smalla.datevalue FROM bqt1.smalla WHERE (bqt1.smalla.intkey = bqt1.smalla.intkey) AND (bqt1.smalla.stringkey = bqt1.smalla.stringkey)"})); //$NON-NLS-1$
- assertEquals("Did not get expected atomic queries for subplan: ", expectedQueries, actualQueries); //$NON-NLS-1$
-
- checkNodeTypes(subplan, 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
- });
-
- }
-
- @Test public void testFunctionOfAggregate1() {
- String sql = "SELECT SUM(IntKey) + 1 AS x FROM BQT1.SmallA GROUP BY IntKey"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- caps.setFunctionSupport("+", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- FakeMetadataFactory.exampleBQTCached(),
- null, capFinder,
- new String[] {"SELECT (SUM(IntKey) + 1) FROM BQT1.SmallA GROUP BY IntKey"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testFunctionOfAggregateCantPush1() {
- String sql = "SELECT SUM(IntKey) + 1 AS x FROM BQT1.SmallA GROUP BY IntKey"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- FakeMetadataFactory.exampleBQTCached(),
- null, capFinder,
- new String[] {"SELECT IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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
- });
- }
-
- @Test public void testFunctionOfAggregateCantPush3() {
- String sql = "SELECT avg(intkey) * 2 FROM BQT1.SmallA "; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- FakeMetadataFactory.exampleBQTCached(),
- null, capFinder,
- new String[] {"SELECT intkey FROM BQT1.SmallA"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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
- });
- }
-
- private void helpTestCase2589NonPushdown(String sql, String[] expected) {
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, false);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
-
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- expected,
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- }
-
- private void helpTestCase2589(String sql, String expected) throws Exception {
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
-
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {expected},
- ComparisonMode.EXACT_COMMAND_STRING );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testCase2589() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589 ON MediumA.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
-
- helpTestCase2589(sql, expected);
- }
-
- @Test public void testCase2589a() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589a ON MediumA.IntKey = SmallA_2589a.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.IntKey = BQT1.SmallB.IntKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- @Test public void testCase2589b() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- @Test public void testCase2589c() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB, BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey " + //$NON-NLS-1$
- "WHERE BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB INNER JOIN (BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10') ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- @Test public void testCase2589d() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB INNER JOIN " + //$NON-NLS-1$
- "(BQT1.MediumA LEFT OUTER JOIN VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey) " + //$NON-NLS-1$
- "ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB INNER JOIN (BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10') ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- @Test public void testCase2589e() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB LEFT OUTER JOIN " + //$NON-NLS-1$
- "(BQT1.MediumA LEFT OUTER JOIN VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey) " + //$NON-NLS-1$
- "ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB LEFT OUTER JOIN (BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10') ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- @Test public void testCase2589f() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB LEFT OUTER JOIN " + //$NON-NLS-1$
- "(BQT1.MediumA INNER JOIN VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey) " + //$NON-NLS-1$
- "ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB LEFT OUTER JOIN (BQT1.MediumA INNER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey) ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey AND BQT1.SmallA.StringNum = '10'";//$NON-NLS-1$";
- helpTestCase2589(sql, expected);
- }
-
- @Test public void testCase2589g() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB LEFT OUTER JOIN " + //$NON-NLS-1$
- "(BQT1.MediumA INNER JOIN VQT.SmallA_2589c ON MediumA.IntKey = SmallA_2589c.IntKey) " + //$NON-NLS-1$
- "ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB LEFT OUTER JOIN " + //$NON-NLS-1$
- "(BQT1.MediumA INNER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB " + //$NON-NLS-1$
- "ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey AND " + //$NON-NLS-1$
- "concat(BQT1.SmallA.StringNum, BQT1.SmallB.StringNum) = '1010') " + //$NON-NLS-1$
- "ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey) ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- @Test public void testCase2589h() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN VQT.SmallA_2589c " + //$NON-NLS-1$
- "ON MediumA.IntKey = SmallA_2589c.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey AND concat(BQT1.SmallA.StringNum, BQT1.SmallB.StringNum) = '1010') ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- @Test public void testCase2589i() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN VQT.SmallA_2589d " + //$NON-NLS-1$
- "ON MediumA.IntKey = SmallA_2589d.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' AND BQT1.SmallA.IntNum = 10"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- /**
- * Test optimization doesn't happen if an outer join isn't involved
- */
- @Test public void testCase2589j() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA INNER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589 ON MediumA.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA, BQT1.SmallA WHERE (BQT1.MediumA.IntKey = BQT1.SmallA.IntKey) AND (BQT1.SmallA.StringNum = '10')"; //$NON-NLS-1$
-
- helpTestCase2589(sql, expected);
- }
-
- /**
- * Test optimization doesn't happen if an outer join isn't involved
- */
- @Test public void testCase2589k() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA INNER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA, BQT1.SmallA, BQT1.SmallB WHERE (BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) AND (BQT1.MediumA.IntKey = BQT1.SmallA.IntKey) AND (BQT1.SmallA.StringNum = '10')"; //$NON-NLS-1$
-
-
- helpTestCase2589(sql, expected);
- }
-
- /**
- * Same as testCase2589 except right outer join
- */
- @Test public void testCase2589l() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM VQT.SmallA_2589 RIGHT OUTER JOIN " + //$NON-NLS-1$
- "BQT1.MediumA ON MediumA.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
-
- helpTestCase2589(sql, expected);
- }
-
- /**
- * Same as testCase2589 except full outer join - criteria "below" full outer join cannot be
- * raised into the join criteria, so basically the virtual groups cannot be merged in this test.
- */
- @Test public void testCase2589m() {
- String sql = "SELECT BQT1.MediumA.IntKey FROM VQT.SmallA_2589 FULL OUTER JOIN " + //$NON-NLS-1$
- "BQT1.MediumA ON MediumA.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
-
- String[] expected = new String[] {
- "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA", //$NON-NLS-1$
- "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA WHERE StringNum = '10'" //$NON-NLS-1$
- };
-
- helpTestCase2589NonPushdown(sql, expected);
- }
-
- /**
- * Same as testCase2589b except full outer join
- */
- @Test public void testCase2589n() {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA FULL OUTER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey"; //$NON-NLS-1$
-
- String[] expected = new String[] {
- "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA", //$NON-NLS-1$
- "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA, BQT1.SmallB WHERE (BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) AND (BQT1.SmallA.StringNum = '10')" //$NON-NLS-1$
- };
- helpTestCase2589NonPushdown(sql, expected);
-
- }
-
- /**
- * Same as testCase2589 except with two virtual layers instead of one
- */
- @Test public void testCase2589o() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589f ON MediumA.IntKey = SmallA_2589f.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
-
- helpTestCase2589(sql, expected);
- }
-
- /**
- * Same as testCase2589b except with two virtual layers instead of one
- */
- @Test public void testCase2589p() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589g ON MediumA.IntKey = SmallA_2589g.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- /**
- * Test 3 frames, where top frame has outer join, middle frame has inner join, and
- * bottom frame has criteria that must be made into join criteria.
- */
- @Test public void testCase2589q() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589h ON MediumA.IntKey = SmallA_2589h.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- /**
- * Similar to testCase2589b, except virtual transformation has criteria on an
- * element from each physical table
- */
- @Test public void testCase2589r() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589i ON MediumA.IntKey = SmallA_2589i.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' AND BQT1.SmallB.StringNum = '10'"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- /**
- * Test user criteria that should NOT be moved into join clause
- */
- @Test public void testCase2589s() throws Exception {
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589 ON MediumA.IntKey = SmallA_2589.IntKey " + //$NON-NLS-1$
- "WHERE BQT1.MediumA.IntNum = 10"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' WHERE BQT1.MediumA.IntNum = 10"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- /**
- * Test user criteria that should NOT be moved into join clause
- */
- @Test public void testCase2589t() throws Exception {
- String sql = "SELECT z.IntKey FROM (SELECT IntKey FROM BQT1.MediumA WHERE BQT1.MediumA.IntNum = 10) as z " + //$NON-NLS-1$
- "LEFT OUTER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589 ON z.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' WHERE BQT1.MediumA.IntNum = 10"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- /**
- * The above test written with an inline view instead of a virtual group.
- * This test translates to - how can this query be rewritten without subqueries such
- * that the same results are produced? More specifically, where should the criteria
- * go - WHERE clause or FROM clause?
- */
- @Test public void testCase2589u() throws Exception {
- String sql = "SELECT z.IntKey FROM (SELECT IntKey FROM BQT1.MediumA WHERE IntNum = 10) as z " + //$NON-NLS-1$
- "LEFT OUTER JOIN " + //$NON-NLS-1$
- "(SELECT IntKey FROM BQT1.SmallA WHERE StringNum = '10') as y " + //$NON-NLS-1$
- "ON z.IntKey = y.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' WHERE BQT1.MediumA.IntNum = 10"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- /**
- * Same sql as testCase2589, but the model doesn't support outer joins, so
- * case 2589 optimization shouldn't happen.
- */
- @Test public void testCase2589v() {
-
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589 ON MediumA.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
-
- String expected[] = new String[] {
- "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA", //$NON-NLS-1$
- "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA WHERE StringNum = '10'" //$NON-NLS-1$
- };
-
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, false);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
-
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- expected,
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Same as previous testCase2589v, but with full outer join.
- */
- @Test public void testCase2589w() {
-
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA FULL OUTER JOIN " + //$NON-NLS-1$
- "VQT.SmallA_2589 ON MediumA.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
-
- String expected[] = new String[] {
- "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA", //$NON-NLS-1$
- "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA WHERE StringNum = '10'" //$NON-NLS-1$
- };
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, false);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
-
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- expected,
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Test a complicated join tree involving multiple models, but with a nested
- * outer join predicate spanning only one model, and see if the case 2589
- * fix happens. The important thing is the criteria "StringNum = '10'" needs
- * to be put in the join criteria, not the where clause, of the second atomic
- * query, because in the user query it is on the inner side of an outer join.
- */
- @Test public void testCase2589x() throws Exception {
-
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT2.SmallA INNER JOIN " + //$NON-NLS-1$
- "(BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
- "(SELECT IntKey FROM BQT1.SmallA WHERE StringNum = '10') as y " + //$NON-NLS-1$
- "ON MediumA.IntKey = y.IntKey) " + //$NON-NLS-1$
- "ON BQT2.SmallA.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
-
- String expected[] = new String[] {
- "SELECT BQT2.SmallA.IntKey FROM BQT2.SmallA", //$NON-NLS-1$
- "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'" //$NON-NLS-1$
- };
-
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
-
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- expected,
- ComparisonMode.EXACT_COMMAND_STRING );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Test two outer joins, one nested within the other, all pushable to one source,
- * with inline views having criteria that each need to be migrated to their
- * respective join predicate join criteria.
- *
- * The tree below illustrates the canonical plan (plus access nodes). 'y' and
- * 'z' are two inline views. Notice each has a SELECT node underneath - the
- * criteria represented by each of those SELECT nodes is on the inner side of
- * their respective left outer joins (LOJ). So, each criteria needs to be
- * migrated to the join criteria.
- *
- * <pre>
- * LOJ
- * / \
- * LOJ SRC z
- * / \ |
- * SRC SRC y SEL
- * MedB | |
- * SEL ACC
- * | |
- * ACC SRC SmA
- * |
- * SRC MedA
- * </pre>
- * Here's a diagram of what the join plan of the resulting atomic query should
- * look like.
- * <pre>
- * ACC
- * |
- * LOJ**
- * / \
- * LOJ** SRC **criteria migrated to here
- * / \ SmA
- * SRC SRC
- * MedB MedA
- * </pre>
- */
- @Test public void testCase2589y() throws Exception {
- String sql = "SELECT L.IntKey, y.IntKey, z.IntKey " + //$NON-NLS-1$
- "FROM (BQT1.MediumB as L LEFT OUTER JOIN " + //$NON-NLS-1$
- "(SELECT IntKey FROM BQT1.MediumA as M WHERE M.IntNum = 4) as y ON y.IntKey = L.IntKey) " + //$NON-NLS-1$
- "LEFT OUTER JOIN (SELECT IntKey FROM BQT1.SmallA as S WHERE S.StringNum = '10') as z " + //$NON-NLS-1$
- "ON z.IntKey = y.IntKey"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumB.IntKey, BQT1.MediumA.IntKey, BQT1.SmallA.IntKey " + //$NON-NLS-1$
- "FROM (BQT1.MediumB LEFT OUTER JOIN " + //$NON-NLS-1$
- "BQT1.MediumA ON BQT1.MediumA.IntKey = BQT1.MediumB.IntKey AND BQT1.MediumA.IntNum = 4) " + //$NON-NLS-1$
- "LEFT OUTER JOIN BQT1.SmallA " + //$NON-NLS-1$
- "ON BQT1.SmallA.IntKey = BQT1.MediumA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- /**
- * Test a complicated join tree involving multiple models, but with a nested
- * outer join predicate spanning only one model, and see if the case 2589
- * fix happens. The important thing is the criteria "StringNum = '10'" needs
- * to be put in the join criteria, not the where clause, of the second atomic
- * query, because in the user query it is on the inner side of an outer join.
- */
- @Test public void testCase2589z() {
-
- String sql = "SELECT BQT1.MediumA.IntKey FROM BQT2.SmallA INNER JOIN " + //$NON-NLS-1$
- "(BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
- "(SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA, BQT1.SmallB " + //$NON-NLS-1$
- "WHERE BQT1.SmallA.IntKey = BQT1.SmallB.IntKey AND BQT1.SmallA.StringNum = '10') as y " + //$NON-NLS-1$
- "ON MediumA.IntKey = y.IntKey) " + //$NON-NLS-1$
- "ON BQT2.SmallA.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
-
- String expected[] = new String[] {
- "SELECT BQT2.SmallA.IntKey FROM BQT2.SmallA", //$NON-NLS-1$
- "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.IntKey = BQT1.SmallB.IntKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'" //$NON-NLS-1$
- };
-
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
-
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- expected,
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Union with multiple joins underneath
- */
- @Test public void testCase2589aa() throws Exception {
- String sql = "SELECT * FROM (SELECT z.IntKey FROM (SELECT IntKey FROM BQT1.MediumA WHERE IntNum = 10) as z " + //$NON-NLS-1$
- "LEFT OUTER JOIN " + //$NON-NLS-1$
- "(SELECT IntKey FROM BQT1.SmallA WHERE StringNum = '10') as y " + //$NON-NLS-1$
- "ON z.IntKey = y.IntKey " + //$NON-NLS-1$
- "UNION ALL SELECT z.IntKey FROM (SELECT IntKey FROM BQT1.MediumA WHERE IntNum = 10) as z " + //$NON-NLS-1$
- "LEFT OUTER JOIN " + //$NON-NLS-1$
- "(SELECT IntKey FROM BQT1.SmallA WHERE StringNum = '10') as y " + //$NON-NLS-1$
- "ON z.IntKey = y.IntKey) as x"; //$NON-NLS-1$
-
- String expected = "SELECT BQT1.MediumA.IntKey AS c_0 FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' WHERE BQT1.MediumA.IntNum = 10 UNION ALL SELECT BQT1.MediumA.IntKey AS c_0 FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' WHERE BQT1.MediumA.IntNum = 10"; //$NON-NLS-1$
- helpTestCase2589(sql, expected);
- }
-
- /**
- * A final rewrite will ensure the correct order by
- */
- @Test public void testOrderByDuplicates() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
- ComparisonMode.EXACT_COMMAND_STRING );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- //Test use of OrderBy with expression
- @Test public void testCase2507() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport("||", true); //$NON-NLS-1$
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- String sql = "SELECT vqt.smallb.a12345 FROM vqt.smallb ORDER BY vqt.smallb.a12345"; //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {"SELECT Concat(stringKey, stringNum) AS EXPR FROM BQT1.SmallA ORDER BY EXPR"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testCase2507A() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {"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$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testCase2507B() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {"SELECT CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum), bqt1.smalla.stringKey AS EXPR_1 FROM bqt1.smalla ORDER BY EXPR_1"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * RulePlanJoins does not initially allow the cross join push.
- * The subsequent RuleRaiseAccess does since we believe it was the intent of the user
- */
- @Test public void testPushCrossJoins() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
-
- ProcessorPlan plan = helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {"SELECT g_2.intkey FROM ((bqt1.SmallA AS g_0 CROSS JOIN bqt1.smalla AS g_1) CROSS JOIN bqt1.mediuma AS g_2) LEFT OUTER JOIN bqt1.mediumb AS g_3 ON g_2.intkey = g_3.intkey"}, //$NON-NLS-1$
- ComparisonMode.EXACT_COMMAND_STRING );
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testCase3023() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
-
- helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {"SELECT bqt1.SmallA.intkey FROM (bqt1.SmallA INNER JOIN (bqt1.SmallB AS BAD LEFT OUTER JOIN bqt1.MediumB ON BAD.intkey = bqt1.MediumB.intkey) ON bqt1.SmallA.intkey = BAD.intkey) INNER JOIN bqt1.MediumA ON BAD.intkey = bqt1.MediumA.intkey"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
- }
-
- @Test public void testCase3367() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- FakeMetadataFacade metadata = example1();
-
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
-
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan("select e1 from pm1.g1 where pm1.g1.e1 IN (SELECT pm1.g2.e1 FROM pm1.g2 WHERE (pm1.g1.e1 = 2))", metadata, //$NON-NLS-1$
- null, capFinder,
- new String[] { "SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 IN (SELECT pm1.g2.e1 FROM pm1.g2 WHERE pm1.g1.e1 = '2')" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /*
- * Set criteria was not getting pushed down correctly when there was a self-join
- * of a virtual table containing a join in it's transformation. All virtual
- * models use the same physical model pm1.
- */
- @Test public void testCase3778() throws Exception {
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- BasicSourceCapabilities caps = getTypicalCapabilities();
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(
- "select a.e1, b.e1 from vm2.g1 a, vm2.g1 b where a.e1 = b.e1 and a.e2 in (select e2 from vm1.g1)", //$NON-NLS-1$
- metadata, null, capFinder, new String[] {"SELECT g_0.e1, g_2.e1 FROM pm1.g1 AS g_0, pm1.g2 AS g_1, pm1.g1 AS g_2, pm1.g2 AS g_3 WHERE (g_2.e2 = g_3.e2) AND (g_0.e2 = g_1.e2) AND (g_0.e1 = g_2.e1) AND (g_0.e2 IN (SELECT g_4.e2 FROM pm1.g1 AS g_4))"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * Ensures that order by expressions are not repeated when multiple criteria span a merge join
- */
- @Test public void testCase3832() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
-
- helpPlan(sql,
- metadata,
- null,
- capFinder,
- new String[] {
- "SELECT bqt2.smallb.intkey, bqt2.smalla.intkey FROM bqt2.smalla, bqt2.smallb WHERE bqt2.smalla.stringkey = bqt2.smallb.stringkey ORDER BY bqt2.smallb.intkey, bqt2.smalla.intkey", //$NON-NLS-1$
- "SELECT bqt1.smalla.intkey FROM bqt1.smalla ORDER BY bqt1.smalla.intkey"}, //$NON-NLS-1$
- ComparisonMode.EXACT_COMMAND_STRING);
-
- }
-
- /*
- * Functions containing exec statements should not be evaluated
- */
- @Test public void testDefect21972() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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(),
- null,
- capFinder,
- new String[] {
- "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}, //$NON-NLS-1$
- SHOULD_SUCCEED);
-
- }
-
- @Test public void testExpressionSymbolPreservation() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
- ComparisonMode.EXACT_COMMAND_STRING );
-
- }
-
- //since this does not support convert, it should not be collapsed
- @Test public void testBadCollapseUnion() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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(),
- null, capFinder, expectedSql, SHOULD_SUCCEED);
-
- 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 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$
- new String[] {} );
-
- checkNodeTypes(plan, new int[] {
- 0, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 0, // MergeJoin
- 0, // Null
- 1, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /*
- * Select literals created by runtime evaluation should not be pushed down.
- */
- @Test public void testCase4017() throws Exception {
-
- String sql = "SELECT env('soap_host') AS HOST, intkey from bqt2.smalla"; //$NON-NLS-1$
-
- helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, new DefaultCapabilitiesFinder(),
- new String[] {"SELECT bqt2.smalla.intkey FROM bqt2.smalla"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
- }
-
- /**
- * Test of RuleCopyCriteria. Criteria should NOT be copied across a join if the join has any other operator
- * other than an equality operator, but if the single group criteria is equality, then we can copy into a join criteria
- */
- @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(),
- 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$
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- }
-
- /**
- * Test of RuleCopyCriteria. Criteria should be copied across a join only for an equality operator in
- * the join criteria.
- */
- @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(),
- new String[] {
- "SELECT g_0.intkey FROM BQT1.SmallA AS g_0 WHERE g_0.IntKey = 1" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
-
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- }
-
- /**
- * The bug was in FrameUtil.convertCriteria() method, where ExistsCriteria was not being checked for.
- */
- @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(),
- new String[] {
- "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA" }); //$NON-NLS-1$
-
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 1, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- }
-
- /**
- * Try substituting "is not null" for "exists" criteria
- */
- @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(),
- new String[] {
- "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA" }); //$NON-NLS-1$
-
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 1, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- }
-
- @Test public void testCase4263() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- FakeMetadataFacade metadata = example1();
-
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
-
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan("select vm1.g1.e1 from vm1.g1 left outer join (select * from vm1.g2 as v where v.e1 = (select max(vm1.g2.e1) from vm1.g2 where v.e1 = vm1.g2.e1)) f2 on (f2.e1 = vm1.g1.e1)", metadata, //$NON-NLS-1$
- null, capFinder,
- new String[] { "SELECT g1__1.e1 FROM pm1.g1 AS g1__1 LEFT OUTER JOIN pm1.g1 AS g1__2 ON g1__2.e1 = g1__1.e1 AND g1__2.e1 = (SELECT MAX(pm1.g1.e1) FROM pm1.g1 WHERE pm1.g1.e1 = g1__2.e1)" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testCase4263b() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- FakeMetadataFacade metadata = example1();
-
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan("select vm1.g1.e1 from vm1.g1 left outer join (select * from vm1.g2 as v where v.e1 = (select max(pm2.g1.e1) from pm2.g1 where v.e1 = pm2.g1.e1)) f2 on (f2.e1 = vm1.g1.e1)", metadata, //$NON-NLS-1$
- null, capFinder,
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT g1__1.e1 FROM pm1.g1 AS g1__1" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testCase4279() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- FakeMetadataFacade metadata = example1();
-
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_CASE, true);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
-
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan("select * from (select v1.e1, v2.e1 as e1_1, v1.e2, v2.e2 as e2_2 from (select * from vm1.g7 where vm1.g7.e2 = 1) v1 left outer join (select * from vm1.g7 where vm1.g7.e2 = 1) v2 on v1.e2 = v2.e2) as v3 where v3.e2 = 1", metadata, //$NON-NLS-1$
- null, capFinder,
- new String[] { "SELECT CASE WHEN g_0.e1 = 'S' THEN 'Pay' WHEN g_0.e1 = 'P' THEN 'Rec' ELSE g_0.e1 END, CASE WHEN g_1.e1 = 'S' THEN 'Pay' WHEN g_1.e1 = 'P' THEN 'Rec' ELSE g_1.e1 END, g_0.e2, g_1.e2 FROM pm1.g1 AS g_0 LEFT OUTER JOIN pm1.g1 AS g_1 ON g_0.e2 = g_1.e2 AND g_1.e2 = 1 WHERE g_0.e2 = 1" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testCase4312() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setFunctionSupport("+", true); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpPlan("select ? + 1, pm1.g1.e1 AS EXPR_1 FROM pm1.g1", example1(), null, capFinder, //$NON-NLS-1$
- new String[] {
- "SELECT (? + 1) AS expr, pm1.g1.e1 FROM pm1.g1"}, true); //$NON-NLS-1$
-
- }
-
- @Test public void testCase2507_2(){
-
- String sql = "SELECT a FROM (SELECT concat(BQT1.SmallA.StringKey, BQT1.SmallA.StringNum) as a " + //$NON-NLS-1$
- "FROM BQT1.SmallA, BQT1.SmallB WHERE SmallA.IntKey = SmallB.IntKey) as X ORDER BY X.a"; //$NON-NLS-1$
-
- String expected = "SELECT concat(BQT1.SmallA.StringKey, BQT1.SmallA.StringNum) AS EXPR " + //$NON-NLS-1$
- "FROM BQT1.SmallA, BQT1.SmallB WHERE BQT1.SmallA.IntKey = BQT1.SmallB.IntKey ORDER BY EXPR"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {expected},
- TestOptimizer.SHOULD_SUCCEED );
-
- TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- private void helpTestCase2430and2507(String sql, String expected) {
-
- // TEST PLANNING
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
- caps.setFunctionSupport("+", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {expected},
- TestOptimizer.SHOULD_SUCCEED );
-
- TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- //Test use of OrderBy with Alias
- @Test public void testCase2430D() {
- String sql = "SELECT bqt1.smalla.longnum + bqt1.smalla.longnum as c1234567890123456789012345678901234567890, " + //$NON-NLS-1$
- "bqt1.smalla.doublenum as EXPR FROM bqt1.smalla ORDER BY c1234567890123456789012345678901234567890, EXPR "; //$NON-NLS-1$
-
- String expected = "SELECT (bqt1.smalla.longnum + bqt1.smalla.longnum) AS c1234567890123456789012345678901234567890, bqt1.smalla.doublenum AS EXPR " + //$NON-NLS-1$
- "FROM bqt1.smalla ORDER BY c1234567890123456789012345678901234567890, EXPR"; //$NON-NLS-1$
- 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$
- helpTestCase2430and2507(sql, expected);
- }
-
- @Test public void testCase2430G() {
- 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$
- helpTestCase2430and2507(sql, expected);
- }
-
- @Test public void testCase2507_1(){
-
- String sql = "SELECT a FROM (SELECT concat(BQT1.SmallA.StringKey, BQT1.SmallA.StringNum) as a " + //$NON-NLS-1$
- "FROM BQT1.SmallA) as X ORDER BY X.a"; //$NON-NLS-1$
-
- String expected = "SELECT concat(BQT1.SmallA.StringKey, BQT1.SmallA.StringNum) AS EXPR FROM BQT1.SmallA ORDER BY EXPR"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {expected},
- TestOptimizer.SHOULD_SUCCEED );
-
- TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * This is taken from testPushCorrelatedSubquery1. However this subquery is not expected to be pushed down since the correlated
- * reference expression cannot be evaluated by the source.
- */
- @Test public void testDefect23614() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- 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$
- null, capFinder,
- new String[] { "SELECT intkey, n.stringkey FROM bqt1.smalla AS n" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Normally the following queries would plan as if they were federated, but setting the connector_id source property
- * allows them to be planned as if they were the same source.
- */
- @Test public void testSameConnector() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setSourceProperty(Capability.CONNECTOR_ID, "1"); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
- metadata, null, capFinder,
- new String[] {
- "SELECT A.IntKey, B.IntKey FROM BQT1.SmallA AS A LEFT OUTER JOIN BQT2.MediumB AS B ON A.IntKey = B.IntKey"}, //$NON-NLS-1$
- true);
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
-
- plan = helpPlan(
- "SELECT A.IntKey FROM BQT1.SmallA A UNION select B.intkey from BQT2.MediumB B", //$NON-NLS-1$
- metadata, null, capFinder,
- new String[] {
- "SELECT A.IntKey FROM BQT1.SmallA AS A UNION SELECT B.intkey FROM BQT2.MediumB AS B"}, //$NON-NLS-1$
- true);
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * Test changes to RuleCollapseSource for removing aliases
- */
- @Test public void testCase4898() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT 'a' as A FROM BQT1.SmallA A UNION select 'b' as B from BQT1.MediumB B", //$NON-NLS-1$
- metadata, null, capFinder,
- new String[] {
- "SELECT 'a' AS A FROM BQT1.SmallA AS A UNION SELECT 'b' FROM BQT1.MediumB AS B"}, //$NON-NLS-1$
- true);
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testDefect13971() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- String sql = "select b from (select distinct booleanvalue b, intkey from bqt1.smalla) as x"; //$NON-NLS-1$
-
- // Plan query
- ProcessorPlan plan = helpPlan(sql, metadata, null, capFinder, new String[] {"SELECT DISTINCT booleanvalue, intkey FROM bqt1.smalla"}, SHOULD_SUCCEED); //$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
- });
- }
-
- /**
- * Ensures that aliases are not stripped from projected symbols if they might conflict with an order by element
- */
- @Test public void testCase5067() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
-
- // Plan query
- ProcessorPlan plan = helpPlan(sql, metadata, null, capFinder, new String[] {"SELECT a.intkey AS stringkey, b.stringkey AS key2 FROM bqt1.smalla AS a, bqt1.smallb AS b WHERE a.intkey = b.intkey ORDER BY stringkey"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testDontPushConvertObject() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT intkey from bqt1.smalla WHERE stringkey = convert(objectvalue, string)", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT stringkey, objectvalue, intkey FROM bqt1.smalla"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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 testDontPushConvertClobToString() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("LOB", caps); //$NON-NLS-1$
-
- // Add join capability to pm1
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = helpPlan(
- "SELECT ClobValue from LOB.LobTbl WHERE convert(ClobValue, string) = ?", //$NON-NLS-1$
- metadata,
- null, capFinder,
- new String[] {"SELECT ClobValue FROM LOB.LobTbl"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
-
- 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 testSelectIntoWithDistinct() throws Exception {
- String sql = "select distinct e1 into #temp from pm1.g1"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.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
- assertFalse(plan.requiresTransaction(false));
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
-
- checkNodeTypes(plan, new int[] {1}, new Class[] {ProjectIntoNode.class});
- }
-
- @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();
-
- 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
- assertTrue(plan.requiresTransaction(false));
-
- checkNodeTypes(plan, new int[] {1}, new Class[] {ProjectIntoNode.class});
- }
-
- /**
- * Ensure that the pushdown check doesn't fail
- * @throws Exception
- */
- @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();
-
- 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
- assertTrue(plan.requiresTransaction(false));
-
- checkNodeTypes(plan, new int[] {1}, new Class[] {ProjectIntoNode.class});
- }
-
- /**
- * previously the subqueries were being pushed too far and then not having the appropriate correlated references
- */
- @Test public void testCorrelatedSubqueryOverJoin() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
-
- ProcessorPlan plan = helpPlan(sql, metadata, null, capFinder,
- new String[] {"SELECT g_0.e1 FROM pm1.g1 AS g_0, pm1.g2 AS g_1 WHERE (g_0.e1 = g_1.e1) AND (EXISTS (SELECT g_2.e2 FROM pm1.g2 AS g_2 WHERE g_2.e1 = g_1.e1)) AND (EXISTS (SELECT g_3.e3 FROM pm1.g2 AS g_3 WHERE g_3.e1 = g_1.e1))"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * see testSimpleCrossJoin3
- */
- @Test public void testMaxFromGroups() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setSourceProperty(Capability.MAX_QUERY_FROM_GROUPS, new Integer(1));
- capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
-
- helpPlan("select pm2.g1.e1 FROM pm2.g1 CROSS JOIN pm2.g2", example1(), null, capFinder, //$NON-NLS-1$
- new String[] { "SELECT pm2.g1.e1 FROM pm2.g1", "SELECT 1 FROM pm2.g2"}, true ); //$NON-NLS-1$ //$NON-NLS-2$
-
- }
-
- @Test public void testCase6249() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- caps.setCapabilitySupport(Capability.QUERY_FUNCTIONS_IN_GROUP_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
-
- 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,
- 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();
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_FUNCTIONS_IN_GROUP_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_CASE, true);
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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$
-
- checkNodeTypes(plan, new int[] {
- 0, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testCase6325() {
- String sql = "select e1 into #temp from pm4.g1 where e1='1'"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpPlan(sql, metadata, new String[] {"SELECT e1 FROM pm4.g1 WHERE e1 = '1'"}); //$NON-NLS-1$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testCase6364() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_FUNCTIONS_IN_GROUP_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- caps.setFunctionSupport("+", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- 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,
- new String[] {"SELECT (1 + SUM(intnum)) FROM bqt1.smalla HAVING SUM(intnum) > 9"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testExceptPushdown() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_EXCEPT, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "select e1 from pm1.g1 except select e1 from pm1.g2"; //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.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);
- }
-
- @Test public void testCase6597() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
- caps.setCapabilitySupport(Capability.CRITERIA_NOT, false);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- // 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,
- new String[] {"SELECT stringkey, IntKey FROM bqt1.smalla"}, TestOptimizer.SHOULD_SUCCEED); //$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 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[] {});
- }
-
- /**
- * Test <code>QueryOptimizer</code>'s ability to plan a fully-pushed-down
- * query containing a <code>BETWEEN</code> comparison in the queries
- * <code>WHERE</code> statement.
- * <p>
- * For example:
- * <p>
- * 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$
- 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$
- }
-
- /**
- * Test <code>QueryOptimizer</code>'s ability to plan a fully-pushed-down
- * query containing a <code>CASE</code> expression in which a
- * <code>BETWEEN</code> comparison is used in the queries
- * <code>SELECT</code> statement.
- * <p>
- * For example:
- * <p>
- * SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1
- */
- @Test public void testBetweenInCase() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- 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,
- new String[] { "SELECT CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END FROM pm1.g1"}, //$NON-NLS-1$
- TestOptimizer.SHOULD_SUCCEED);
- }
-
- /**
- * Test <code>QueryOptimizer</code>'s ability to plan a fully-pushed-down
- * query containing an aggregate SUM with a <code>CASE</code> expression
- * in which a <code>BETWEEN</code> comparison is used in the queries
- * <code>SELECT</code> statement.
- * <p>
- * For example:
- * <p>
- * SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1
- */
- @Test public void testBetweenInCaseInSum() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- 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,
- 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);
- }
-
- /**
- * Test <code>QueryOptimizer</code>'s ability to plan a fully-pushed-down
- * query containing an aggregate SUM with a <code>CASE</code> expression
- * in which a <code>BETWEEN</code> comparison is used in the queries
- * <code>SELECT</code> statement and a GROUP BY is specified.
- * <p>
- * For example:
- * <p>
- * SELECT e1, SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END)
- * FROM pm1.g1 GROUP BY e1
- */
- @Test public void testBetweenInCaseInSumWithGroupBy() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- 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,
- 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);
- }
-
- /**
- * Test the query optimizer's ability to properly plan and optimize a query
- * that uses ambiguous alias names in the top level query and its sub-query.
- * <p>
- * No source table is being used. For example, <code>SELECT A.e2 FROM
- * (SELECT e2 FROM (SELECT 1 AS e2) AS A) AS A</code>
- * <p>
- * The test is to ensure that A.e2 from the top level is not confused with
- * e2 in the second level.
- * <p>
- * Related Defects: JBEDSP-1137
- */
- @Test public void testAmbiguousAliasInSubQueryNoSource() {
- // Create query
- String sql = "SELECT A.e2 AS e2 FROM (" + //$NON-NLS-1$
- " SELECT e2 AS e2 FROM (" + //$NON-NLS-1$
- " SELECT 5 AS e2" + //$NON-NLS-1$
- " ) AS A" + //$NON-NLS-1$
- ") AS A"; //$NON-NLS-1$
-
- helpPlan(sql, FakeMetadataFactory.example1Cached(), new String[] {});
- }
-
- /**
- * Test the query optimizer's ability to properly plan and optimize a query
- * that uses ambiguous alias names in the top level query and its sub-query
- * and uses columns belonging to the alias as a parameter to a function.
- * <p>
- * No source table is being used. For example, <code>SELECT CONVERT(A.e2,
- * biginteger) AS e2 FROM (SELECT CONVERT(e2, long) AS e2 FROM (SELECT 1 AS
- * e2) AS A) AS A</code>
- * <p>
- * The test is to ensure that A.e2 from the top level is not confused with
- * e2 in the second level.
- * <p>
- * Related Defects: JBEDSP-1137
- */
- @Test public void testAmbiguousAliasFunctionInSubQueryNoSource() {
- // Create query
- String sql = "SELECT CONVERT(A.e2, biginteger) AS e2 FROM (" + //$NON-NLS-1$
- " SELECT CONVERT(e2, long) AS e2 FROM (" + //$NON-NLS-1$
- " SELECT 5 AS e2" + //$NON-NLS-1$
- " ) AS A" + //$NON-NLS-1$
- ") AS A"; //$NON-NLS-1$
-
- helpPlan(sql, FakeMetadataFactory.example1Cached(), new String[] {});
- }
-
- /**
- * Test the query optimizer's ability to properly plan and optimize a query
- * that uses ambiguous alias names in the top level query and its sub-query.
- * <p>
- * For example, <code>SELECT A.e2 FROM (SELECT e12FROM pm1.g1 AS A) AS A</code>
- * <p>
- * The test is to ensure that A.e2 from the top level is not confused with
- * e2 in the second level.
- * <p>
- * Related Defects: JBEDSP-1137
- */
- @Test public void testAmbiguousAliasInSubQuerySource() {
- // Create query
- String sql = "SELECT A.e2 AS e2 FROM (" + //$NON-NLS-1$
- " 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$
- }
-
- /**
- * Test the query optimizer's ability to properly plan and optimize a query
- * that uses ambiguous alias names in the top level query and its sub-query
- * and uses columns belonging to the alias as a parameter to a function.
- * <p>
- * For example, <code>SELECT CONVERT(A.e2, biginteger) AS e2 FROM (SELECT
- * CONVERT(e2, long) AS e2 FROM pm1.g1 AS A) AS A</code>
- * <p>
- * The test is to ensure that A.e2 from the top level is not confused with
- * e2 in the second level.
- * <p>
- * Related Defects: JBEDSP-1137
- */
- @Test public void testAmbiguousAliasFunctionInSubQuerySource() {
- // Create query
- String sql = "SELECT CONVERT(A.e2, biginteger) AS e2 FROM (" + //$NON-NLS-1$
- " SELECT CONVERT(e2, long) AS e2 FROM pm1.g1 AS A" + //$NON-NLS-1$
- ") AS A"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- helpPlan(sql, metadata, new String[] {"SELECT e2 FROM pm1.g1 AS A"}); //$NON-NLS-1$
-
- // Add convert capability to pm1 and try it again
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpPlan(sql, metadata, null, capFinder,
- new String[] {"SELECT CONVERT(CONVERT(e2, long), biginteger) FROM pm1.g1 AS A"}, //$NON-NLS-1$
- SHOULD_SUCCEED );
- }
-
- @Test public void testNestedTable() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
- ProcessorPlan plan = helpPlan("select pm2.g1.e1, x.e1 from pm2.g1, table(select * from pm2.g2 where pm2.g1.e1=pm2.g2.e1) x where pm2.g1.e2 IN (1, 2)", example1(), //$NON-NLS-1$
- new String[] { "SELECT g_0.e1 FROM pm2.g2 AS g_0 WHERE g_0.e1 = pm2.g1.e1", "SELECT g_0.e1 FROM pm2.g1 AS g_0 WHERE g_0.e2 IN (1, 2)" }, capFinder, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {1}, new Class[] {NestedTableJoinStrategy.class});
- }
-
- @Test public void testUpdatePushdownFails() {
- helpPlan("update pm1.g1 set e1 = 1 where exists (select 1 from pm1.g2)", FakeMetadataFactory.example1Cached(), null, //$NON-NLS-1$
- null, null, false); //$NON-NLS-1$
- }
-
- public static final boolean DEBUG = false;
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,6592 @@
+/*
+ * 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;
+
+import static org.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Test;
+import org.teiid.api.exception.query.QueryPlannerException;
+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.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.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;
+import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.optimizer.relational.AliasGenerator;
+import org.teiid.query.optimizer.relational.rules.CapabilitiesUtil;
+import org.teiid.query.optimizer.relational.rules.RuleChooseDependent;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.relational.AccessNode;
+import org.teiid.query.processor.relational.DependentAccessNode;
+import org.teiid.query.processor.relational.EnhancedSortMergeJoinStrategy;
+import org.teiid.query.processor.relational.GroupingNode;
+import org.teiid.query.processor.relational.JoinNode;
+import org.teiid.query.processor.relational.JoinStrategy;
+import org.teiid.query.processor.relational.MergeJoinStrategy;
+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.PlanExecutionNode;
+import org.teiid.query.processor.relational.ProjectIntoNode;
+import org.teiid.query.processor.relational.ProjectNode;
+import org.teiid.query.processor.relational.RelationalNode;
+import org.teiid.query.processor.relational.RelationalPlan;
+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.processor.relational.SortUtility.Mode;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.resolver.TestResolver;
+import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.JoinType;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+import org.teiid.query.validator.Validator;
+import org.teiid.query.validator.ValidatorReport;
+import org.teiid.translator.SourceSystemFunctions;
+
+ at SuppressWarnings({"nls", "unchecked"})
+public class TestOptimizer {
+
+ public interface DependentJoin {}
+ public interface DependentSelectNode {}
+ public interface SemiJoin {}
+ public interface AntiSemiJoin {}
+ public interface DependentProjectNode {}
+ public interface DupRemoveNode {}
+ public interface DupRemoveSortNode {}
+
+ public static final int[] FULL_PUSHDOWN = new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ };
+
+ public enum ComparisonMode { EXACT_COMMAND_STRING, CORRECTED_COMMAND_STRING, FAILED_PLANNING }
+
+ public static final boolean SHOULD_SUCCEED = true;
+ public static final boolean SHOULD_FAIL = false;
+
+ // ################################## TEST HELPERS ################################
+
+ public static BasicSourceCapabilities getTypicalCapabilities() {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_BETWEEN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_LIKE_ESCAPE, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_ISNULL, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_OR, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY_UNRELATED, true);
+
+ // set typical max set size
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ return caps;
+ }
+
+ public static CapabilitiesFinder getGenericFinder(boolean supportsJoins) {
+ final BasicSourceCapabilities caps = getTypicalCapabilities();
+ if (!supportsJoins) {
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, false);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ }
+ return new DefaultCapabilitiesFinder(caps);
+ }
+
+ public static CapabilitiesFinder getGenericFinder() {
+ return getGenericFinder(true);
+ }
+
+ public static ProcessorPlan helpPlan(String sql, QueryMetadataInterface md, String[] expectedAtomic) {
+ return helpPlan(sql, md, null, getGenericFinder(), expectedAtomic, SHOULD_SUCCEED);
+ }
+
+ public static ProcessorPlan helpPlan(String sql,
+ QueryMetadataInterface md, String[] expected,
+ CapabilitiesFinder capFinder,
+ ComparisonMode mode) throws TeiidComponentException, TeiidProcessingException {
+ return helpPlan(sql, md, null, capFinder, expected, mode);
+ }
+
+ public static ProcessorPlan helpPlan(String sql, QueryMetadataInterface md, String[] expectedAtomic, ComparisonMode mode) throws TeiidComponentException, TeiidProcessingException {
+ return helpPlan(sql, md, null, getGenericFinder(), expectedAtomic, mode);
+ }
+
+ public static ProcessorPlan helpPlan(String sql, QueryMetadataInterface md, List bindings, CapabilitiesFinder capFinder, String[] expectedAtomic, boolean shouldSucceed) {
+ Command command;
+ try {
+ command = helpGetCommand(sql, md, bindings);
+ } catch (TeiidException err) {
+ throw new TeiidRuntimeException(err);
+ }
+
+ return helpPlanCommand(command, md, capFinder, null, expectedAtomic, shouldSucceed ? ComparisonMode.CORRECTED_COMMAND_STRING : ComparisonMode.FAILED_PLANNING);
+ }
+
+ public static ProcessorPlan helpPlan(String sql, QueryMetadataInterface md, List bindings, CapabilitiesFinder capFinder, String[] expectedAtomic, ComparisonMode mode) throws TeiidComponentException, TeiidProcessingException {
+ Command command = helpGetCommand(sql, md, bindings);
+
+ return helpPlanCommand(command, md, capFinder, null, expectedAtomic, mode);
+ }
+
+
+ public static Command helpGetCommand(String sql, QueryMetadataInterface md, List bindings) throws TeiidComponentException, TeiidProcessingException {
+ if(DEBUG) System.out.println("\n####################################\n" + sql); //$NON-NLS-1$
+ Command command = null;
+ if (bindings != null && !bindings.isEmpty()) {
+ command = TestResolver.helpResolveWithBindings(sql, md, bindings);
+ } else {
+ command = QueryParser.getQueryParser().parseCommand(sql);
+ QueryResolver.resolveCommand(command, md);
+ }
+
+ ValidatorReport repo = Validator.validate(command, md);
+
+ Collection failures = new ArrayList();
+ repo.collectInvalidObjects(failures);
+ if (failures.size() > 0){
+ fail("Exception during validation (" + repo); //$NON-NLS-1$
+ }
+
+ // rewrite
+ command = QueryRewriter.rewrite(command, md, new CommandContext());
+
+ return command;
+ }
+
+ public static ProcessorPlan helpPlanCommand(Command command, QueryMetadataInterface md, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord, String[] expectedAtomic, ComparisonMode mode) {
+ if (capFinder == null){
+ capFinder = getGenericFinder();
+ }
+
+ // Collect atomic queries
+ ProcessorPlan plan = getPlan(command, md, capFinder, analysisRecord, mode != ComparisonMode.FAILED_PLANNING, new CommandContext());
+
+ if (mode == ComparisonMode.CORRECTED_COMMAND_STRING) {
+ checkAtomicQueries(expectedAtomic, plan, md, capFinder);
+ } else if (mode == ComparisonMode.EXACT_COMMAND_STRING) {
+ checkAtomicQueries(expectedAtomic, plan);
+ }
+
+ return plan;
+ }
+
+ public static void checkAtomicQueries(String[] expectedAtomic,
+ ProcessorPlan plan) {
+ Set<String> actualQueries = getAtomicQueries(plan);
+
+ if (actualQueries.size() != 1 || expectedAtomic.length != 1) {
+ // Compare atomic queries
+ HashSet<String> expectedQueries = new HashSet<String>(Arrays.asList(expectedAtomic));
+ assertEquals("Did not get expected atomic queries: ", expectedQueries, actualQueries); //$NON-NLS-1$
+ } else {
+ assertEquals("Did not get expected atomic query: ", expectedAtomic[0], actualQueries.iterator().next()); //$NON-NLS-1$
+ }
+ }
+
+ public static void checkAtomicQueries(String[] expectedAtomic,
+ ProcessorPlan plan, QueryMetadataInterface md, CapabilitiesFinder capFinder) {
+ Set actualQueries = getAtomicQueries(plan);
+
+ HashSet<String> expectedQueries = new HashSet<String>();
+
+ // Compare atomic queries
+ for (int i = 0; i < expectedAtomic.length; i++) {
+ final String sql = expectedAtomic[i];
+ Command command;
+ try {
+ command = helpGetCommand(sql, md, null);
+ Collection groups = GroupCollectorVisitor.getGroupsIgnoreInlineViews(command, false);
+ final GroupSymbol symbol = (GroupSymbol)groups.iterator().next();
+ Object modelId = md.getModelID(symbol.getMetadataID());
+ boolean supportsGroupAliases = CapabilitiesUtil.supportsGroupAliases(modelId, md, capFinder);
+ boolean supportsProjection = CapabilitiesUtil.supports(Capability.QUERY_SELECT_EXPRESSION, modelId, md, capFinder);
+ command.acceptVisitor(new AliasGenerator(supportsGroupAliases, !supportsProjection));
+ expectedQueries.add(command.toString());
+ } catch (Exception err) {
+ throw new RuntimeException(err);
+ }
+ }
+
+ assertEquals("Did not get expected atomic queries: ", expectedQueries, actualQueries); //$NON-NLS-1$
+ }
+
+ public static ProcessorPlan getPlan(Command command, QueryMetadataInterface md, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord, boolean shouldSucceed, CommandContext cc) {
+ ProcessorPlan plan = null;
+ if (analysisRecord == null) {
+ analysisRecord = new AnalysisRecord(false, DEBUG);
+ }
+ Exception exception = null;
+ try {
+ //do planning
+ plan = QueryOptimizer.optimizePlan(command, md, null, capFinder, analysisRecord, cc);
+ } catch (QueryPlannerException e) {
+ exception = e;
+ } catch (TeiidComponentException e) {
+ exception = e;
+ } catch (Throwable e) {
+ throw new TeiidRuntimeException(e);
+ } finally {
+ if(DEBUG) {
+ System.out.println(analysisRecord.getDebugLog());
+ }
+ }
+ if (!shouldSucceed) {
+ assertNotNull("Expected exception but did not get one.", exception); //$NON-NLS-1$
+ return null;
+ }
+ if (plan == null) {
+ throw new TeiidRuntimeException(exception);
+ }
+ assertNotNull("Output elements are null", plan.getOutputElements()); //$NON-NLS-1$
+ if(DEBUG) System.out.println("\n" + plan); //$NON-NLS-1$
+ return plan;
+ }
+
+ public static Set<String> getAtomicQueries(ProcessorPlan plan) {
+ Set<Command> atomicQueries = new HashSet<Command>();
+ if(plan instanceof RelationalPlan) {
+ getAtomicCommands( ((RelationalPlan)plan).getRootNode(), atomicQueries );
+ }
+
+ Set<String> stringQueries = new HashSet<String>();
+
+ for (Command command : atomicQueries) {
+ stringQueries.add(command.toString());
+ }
+
+ return stringQueries;
+ }
+
+ private static void getAtomicCommands(RelationalNode node, Set<Command> atomicQueries) {
+ if(node instanceof AccessNode) {
+ AccessNode accessNode = (AccessNode) node;
+ atomicQueries.add( accessNode.getCommand());
+ }
+
+ // Recurse through children
+ RelationalNode[] children = node.getChildren();
+ for(int i=0; i<children.length; i++) {
+ if(children[i] != null) {
+ getAtomicCommands(children[i], atomicQueries);
+ } else {
+ break;
+ }
+ }
+ }
+
+ // Counts are (mostly) alphabetical:
+ // Access, DependentAccess, DependentSelect, DependentProject, DupRemove, Grouping, NestedLoopJoinStrategy, Null, PlanExecution, Project, Select, Sort, UnionAll
+ private static final Class[] COUNT_TYPES = new Class[] {
+ AccessNode.class,
+ DependentAccessNode.class,
+ DependentSelectNode.class,
+ DependentProjectNode.class,
+ DupRemoveNode.class,
+ GroupingNode.class,
+ NestedLoopJoinStrategy.class,
+ MergeJoinStrategy.class,
+ NullNode.class,
+ PlanExecutionNode.class,
+ ProjectNode.class,
+ SelectNode.class,
+ SortNode.class,
+ UnionAllNode.class
+ };
+
+ public static void checkNodeTypes(ProcessorPlan root, int[] expectedCounts) {
+ checkNodeTypes(root, expectedCounts, COUNT_TYPES);
+ }
+
+ public static void checkNodeTypes(ProcessorPlan root, int[] expectedCounts, Class[] types) {
+ if(! (root instanceof RelationalPlan)) {
+ return;
+ }
+
+ int[] actualCounts = new int[types.length];
+ collectCounts(((RelationalPlan)root).getRootNode(), actualCounts, types);
+
+ for(int i=0; i<expectedCounts.length; i++) {
+ assertEquals("Did not find the correct number of nodes for type " + types[i], //$NON-NLS-1$
+ expectedCounts[i], actualCounts[i]);
+ }
+ }
+
+ /**
+ * Method collectCounts.
+ * @param relationalNode
+ * @return int[]
+ */
+ static void collectCounts(RelationalNode relationalNode, int[] counts, Class<?>[] types) {
+ Class<?> nodeType = relationalNode.getClass();
+ if(nodeType.equals(JoinNode.class)) {
+ JoinStrategy strategy = ((JoinNode)relationalNode).getJoinStrategy();
+ if (((JoinNode)relationalNode).getJoinType().equals(JoinType.JOIN_SEMI)) {
+ updateCounts(SemiJoin.class, counts, types);
+ } else if (((JoinNode)relationalNode).getJoinType().equals(JoinType.JOIN_ANTI_SEMI)) {
+ updateCounts(AntiSemiJoin.class, counts, types);
+ }
+ if (strategy instanceof NestedLoopJoinStrategy) {
+ updateCounts(NestedLoopJoinStrategy.class, counts, types);
+ } else if (strategy instanceof MergeJoinStrategy) {
+ updateCounts(MergeJoinStrategy.class, counts, types);
+ if (strategy instanceof EnhancedSortMergeJoinStrategy) {
+ updateCounts(EnhancedSortMergeJoinStrategy.class, counts, types);
+ }
+ } else if (strategy instanceof NestedTableJoinStrategy) {
+ updateCounts(NestedTableJoinStrategy.class, counts, types);
+ }
+ if (((JoinNode)relationalNode).isDependent()) {
+ updateCounts(DependentJoin.class, counts, types);
+ }
+ }else if (nodeType.equals(ProjectNode.class)){
+ if (ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(((ProjectNode)relationalNode).getSelectSymbols()).isEmpty()) {
+ updateCounts(ProjectNode.class, counts, types);
+ } else {
+ updateCounts(DependentProjectNode.class, counts, types);
+ }
+ }else if (nodeType.equals(SelectNode.class)){
+ if (ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(((SelectNode)relationalNode).getCriteria()).isEmpty()) {
+ updateCounts(SelectNode.class, counts, types);
+ } else {
+ updateCounts(DependentSelectNode.class, counts, types);
+ }
+ } else if (nodeType.equals(SortNode.class)) {
+ Mode mode = ((SortNode)relationalNode).getMode();
+ switch(mode) {
+ case DUP_REMOVE:
+ updateCounts(DupRemoveNode.class, counts, types);
+ break;
+ case DUP_REMOVE_SORT:
+ updateCounts(DupRemoveSortNode.class, counts, types);
+ break;
+ case SORT:
+ updateCounts(SortNode.class, counts, types);
+ break;
+ }
+ } else {
+ updateCounts(nodeType, counts, types);
+ }
+
+ RelationalNode[] children = relationalNode.getChildren();
+ for(int i=0; i<children.length; i++) {
+ if(children[i] != null) {
+ collectCounts(children[i], counts, types);
+ } else {
+ break;
+ }
+ }
+ }
+
+ private static void updateCounts(Class nodeClass, int[] counts, Class[] types) {
+ for(int i=0; i<types.length; i++) {
+ if(types[i].equals(nodeClass)) {
+ counts[i] = counts[i] + 1;
+ return;
+ }
+ }
+ }
+
+ public static void checkDependentJoinCount(ProcessorPlan plan, int expectedCount) {
+ checkNodeTypes(plan, new int[] {expectedCount}, new Class[] {DependentJoin.class});
+ }
+
+ public static TransformationMetadata example1() {
+ MetadataStore metadataStore = new MetadataStore();
+ // Create models
+ 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
+ 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
+ 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 });
+ 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 });
+ 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 });
+ RealMetadataFactory.createElements(pm1g4,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING });
+ RealMetadataFactory.createElements(pm1g5,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING });
+ RealMetadataFactory.createElements(pm1g6,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING });
+ RealMetadataFactory.createElements(pm1g7,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING });
+ RealMetadataFactory.createElements(pm1g8,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING });
+ 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 });
+ 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 });
+ 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$
+ Table vm1g1 = RealMetadataFactory.createUpdatableVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
+
+ QueryNode vm1g2n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+ 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$
+ Table vm1sub1 = RealMetadataFactory.createVirtualGroup("sub1", vm1, vm1sub1n1); //$NON-NLS-1$
+
+ QueryNode vm1g3n1 = new QueryNode("SELECT * FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ Table vm1g7 = RealMetadataFactory.createVirtualGroup("g7", vm1, vm1g7n1); //$NON-NLS-1$
+
+ // Create virtual elements
+ 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 });
+ 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 });
+ 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
+ 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 });
+ RealMetadataFactory.createElements(vm1g4,
+ new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+ RealMetadataFactory.createElements(vm1g5,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING});
+ 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 });
+ RealMetadataFactory.createElements(vm1g7,
+ new String[] { "e1", "e2"}, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
+ 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 });
+ 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 });
+ RealMetadataFactory.createElements(vm1u3,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING });
+ RealMetadataFactory.createElements(vm1u4,
+ new String[] { "v1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING });
+ RealMetadataFactory.createElements(vm1u5,
+ new String[] { "v1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING });
+ RealMetadataFactory.createElements(vm1u6,
+ new String[] { "elem", "const" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+ RealMetadataFactory.createElements(vm1u7,
+ new String[] { "const", "e1" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+ RealMetadataFactory.createElements(vm1u8,
+ new String[] { "const", "e1" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+ RealMetadataFactory.createElements(vm1u9,
+ new String[] { "a", "b" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+ RealMetadataFactory.createElements(vm1a1,
+ new String[] { "e1", "sum_e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.LONG });
+ RealMetadataFactory.createElements(vm1a2,
+ new String[] { "e1", "sum_e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.LONG });
+ RealMetadataFactory.createElements(vm1a3,
+ new String[] { "sum_e2" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.LONG });
+ RealMetadataFactory.createElements(vm1a4,
+ new String[] { "count" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.INTEGER });
+ RealMetadataFactory.createElements(vm1a5,
+ new String[] { "count" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.INTEGER });
+ RealMetadataFactory.createElements(vm1a6,
+ new String[] { "count" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.INTEGER });
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "example1");
+ }
+
+ // ################################## ACTUAL TESTS ################################
+
+ /**
+ * Test defect 8096 - query a virtual group with subquery of another virtual group
+ */
+ @Test public void testVirtualSubqueryINClause_8096() {
+ helpPlan("SELECT * FROM vm1.sub1", example1(), //$NON-NLS-1$
+ new String[] {"SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1"} ); //$NON-NLS-1$
+ }
+
+ @Test public void testQueryPhysical() {
+ 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", 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", 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", 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", 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)", 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)", 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'", 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$
+ }
+
+ @Test public void testUpdate2() throws Exception {
+ 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)", 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$
+ }
+
+ @Test public void testDelete() throws Exception {
+ 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)", 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$
+ }
+
+ // ############################# TESTS ON EXAMPLE 1 ############################
+
+ @Test public void testCopyInAcrossJoin() throws Exception {
+ ProcessorPlan plan = helpPlan("select pm1.g1.e1, pm2.g2.e1 from pm1.g1, pm2.g2 where pm1.g1.e1=pm2.g2.e1 and pm1.g1.e1 IN ('a', 'b')", example1(), //$NON-NLS-1$
+ new String[] { "SELECT g_0.e1 AS c_0 FROM pm2.g2 AS g_0 WHERE g_0.e1 IN ('a', 'b') ORDER BY c_0", //$NON-NLS-1$
+ "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 WHERE g_0.e1 IN ('a', 'b') ORDER BY c_0" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testCopyMatchAcrossJoin() throws Exception {
+ helpPlan("select pm1.g1.e1, pm2.g2.e1 from pm1.g1, pm2.g2 where pm1.g1.e1=pm2.g2.e1 and pm1.g1.e1 LIKE '%1'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 WHERE g_0.e1 LIKE '%1' ORDER BY c_0", //$NON-NLS-1$
+ "SELECT g_0.e1 AS c_0 FROM pm2.g2 AS g_0 WHERE g_0.e1 LIKE '%1' ORDER BY c_0" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+ }
+
+ @Test public void testCopyOrAcrossJoin() throws Exception {
+ helpPlan("select pm1.g1.e1, pm1.g2.e1 from pm1.g1, pm1.g2 where pm1.g1.e1=pm1.g2.e1 and (pm1.g1.e1 = 'abc' OR pm1.g1.e1 = 'def')", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 WHERE (pm1.g1.e1 = 'abc') OR (pm1.g1.e1 = 'def')", //$NON-NLS-1$
+ "SELECT pm1.g2.e1 FROM pm1.g2 WHERE (pm1.g2.e1 = 'abc') OR (pm1.g2.e1 = 'def')" }, getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$
+ }
+
+ @Test public void testCopyMultiElementCritAcrossJoin() throws Exception {
+ helpPlan("select pm1.g1.e1, pm1.g2.e1 from pm1.g1, pm1.g2 where pm1.g1.e1=pm1.g2.e1 and pm1.g1.e2=pm1.g2.e2 and (pm1.g1.e1 = 'abc' OR pm1.g1.e2 = 5)", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g2.e1, pm1.g2.e2 FROM pm1.g2 WHERE (pm1.g2.e1 = 'abc') OR (pm1.g2.e2 = 5)", "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 WHERE (pm1.g1.e1 = 'abc') OR (pm1.g1.e2 = 5)" }, getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCantCopyAcrossJoin1() throws Exception {
+ helpPlan("select pm1.g1.e1, pm1.g2.e1 from pm1.g1, pm1.g2 where pm1.g1.e1=pm1.g2.e1 and concat(pm1.g1.e1, pm1.g1.e2) = 'abc'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1", //$NON-NLS-1$
+ "SELECT pm1.g2.e1 FROM pm1.g2" }, getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$
+ }
+
+ @Test public void testCantCopyAcrossJoin2() throws Exception {
+ helpPlan("select pm1.g1.e1, pm1.g2.e1 from pm1.g1, pm1.g2 where pm1.g1.e1=pm1.g2.e1 and (pm1.g1.e1 = 'abc' OR pm1.g1.e2 = 5)", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 WHERE (pm1.g1.e1 = 'abc') OR (pm1.g1.e2 = 5)", //$NON-NLS-1$
+ "SELECT pm1.g2.e1 FROM pm1.g2" }, getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$
+ }
+
+ @Test public void testPushingCriteriaThroughFrame1() {
+ helpPlan("select * from vm1.g1, vm1.g2 where vm1.g1.e1='abc' and vm1.g1.e1=vm1.g2.e1", example1(), //$NON-NLS-1$
+ new String[] { "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$
+ "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushingCriteriaThroughFrame2() throws Exception {
+ helpPlan("select * from vm1.g1, vm1.g3 where vm1.g1.e1='abc' and vm1.g1.e1=vm1.g3.e1", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2 WHERE pm1.g2.e1 = 'abc'", //$NON-NLS-1$
+ "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'" }, getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushingCriteriaThroughFrame3() {
+ helpPlan("select * from vm1.g1, vm1.g2, vm1.g1 as a where vm1.g1.e1='abc' and vm1.g1.e1=vm1.g2.e1 and vm1.g1.e1=a.e1", example1(), //$NON-NLS-1$
+ new String[] { "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$
+ "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'", //$NON-NLS-1$
+ "SELECT g1__2.e1, g1__2.e2, g1__2.e3, g1__2.e4 FROM pm1.g1 AS g1__2 WHERE g1__2.e1 = 'abc'" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushingCriteriaThroughUnion1() {
+ helpPlan("select e1 from vm1.u1 where e1='abc'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g3.e1, pm1.g3.e2, pm1.g3.e3, pm1.g3.e4 FROM pm1.g3 WHERE pm1.g3.e1 = 'abc'", //$NON-NLS-1$
+ "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2 WHERE pm1.g2.e1 = 'abc'", //$NON-NLS-1$
+ "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushingCriteriaThroughUnion2() {
+ helpPlan("select e1 from vm1.u2 where e1='abc'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2 WHERE pm1.g2.e1 = 'abc'", //$NON-NLS-1$
+ "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushingCriteriaThroughUnion3() {
+ helpPlan("select e1 from vm1.u1 where e1='abc' and e2=5", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g3.e1, pm1.g3.e2, pm1.g3.e3, pm1.g3.e4 FROM pm1.g3 WHERE (pm1.g3.e1 = 'abc') AND (pm1.g3.e2 = 5)", //$NON-NLS-1$
+ "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2 WHERE (pm1.g2.e1 = 'abc') AND (pm1.g2.e2 = 5)", //$NON-NLS-1$
+ "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE (pm1.g1.e1 = 'abc') AND (pm1.g1.e2 = 5)" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushingCriteriaThroughUnion4() {
+ helpPlan("select e1 from vm1.u1 where e1='abc' or e2=5", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g3.e1, pm1.g3.e2, pm1.g3.e3, pm1.g3.e4 FROM pm1.g3 WHERE (pm1.g3.e1 = 'abc') OR (pm1.g3.e2 = 5)", //$NON-NLS-1$
+ "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE (pm1.g1.e1 = 'abc') OR (pm1.g1.e2 = 5)", //$NON-NLS-1$
+ "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2 WHERE (pm1.g2.e1 = 'abc') OR (pm1.g2.e2 = 5)" } ); //$NON-NLS-1$
+ }
+
+ // expression in a subquery of the union
+ @Test public void testPushingCriteriaThroughUnion5() {
+ helpPlan("select e1 from vm1.u3 where e1='abc'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT DISTINCT e1 FROM pm1.g1 WHERE e1 = 'abc'" } ); //$NON-NLS-1$
+ }
+
+ /** defect #4956 */
+ @Test public void testPushCriteriaThroughUnion6() {
+ helpPlan("select v1 from vm1.u4 where vm1.u4.v1='x'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1 FROM pm1.g1", //$NON-NLS-1$
+ "SELECT e1 FROM pm1.g2 WHERE e1 = 'x'" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushCriteriaThroughUnion7() {
+ helpPlan("select v1 from vm1.u5 where vm1.u5.v1='x'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1 FROM pm1.g1", //$NON-NLS-1$
+ "SELECT e1 FROM pm1.g2" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushCriteriaThroughUnion8() {
+ helpPlan("select v1 from vm1.u5 where length(v1) > 0", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1 FROM pm1.g1", //$NON-NLS-1$
+ "SELECT e1 FROM pm1.g2" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushCriteriaThroughUnion11() {
+ helpPlan("select * from vm1.u8 where const = 's3' or e1 is null", example1(), //$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 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 */
+ @Test public void testCountStarNoRows() {
+ ProcessorPlan plan = helpPlan("select count(*) from vm1.u4", example1(), //$NON-NLS-1$
+ new String[] { "SELECT 1 FROM pm1.g2", //$NON-NLS-1$
+ "SELECT 1 FROM pm1.g1" } ); //$NON-NLS-1$
+ 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 testPushingCriteriaWithCopy() {
+ ProcessorPlan plan = helpPlan("select vm1.u1.e1 from vm1.u1, pm1.g1 where vm1.u1.e1='abc' and vm1.u1.e1=pm1.g1.e1", example1(), //$NON-NLS-1$
+ new String[] { "SELECT 1 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'", //$NON-NLS-1$
+ "SELECT pm1.g3.e1, pm1.g3.e2, pm1.g3.e3, pm1.g3.e4 FROM pm1.g3 WHERE pm1.g3.e1 = 'abc'", //$NON-NLS-1$
+ "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2 WHERE pm1.g2.e1 = 'abc'", //$NON-NLS-1$
+ "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'" } ); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 4, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 1, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 2 // UnionAll
+ });
+ }
+
+ @Test public void testVirtualGroupWithAliasedElement() {
+ helpPlan("select elem FROM vm1.u6 where elem='abc' and const='xyz'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT x1.e1 FROM pm1.g1 AS x1 WHERE x1.e1 = 'abc'" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushThroughGroup1() {
+ helpPlan("select * FROM vm1.a1 WHERE e1 = 'x'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1, e2 FROM pm1.g1 WHERE e1 = 'x'" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushThroughGroup2() {
+ helpPlan("select * FROM vm1.a2 WHERE e1 = 'x'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1, e2 FROM pm1.g1 WHERE e1 = 'x'" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushThroughGroup3() {
+ helpPlan("select * FROM vm1.a3 WHERE sum_e2 > 0", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e2 FROM pm1.g1" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushMultiGroupCriteria() {
+ ProcessorPlan plan = 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)", example1(), //$NON-NLS-1$
+ new String[] { "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))" } ); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testSimpleCrossJoin1() throws Exception {
+ helpPlan("select pm1.g1.e1 FROM pm1.g1, pm1.g2", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
+ "SELECT pm1.g2.e1 FROM pm1.g2" }, new DefaultCapabilitiesFinder(), ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
+ }
+
+ @Test public void testSimpleCrossJoin2() {
+ helpPlan("select pm2.g1.e1 FROM pm2.g1, pm2.g2", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm2.g1.e1 FROM pm2.g1, pm2.g2"} ); //$NON-NLS-1$
+
+ }
+
+ @Test public void testSimpleCrossJoin3() {
+ helpPlan("select pm2.g1.e1 FROM pm2.g1 CROSS JOIN pm2.g2", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm2.g1.e1 FROM pm2.g1, pm2.g2"} ); //$NON-NLS-1$
+
+ }
+
+ @Test public void testMultiSourceCrossJoin() throws Exception {
+ helpPlan("select pm1.g1.e1 FROM pm1.g1, pm1.g2, pm1.g3", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
+ "SELECT pm1.g2.e1 FROM pm1.g2", //$NON-NLS-1$
+ "SELECT pm1.g3.e1 FROM pm1.g3" }, new DefaultCapabilitiesFinder(), ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
+ }
+
+ @Test public void testSingleSourceCrossJoin() {
+ helpPlan("select pm2.g1.e1 FROM pm2.g1, pm2.g2, pm2.g3", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm2.g1.e1 FROM pm2.g1, pm2.g2, pm2.g3"} ); //$NON-NLS-1$
+ }
+
+ @Test public void testSelfJoins() {
+ helpPlan("select pm2.g1.e1 FROM pm2.g1 JOIN pm2.g1 AS x ON pm2.g1.e1=x.e1", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm2.g1.e1 FROM pm2.g1 order by e1", //$NON-NLS-1$
+ "SELECT x.e1 FROM pm2.g1 AS x order by e1" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testDefect5282_1() {
+ helpPlan("select * FROM vm1.a4 WHERE vm1.a4.count > 0", example1(), //$NON-NLS-1$
+ new String[] { "SELECT 1 FROM pm1.g1" } ); //$NON-NLS-1$
+ }
+
+ @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$
+ }
+
+ @Test public void testDefect5282_3() {
+ helpPlan("select * FROM vm1.a5 WHERE vm1.a5.count > 0", example1(), //$NON-NLS-1$
+ new String[] { "SELECT 1 FROM pm1.g1" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testDepJoinHintBaseline() throws Exception {
+ ProcessorPlan plan = helpPlan("select * FROM vm1.g4", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
+ "SELECT pm1.g2.e1 FROM pm1.g2" }, new DefaultCapabilitiesFinder(), ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testDefect6425_1() {
+ helpPlan("select * from vm1.u9", example1(), //$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() {
+ helpPlan("select count(*) from vm1.u9", example1(), //$NON-NLS-1$
+ new String[] { "SELECT 1 FROM pm1.g1", //$NON-NLS-1$
+ "SELECT 1 FROM pm1.g2" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testPushMatchCritWithReference() throws Exception {
+ List bindings = new ArrayList();
+ bindings.add("pm1.g2.e1"); //$NON-NLS-1$
+ helpPlan("select e1 FROM pm1.g1 WHERE e1 LIKE ?", example1(), bindings, null, //$NON-NLS-1$
+ new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 LIKE PM1.G2.e1" }, ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
+ }
+
+ @Test public void testDefect6517() {
+ helpPlan("select count(*) from vm1.g5", example1(), //$NON-NLS-1$
+ new String[] { "SELECT DISTINCT pm1.g1.e1 FROM pm1.g1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testDefect5283() {
+ helpPlan("select * from vm1.a6", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1", //$NON-NLS-1$
+ "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testManyJoinsOverThreshold() throws Exception {
+ long begin = System.currentTimeMillis();
+ helpPlan("SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2, pm1.g3, pm1.g4, pm1.g5, pm1.g6, pm1.g7, pm1.g8, pm1.g1 AS x, pm1.g2 AS y WHERE pm1.g1.e1 = pm1.g2.e1 AND pm1.g2.e1 = pm1.g3.e1 AND pm1.g3.e1 = pm1.g4.e1 AND pm1.g4.e1 = pm1.g5.e1 AND pm1.g5.e1=pm1.g6.e1 AND pm1.g6.e1=pm1.g7.e1 AND pm1.g7.e1=pm1.g8.e1", //$NON-NLS-1$
+ example1(),
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
+ "SELECT pm1.g2.e1 FROM pm1.g2", //$NON-NLS-1$
+ "SELECT pm1.g3.e1 FROM pm1.g3", //$NON-NLS-1$
+ "SELECT pm1.g4.e1 FROM pm1.g4", //$NON-NLS-1$
+ "SELECT pm1.g5.e1 FROM pm1.g5", //$NON-NLS-1$
+ "SELECT pm1.g6.e1 FROM pm1.g6", //$NON-NLS-1$
+ "SELECT pm1.g7.e1 FROM pm1.g7", //$NON-NLS-1$
+ "SELECT pm1.g8.e1 FROM pm1.g8", //$NON-NLS-1$
+ "SELECT x.e1 FROM pm1.g1 AS x", //$NON-NLS-1$
+ "SELECT y.e1 FROM pm1.g2 AS y" }, new DefaultCapabilitiesFinder(), ComparisonMode.CORRECTED_COMMAND_STRING ); //$NON-NLS-1$
+
+ long elapsed = System.currentTimeMillis() - begin;
+ assertTrue("Did not plan many join query in reasonable time frame: " + elapsed + " ms", elapsed < 4000); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testAggregateWithoutGroupBy() {
+ ProcessorPlan plan = helpPlan("select count(e2) from pm1.g1", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e2 FROM pm1.g1" } ); //$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
+ });
+ }
+
+ @Test public void testHavingWithoutGroupBy() {
+ ProcessorPlan plan = helpPlan("select count(e2) from pm1.g1 HAVING count(e2) > 0", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e2 FROM pm1.g1" } ); //$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
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testHavingAndGroupBy() {
+ ProcessorPlan plan = helpPlan("select e1, count(e2) from pm1.g1 group by e1 having count(e2) > 0 and sum(e2) > 0", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1, e2 FROM pm1.g1" } ); //$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
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testAllJoinsInSingleClause() throws Exception {
+ ProcessorPlan plan = helpPlan("select pm1.g1.e1 FROM pm1.g1 join (pm1.g2 right outer join pm1.g3 on pm1.g2.e1=pm1.g3.e1) on pm1.g1.e1=pm1.g3.e1", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$
+ "SELECT pm1.g2.e1 FROM pm1.g2", //$NON-NLS-1$
+ "SELECT pm1.g3.e1 FROM pm1.g3" }, new DefaultCapabilitiesFinder(), ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 3, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testSelectCountStarFalseCriteria() {
+ ProcessorPlan plan = helpPlan("Select count(*) from pm1.g1 where 1=0", example1(), //$NON-NLS-1$
+ new String[] { });
+ checkNodeTypes(plan, new int[] {
+ 0, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 1, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testSubquery1() {
+ ProcessorPlan plan = helpPlan("Select e1 from (select e1 FROM pm1.g1) AS x", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testSubquery2() {
+ ProcessorPlan plan = helpPlan("Select e1, a from (select e1 FROM pm1.g1) AS x, (select e1 as a FROM pm1.g2) AS y WHERE x.e1=y.a", example1(), //$NON-NLS-1$
+ new String[] { "SELECT g_0.e1, g_1.e1 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 testSubquery3() {
+ ProcessorPlan plan = helpPlan("Select e1 from (select e1 FROM pm1.g1) AS x WHERE x.e1 = 'a'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 = 'a'" }); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testSubquery4() {
+ ProcessorPlan plan = helpPlan("Select e1 from (select e1 FROM pm1.g1 WHERE e1 = 'a') AS x", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 = 'a'" }); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testSubqueryInClause1() {
+ ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select e1 FROM pm2.g1)", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // 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 testCompareSubquery1() {
+ ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 < ALL (select e1 FROM pm2.g1)", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // 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 testCompareSubquery3() {
+ ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 >= all (select e1 FROM pm2.g1)", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // 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 testExistsSubquery1() {
+ ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where exists (select e1 FROM pm2.g1)", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // 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 testNotPushDistinct() throws Exception {
+ 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testPushDistinct() {
+ 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", 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'", 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", 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", 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", 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", 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", 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", 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", 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", 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", 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);
+ }
+
+ /**
+ * Defect #7819
+ */
+ @Test public void testPushDistinctWithExpressions() {
+ 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @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", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+ new String[] { "SELECT IntKey, LongNum FROM BQT2.SmallA order by intkey" }); //$NON-NLS-1$
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /** 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", 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);
+ }
+
+ /** 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", 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$
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 1, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Tests that user's order by gets pushed to the source, but query
+ * transformation order by is discarded
+ */
+ @Test public void testPushOrderByThroughFrame() {
+ 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);
+ }
+
+ /**
+ * 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", 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);
+ }
+
+ /**
+ * Tests that a user's order by does not get pushed to the source
+ * 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", 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$
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 1, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ /** Tests outer join defect #7945 - see also defect #10050*/
+ @Test public void testOuterJoinDefect7945() {
+ ProcessorPlan plan = helpPlan(
+ "SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey, BQT3.MediumB.IntKey AS MediumC_IntKey " + //$NON-NLS-1$
+ "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$
+ 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$
+ "SELECT BQT2.MediumB.IntKey FROM BQT2.MediumB WHERE BQT2.MediumB.IntKey < 1500 order by intkey" }); //$NON-NLS-1$
+
+ checkNodeTypes(plan, new int[] {
+ 3, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /** Tests outer join defect #7945 */
+ @Test public void testFunctionSimplification1() {
+ ProcessorPlan plan = helpPlan(
+ "SELECT x FROM vm1.g18 WHERE x = 92.0", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ new String[] {
+ "SELECT e4 FROM pm1.g1 WHERE e4 = 0.92" }); //$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 testCantPushJoin1() {
+ ProcessorPlan plan = helpPlan(
+ "SELECT a.e1, b.e2 FROM pm1.g1 a, pm1.g2 b WHERE a.e1 = b.e1", //$NON-NLS-1$
+ 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 );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @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$
+ 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$
+ "SELECT c.e1 FROM pm2.g1 AS c"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 3, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testPushSelfJoin1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ 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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT a.e1, b.e2 FROM pm1.g1 AS a, pm1.g1 AS b WHERE a.e1 = b.e1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushSelfJoin2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ 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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT a.e1, a.e2, b.e2 FROM pm1.g1 AS a, pm1.g1 AS b WHERE a.e1 = b.e1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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 testPushOuterJoin1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ 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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT pm1.g1.e1 FROM pm1.g2 LEFT OUTER JOIN pm1.g1 ON pm1.g1.e1 = pm1.g2.e1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushOuterJoin2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ 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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2"}, //$NON-NLS-1$ //$NON-NLS-2$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ // With join expression that can't be pushed
+ @Test public void testPushOuterJoin3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ 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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2"}, //$NON-NLS-1$ //$NON-NLS-2$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ }
+
+ @Test public void testPushGroupBy1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT e1, e2 as x FROM pm1.g1 GROUP BY e1, e2", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT e1, e2 FROM pm1.g1 GROUP BY e1, e2"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+
+ }
+
+ @Test public void testPushGroupBy2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT e1, max(e2) as x FROM pm1.g1 GROUP BY e1", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT e1, MAX(e2) FROM pm1.g1 GROUP BY e1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+
+ }
+
+ @Test public void testPushGroupBy3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, false);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT e1, e2 as x FROM pm1.g1 GROUP BY e1, e2", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT e1, e2 FROM pm1.g1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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
+ });
+
+ }
+
+ @Test public void testPushGroupBy4() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT MAX(e2) FROM pm1.g1 GROUP BY e1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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 testPushHaving1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT e1 FROM pm1.g1 GROUP BY e1 HAVING MAX(e1) = 'zzz'", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT e1 FROM pm1.g1 GROUP BY e1 HAVING MAX(e1) = 'zzz'"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushHaving2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, false);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT e1 FROM pm1.g1 GROUP BY e1 HAVING MAX(e1) = 'zzz'", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testPushHaving3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, false);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT e1 FROM pm1.g1 GROUP BY e1 HAVING MAX(e1) = 'zzz'", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testPushAggregate1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT MAX(e1) FROM pm1.g1", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT MAX(e1) FROM pm1.g1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushAggregate2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT MAX(e1) FROM pm1.g1 GROUP BY e1", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT MAX(e1) FROM pm1.g1 GROUP BY e1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushAggregate3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushAggregate4() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2 HAVING COUNT(e1) > 0", //$NON-NLS-1$
+ 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 );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /**
+ * Can't push aggs due to not being able to push COUNT in the HAVING clause.
+ */
+ @Test public void testPushAggregate5() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, false);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2 HAVING COUNT(e1) > 0", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT e2, e1 FROM pm1.g1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Can't push aggs due to not being able to push function inside the aggregate
+ */
+ @Test public void testPushAggregate6() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT COUNT(length(e1)) FROM pm1.g1", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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
+ });
+ }
+
+ /**
+ * Can't push aggs due to not being able to push function inside having
+ */
+ @Test public void testPushAggregate7() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT COUNT(*) FROM pm1.g1 GROUP BY e1 HAVING length(e1) > 0", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, capFinder,
+ new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * BQT query that is failing
+ */
+ @Test public void testPushAggregate8() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ String sqlIn =
+ "SELECT intkey FROM bqt1.smalla AS sa WHERE (sa.intkey = 46) AND " + //$NON-NLS-1$
+ "(sa.stringkey IN (46)) AND (sa.datevalue = (" + //$NON-NLS-1$
+ "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$
+
+ ProcessorPlan plan = helpPlan(sqlIn,
+ RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] {sqlOut},
+ ComparisonMode.EXACT_COMMAND_STRING );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testQueryManyJoin() throws Exception {
+ 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$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushSelectDistinct() {
+ 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$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushFunctionInCriteria1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT e1 FROM pm1.g1 WHERE upper(e1) = 'X'", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT e1 FROM pm1.g1 WHERE ucase(e1) = 'X'"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushFunctionInSelect1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
+ caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT lower(e1) FROM pm1.g1 WHERE upper(e1) = 'X'", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT lower(e1) FROM pm1.g1 WHERE ucase(e1) = 'X'"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushFunctionInSelect2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
+ caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT lower(e1), upper(e1), e2 FROM pm1.g1 WHERE upper(e1) = 'X'", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT lower(e1), upper(e1), e2 FROM pm1.g1 WHERE ucase(e1) = 'X'"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushFunctionInSelect3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
+ caps.setFunctionSupport(SourceSystemFunctions.LCASE, false);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT lower(e1), upper(e1) FROM pm1.g1 WHERE upper(e1) = 'X'", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT e1 FROM pm1.g1 WHERE ucase(e1) = 'X'"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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 testPushFunctionInSelect4() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
+ caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ 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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT lcase(e1) FROM pm1.g1 WHERE ucase(e1) = 'X'"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushFunctionInSelect5() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
+ caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ 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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT ucase(e1), e1, lcase(e1) FROM pm1.g1 WHERE ucase(e1) = 'X'"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushFunctionInSelect6_defect_10081() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setFunctionSupport("upper", true); //$NON-NLS-1$
+ caps.setFunctionSupport("lower", false); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT upper(lower(e1)) FROM pm1.g1", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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 testPushFunctionInSelectWithOrderBy1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
+ caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT e1, lower(e1) FROM pm1.g1 WHERE upper(e1) = 'X' ORDER BY e1", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT e1, lcase(e1) FROM pm1.g1 WHERE ucase(e1) = 'X' ORDER BY e1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /** defect 13336 */
+ @Test public void testPushFunctionInSelectWithOrderBy1a() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
+ caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ 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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT e1, lcase(e1) AS x FROM pm1.g1 WHERE ucase(e1) = 'X' ORDER BY x"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /** defect 13336 */
+ @Test public void testPushFunctionInSelectWithOrderBy2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
+ caps.setFunctionSupport(SourceSystemFunctions.LCASE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ 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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT e1, lcase(e1) AS EXPR FROM pm1.g1 WHERE ucase(e1) = 'X' ORDER BY EXPR"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushFunctionInJoin1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ 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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT pm1.g1.e1, pm1.g2.e3 FROM pm1.g1, pm1.g2 WHERE (pm1.g1.e1 = convert(pm1.g2.e2, string)) AND (ucase(pm1.g1.e1) = 'X') AND (ucase(convert(pm1.g2.e2, string)) = 'X')"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushFunctionInJoin2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ 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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT pm1.g1.e1, pm1.g2.e3 FROM pm1.g1, pm1.g2 WHERE (pm1.g1.e1 = convert(pm1.g2.e2, string)) AND (ucase(pm1.g1.e1) = 'X') AND (ucase(convert(pm1.g2.e2, string)) = 'X')", //$NON-NLS-1$
+ "SELECT pm1.g3.e1 FROM pm1.g3"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testPushFunctionInJoin3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setFunctionSupport(SourceSystemFunctions.UCASE, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ 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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT pm1.g1.e1, pm1.g2.e3 FROM pm1.g1, pm1.g2 WHERE (pm1.g1.e1 = convert(pm1.g2.e2, string)) AND (ucase(pm1.g1.e1) = 'X') AND (ucase(convert(pm1.g2.e2, string)) = 'X')", //$NON-NLS-1$
+ "SELECT e1 FROM pm1.g3"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testUnionOverFunctions() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT StringCol AS E " + //$NON-NLS-1$
+ "FROM (SELECT CONVERT(BQT1.SmallA.IntNum, string) AS StringCol, BQT1.SmallA.IntNum AS IntCol FROM BQT1.SmallA " + //$NON-NLS-1$
+ "UNION ALL SELECT BQT1.SmallB.StringNum, CONVERT(BQT1.SmallB.StringNum, integer) FROM BQT1.SmallB) AS x", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT CONVERT(BQT1.SmallA.IntNum, string) FROM BQT1.SmallA", //$NON-NLS-1$
+ "SELECT BQT1.SmallB.StringNum FROM BQT1.SmallB"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ @Test public void testDefect9827() {
+ 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$
+
+ 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
+ 1, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * This tests that a criteria with no elements is not pushed down,
+ * but instead is cleaned up properly later
+ * See defect 9865
+ */
+ @Test public void testCrossJoinNoElementCriteriaOptimization2() {
+ ProcessorPlan plan = helpPlan("select Y.e1, Y.e2 FROM vm1.g1 X, vm1.g1 Y where {b'true'} = {b'true'}", example1(), //$NON-NLS-1$
+ new String[]{"SELECT 1 FROM pm1.g1 AS g1__1", "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}); //$NON-NLS-1$ //$NON-NLS-2$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * <p>This tests that a SELECT node with no groups is not pushed down without the capability to have a subquery in the where clause.
+ */
+ @Test public void testCrossJoinNoElementCriteriaOptimization3() {
+ ProcessorPlan plan = helpPlan("select Y.e1, Y.e2 FROM vm1.g1 X, vm1.g1 Y where {b'true'} in (select e3 FROM vm1.g1)", example1(), //$NON-NLS-1$
+ new String[]{"SELECT 1 FROM pm1.g1 AS g1__1", "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}); //$NON-NLS-1$ //$NON-NLS-2$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * <p>This tests that a SELECT node with no groups is pushed down.
+ */
+ @Test public void testCrossJoinNoElementCriteriaOptimization4() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan("select Y.e1, Y.e2 FROM vm1.g1 X, vm1.g1 Y where {b'true'} in (select e3 FROM vm1.g1)", example1(), null, capFinder, //$NON-NLS-1$
+ new String[]{"SELECT 1 FROM pm1.g1 AS g1__1 WHERE TRUE IN (SELECT pm1.g1.e3 FROM pm1.g1)", "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}, true); //$NON-NLS-1$ //$NON-NLS-2$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Criteria should be copied across this join
+ */
+ @Test public void testCopyCriteriaWithOuterJoin_defect10050(){
+
+ ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1 left outer join pm2.g2 on pm2.g1.e1=pm2.g2.e1 where pm2.g1.e1 IN ('a', 'b')", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm2.g1.e1, pm2.g2.e1 FROM pm2.g1 LEFT OUTER JOIN pm2.g2 ON pm2.g1.e1 = pm2.g2.e1 AND pm2.g2.e1 IN ('a', 'b') WHERE pm2.g1.e1 IN ('a', 'b')" }); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /**
+ * Criteria should be copied across this join
+ */
+ @Test public void testCopyCriteriaWithOuterJoin2_defect10050(){
+
+ ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1 left outer join pm2.g2 on pm2.g1.e1=pm2.g2.e1 and pm2.g1.e2=pm2.g2.e2 where pm2.g1.e1 = 'a' and pm2.g1.e2 = 1", example1(), //$NON-NLS-1$
+ new String[] { "SELECT g_0.e1, g_1.e1 FROM pm2.g1 AS g_0 LEFT OUTER JOIN pm2.g2 AS g_1 ON g_0.e1 = g_1.e1 AND g_0.e2 = g_1.e2 AND g_1.e1 = 'a' AND g_1.e2 = 1 WHERE (g_0.e1 = 'a') AND (g_0.e2 = 1)" }); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /**
+ * See also case 2912.
+ */
+ @Test public void testCopyCriteriaWithOuterJoin5_defect10050(){
+
+ ProcessorPlan plan = helpPlan(
+ "select pm2.g1.e1, pm2.g2.e1, pm2.g3.e1 from ( (pm2.g1 right outer join pm2.g2 on pm2.g1.e1=pm2.g2.e1) right outer join pm2.g3 on pm2.g2.e1=pm2.g3.e1) where pm2.g3.e1 = 'a'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT g_2.e1, g_1.e1, g_0.e1 FROM pm2.g3 AS g_0 LEFT OUTER JOIN (pm2.g2 AS g_1 LEFT OUTER JOIN pm2.g1 AS g_2 ON g_2.e1 = g_1.e1 AND g_2.e1 = 'a') ON g_1.e1 = g_0.e1 AND g_1.e1 = 'a' WHERE g_0.e1 = 'a'" }); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /**
+ *
+ */
+ @Test public void testCopyCriteriaWithOuterJoin6_defect10050(){
+
+ ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1 left outer join pm2.g2 on pm2.g2.e1=pm2.g1.e1 where pm2.g1.e1 IN ('a', 'b')", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm2.g1.e1, pm2.g2.e1 FROM pm2.g1 LEFT OUTER JOIN pm2.g2 ON pm2.g2.e1 = pm2.g1.e1 AND pm2.g2.e1 IN ('a', 'b') WHERE pm2.g1.e1 IN ('a', 'b')" }); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /**
+ * Same as previous test, only right outer join
+ */
+ @Test public void testCopyCriteriaWithOuterJoin7_defect10050(){
+
+ ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1 right outer join pm2.g2 on pm2.g2.e1=pm2.g1.e1 where pm2.g2.e1 IN ('a', 'b')", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm2.g1.e1, pm2.g2.e1 FROM pm2.g2 LEFT OUTER JOIN pm2.g1 ON pm2.g2.e1 = pm2.g1.e1 AND pm2.g1.e1 IN ('a', 'b') WHERE pm2.g2.e1 IN ('a', 'b')" }); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testCleanCriteria(){
+
+ ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1, pm2.g2 where pm2.g1.e1=pm2.g2.e1 and pm2.g1.e2 IN (1, 2)", example1(), //$NON-NLS-1$
+ new String[] { "SELECT pm2.g1.e1, pm2.g2.e1 FROM pm2.g1, pm2.g2 WHERE (pm2.g1.e1 = pm2.g2.e1) AND (pm2.g1.e2 IN (1, 2))" }); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testCleanCriteria2(){
+
+ ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1, pm2.g2 where pm2.g1.e1=pm2.g2.e1 and pm2.g1.e1 = 'a'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT g_0.e1, g_1.e1 FROM pm2.g1 AS g_0, pm2.g2 AS g_1 WHERE (g_0.e1 = g_1.e1) AND (g_0.e1 = 'a') AND (g_1.e1 = 'a')" }); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testCleanCriteria3(){
+
+ ProcessorPlan plan = helpPlan("select pm2.g1.e1, pm2.g2.e1 from pm2.g1 inner join pm2.g2 on pm2.g1.e1=pm2.g2.e1 where pm2.g1.e1 = 'a'", example1(), //$NON-NLS-1$
+ new String[] { "SELECT g_0.e1, g_1.e1 FROM pm2.g1 AS g_0, pm2.g2 AS g_1 WHERE (g_0.e1 = g_1.e1) AND (g_0.e1 = 'a') AND (g_1.e1 = 'a')" }); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+
+ @Test public void testPushSubqueryInWhereClause1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select e1 FROM pm1.g2)", example1(), //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 IN (SELECT e1 FROM pm1.g2)"}, SHOULD_SUCCEED ); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushSubqueryInWhereClause2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select max(e1) FROM pm1.g2)", example1(), //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 IN (SELECT MAX(e1) FROM pm1.g2)" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /**
+ * Check that subquery is pushed if the subquery selects a function that is pushed
+ */
+ @Test public void testPushSubqueryInWhereClause3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setFunctionSupport("ltrim", true); //$NON-NLS-1$
+ 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)", 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);
+ }
+
+ /**
+ * Check that subquery is pushed if the subquery selects an aliased function that is pushed
+ */
+ @Test public void testPushSubqueryInWhereClause4() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setFunctionSupport("ltrim", true); //$NON-NLS-1$
+ 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)", 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);
+ }
+
+ /** Case 1456, defect 10492*/
+ @Test public void testAliasingDefect1(){
+ // Create query
+ String sql = "SELECT e1 FROM vm1.g1 X WHERE e2 = (SELECT MAX(e2) FROM vm1.g1 Y WHERE X.e1 = Y.e1)";//$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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);
+ }
+
+ /** Case 1456, defect 10492*/
+ @Test public void testAliasingDefect2(){
+ // Create query
+ String sql = "SELECT X.e1 FROM vm1.g1 X, vm1.g1 Z WHERE X.e2 = (SELECT MAX(e2) FROM vm1.g1 Y WHERE X.e1 = Y.e1 AND Y.e2 = Z.e2) AND X.e1 = Z.e1";//$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(sql, metadata,
+ null, capFinder,
+ new String[] { "SELECT g1__1.e1 FROM pm1.g1 AS g1__1, pm1.g1 AS g1__2 WHERE (g1__1.e2 = (SELECT MAX(pm1.g1.e2) FROM pm1.g1 WHERE (pm1.g1.e1 = g1__1.e1) AND (pm1.g1.e2 = g1__2.e2))) AND (g1__1.e1 = g1__2.e1)" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /** Case 1456, defect 10492*/
+ @Test public void testAliasingDefect3() throws Exception {
+ // Create query
+ String sql = "SELECT X.e1 FROM pm1.g2, vm1.g1 X WHERE X.e2 = ALL (SELECT MAX(e2) FROM vm1.g1 Y WHERE X.e1 = Y.e1) AND X.e1 = pm1.g2.e1";//$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(sql, metadata,
+ null, capFinder,
+ new String[] { "SELECT g_1.e1 FROM pm1.g2 AS g_0, pm1.g1 AS g_1 WHERE (g_1.e1 = g_0.e1) AND (g_1.e2 = ALL (SELECT MAX(g_2.e2) FROM pm1.g1 AS g_2 WHERE g_2.e1 = g_1.e1))" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /** Should use merge join since neither access node is "strong" - order by's pushed to source */
+ @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$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1();
+ RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1, metadata);
+
+ ProcessorPlan plan = helpPlan(sql, metadata,
+ null, capFinder,
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY pm1.g1.e1", "SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY pm1.g2.e1" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /** Model supports order by, should be pushed to the source */
+ @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$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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,
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY pm1.g1.e1", "SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY pm1.g2.e1" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /** Should use merge join, since costs are not known, neither access node is "strong" */
+ @Test public void testUseMergeJoin5_CostsNotKnown(){
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(sql, metadata,
+ null, capFinder,
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /** one side of join supports order by, the other doesn't*/
+ @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$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ 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,
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY pm1.g1.e1", "SELECT pm2.g2.e1 FROM pm2.g2" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /** reverse of testUseMergeJoin7 */
+ @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$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ 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,
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm2.g2.e1 FROM pm2.g2 ORDER BY pm2.g2.e1" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /** function on one side of join should prevent order by from being pushed down*/
+ @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$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ 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,
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm2.g2.e1 FROM pm2.g2 ORDER BY pm2.g2.e1" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /** Model supports order by, functions in join criteria */
+ @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$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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,
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 3, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /** should be one dependent join */
+ @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$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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,
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2", "SELECT pm1.g3.e1 FROM pm1.g3" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ checkNodeTypes(plan, new int[] {
+ 3, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testLargeSetCriteria() {
+ // Create query
+ String sql = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA INNER JOIN BQT2.SmallB ON BQT1.SmallA.IntKey = BQT2.SmallB.IntKey WHERE BQT1.SmallA.IntKey IN (1,2,3,4,5)"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ 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$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 2, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testMergeJoin_defect11236(){
+ // Create query
+ String sql = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA, BQT1.SmallB WHERE BQT1.SmallA.IntKey = (BQT1.SmallB.IntKey + 1)"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = helpPlan(sql, metadata,
+ null, capFinder,
+ new String[] { "SELECT BQT1.SmallB.IntKey FROM BQT1.SmallB", //$NON-NLS-1$
+ "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA ORDER BY BQT1.SmallA.IntKey" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testNoFrom() {
+ ProcessorPlan plan = helpPlan("SELECT 1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ new String[] {} );
+
+ checkNodeTypes(plan, new int[] {
+ 0, // 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 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$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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,
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY pm1.g1.e1", "SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY pm1.g2.e1"}, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testDefect10711(){
+ 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);
+
+ }
+
+ // SELECT 5, SUM(IntKey) FROM BQT1.SmallA
+ @Test public void testAggregateNoGroupByWithExpression() {
+ 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[] {
+ 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
+ });
+ }
+
+ /** 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", 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);
+
+ }
+
+ /** 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", 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[] {
+ 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
+ });
+
+ }
+
+ /** defect 21965 */
+ @Test public void testLookupFunctionInSelect() {
+ 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);
+ }
+
+ // 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", 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ // 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", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+ new String[] {
+ "SELECT IntKey, IntNum FROM BQT1.SmallA WHERE IntNum = 0", //$NON-NLS-1$
+ "SELECT IntKey FROM BQT1.SmallA WHERE IntKey = 0" }); //$NON-NLS-1$
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ // 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", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+ new String[] {
+ "SELECT IntKey, IntNum FROM BQT1.SmallA WHERE IntNum = 0", //$NON-NLS-1$
+ "SELECT IntKey FROM BQT1.SmallA WHERE IntKey = 0" }); //$NON-NLS-1$
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ @Test public void testCountStarOverSelectDistinct() {
+ 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$
+
+ 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
+ });
+ }
+
+ //virtual group with two elements. One selectable, one not
+ @Test public void testVirtualGroup1() {
+ 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);
+ }
+
+ @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, 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$
+
+ 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 void helpTestUnionPushdown(boolean queryHasOrderBy, boolean hasUnionCapability, boolean hasUnionOrderByCapability) {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, hasUnionCapability);
+ caps.setCapabilitySupport((Capability.QUERY_ORDERBY), hasUnionOrderByCapability);
+ caps.setCapabilitySupport((Capability.QUERY_SET_ORDER_BY), hasUnionOrderByCapability);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ String sqlUnion = "SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB";//$NON-NLS-1$
+ String sqlOrderBy = sqlUnion + " ORDER BY IntKey"; //$NON-NLS-1$
+ String sql = null;
+ if(queryHasOrderBy) {
+ sql = sqlOrderBy;
+ } else {
+ sql = sqlUnion;
+ }
+
+ String[] expectedSql = null;
+ if(hasUnionCapability) {
+ if(queryHasOrderBy && hasUnionOrderByCapability) {
+ expectedSql = new String[] {sqlOrderBy };
+ } else {
+ expectedSql = new String[] {sqlUnion };
+ }
+ } else {
+ expectedSql = new String[] { "SELECT IntKey FROM BQT1.SmallA", "SELECT IntKey FROM BQT1.SmallB" }; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = helpPlan(sql, metadata,
+ null, capFinder, expectedSql, SHOULD_SUCCEED);
+
+ int accessCount = hasUnionCapability ? 1 : 2;
+ int projectCount = 0;
+ int sortCount = 0;
+ if(queryHasOrderBy && ! (hasUnionCapability && hasUnionOrderByCapability)) {
+ sortCount = 1;
+ }
+ int unionCount = hasUnionCapability ? 0 : 1;
+
+
+
+ checkNodeTypes(plan, new int[] {
+ accessCount, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ projectCount, // Project
+ 0, // Select
+ sortCount, // Sort
+ unionCount // UnionAll
+ });
+ }
+
+ /**
+ * Query has union but no order by and no capabilities.
+ */
+ @Test public void testUnionPushdown1() {
+ helpTestUnionPushdown(false, false, false);
+ }
+
+ /**
+ * Query has union but no order by and only union capability.
+ */
+ @Test public void testUnionPushdown2() {
+ helpTestUnionPushdown(false, true, false);
+ }
+
+ /**
+ * Query has union with order by and no capabilities.
+ */
+ @Test public void testUnionPushdown3() {
+ helpTestUnionPushdown(true, false, false);
+ }
+
+ /**
+ * Query has union with order by and just union capability.
+ */
+ @Test public void testUnionPushdown4() {
+ helpTestUnionPushdown(true, true, false);
+ }
+
+ /**
+ * Query has union with order by and both capabilities.
+ */
+ @Test public void testUnionPushdown5() {
+ helpTestUnionPushdown(true, true, true);
+ }
+
+ @Test public void testUnionPushdownWithSelectNoFrom() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
+ capFinder.addCapabilities("BQT1", caps); //$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[] {
+ 0, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ @Test public void testUnionPushdownWithSelectNoFromFirstBranch() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ 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", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+ null, capFinder, new String[] {"SELECT IntKey FROM BQT1.SmallA"}, SHOULD_SUCCEED); //$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
+ 1 // UnionAll
+ });
+ }
+
+ @Test public void testUnionPushdownWithSelectNoFromSecondBranch() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ 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", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+ null, capFinder, new String[] {"SELECT IntKey FROM BQT1.SmallA"}, SHOULD_SUCCEED); //$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
+ 1 // UnionAll
+ });
+ }
+
+ @Test public void testUnionPushdownMultipleBranches() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ 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", 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);
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testUnionPushdownMultipleBranchesMixedModels1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
+ 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", 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);
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ @Test public void testUnionPushdownMultipleBranchesNoDupRemoval() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ 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", 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);
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testAggregateOverUnionPushdown() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ 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", 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);
+
+ 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
+ });
+ }
+
+ @Test public void testUnionPushdownWithFunctionsAndAliases() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
+ 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", 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);
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testUnionPushdownWithInternalOrderBy() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
+ 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", 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);
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testUnionPushdownWithInternalDistinct() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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,
+ new String[] {"SELECT DISTINCT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB"}, //$NON-NLS-1$
+ SHOULD_SUCCEED);
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testUnionNoAllPushdownInInlineView() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
+ 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", 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);
+
+ 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 testUnionAllPushdownInInlineView() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
+ 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", 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);
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testUnionAllPushdownVirtualGroup() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$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);
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testUnionAllPushdownVirtualGroup2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
+ capFinder.addCapabilities("pm3", caps); //$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);
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testUnionAllPushdownVirtualGroup3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
+ 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$
+ RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] {"SELECT intkey FROM BQT1.SmallA", "SELECT IntNum FROM bqt1.smalla"}, //$NON-NLS-1$ //$NON-NLS-2$
+ SHOULD_SUCCEED);
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ // Allow pushing literals
+ @Test public void testUnionAllPushdownVirtualGroup4() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ 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$
+ 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);
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushCaseInSelect() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_CASE, true);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT CASE WHEN e1 = 'a' THEN 10 ELSE 0 END FROM pm1.g1", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT CASE WHEN e1 = 'a' THEN 10 ELSE 0 END FROM pm1.g1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testCantPushCaseInSelectWithFunction() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_CASE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT CASE e1 WHEN 'a' THEN 10 ELSE (e2+0) END FROM pm1.g1", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT e1, e2 FROM pm1.g1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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 testPushSearchedCaseInSelect() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT CASE WHEN e1 = 'a' THEN 10 ELSE 0 END FROM pm1.g1", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT CASE WHEN e1 = 'a' THEN 10 ELSE 0 END FROM pm1.g1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testCantPushSearchedCaseInSelectWithFunction() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT CASE WHEN e1 = 'a' THEN 10 ELSE (e2+0) END FROM pm1.g1", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT e1, e2 FROM pm1.g1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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 testPushdownFunctionNotEvaluated() {
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
+ caps.setFunctionSupport("xyz", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT e1 FROM pm1.g1 WHERE xyz() > 0", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT e1 FROM pm1.g1 WHERE xyz() > 0"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @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'", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+ new String[] { });
+
+ checkNodeTypes(plan, new int[] {
+ 0, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /** defect 14510 */
+ @Test public void testDefect14510LookupFunction() throws Exception {
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("BQT1", caps); //$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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT g_1.StringKey, g_0.IntKey FROM BQT1.SmallA AS g_0, BQT1.SmallB AS g_1 WHERE g_0.IntKey = 1"}, //$NON-NLS-1$ //$NON-NLS-2$
+ SHOULD_SUCCEED );
+
+ 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
+ });
+ }
+
+ /** defect 14510 */
+ @Test public void testDefect14510LookupFunction2() throws Exception {
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ capFinder.addCapabilities("BQT1", caps); //$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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA", "SELECT BQT1.MediumB.StringKey, BQT1.MediumB.IntKey FROM BQT1.MediumB"}, //$NON-NLS-1$ //$NON-NLS-2$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /** defect 14510 */
+ @Test public void testDefect14510LookupFunction3() throws Exception {
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ capFinder.addCapabilities("BQT1", caps); //$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$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA", "SELECT BQT1.MediumB.StringKey, BQT1.MediumB.IntKey FROM BQT1.MediumB"}, //$NON-NLS-1$ //$NON-NLS-2$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testCase2125() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, false);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ String sql = "SELECT OD.IntKEy, P.IntKEy, O.IntKey " + //$NON-NLS-1$
+ "FROM (bqt1.smalla AS OD INNER JOIN bqt1.smallb AS P ON OD.StringKey = P.StringKey) " + //$NON-NLS-1$
+ "INNER JOIN bqt1.mediuma AS O ON O.IntKey = OD.IntKey " + //$NON-NLS-1$
+ "WHERE (OD.IntNum > (SELECT SUM(IntNum) FROM bqt1.smalla)) AND " + //$NON-NLS-1$
+ "(P.longnum > (SELECT AVG(LongNum) FROM bqt1.smallb WHERE bqt1.smallb.datevalue = O.datevalue))"; //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ 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 );
+
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // 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 testPushdownLiteralInSelectUnderAggregate() {
+ String sql = "SELECT COUNT(*) FROM (SELECT '' AS y, a.IntKey FROM BQT1.SmallA a union all select '', b.intkey from bqt1.smallb b) AS x"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ 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 );
+
+ 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
+ });
+ }
+
+ @Test public void testPushdownLiteralInSelectUnderAggregate2() {
+ String sql = "SELECT SUM(z) FROM (SELECT '' AS y, a.IntKey as z FROM BQT1.SmallA a union all select b.stringkey, 0 from bqt1.smallb b) AS x group by z"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ 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 );
+
+ 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
+ });
+ }
+
+ @Test public void testPushdownLiteralInSelectUnderAggregate3() {
+ String sql = "SELECT code, SUM(ID) FROM (SELECT IntKey AS ID, '' AS Code FROM BQT1.SmallA union all select intkey, stringkey from bqt1.smallb b) AS x group by code"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ 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 );
+
+ 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
+ });
+ }
+
+ @Test public void testPushdownLiteralInSelectWithOrderBy() {
+ String sql = "SELECT 1, concat('a', 'b' ) AS X FROM BQT1.SmallA where intkey = 0 " + //$NON-NLS-1$
+ "UNION ALL " + //$NON-NLS-1$
+ "select 2, 'Hello2' from BQT1.SmallA where intkey = 1 order by X desc"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ 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 );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testUpdateWithElement() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setFunctionSupport(SourceSystemFunctions.ADD_OP, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ String sql = "UPDATE BQT1.SmallA SET IntKey = IntKey + 1"; //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] {"UPDATE BQT1.SmallA SET IntKey = (IntKey + 1)"}, //$NON-NLS-1$
+ ComparisonMode.EXACT_COMMAND_STRING );
+
+ checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testCase2187() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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$
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT a.IntKey FROM ((bqt1.smalla AS a LEFT OUTER JOIN bqt1.smallb AS b ON a.intkey = b.intkey) CROSS JOIN bqt1.smalla AS x) FULL OUTER JOIN bqt1.smallb AS c ON a.IntKey = c.intkey"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testMultiUnionMergeVirtual() throws Exception {
+ String sql = "SELECT * FROM " + //$NON-NLS-1$
+ "(SELECT IntKey, 'a' AS s FROM (SELECT intkey, stringkey from BQT1.SmallA) as a union all " + //$NON-NLS-1$
+ "select IntKey, 'b' FROM (SELECT intkey, stringkey from BQT1.SmallA) as b union all " + //$NON-NLS-1$
+ "select IntKey, 'c' FROM (SELECT intkey, stringkey from BQT1.SmallA) as c " + //$NON-NLS-1$
+ ") AS x"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ 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 );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testDefect16848_groupAliasNotSupported_1() {
+ String sql = "SELECT sa.intkey, sa.objectvalue FROM bqt1.smalla AS sa WHERE (sa.intkey = 46) AND (sa.stringkey IN (46)) AND (sa.datevalue = (SELECT MAX(sb.datevalue) FROM bqt1.smalla AS sb WHERE (sb.intkey = sa.intkey) AND (sa.stringkey = sb.stringkey) ))"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ RelationalPlan plan = (RelationalPlan)helpPlan(sql,
+ 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 );
+
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ ProcessorPlan subplan = ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(((SelectNode)plan.getRootNode().getChildren()[0]).getCriteria()).get(0).getCommand().getProcessorPlan();
+
+ // Collect atomic queries
+ Set<String> actualQueries = getAtomicQueries(subplan);
+
+ // Compare atomic queries
+ HashSet<String> expectedQueries = new HashSet<String>(Arrays.asList(new String[] { "SELECT bqt1.smalla.datevalue FROM bqt1.smalla WHERE (bqt1.smalla.intkey = bqt1.smalla.intkey) AND (bqt1.smalla.stringkey = bqt1.smalla.stringkey)"})); //$NON-NLS-1$
+ assertEquals("Did not get expected atomic queries for subplan: ", expectedQueries, actualQueries); //$NON-NLS-1$
+
+ checkNodeTypes(subplan, 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
+ });
+
+ }
+
+ @Test public void testFunctionOfAggregate1() {
+ String sql = "SELECT SUM(IntKey) + 1 AS x FROM BQT1.SmallA GROUP BY IntKey"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ caps.setFunctionSupport("+", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] {"SELECT (SUM(IntKey) + 1) FROM BQT1.SmallA GROUP BY IntKey"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testFunctionOfAggregateCantPush1() {
+ String sql = "SELECT SUM(IntKey) + 1 AS x FROM BQT1.SmallA GROUP BY IntKey"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] {"SELECT IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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
+ });
+ }
+
+ @Test public void testFunctionOfAggregateCantPush3() {
+ String sql = "SELECT avg(intkey) * 2 FROM BQT1.SmallA "; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] {"SELECT intkey FROM BQT1.SmallA"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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
+ });
+ }
+
+ private void helpTestCase2589NonPushdown(String sql, String[] expected) {
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, false);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ expected,
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ }
+
+ private void helpTestCase2589(String sql, String expected) throws Exception {
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {expected},
+ ComparisonMode.EXACT_COMMAND_STRING );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testCase2589() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589 ON MediumA.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
+
+ helpTestCase2589(sql, expected);
+ }
+
+ @Test public void testCase2589a() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589a ON MediumA.IntKey = SmallA_2589a.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.IntKey = BQT1.SmallB.IntKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ @Test public void testCase2589b() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ @Test public void testCase2589c() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB, BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey " + //$NON-NLS-1$
+ "WHERE BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB INNER JOIN (BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10') ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ @Test public void testCase2589d() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB INNER JOIN " + //$NON-NLS-1$
+ "(BQT1.MediumA LEFT OUTER JOIN VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey) " + //$NON-NLS-1$
+ "ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB INNER JOIN (BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10') ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ @Test public void testCase2589e() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB LEFT OUTER JOIN " + //$NON-NLS-1$
+ "(BQT1.MediumA LEFT OUTER JOIN VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey) " + //$NON-NLS-1$
+ "ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB LEFT OUTER JOIN (BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10') ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ @Test public void testCase2589f() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB LEFT OUTER JOIN " + //$NON-NLS-1$
+ "(BQT1.MediumA INNER JOIN VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey) " + //$NON-NLS-1$
+ "ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB LEFT OUTER JOIN (BQT1.MediumA INNER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey) ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey AND BQT1.SmallA.StringNum = '10'";//$NON-NLS-1$";
+ helpTestCase2589(sql, expected);
+ }
+
+ @Test public void testCase2589g() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB LEFT OUTER JOIN " + //$NON-NLS-1$
+ "(BQT1.MediumA INNER JOIN VQT.SmallA_2589c ON MediumA.IntKey = SmallA_2589c.IntKey) " + //$NON-NLS-1$
+ "ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumB LEFT OUTER JOIN " + //$NON-NLS-1$
+ "(BQT1.MediumA INNER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB " + //$NON-NLS-1$
+ "ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey AND " + //$NON-NLS-1$
+ "concat(BQT1.SmallA.StringNum, BQT1.SmallB.StringNum) = '1010') " + //$NON-NLS-1$
+ "ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey) ON BQT1.MediumB.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ @Test public void testCase2589h() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN VQT.SmallA_2589c " + //$NON-NLS-1$
+ "ON MediumA.IntKey = SmallA_2589c.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey AND concat(BQT1.SmallA.StringNum, BQT1.SmallB.StringNum) = '1010') ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ @Test public void testCase2589i() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN VQT.SmallA_2589d " + //$NON-NLS-1$
+ "ON MediumA.IntKey = SmallA_2589d.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' AND BQT1.SmallA.IntNum = 10"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ /**
+ * Test optimization doesn't happen if an outer join isn't involved
+ */
+ @Test public void testCase2589j() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA INNER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589 ON MediumA.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA, BQT1.SmallA WHERE (BQT1.MediumA.IntKey = BQT1.SmallA.IntKey) AND (BQT1.SmallA.StringNum = '10')"; //$NON-NLS-1$
+
+ helpTestCase2589(sql, expected);
+ }
+
+ /**
+ * Test optimization doesn't happen if an outer join isn't involved
+ */
+ @Test public void testCase2589k() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA INNER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA, BQT1.SmallA, BQT1.SmallB WHERE (BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) AND (BQT1.MediumA.IntKey = BQT1.SmallA.IntKey) AND (BQT1.SmallA.StringNum = '10')"; //$NON-NLS-1$
+
+
+ helpTestCase2589(sql, expected);
+ }
+
+ /**
+ * Same as testCase2589 except right outer join
+ */
+ @Test public void testCase2589l() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM VQT.SmallA_2589 RIGHT OUTER JOIN " + //$NON-NLS-1$
+ "BQT1.MediumA ON MediumA.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
+
+ helpTestCase2589(sql, expected);
+ }
+
+ /**
+ * Same as testCase2589 except full outer join - criteria "below" full outer join cannot be
+ * raised into the join criteria, so basically the virtual groups cannot be merged in this test.
+ */
+ @Test public void testCase2589m() {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM VQT.SmallA_2589 FULL OUTER JOIN " + //$NON-NLS-1$
+ "BQT1.MediumA ON MediumA.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
+
+ String[] expected = new String[] {
+ "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA", //$NON-NLS-1$
+ "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA WHERE StringNum = '10'" //$NON-NLS-1$
+ };
+
+ helpTestCase2589NonPushdown(sql, expected);
+ }
+
+ /**
+ * Same as testCase2589b except full outer join
+ */
+ @Test public void testCase2589n() {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA FULL OUTER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589b ON MediumA.IntKey = SmallA_2589b.IntKey"; //$NON-NLS-1$
+
+ String[] expected = new String[] {
+ "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA", //$NON-NLS-1$
+ "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA, BQT1.SmallB WHERE (BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) AND (BQT1.SmallA.StringNum = '10')" //$NON-NLS-1$
+ };
+ helpTestCase2589NonPushdown(sql, expected);
+
+ }
+
+ /**
+ * Same as testCase2589 except with two virtual layers instead of one
+ */
+ @Test public void testCase2589o() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589f ON MediumA.IntKey = SmallA_2589f.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
+
+ helpTestCase2589(sql, expected);
+ }
+
+ /**
+ * Same as testCase2589b except with two virtual layers instead of one
+ */
+ @Test public void testCase2589p() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589g ON MediumA.IntKey = SmallA_2589g.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ /**
+ * Test 3 frames, where top frame has outer join, middle frame has inner join, and
+ * bottom frame has criteria that must be made into join criteria.
+ */
+ @Test public void testCase2589q() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589h ON MediumA.IntKey = SmallA_2589h.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ /**
+ * Similar to testCase2589b, except virtual transformation has criteria on an
+ * element from each physical table
+ */
+ @Test public void testCase2589r() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589i ON MediumA.IntKey = SmallA_2589i.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.StringKey = BQT1.SmallB.StringKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' AND BQT1.SmallB.StringNum = '10'"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ /**
+ * Test user criteria that should NOT be moved into join clause
+ */
+ @Test public void testCase2589s() throws Exception {
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589 ON MediumA.IntKey = SmallA_2589.IntKey " + //$NON-NLS-1$
+ "WHERE BQT1.MediumA.IntNum = 10"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' WHERE BQT1.MediumA.IntNum = 10"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ /**
+ * Test user criteria that should NOT be moved into join clause
+ */
+ @Test public void testCase2589t() throws Exception {
+ String sql = "SELECT z.IntKey FROM (SELECT IntKey FROM BQT1.MediumA WHERE BQT1.MediumA.IntNum = 10) as z " + //$NON-NLS-1$
+ "LEFT OUTER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589 ON z.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' WHERE BQT1.MediumA.IntNum = 10"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ /**
+ * The above test written with an inline view instead of a virtual group.
+ * This test translates to - how can this query be rewritten without subqueries such
+ * that the same results are produced? More specifically, where should the criteria
+ * go - WHERE clause or FROM clause?
+ */
+ @Test public void testCase2589u() throws Exception {
+ String sql = "SELECT z.IntKey FROM (SELECT IntKey FROM BQT1.MediumA WHERE IntNum = 10) as z " + //$NON-NLS-1$
+ "LEFT OUTER JOIN " + //$NON-NLS-1$
+ "(SELECT IntKey FROM BQT1.SmallA WHERE StringNum = '10') as y " + //$NON-NLS-1$
+ "ON z.IntKey = y.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' WHERE BQT1.MediumA.IntNum = 10"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ /**
+ * Same sql as testCase2589, but the model doesn't support outer joins, so
+ * case 2589 optimization shouldn't happen.
+ */
+ @Test public void testCase2589v() {
+
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589 ON MediumA.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
+
+ String expected[] = new String[] {
+ "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA", //$NON-NLS-1$
+ "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA WHERE StringNum = '10'" //$NON-NLS-1$
+ };
+
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, false);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ expected,
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Same as previous testCase2589v, but with full outer join.
+ */
+ @Test public void testCase2589w() {
+
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA FULL OUTER JOIN " + //$NON-NLS-1$
+ "VQT.SmallA_2589 ON MediumA.IntKey = SmallA_2589.IntKey"; //$NON-NLS-1$
+
+ String expected[] = new String[] {
+ "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA", //$NON-NLS-1$
+ "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA WHERE StringNum = '10'" //$NON-NLS-1$
+ };
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, false);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ expected,
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Test a complicated join tree involving multiple models, but with a nested
+ * outer join predicate spanning only one model, and see if the case 2589
+ * fix happens. The important thing is the criteria "StringNum = '10'" needs
+ * to be put in the join criteria, not the where clause, of the second atomic
+ * query, because in the user query it is on the inner side of an outer join.
+ */
+ @Test public void testCase2589x() throws Exception {
+
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT2.SmallA INNER JOIN " + //$NON-NLS-1$
+ "(BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
+ "(SELECT IntKey FROM BQT1.SmallA WHERE StringNum = '10') as y " + //$NON-NLS-1$
+ "ON MediumA.IntKey = y.IntKey) " + //$NON-NLS-1$
+ "ON BQT2.SmallA.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
+
+ String expected[] = new String[] {
+ "SELECT BQT2.SmallA.IntKey FROM BQT2.SmallA", //$NON-NLS-1$
+ "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'" //$NON-NLS-1$
+ };
+
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ expected,
+ ComparisonMode.EXACT_COMMAND_STRING );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Test two outer joins, one nested within the other, all pushable to one source,
+ * with inline views having criteria that each need to be migrated to their
+ * respective join predicate join criteria.
+ *
+ * The tree below illustrates the canonical plan (plus access nodes). 'y' and
+ * 'z' are two inline views. Notice each has a SELECT node underneath - the
+ * criteria represented by each of those SELECT nodes is on the inner side of
+ * their respective left outer joins (LOJ). So, each criteria needs to be
+ * migrated to the join criteria.
+ *
+ * <pre>
+ * LOJ
+ * / \
+ * LOJ SRC z
+ * / \ |
+ * SRC SRC y SEL
+ * MedB | |
+ * SEL ACC
+ * | |
+ * ACC SRC SmA
+ * |
+ * SRC MedA
+ * </pre>
+ * Here's a diagram of what the join plan of the resulting atomic query should
+ * look like.
+ * <pre>
+ * ACC
+ * |
+ * LOJ**
+ * / \
+ * LOJ** SRC **criteria migrated to here
+ * / \ SmA
+ * SRC SRC
+ * MedB MedA
+ * </pre>
+ */
+ @Test public void testCase2589y() throws Exception {
+ String sql = "SELECT L.IntKey, y.IntKey, z.IntKey " + //$NON-NLS-1$
+ "FROM (BQT1.MediumB as L LEFT OUTER JOIN " + //$NON-NLS-1$
+ "(SELECT IntKey FROM BQT1.MediumA as M WHERE M.IntNum = 4) as y ON y.IntKey = L.IntKey) " + //$NON-NLS-1$
+ "LEFT OUTER JOIN (SELECT IntKey FROM BQT1.SmallA as S WHERE S.StringNum = '10') as z " + //$NON-NLS-1$
+ "ON z.IntKey = y.IntKey"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumB.IntKey, BQT1.MediumA.IntKey, BQT1.SmallA.IntKey " + //$NON-NLS-1$
+ "FROM (BQT1.MediumB LEFT OUTER JOIN " + //$NON-NLS-1$
+ "BQT1.MediumA ON BQT1.MediumA.IntKey = BQT1.MediumB.IntKey AND BQT1.MediumA.IntNum = 4) " + //$NON-NLS-1$
+ "LEFT OUTER JOIN BQT1.SmallA " + //$NON-NLS-1$
+ "ON BQT1.SmallA.IntKey = BQT1.MediumA.IntKey AND BQT1.SmallA.StringNum = '10'"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ /**
+ * Test a complicated join tree involving multiple models, but with a nested
+ * outer join predicate spanning only one model, and see if the case 2589
+ * fix happens. The important thing is the criteria "StringNum = '10'" needs
+ * to be put in the join criteria, not the where clause, of the second atomic
+ * query, because in the user query it is on the inner side of an outer join.
+ */
+ @Test public void testCase2589z() {
+
+ String sql = "SELECT BQT1.MediumA.IntKey FROM BQT2.SmallA INNER JOIN " + //$NON-NLS-1$
+ "(BQT1.MediumA LEFT OUTER JOIN " + //$NON-NLS-1$
+ "(SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA, BQT1.SmallB " + //$NON-NLS-1$
+ "WHERE BQT1.SmallA.IntKey = BQT1.SmallB.IntKey AND BQT1.SmallA.StringNum = '10') as y " + //$NON-NLS-1$
+ "ON MediumA.IntKey = y.IntKey) " + //$NON-NLS-1$
+ "ON BQT2.SmallA.IntKey = BQT1.MediumA.IntKey"; //$NON-NLS-1$
+
+ String expected[] = new String[] {
+ "SELECT BQT2.SmallA.IntKey FROM BQT2.SmallA", //$NON-NLS-1$
+ "SELECT BQT1.MediumA.IntKey FROM BQT1.MediumA LEFT OUTER JOIN (BQT1.SmallA INNER JOIN BQT1.SmallB ON BQT1.SmallA.IntKey = BQT1.SmallB.IntKey) ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10'" //$NON-NLS-1$
+ };
+
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ expected,
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Union with multiple joins underneath
+ */
+ @Test public void testCase2589aa() throws Exception {
+ String sql = "SELECT * FROM (SELECT z.IntKey FROM (SELECT IntKey FROM BQT1.MediumA WHERE IntNum = 10) as z " + //$NON-NLS-1$
+ "LEFT OUTER JOIN " + //$NON-NLS-1$
+ "(SELECT IntKey FROM BQT1.SmallA WHERE StringNum = '10') as y " + //$NON-NLS-1$
+ "ON z.IntKey = y.IntKey " + //$NON-NLS-1$
+ "UNION ALL SELECT z.IntKey FROM (SELECT IntKey FROM BQT1.MediumA WHERE IntNum = 10) as z " + //$NON-NLS-1$
+ "LEFT OUTER JOIN " + //$NON-NLS-1$
+ "(SELECT IntKey FROM BQT1.SmallA WHERE StringNum = '10') as y " + //$NON-NLS-1$
+ "ON z.IntKey = y.IntKey) as x"; //$NON-NLS-1$
+
+ String expected = "SELECT BQT1.MediumA.IntKey AS c_0 FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' WHERE BQT1.MediumA.IntNum = 10 UNION ALL SELECT BQT1.MediumA.IntKey AS c_0 FROM BQT1.MediumA LEFT OUTER JOIN BQT1.SmallA ON BQT1.MediumA.IntKey = BQT1.SmallA.IntKey AND BQT1.SmallA.StringNum = '10' WHERE BQT1.MediumA.IntNum = 10"; //$NON-NLS-1$
+ helpTestCase2589(sql, expected);
+ }
+
+ /**
+ * A final rewrite will ensure the correct order by
+ */
+ @Test public void testOrderByDuplicates() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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 FROM bqt1.smalla AS g_0 ORDER BY g_0.intkey"}, //$NON-NLS-1$
+ ComparisonMode.EXACT_COMMAND_STRING );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ //Test use of OrderBy with expression
+ @Test public void testCase2507() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport("||", true); //$NON-NLS-1$
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ String sql = "SELECT vqt.smallb.a12345 FROM vqt.smallb ORDER BY vqt.smallb.a12345"; //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT Concat(stringKey, stringNum) AS EXPR FROM BQT1.SmallA ORDER BY EXPR"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testCase2507A() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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$
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {"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$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testCase2507B() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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$
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum), bqt1.smalla.stringKey AS EXPR_1 FROM bqt1.smalla ORDER BY EXPR_1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /**
+ * RulePlanJoins does not initially allow the cross join push.
+ * The subsequent RuleRaiseAccess does since we believe it was the intent of the user
+ */
+ @Test public void testPushCrossJoins() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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$
+
+ ProcessorPlan plan = helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT g_2.intkey FROM ((bqt1.SmallA AS g_0 CROSS JOIN bqt1.smalla AS g_1) CROSS JOIN bqt1.mediuma AS g_2) LEFT OUTER JOIN bqt1.mediumb AS g_3 ON g_2.intkey = g_3.intkey"}, //$NON-NLS-1$
+ ComparisonMode.EXACT_COMMAND_STRING );
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testCase3023() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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$
+
+ helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT bqt1.SmallA.intkey FROM (bqt1.SmallA INNER JOIN (bqt1.SmallB AS BAD LEFT OUTER JOIN bqt1.MediumB ON BAD.intkey = bqt1.MediumB.intkey) ON bqt1.SmallA.intkey = BAD.intkey) INNER JOIN bqt1.MediumA ON BAD.intkey = bqt1.MediumA.intkey"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+ }
+
+ @Test public void testCase3367() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ QueryMetadataInterface metadata = example1();
+
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan("select e1 from pm1.g1 where pm1.g1.e1 IN (SELECT pm1.g2.e1 FROM pm1.g2 WHERE (pm1.g1.e1 = 2))", metadata, //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 IN (SELECT pm1.g2.e1 FROM pm1.g2 WHERE pm1.g1.e1 = '2')" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /*
+ * Set criteria was not getting pushed down correctly when there was a self-join
+ * of a virtual table containing a join in it's transformation. All virtual
+ * models use the same physical model pm1.
+ */
+ @Test public void testCase3778() throws Exception {
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan(
+ "select a.e1, b.e1 from vm2.g1 a, vm2.g1 b where a.e1 = b.e1 and a.e2 in (select e2 from vm1.g1)", //$NON-NLS-1$
+ metadata, null, capFinder, new String[] {"SELECT g_0.e1, g_2.e1 FROM pm1.g1 AS g_0, pm1.g2 AS g_1, pm1.g1 AS g_2, pm1.g2 AS g_3 WHERE (g_2.e2 = g_3.e2) AND (g_0.e2 = g_1.e2) AND (g_0.e1 = g_2.e1) AND (g_0.e2 IN (SELECT g_4.e2 FROM pm1.g1 AS g_4))"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /**
+ * Ensures that order by expressions are not repeated when multiple criteria span a merge join
+ */
+ @Test public void testCase3832() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ 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$
+
+ helpPlan(sql,
+ metadata,
+ null,
+ capFinder,
+ new String[] {
+ "SELECT bqt2.smallb.intkey, bqt2.smalla.intkey FROM bqt2.smalla, bqt2.smallb WHERE bqt2.smalla.stringkey = bqt2.smallb.stringkey ORDER BY bqt2.smallb.intkey, bqt2.smalla.intkey", //$NON-NLS-1$
+ "SELECT bqt1.smalla.intkey FROM bqt1.smalla ORDER BY bqt1.smalla.intkey"}, //$NON-NLS-1$
+ ComparisonMode.EXACT_COMMAND_STRING);
+
+ }
+
+ /*
+ * Functions containing exec statements should not be evaluated
+ */
+ @Test public void testDefect21972() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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,
+ RealMetadataFactory.example1Cached(),
+ null,
+ capFinder,
+ new String[] {
+ "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}, //$NON-NLS-1$
+ SHOULD_SUCCEED);
+
+ }
+
+ @Test public void testExpressionSymbolPreservation() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ 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 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 );
+
+ }
+
+ //since this does not support convert, it should not be collapsed
+ @Test public void testBadCollapseUnion() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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, RealMetadataFactory.example1Cached(),
+ null, capFinder, expectedSql, SHOULD_SUCCEED);
+
+ 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 testCase3966() {
+ 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[] {
+ 0, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 1, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /*
+ * Select literals created by runtime evaluation should not be pushed down.
+ */
+ @Test public void testCase4017() throws Exception {
+
+ String sql = "SELECT env('soap_host') AS HOST, intkey from bqt2.smalla"; //$NON-NLS-1$
+
+ helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, new DefaultCapabilitiesFinder(),
+ new String[] {"SELECT bqt2.smalla.intkey FROM bqt2.smalla"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+ }
+
+ /**
+ * Test of RuleCopyCriteria. Criteria should NOT be copied across a join if the join has any other operator
+ * other than an equality operator, but if the single group criteria is equality, then we can copy into a join criteria
+ */
+ @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, 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$
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ }
+
+ /**
+ * Test of RuleCopyCriteria. Criteria should be copied across a join only for an equality operator in
+ * the join criteria.
+ */
+ @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, 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$
+
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ }
+
+ /**
+ * The bug was in FrameUtil.convertCriteria() method, where ExistsCriteria was not being checked for.
+ */
+ @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, RealMetadataFactory.exampleBQTCached(),
+ new String[] {
+ "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA" }); //$NON-NLS-1$
+
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 1, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ }
+
+ /**
+ * Try substituting "is not null" for "exists" criteria
+ */
+ @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, RealMetadataFactory.exampleBQTCached(),
+ new String[] {
+ "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA" }); //$NON-NLS-1$
+
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 1, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ }
+
+ @Test public void testCase4263() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ QueryMetadataInterface metadata = example1();
+
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan("select vm1.g1.e1 from vm1.g1 left outer join (select * from vm1.g2 as v where v.e1 = (select max(vm1.g2.e1) from vm1.g2 where v.e1 = vm1.g2.e1)) f2 on (f2.e1 = vm1.g1.e1)", metadata, //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT g1__1.e1 FROM pm1.g1 AS g1__1 LEFT OUTER JOIN pm1.g1 AS g1__2 ON g1__2.e1 = g1__1.e1 AND g1__2.e1 = (SELECT MAX(pm1.g1.e1) FROM pm1.g1 WHERE pm1.g1.e1 = g1__2.e1)" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testCase4263b() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ QueryMetadataInterface metadata = example1();
+
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan("select vm1.g1.e1 from vm1.g1 left outer join (select * from vm1.g2 as v where v.e1 = (select max(pm2.g1.e1) from pm2.g1 where v.e1 = pm2.g1.e1)) f2 on (f2.e1 = vm1.g1.e1)", metadata, //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT g1__1.e1 FROM pm1.g1 AS g1__1" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testCase4279() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ QueryMetadataInterface metadata = example1();
+
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_CASE, true);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan("select * from (select v1.e1, v2.e1 as e1_1, v1.e2, v2.e2 as e2_2 from (select * from vm1.g7 where vm1.g7.e2 = 1) v1 left outer join (select * from vm1.g7 where vm1.g7.e2 = 1) v2 on v1.e2 = v2.e2) as v3 where v3.e2 = 1", metadata, //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT CASE WHEN g_0.e1 = 'S' THEN 'Pay' WHEN g_0.e1 = 'P' THEN 'Rec' ELSE g_0.e1 END, CASE WHEN g_1.e1 = 'S' THEN 'Pay' WHEN g_1.e1 = 'P' THEN 'Rec' ELSE g_1.e1 END, g_0.e2, g_1.e2 FROM pm1.g1 AS g_0 LEFT OUTER JOIN pm1.g1 AS g_1 ON g_0.e2 = g_1.e2 AND g_1.e2 = 1 WHERE g_0.e2 = 1" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testCase4312() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setFunctionSupport("+", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpPlan("select ? + 1, pm1.g1.e1 AS EXPR_1 FROM pm1.g1", example1(), null, capFinder, //$NON-NLS-1$
+ new String[] {
+ "SELECT (? + 1) AS expr, pm1.g1.e1 FROM pm1.g1"}, true); //$NON-NLS-1$
+
+ }
+
+ @Test public void testCase2507_2(){
+
+ String sql = "SELECT a FROM (SELECT concat(BQT1.SmallA.StringKey, BQT1.SmallA.StringNum) as a " + //$NON-NLS-1$
+ "FROM BQT1.SmallA, BQT1.SmallB WHERE SmallA.IntKey = SmallB.IntKey) as X ORDER BY X.a"; //$NON-NLS-1$
+
+ String expected = "SELECT concat(BQT1.SmallA.StringKey, BQT1.SmallA.StringNum) AS EXPR " + //$NON-NLS-1$
+ "FROM BQT1.SmallA, BQT1.SmallB WHERE BQT1.SmallA.IntKey = BQT1.SmallB.IntKey ORDER BY EXPR"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {expected},
+ TestOptimizer.SHOULD_SUCCEED );
+
+ TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ private void helpTestCase2430and2507(String sql, String expected) {
+
+ // TEST PLANNING
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+ caps.setFunctionSupport("+", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {expected},
+ TestOptimizer.SHOULD_SUCCEED );
+
+ TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ //Test use of OrderBy with Alias
+ @Test public void testCase2430D() {
+ String sql = "SELECT bqt1.smalla.longnum + bqt1.smalla.longnum as c1234567890123456789012345678901234567890, " + //$NON-NLS-1$
+ "bqt1.smalla.doublenum as EXPR FROM bqt1.smalla ORDER BY c1234567890123456789012345678901234567890, EXPR "; //$NON-NLS-1$
+
+ String expected = "SELECT (bqt1.smalla.longnum + bqt1.smalla.longnum) AS c1234567890123456789012345678901234567890, bqt1.smalla.doublenum AS EXPR " + //$NON-NLS-1$
+ "FROM bqt1.smalla ORDER BY c1234567890123456789012345678901234567890, EXPR"; //$NON-NLS-1$
+ helpTestCase2430and2507(sql, expected);
+ }
+
+ @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 c_0 " + //$NON-NLS-1$
+ "FROM bqt1.smalla ORDER BY c_0"; //$NON-NLS-1$
+ helpTestCase2430and2507(sql, expected);
+ }
+
+ @Test public void testCase2430G() {
+ 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 c_0 " + //$NON-NLS-1$
+ "FROM bqt1.smalla ORDER BY c_0"; //$NON-NLS-1$
+ helpTestCase2430and2507(sql, expected);
+ }
+
+ @Test public void testCase2507_1(){
+
+ String sql = "SELECT a FROM (SELECT concat(BQT1.SmallA.StringKey, BQT1.SmallA.StringNum) as a " + //$NON-NLS-1$
+ "FROM BQT1.SmallA) as X ORDER BY X.a"; //$NON-NLS-1$
+
+ String expected = "SELECT concat(BQT1.SmallA.StringKey, BQT1.SmallA.StringNum) AS EXPR FROM BQT1.SmallA ORDER BY EXPR"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {expected},
+ TestOptimizer.SHOULD_SUCCEED );
+
+ TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /**
+ * This is taken from testPushCorrelatedSubquery1. However this subquery is not expected to be pushed down since the correlated
+ * reference expression cannot be evaluated by the source.
+ */
+ @Test public void testDefect23614() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ 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') )", 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[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Normally the following queries would plan as if they were federated, but setting the connector_id source property
+ * allows them to be planned as if they were the same source.
+ */
+ @Test public void testSameConnector() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setSourceProperty(Capability.CONNECTOR_ID, "1"); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ 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$
+ metadata, null, capFinder,
+ new String[] {
+ "SELECT A.IntKey, B.IntKey FROM BQT1.SmallA AS A LEFT OUTER JOIN BQT2.MediumB AS B ON A.IntKey = B.IntKey"}, //$NON-NLS-1$
+ true);
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+
+ plan = helpPlan(
+ "SELECT A.IntKey FROM BQT1.SmallA A UNION select B.intkey from BQT2.MediumB B", //$NON-NLS-1$
+ metadata, null, capFinder,
+ new String[] {
+ "SELECT A.IntKey FROM BQT1.SmallA AS A UNION SELECT B.intkey FROM BQT2.MediumB AS B"}, //$NON-NLS-1$
+ true);
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /**
+ * Test changes to RuleCollapseSource for removing aliases
+ */
+ @Test public void testCase4898() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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$
+ metadata, null, capFinder,
+ new String[] {
+ "SELECT 'a' AS A FROM BQT1.SmallA AS A UNION SELECT 'b' FROM BQT1.MediumB AS B"}, //$NON-NLS-1$
+ true);
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testDefect13971() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ String sql = "select b from (select distinct booleanvalue b, intkey from bqt1.smalla) as x"; //$NON-NLS-1$
+
+ // Plan query
+ ProcessorPlan plan = helpPlan(sql, metadata, null, capFinder, new String[] {"SELECT DISTINCT booleanvalue, intkey FROM bqt1.smalla"}, SHOULD_SUCCEED); //$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
+ });
+ }
+
+ /**
+ * Ensures that aliases are not stripped from projected symbols if they might conflict with an order by element
+ */
+ @Test public void testCase5067() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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$
+
+ // Plan query
+ ProcessorPlan plan = helpPlan(sql, metadata, null, capFinder, new String[] {"SELECT a.intkey AS stringkey, b.stringkey AS key2 FROM bqt1.smalla AS a, bqt1.smallb AS b WHERE a.intkey = b.intkey ORDER BY stringkey"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testDontPushConvertObject() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT intkey from bqt1.smalla WHERE stringkey = convert(objectvalue, string)", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT stringkey, objectvalue, intkey FROM bqt1.smalla"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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 testDontPushConvertClobToString() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("LOB", caps); //$NON-NLS-1$
+
+ // Add join capability to pm1
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = helpPlan(
+ "SELECT ClobValue from LOB.LobTbl WHERE convert(ClobValue, string) = ?", //$NON-NLS-1$
+ metadata,
+ null, capFinder,
+ new String[] {"SELECT ClobValue FROM LOB.LobTbl"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+
+ 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 testSelectIntoWithDistinct() throws Exception {
+ String sql = "select distinct e1 into #temp from pm1.g1"; //$NON-NLS-1$
+
+ 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
+ assertFalse(plan.requiresTransaction(false));
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+
+ checkNodeTypes(plan, new int[] {1}, new Class[] {ProjectIntoNode.class});
+ }
+
+ @Test public void testInsertQueryExpression() throws Exception {
+ String sql = "insert into pm1.g1 (e1) select e1 from pm1.g2"; //$NON-NLS-1$
+
+ 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
+ assertTrue(plan.requiresTransaction(false));
+
+ checkNodeTypes(plan, new int[] {1}, new Class[] {ProjectIntoNode.class});
+ }
+
+ /**
+ * Ensure that the pushdown check doesn't fail
+ * @throws Exception
+ */
+ @Test public void testInsertQueryExpression1() throws Exception {
+ String sql = "insert into pm1.g1 (e1) select e1 || 1 from pm1.g2"; //$NON-NLS-1$
+
+ 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
+ assertTrue(plan.requiresTransaction(false));
+
+ checkNodeTypes(plan, new int[] {1}, new Class[] {ProjectIntoNode.class});
+ }
+
+ /**
+ * previously the subqueries were being pushed too far and then not having the appropriate correlated references
+ */
+ @Test public void testCorrelatedSubqueryOverJoin() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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$
+
+ ProcessorPlan plan = helpPlan(sql, metadata, null, capFinder,
+ new String[] {"SELECT g_0.e1 FROM pm1.g1 AS g_0, pm1.g2 AS g_1 WHERE (g_0.e1 = g_1.e1) AND (EXISTS (SELECT g_2.e2 FROM pm1.g2 AS g_2 WHERE g_2.e1 = g_1.e1)) AND (EXISTS (SELECT g_3.e3 FROM pm1.g2 AS g_3 WHERE g_3.e1 = g_1.e1))"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /**
+ * see testSimpleCrossJoin3
+ */
+ @Test public void testMaxFromGroups() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setSourceProperty(Capability.MAX_QUERY_FROM_GROUPS, new Integer(1));
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ helpPlan("select pm2.g1.e1 FROM pm2.g1 CROSS JOIN pm2.g2", example1(), null, capFinder, //$NON-NLS-1$
+ new String[] { "SELECT pm2.g1.e1 FROM pm2.g1", "SELECT 1 FROM pm2.g2"}, true ); //$NON-NLS-1$ //$NON-NLS-2$
+
+ }
+
+ @Test public void testCase6249() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FUNCTIONS_IN_GROUP_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
+
+ 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, 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 {
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_FUNCTIONS_IN_GROUP_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_CASE, true);
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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$
+
+ checkNodeTypes(plan, new int[] {
+ 0, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testCase6325() {
+ String sql = "select e1 into #temp from pm4.g1 where e1='1'"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpPlan(sql, metadata, new String[] {"SELECT e1 FROM pm4.g1 WHERE e1 = '1'"}); //$NON-NLS-1$
+
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testCase6364() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_FUNCTIONS_IN_GROUP_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ caps.setFunctionSupport("+", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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, 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);
+ }
+
+ @Test public void testExceptPushdown() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_EXCEPT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "select e1 from pm1.g1 except select e1 from pm1.g2"; //$NON-NLS-1$
+
+ 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);
+ }
+
+ @Test public void testCase6597() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_NOT, false);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ // Create query
+ String sql = "select IntKey from bqt1.smalla where stringkey not like '2%'"; //$NON-NLS-1$
+
+ 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[] {
+ 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 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, RealMetadataFactory.exampleBQTCached(), new String[] {});
+ }
+
+ /**
+ * Test <code>QueryOptimizer</code>'s ability to plan a fully-pushed-down
+ * query containing a <code>BETWEEN</code> comparison in the queries
+ * <code>WHERE</code> statement.
+ * <p>
+ * For example:
+ * <p>
+ * 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", 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$
+ }
+
+ /**
+ * Test <code>QueryOptimizer</code>'s ability to plan a fully-pushed-down
+ * query containing a <code>CASE</code> expression in which a
+ * <code>BETWEEN</code> comparison is used in the queries
+ * <code>SELECT</code> statement.
+ * <p>
+ * For example:
+ * <p>
+ * SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1
+ */
+ @Test public void testBetweenInCase() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ 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$
+ 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);
+ }
+
+ /**
+ * Test <code>QueryOptimizer</code>'s ability to plan a fully-pushed-down
+ * query containing an aggregate SUM with a <code>CASE</code> expression
+ * in which a <code>BETWEEN</code> comparison is used in the queries
+ * <code>SELECT</code> statement.
+ * <p>
+ * For example:
+ * <p>
+ * SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1
+ */
+ @Test public void testBetweenInCaseInSum() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ 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$
+ 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);
+ }
+
+ /**
+ * Test <code>QueryOptimizer</code>'s ability to plan a fully-pushed-down
+ * query containing an aggregate SUM with a <code>CASE</code> expression
+ * in which a <code>BETWEEN</code> comparison is used in the queries
+ * <code>SELECT</code> statement and a GROUP BY is specified.
+ * <p>
+ * For example:
+ * <p>
+ * SELECT e1, SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END)
+ * FROM pm1.g1 GROUP BY e1
+ */
+ @Test public void testBetweenInCaseInSumWithGroupBy() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ 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$
+ 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);
+ }
+
+ /**
+ * Test the query optimizer's ability to properly plan and optimize a query
+ * that uses ambiguous alias names in the top level query and its sub-query.
+ * <p>
+ * No source table is being used. For example, <code>SELECT A.e2 FROM
+ * (SELECT e2 FROM (SELECT 1 AS e2) AS A) AS A</code>
+ * <p>
+ * The test is to ensure that A.e2 from the top level is not confused with
+ * e2 in the second level.
+ * <p>
+ * Related Defects: JBEDSP-1137
+ */
+ @Test public void testAmbiguousAliasInSubQueryNoSource() {
+ // Create query
+ String sql = "SELECT A.e2 AS e2 FROM (" + //$NON-NLS-1$
+ " SELECT e2 AS e2 FROM (" + //$NON-NLS-1$
+ " SELECT 5 AS e2" + //$NON-NLS-1$
+ " ) AS A" + //$NON-NLS-1$
+ ") AS A"; //$NON-NLS-1$
+
+ helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {});
+ }
+
+ /**
+ * Test the query optimizer's ability to properly plan and optimize a query
+ * that uses ambiguous alias names in the top level query and its sub-query
+ * and uses columns belonging to the alias as a parameter to a function.
+ * <p>
+ * No source table is being used. For example, <code>SELECT CONVERT(A.e2,
+ * biginteger) AS e2 FROM (SELECT CONVERT(e2, long) AS e2 FROM (SELECT 1 AS
+ * e2) AS A) AS A</code>
+ * <p>
+ * The test is to ensure that A.e2 from the top level is not confused with
+ * e2 in the second level.
+ * <p>
+ * Related Defects: JBEDSP-1137
+ */
+ @Test public void testAmbiguousAliasFunctionInSubQueryNoSource() {
+ // Create query
+ String sql = "SELECT CONVERT(A.e2, biginteger) AS e2 FROM (" + //$NON-NLS-1$
+ " SELECT CONVERT(e2, long) AS e2 FROM (" + //$NON-NLS-1$
+ " SELECT 5 AS e2" + //$NON-NLS-1$
+ " ) AS A" + //$NON-NLS-1$
+ ") AS A"; //$NON-NLS-1$
+
+ helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {});
+ }
+
+ /**
+ * Test the query optimizer's ability to properly plan and optimize a query
+ * that uses ambiguous alias names in the top level query and its sub-query.
+ * <p>
+ * For example, <code>SELECT A.e2 FROM (SELECT e12FROM pm1.g1 AS A) AS A</code>
+ * <p>
+ * The test is to ensure that A.e2 from the top level is not confused with
+ * e2 in the second level.
+ * <p>
+ * Related Defects: JBEDSP-1137
+ */
+ @Test public void testAmbiguousAliasInSubQuerySource() {
+ // Create query
+ String sql = "SELECT A.e2 AS e2 FROM (" + //$NON-NLS-1$
+ " SELECT e2 AS e2 FROM pm1.g1 AS A" + //$NON-NLS-1$
+ ") AS A"; //$NON-NLS-1$
+
+ helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {"SELECT e2 FROM pm1.g1 AS A"}); //$NON-NLS-1$
+ }
+
+ /**
+ * Test the query optimizer's ability to properly plan and optimize a query
+ * that uses ambiguous alias names in the top level query and its sub-query
+ * and uses columns belonging to the alias as a parameter to a function.
+ * <p>
+ * For example, <code>SELECT CONVERT(A.e2, biginteger) AS e2 FROM (SELECT
+ * CONVERT(e2, long) AS e2 FROM pm1.g1 AS A) AS A</code>
+ * <p>
+ * The test is to ensure that A.e2 from the top level is not confused with
+ * e2 in the second level.
+ * <p>
+ * Related Defects: JBEDSP-1137
+ */
+ @Test public void testAmbiguousAliasFunctionInSubQuerySource() {
+ // Create query
+ String sql = "SELECT CONVERT(A.e2, biginteger) AS e2 FROM (" + //$NON-NLS-1$
+ " SELECT CONVERT(e2, long) AS e2 FROM pm1.g1 AS A" + //$NON-NLS-1$
+ ") AS A"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ helpPlan(sql, metadata, new String[] {"SELECT e2 FROM pm1.g1 AS A"}); //$NON-NLS-1$
+
+ // Add convert capability to pm1 and try it again
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpPlan(sql, metadata, null, capFinder,
+ new String[] {"SELECT CONVERT(CONVERT(e2, long), biginteger) FROM pm1.g1 AS A"}, //$NON-NLS-1$
+ SHOULD_SUCCEED );
+ }
+
+ @Test public void testNestedTable() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+ ProcessorPlan plan = helpPlan("select pm2.g1.e1, x.e1 from pm2.g1, table(select * from pm2.g2 where pm2.g1.e1=pm2.g2.e1) x where pm2.g1.e2 IN (1, 2)", example1(), //$NON-NLS-1$
+ new String[] { "SELECT g_0.e1 FROM pm2.g2 AS g_0 WHERE g_0.e1 = pm2.g1.e1", "SELECT g_0.e1 FROM pm2.g1 AS g_0 WHERE g_0.e2 IN (1, 2)" }, capFinder, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {1}, new Class[] {NestedTableJoinStrategy.class});
+ }
+
+ @Test public void testUpdatePushdownFails() {
+ 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$
+ }
+
+ public static final boolean DEBUG = false;
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,582 +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.optimizer;
-
-import org.junit.Test;
-import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
- at 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$
- 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$
- 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$
- 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$
- new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
-
- TestOptimizer.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
- });
- }
-
- @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$
- 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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @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$
- 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$
- 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$
- 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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
-
- TestOptimizer.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
- });
- }
-
- /**
- * 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$
- 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[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @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$
- 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$
- new String[] {"SELECT e2, e3 FROM pm1.g1"} ); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 0, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @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$
- new String[] {"SELECT e3 FROM pm1.g1"} ); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // 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
- 0 // UnionAll
- });
- }
-
- @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$
- 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$
- 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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * 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$
- 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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 3, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Union should 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$
- 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[] {
- 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$
- new String[] {"SELECT e3 FROM pm1.g1"} ); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // 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
- 0 // UnionAll
- });
- }
-
- @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$
- 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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Cross Joins do not allow for join removal
- * This could be optimized though as an exists predicate
- */
- @Test public void testOptionalJoinWithoutHint_crossJoin() {
- ProcessorPlan plan = TestOptimizer
- .helpPlan(
- "SELECT distinct pm1.g1.e1 from pm1.g1, pm1.g2", FakeMetadataFactory.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);
- }
-
- @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$
- new String[] { "SELECT DISTINCT g_0.e2 FROM pm1.g1 AS g_0" }); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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$
- new String[] { "SELECT g_0.e3, g_0.e2 FROM pm1.g1 AS g_0" }); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * The average agg will prevent the join removal
- */
- @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$
- 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[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @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$
- new String[] { "SELECT g_0.e3 FROM pm1.g1 AS g_0" }); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 0, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- @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$
- 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[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 0, // Join
- 0, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @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$
- 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$
- 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$
- 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$
- 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[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,582 @@
+/*
+ * 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;
+
+import org.junit.Test;
+import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+ at SuppressWarnings("nls")
+public class TestOptionalJoins {
+
+ @Test public void testOptionalJoinNode1() {
+ 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", 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", 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", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
+
+ TestOptimizer.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
+ });
+ }
+
+ @Test public void testOptionalJoinNode1_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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testOptionalJoinNode2() {
+ 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", 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", 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @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", 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", 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", 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", 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", 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", 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", 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", 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", 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", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
+
+ TestOptimizer.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
+ });
+ }
+
+ /**
+ * The distinct prevents the removal of the optional join
+ */
+ @Test public void testOptionalJoinNode14() throws Exception {
+ 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[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @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", 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", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ new String[] {"SELECT e2, e3 FROM pm1.g1"} ); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @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", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ new String[] {"SELECT e3 FROM pm1.g1"} ); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // 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
+ 0 // UnionAll
+ });
+ }
+
+ @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", 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", 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * 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", 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 3, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Union should 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", 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[] {
+ 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'", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ new String[] {"SELECT e3 FROM pm1.g1"} ); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // 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
+ 0 // UnionAll
+ });
+ }
+
+ @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", 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Cross Joins do not allow for join removal
+ * This could be optimized though as an exists predicate
+ */
+ @Test public void testOptionalJoinWithoutHint_crossJoin() {
+ ProcessorPlan plan = TestOptimizer
+ .helpPlan(
+ "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);
+ }
+
+ @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)", 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);
+ }
+
+ @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", 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[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * The average agg will prevent the join removal
+ */
+ @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", 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[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @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", 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[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ @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", 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[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 0, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @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", 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", 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", 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", 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[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,83 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright (C) 2009 Red Hat, Inc.
- * Licensed to Red Hat, Inc. under one or more contributor
- * license agreements. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * 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;
-
-import static org.teiid.query.optimizer.TestOptimizer.*;
-
-import org.junit.Test;
-import org.teiid.common.buffer.BufferManager;
-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;
-
-
-public class TestPartitionedJoinPlanning {
-
- @Test public void testUsePartitionedMergeJoin(){
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- 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);
-
- ProcessorPlan plan = helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY pm1.g1.e1", "SELECT pm1.g2.e1 FROM pm1.g2" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
- checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkNodeTypes(plan, new int[] {1}, new Class[] {EnhancedSortMergeJoinStrategy.class});
- }
-
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,80 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright (C) 2009 Red Hat, Inc.
+ * Licensed to Red Hat, Inc. under one or more contributor
+ * license agreements. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * 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;
+
+import static org.teiid.query.optimizer.TestOptimizer.*;
+
+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.RealMetadataFactory;
+
+ at SuppressWarnings("nls")
+public class TestPartitionedJoinPlanning {
+
+ @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$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, 100);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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,
+ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY pm1.g1.e1", "SELECT pm1.g2.e1 FROM pm1.g2" }, SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
+ checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkNodeTypes(plan, new int[] {1}, new Class[] {EnhancedSortMergeJoinStrategy.class});
+ }
+
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,395 +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.optimizer;
-
-import static junit.framework.Assert.*;
-
-import org.junit.Test;
-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.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;
-
- at 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(),
- new String[] {
- "SELECT MAX(e2) AS x FROM pm1.g1 GROUP BY e1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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(),
- 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$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * Same as above but all required symbols are selected
- */
- @Test public void testSimpleMergeGroupBy2() {
- FakeMetadataFacade metadata = FakeMetadataFactory.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(),
- new String[] {
- "SELECT DISTINCT MAX(e2) AS x, e1 FROM pm1.g1 GROUP BY e1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testSimpleMergeGroupBy3() {
- FakeMetadataFacade metadata = FakeMetadataFactory.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(),
- new String[] {
- "SELECT DISTINCT MAX(e2) AS x, MIN(e1) FROM pm1.g1 GROUP BY e1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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(),
- 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$
-
- 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(),
- new String[] {
- "SELECT MAX(e2) AS x FROM pm1.g1 GROUP BY e1 HAVING MAX(e2) = 1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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(),
- new String[] {
- "SELECT MAX(e2) AS x FROM pm1.g1 GROUP BY e1 HAVING MAX(e2) = 1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testSimpleMergeGroupBy7() {
- FakeMetadataFacade metadata = FakeMetadataFactory.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(),
- new String[] {
- "SELECT DISTINCT MAX(e2) AS x, MIN(e1) FROM pm1.g1 GROUP BY e1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testSimpleMergeUnion() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- 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,
- new String[] {
- "SELECT '1' AS x FROM pm1.g1 UNION ALL SELECT e1 FROM pm1.g2"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testSimpleMergeUnion1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- 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,
- new String[] {
- "SELECT '1' AS x FROM pm1.g1 UNION SELECT e1 FROM pm1.g2"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * Same as above, but the expression will prevent the source removal
- */
- @Test public void testSimpleMergeUnion2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- 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,
- new String[] {
- "SELECT '1' AS x FROM pm1.g1 UNION ALL SELECT e1 FROM pm1.g2"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- //see TEIID-1562
- @Test public void testSimpleMergeUnderUnionWithJoin() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- 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,
- 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);
- }
-
- @Test public void testSimpleMergeUnion3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- 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,
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 1, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testSimpleMergeWithLimit() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- 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,
- new String[] {
- "SELECT e1 FROM pm1.g1 LIMIT 1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testSimpleMergeWithLimit1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- 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,
- new String[] {
- "SELECT e1 FROM pm1.g1 LIMIT 1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Limit
- 0, // NestedLoopJoinStrategy
-
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 1, // Sort
- 0 // UnionAll
- }, TestLimit.NODE_TYPES);
- }
-
- @Test public void testSimpleMergeUnionSecondBranchWithOrderBy() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
- 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,
- 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);
- }
-
- @Test public void testSimpleMergeUnionSecondBranchWithOrderBy1() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, true);
- 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,
- 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);
- }
-
- /**
- * Note that the merge is not performed since it would create an expression in the group by clause
- */
- @Test public void testViewPreservationWithGroupByExpression() throws Exception {
- String sql = "SELECT gbl_date " + //$NON-NLS-1$
- "FROM " + //$NON-NLS-1$
- "(SELECT a.intkey as x, convert(a.TimestampValue, date) AS gbl_date, b.intkey as y " + //$NON-NLS-1$
- "FROM bqt1.smalla a INNER JOIN bqt1.smallb b on a.stringkey=b.stringkey) as z " + //$NON-NLS-1$
- "GROUP BY gbl_date"; //$NON-NLS-1$
-
- // Create capabilities
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT v_0.c_0 FROM (SELECT convert(g_0.TimestampValue, date) AS c_0 FROM bqt1.smalla AS g_0, bqt1.smallb AS g_1 WHERE g_0.stringkey = g_1.stringkey) AS v_0 GROUP BY v_0.c_0" }, //$NON-NLS-1$
- TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testSortAliasWithSameName() throws Exception {
- String sql = "select e1 from (select distinct pm1.g1.e1 as e1 from pm1.g1) x order by e1"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(sql, FakeMetadataFactory.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();
- assertTrue("Alias was not accounted for in sort node", node.getElements().get(0).equals(node.getSortElements().get(0).getSymbol())); //$NON-NLS-1$
- }
-
- @Test public void testSortAliasWithSameNameUnion() throws Exception {
- String sql = "select e1 from (select distinct pm1.g1.e1 as e1 from pm1.g1) x union all select e1 from pm1.g2 order by e1"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(sql, FakeMetadataFactory.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();
- assertTrue("Alias was not accounted for in sort node", node.getElements().get(0).equals(node.getSortElements().get(0).getSymbol())); //$NON-NLS-1$
- }
-
- @Test public void testMergeImplicitGroupBy() throws Exception {
- 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),
- new String[] {
- "SELECT MAX(g_0.e1) FROM pm1.g1 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testMergeGroupBy() throws Exception {
- 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),
- 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$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.query.optimizer;
+
+import static junit.framework.Assert.*;
+
+import org.junit.Test;
+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.processor.ProcessorPlan;
+import org.teiid.query.processor.relational.RelationalPlan;
+import org.teiid.query.processor.relational.SortNode;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+ at 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$
+ RealMetadataFactory.example1Cached(), null, TestAggregatePushdown.getAggregatesFinder(),
+ new String[] {
+ "SELECT MAX(e2) AS x FROM pm1.g1 GROUP BY e1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @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$
+ 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$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ /**
+ * Same as above but all required symbols are selected
+ */
+ @Test public void testSimpleMergeGroupBy2() {
+ 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(),
+ new String[] {
+ "SELECT DISTINCT MAX(e2) AS x, e1 FROM pm1.g1 GROUP BY e1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testSimpleMergeGroupBy3() {
+ 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(),
+ new String[] {
+ "SELECT DISTINCT MAX(e2) AS x, MIN(e1) FROM pm1.g1 GROUP BY e1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @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$
+ RealMetadataFactory.example1Cached(), null, TestAggregatePushdown.getAggregatesFinder(),
+ new String[] {
+ "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$
+ 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$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @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$
+ 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$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testSimpleMergeGroupBy7() {
+ 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(),
+ new String[] {
+ "SELECT DISTINCT MAX(e2) AS x, MIN(e1) FROM pm1.g1 GROUP BY e1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testSimpleMergeUnion() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ 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$
+ 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$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testSimpleMergeUnion1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ 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$
+ 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$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ /**
+ * Same as above, but the expression will prevent the source removal
+ */
+ @Test public void testSimpleMergeUnion2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ 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$
+ 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$
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ //see TEIID-1562
+ @Test public void testSimpleMergeUnderUnionWithJoin() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ 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$
+ 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);
+ }
+
+ @Test public void testSimpleMergeUnion3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ 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$
+ 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$
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 1, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testSimpleMergeWithLimit() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = TestOptimizer.helpPlan("select * from (select e1 from pm1.g1 limit 1) x", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(), null, capFinder,
+ new String[] {
+ "SELECT e1 FROM pm1.g1 LIMIT 1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testSimpleMergeWithLimit1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ 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$
+ RealMetadataFactory.example1Cached(), null, capFinder,
+ new String[] {
+ "SELECT e1 FROM pm1.g1 LIMIT 1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Limit
+ 0, // NestedLoopJoinStrategy
+
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 1, // Sort
+ 0 // UnionAll
+ }, TestLimit.NODE_TYPES);
+ }
+
+ @Test public void testSimpleMergeUnionSecondBranchWithOrderBy() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
+ 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$
+ 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);
+ }
+
+ @Test public void testSimpleMergeUnionSecondBranchWithOrderBy1() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, true);
+ 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$
+ 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);
+ }
+
+ /**
+ * Note that the merge is not performed since it would create an expression in the group by clause
+ */
+ @Test public void testViewPreservationWithGroupByExpression() throws Exception {
+ String sql = "SELECT gbl_date " + //$NON-NLS-1$
+ "FROM " + //$NON-NLS-1$
+ "(SELECT a.intkey as x, convert(a.TimestampValue, date) AS gbl_date, b.intkey as y " + //$NON-NLS-1$
+ "FROM bqt1.smalla a INNER JOIN bqt1.smallb b on a.stringkey=b.stringkey) as z " + //$NON-NLS-1$
+ "GROUP BY gbl_date"; //$NON-NLS-1$
+
+ // Create capabilities
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ // Plan query
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
+ null, capFinder,
+ new String[] { "SELECT v_0.c_0 FROM (SELECT convert(g_0.TimestampValue, date) AS c_0 FROM bqt1.smalla AS g_0, bqt1.smallb AS g_1 WHERE g_0.stringkey = g_1.stringkey) AS v_0 GROUP BY v_0.c_0" }, //$NON-NLS-1$
+ TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testSortAliasWithSameName() throws Exception {
+ String sql = "select e1 from (select distinct pm1.g1.e1 as e1 from pm1.g1) x order by e1"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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();
+ assertTrue("Alias was not accounted for in sort node", node.getElements().get(0).equals(node.getSortElements().get(0).getSymbol())); //$NON-NLS-1$
+ }
+
+ @Test public void testSortAliasWithSameNameUnion() throws Exception {
+ String sql = "select e1 from (select distinct pm1.g1.e1 as e1 from pm1.g1) x union all select e1 from pm1.g2 order by e1"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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();
+ assertTrue("Alias was not accounted for in sort node", node.getElements().get(0).equals(node.getSortElements().get(0).getSymbol())); //$NON-NLS-1$
+ }
+
+ @Test public void testMergeImplicitGroupBy() throws Exception {
+ 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$
+ 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$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testMergeGroupBy() throws Exception {
+ 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$
+ 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$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,358 +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.optimizer;
-
-import static org.junit.Assert.*;
-
-import java.util.Arrays;
-
-import org.junit.Test;
-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.RelationalPlan;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
-public class TestRuleRaiseNull {
-
- public static final int[] FULLY_NULL = new int[] {
- 0, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 1, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- };
-
- /**
- * Test that criteria will cause a branch of a union to be excised if the criteria renders it
- * impossible that the branch of the union would return results. In the following test,
- * each branch of the union projects a "null" in a different column. So, an equality criteria on
- * one of those columns should render one of the branches of the union unnecessary (since null
- * never equals anything). Expected behavior is that a NullNode is inserted in place of the
- * unnecessary access node.
- */
- @Test public void testUnionCriteriaOptimization() {
-
- 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$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
-
- }
-
- @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(),
- new String[]{});
- TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
- }
-
- @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(),
- new String[]{"SELECT null FROM bqt1.smalla"}); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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(),
- new String[]{"SELECT null FROM bqt1.smalla"}); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testRaiseNullWithOuterJoin1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- 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$
- 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(),
- new String[]{"SELECT IntNum FROM bqt1.smalla"}); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
-
- assertEquals(Arrays.asList(new Object[] {new ElementSymbol("b.x")}), plan.getOutputElements()); //$NON-NLS-1$
- }
-
- @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(),
- new String[]{"SELECT intkey FROM bqt1.smalla"}); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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$
- 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
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- @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(),
- new String[]{});
- TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
- }
-
- @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$
- 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(),
- new String[]{"SELECT intkey FROM bqt1.smalla"}); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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(),
- 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
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- @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$
- }
-
- @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$
- }
-
- @Test public void testRaiseNullWithOuterJoinAndHaving() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- 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,
- new String[]{"SELECT bqt1.smalla.intkey FROM bqt1.smalla"}, true); //$NON-NLS-1$
- TestOptimizer.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
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Ensures proper handling of the removal of the first branch and
- * duplicate symbol names in the next branch
- */
- @Test public void testRaiseNullWithUnion7() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
-
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
- 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,
- 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);
- }
-
- @Test public void testRaiseNullWithUnionOrderBy() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- String sql = "select intkey from bqt1.smalla where 1 = 0 union all select intnum from bqt2.smalla order by intkey"; //$NON-NLS-1$
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, null, capFinder,
- new String[]{"SELECT intnum AS intkey FROM bqt2.smalla ORDER BY intkey"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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[]{});
-
- TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
- }
-
- @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[]{});
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 0, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 1, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @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$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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[]{});
-
- TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
- }
-
- /**
- * This tests that a criteria with no elements is not pushed down,
- * but instead is cleaned up properly later
- * See defect 9865
- */
- @Test public void testCrossJoinNoElementCriteriaOptimization() {
- ProcessorPlan plan = TestOptimizer.helpPlan("select Y.e1, Y.e2 FROM vm1.g1 X, vm1.g1 Y where {b'true'} = {b'false'}", TestOptimizer.example1(), //$NON-NLS-1$
- new String[0]);
- TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
- }
-
- @Test public void testSelectLiteralFalseCriteria() {
- ProcessorPlan plan = TestOptimizer.helpPlan("Select 'x' from pm1.g1 where 1=0", TestOptimizer.example1(), //$NON-NLS-1$
- new String[] { });
- TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
- }
-
- @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(),
- new String[]{"SELECT DISTINCT intkey FROM bqt2.smalla"}); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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(),
- 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);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,358 @@
+/*
+ * 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;
+
+import static org.junit.Assert.*;
+
+import java.util.Arrays;
+
+import org.junit.Test;
+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.RelationalPlan;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+public class TestRuleRaiseNull {
+
+ public static final int[] FULLY_NULL = new int[] {
+ 0, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 1, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ };
+
+ /**
+ * Test that criteria will cause a branch of a union to be excised if the criteria renders it
+ * impossible that the branch of the union would return results. In the following test,
+ * each branch of the union projects a "null" in a different column. So, an equality criteria on
+ * one of those columns should render one of the branches of the union unnecessary (since null
+ * never equals anything). Expected behavior is that a NullNode is inserted in place of the
+ * unnecessary access node.
+ */
+ @Test public void testUnionCriteriaOptimization() {
+
+ 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, RealMetadataFactory.exampleBQTCached(),
+ new String[] {"SELECT intkey, intnum FROM bqt1.smalla WHERE intkey = 1"} ); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+
+ }
+
+ @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, RealMetadataFactory.exampleBQTCached(),
+ new String[]{});
+ TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
+ }
+
+ @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, RealMetadataFactory.exampleBQTCached(),
+ new String[]{"SELECT null FROM bqt1.smalla"}); //$NON-NLS-1$
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @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, RealMetadataFactory.exampleBQTCached(),
+ new String[]{"SELECT null FROM bqt1.smalla"}); //$NON-NLS-1$
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testRaiseNullWithOuterJoin1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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, 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, RealMetadataFactory.exampleBQTCached(),
+ new String[]{"SELECT IntNum FROM bqt1.smalla"}); //$NON-NLS-1$
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+
+ assertEquals(Arrays.asList(new Object[] {new ElementSymbol("b.x")}), plan.getOutputElements()); //$NON-NLS-1$
+ }
+
+ @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, RealMetadataFactory.exampleBQTCached(),
+ new String[]{"SELECT intkey FROM bqt1.smalla"}); //$NON-NLS-1$
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @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, 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
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ @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, RealMetadataFactory.exampleBQTCached(),
+ new String[]{});
+ TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
+ }
+
+ @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, 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, RealMetadataFactory.exampleBQTCached(),
+ new String[]{"SELECT intkey FROM bqt1.smalla"}); //$NON-NLS-1$
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ @Test public void testPushCriteriaThroughUnion9() {
+ TestOptimizer.helpPlan("select * from vm1.u8 where const = 's1'", TestOptimizer.example1(), //$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 e1 FROM pm1.g3" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testRaiseNullWithOuterJoinAndHaving() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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, RealMetadataFactory.exampleBQTCached(), null, capFinder,
+ new String[]{"SELECT bqt1.smalla.intkey FROM bqt1.smalla"}, true); //$NON-NLS-1$
+ TestOptimizer.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
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Ensures proper handling of the removal of the first branch and
+ * duplicate symbol names in the next branch
+ */
+ @Test public void testRaiseNullWithUnion7() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ 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, 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);
+ }
+
+ @Test public void testRaiseNullWithUnionOrderBy() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ String sql = "select intkey from bqt1.smalla where 1 = 0 union all select intnum from bqt2.smalla order by intkey"; //$NON-NLS-1$
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, null, capFinder,
+ new String[]{"SELECT intnum AS intkey FROM bqt2.smalla ORDER BY intkey"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @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, RealMetadataFactory.example1Cached(), new String[]{});
+
+ TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
+ }
+
+ @Test public void testRaiseNullWithGroupBy1() {
+ String sql = "select max(e2) from pm1.g1 where 1 = 0"; //$NON-NLS-1$
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), new String[]{});
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 0, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 1, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @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, RealMetadataFactory.example1Cached(), new String[]{"SELECT DISTINCT g_0.e1 FROM pm1.g1 AS g_0"}); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @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, RealMetadataFactory.example1Cached(), new String[]{});
+
+ TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
+ }
+
+ /**
+ * This tests that a criteria with no elements is not pushed down,
+ * but instead is cleaned up properly later
+ * See defect 9865
+ */
+ @Test public void testCrossJoinNoElementCriteriaOptimization() {
+ ProcessorPlan plan = TestOptimizer.helpPlan("select Y.e1, Y.e2 FROM vm1.g1 X, vm1.g1 Y where {b'true'} = {b'false'}", TestOptimizer.example1(), //$NON-NLS-1$
+ new String[0]);
+ TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
+ }
+
+ @Test public void testSelectLiteralFalseCriteria() {
+ ProcessorPlan plan = TestOptimizer.helpPlan("Select 'x' from pm1.g1 where 1=0", TestOptimizer.example1(), //$NON-NLS-1$
+ new String[] { });
+ TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
+ }
+
+ @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, RealMetadataFactory.exampleBQTCached(),
+ new String[]{"SELECT DISTINCT intkey FROM bqt2.smalla"}); //$NON-NLS-1$
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @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, 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);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.query.optimizer;
-
-import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
-import junit.framework.TestCase;
-
-
-public class TestRuleRemoveSorts extends TestCase {
-
- /** 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$
- new String[] { "SELECT pm3.g1.e1, pm3.g1.e2 FROM pm3.g1"}); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * Tests an order by in a query transformation, where the
- * 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$
- new String[] { "SELECT e1, e2 FROM pm1.g1"}); //$NON-NLS-1$
-
- TestOptimizer.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
- });
- }
-
- /**
- * Tests an order by in a query transformation, where the
- * query transformation contains a function
- */
- public void testRemovedOrderByFromQueryTransform3() {
- ProcessorPlan plan = TestOptimizer.helpPlan("SELECT e, e2 FROM vm1.g16", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
- new String[] { "SELECT e1, e2 FROM pm3.g1"}); //$NON-NLS-1$
-
- TestOptimizer.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
- });
- }
-
- /** 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$
- 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[] {
- 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
- });
- }
-
- /** 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$
- 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);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,125 @@
+/*
+ * 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;
+
+import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+import junit.framework.TestCase;
+
+
+public class TestRuleRemoveSorts extends TestCase {
+
+ /** Tests an order by in a query transformation */
+ public void testRemovedOrderByFromQueryTransform() {
+ 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);
+ }
+
+ /**
+ * Tests an order by in a query transformation, where the
+ * physical model does not support pushing order bys
+ */
+ public void testRemovedOrderByFromQueryTransform2() {
+ 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[] {
+ 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
+ });
+ }
+
+ /**
+ * Tests an order by in a query transformation, where the
+ * query transformation contains a function
+ */
+ public void testRemovedOrderByFromQueryTransform3() {
+ 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[] {
+ 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
+ });
+ }
+
+ /** Tests an order by in a query transformation */
+ public void testRemovedOrderByFromQueryTransform4() {
+ 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[] {
+ 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
+ });
+ }
+
+ /** 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", 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);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,258 +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.optimizer;
-
-import static org.junit.Assert.*;
-import static org.teiid.query.optimizer.TestOptimizer.*;
-
-import org.junit.Test;
-import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
-import org.teiid.query.optimizer.TestOptimizer.DupRemoveSortNode;
-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.processor.ProcessorPlan;
-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;
-
-
-public class TestSortOptimization {
-
- @Test public void testSortDupCombination() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // 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,
- new String[] {"SELECT e1, e2 FROM pm1.g1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- checkNodeTypes(plan, FULL_PUSHDOWN);
- checkNodeTypes(plan, new int[] {1}, new Class[] {DupRemoveSortNode.class});
- }
-
- @Test public void testSortDupCombination1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // 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,
- 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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- checkNodeTypes(plan, new int[] {1}, new Class[] {DupRemoveSortNode.class});
- }
-
- @Test public void testSortDupCombination2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // 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,
- 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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkNodeTypes(plan, new int[] {0}, new Class[] {DupRemoveSortNode.class});
- }
-
- @Test public void testGroupDupCombination() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // 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,
- 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[] {0}, new Class[] {DupRemoveSortNode.class});
- }
-
- @Test public void testSortGroupCombination() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // 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,
- new String[] {"SELECT pm1.g1.e2, pm1.g1.e1 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[] {0}, new Class[] {DupRemoveSortNode.class});
- }
-
- @Test public void testProjectionRaisingWithLimit() {
- // 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(),
- new String[] {"SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- assertTrue(plan.getRootNode() instanceof ProjectNode);
- }
-
- @Test public void testProjectionRaisingWithLimit1() {
- // 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(),
- new String[] {"SELECT pm1.g1.e2 FROM pm1.g1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
-
- assertTrue(plan.getRootNode() instanceof LimitNode);
- }
-
- @Test public void testProjectionRaisingWithAccess() throws Exception {
- // 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(),
- 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$
- }
-
- @Test public void testProjectionRaisingWithAccessAndLimit() throws Exception {
- // 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(),
- 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$
- }
-
- @Test public void testProjectionRaisingForUnrelatedWithLimit() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
-
- 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,
- 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$
- }
-
- @Test public void testProjectionRaisingForUnrelated() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
-
- String sql = "select e2 from pm1.g1 as x order by e1"; //$NON-NLS-1$
-
- helpPlan(sql, FakeMetadataFactory.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$
- }
-
- @Test public void testProjectionRaisingWithAlias() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
-
- 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,
- 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$
- }
-
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,258 @@
+/*
+ * 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;
+
+import static org.junit.Assert.*;
+import static org.teiid.query.optimizer.TestOptimizer.*;
+
+import org.junit.Test;
+import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
+import org.teiid.query.optimizer.TestOptimizer.DupRemoveSortNode;
+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.processor.ProcessorPlan;
+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.RealMetadataFactory;
+
+
+public class TestSortOptimization {
+
+ @Test public void testSortDupCombination() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Create query
+ String sql = "select distinct e1, e2 from pm1.g1 order by e2"; //$NON-NLS-1$
+
+ 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);
+ checkNodeTypes(plan, new int[] {1}, new Class[] {DupRemoveSortNode.class});
+ }
+
+ @Test public void testSortDupCombination1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // 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, 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ checkNodeTypes(plan, new int[] {1}, new Class[] {DupRemoveSortNode.class});
+ }
+
+ @Test public void testSortDupCombination2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // 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, 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkNodeTypes(plan, new int[] {0}, new Class[] {DupRemoveSortNode.class});
+ }
+
+ @Test public void testGroupDupCombination() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // 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, 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[] {0}, new Class[] {DupRemoveSortNode.class});
+ }
+
+ @Test public void testSortGroupCombination() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // 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, 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[] {
+ 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[] {0}, new Class[] {DupRemoveSortNode.class});
+ }
+
+ @Test public void testProjectionRaisingWithLimit() {
+ // 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, 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);
+ }
+
+ @Test public void testProjectionRaisingWithLimit1() {
+ // 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, 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);
+ }
+
+ @Test public void testProjectionRaisingWithAccess() throws Exception {
+ // 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, 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$
+ }
+
+ @Test public void testProjectionRaisingWithAccessAndLimit() throws Exception {
+ // 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, 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$
+ }
+
+ @Test public void testProjectionRaisingForUnrelatedWithLimit() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ 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, 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$
+ }
+
+ @Test public void testProjectionRaisingForUnrelated() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ String sql = "select e2 from pm1.g1 as x order by e1"; //$NON-NLS-1$
+
+ 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$
+ }
+
+ @Test public void testProjectionRaisingWithAlias() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ 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, 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$
+ }
+
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,430 +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.optimizer;
-
-import org.junit.Ignore;
-import org.junit.Test;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.metadata.TempMetadataStore;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
-
-public class TestStoredProcedurePlanning {
-
- /**
- * Test planning stored queries. GeminiStoredQueryTestPlan - 1a
- */
- @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$
- new String[] { "SELECT e1, e2 FROM pm1.g1" }); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * Test planning stored queries
- */
- @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$
- new String[] { "SELECT e1, e2 FROM pm1.g1" }); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * Test planning stored queries. GeminiStoredQueryTestPlan - 1b
- */
- @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$
- 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$
- 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$
- new String[] { "EXEC pm1.sp1()" }); //$NON-NLS-1$
- TestOptimizer.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 testStoredQuery6() {
- ProcessorPlan plan = TestOptimizer.helpPlan("select x.e1 from (EXEC pm1.sp1()) as x", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
- new String[] { "EXEC pm1.sp1()" }); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @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$
- new String[] { "EXEC pm1.sp1()" }); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Test planning stored queries. GeminiStoredQueryTestPlan - 1c
- */
- @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$
- 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
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- /**
- * Test planning stored queries. GeminiStoredQueryTestPlan - 5a
- */
- @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$
- new String[] {"SELECT e1, e2 FROM pm1.g1" }); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * Test planning stored queries. GeminiStoredQueryTestPlan - 5b
- */
- @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$
- new String[] { "SELECT e1, e2 FROM pm1.g1 WHERE e1 = '1'"}); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * Test planning stored queries. GeminiStoredQueryTestPlan - 5c
- */
- @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$
- new String[] {"SELECT e1, e2 FROM pm1.g1 WHERE e1 = '1'" }); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * Test planning stored queries. GeminiStoredQueryTestPlan - 6a
- */
- @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$
- new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * Test planning stored queries. GeminiStoredQueryTestPlan - 6c
- */
- @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$
- new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 = '1'" }); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * Test planning stored queries. GeminiStoredQueryTestPlan - 6b
- */
- @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$
- new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 = '1'" }); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * Test planning stored queries. GeminiStoredQueryTestPlan - 6d
- */
- @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$
- new String[] { "SELECT e1 FROM pm1.g1 WHERE (e1 = '1') AND (e2 = 2)" }); //$NON-NLS-1$
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * 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$
- new String[] { "EXEC pm1.sp2(1)" }); //$NON-NLS-1$
- TestOptimizer.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 planning stored queries. GeminiStoredQueryTestPlan - 6d
- */
- @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$
- new String[] { "EXEC pm1.sp2(?)" }); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- //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$
- new String[] { "INSERT INTO pm1.g1 (e1, e2) VALUES ('1', 1)" }); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- //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$
- new String[] { "INSERT INTO pm1.g1 (e1, e2) VALUES ('1', 2)" }); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- //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$
- new String[] { "UPDATE pm1.g1 SET e1 = '1' WHERE e2 = 2" }); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- //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$
- new String[] { "DELETE FROM pm1.g1 WHERE (e1 = '1') AND (e2 = 2)" }); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @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$
- 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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- @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$
- 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$
- new String[] { "EXEC pm1.sp3()" }); //$NON-NLS-1$
-
- TestOptimizer.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 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$
- 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$
- }
-
- /**
- * 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$
- new String[] { "EXEC pm1.sp2(1)", "EXEC pm1.sp2(2)" }); //$NON-NLS-1$ //$NON-NLS-2$
- 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
- 4, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- /**
- * 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$
- 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
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,430 @@
+/*
+ * 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;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+
+public class TestStoredProcedurePlanning {
+
+ /**
+ * Test planning stored queries. GeminiStoredQueryTestPlan - 1a
+ */
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery1() {
+ 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);
+ }
+
+ /**
+ * Test planning stored queries
+ */
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery2() {
+ 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);
+ }
+
+ /**
+ * Test planning stored queries. GeminiStoredQueryTestPlan - 1b
+ */
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery3() {
+ 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(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(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+ new String[] { "EXEC pm1.sp1()" }); //$NON-NLS-1$
+ TestOptimizer.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 testStoredQuery6() {
+ 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery7() {
+ 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Test planning stored queries. GeminiStoredQueryTestPlan - 1c
+ */
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery8() {
+ 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ /**
+ * Test planning stored queries. GeminiStoredQueryTestPlan - 5a
+ */
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery9() {
+ 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);
+ }
+
+ /**
+ * Test planning stored queries. GeminiStoredQueryTestPlan - 5b
+ */
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery10() {
+ 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);
+ }
+
+ /**
+ * Test planning stored queries. GeminiStoredQueryTestPlan - 5c
+ */
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery11() {
+ 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);
+ }
+
+ /**
+ * Test planning stored queries. GeminiStoredQueryTestPlan - 6a
+ */
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery12() {
+ 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);
+ }
+
+ /**
+ * Test planning stored queries. GeminiStoredQueryTestPlan - 6c
+ */
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery13() {
+ 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);
+ }
+
+ /**
+ * Test planning stored queries. GeminiStoredQueryTestPlan - 6b
+ */
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery14() {
+ 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);
+ }
+
+ /**
+ * Test planning stored queries. GeminiStoredQueryTestPlan - 6d
+ */
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery15() {
+ 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);
+ }
+
+ /**
+ * Test planning stored queries.
+ */
+ @Test public void testStoredQuery16() {
+ 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
+ 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 planning stored queries. GeminiStoredQueryTestPlan - 6d
+ */
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery17() {
+ 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[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ //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(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);
+ }
+
+ //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(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);
+ }
+
+ //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(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);
+ }
+
+ //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(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);
+ }
+
+ @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(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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ @Ignore("stored procedure wrapper removal logic has been removed")
+ @Test public void testStoredQuery23() {
+ 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(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+ new String[] { "EXEC pm1.sp3()" }); //$NON-NLS-1$
+
+ TestOptimizer.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 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(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(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(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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 4, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ /**
+ * 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(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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1035 +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.optimizer;
-
-import static org.teiid.query.optimizer.TestOptimizer.*;
-
-import org.junit.After;
-import org.junit.Test;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.query.optimizer.TestOptimizer.AntiSemiJoin;
-import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
-import org.teiid.query.optimizer.TestOptimizer.SemiJoin;
-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.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;
-
- at SuppressWarnings("nls")
-public class TestSubqueryPushdown {
-
- @Test public void testPushSubqueryBelowVirtual() throws Exception {
- String sql = "select g3.e1 from (select e1, max(e2) y from pm1.g1 group by e1) x, pm1.g3 where exists (select e1 from pm1.g2 where x.e1 = e1)"; //$NON-NLS-1$
-
- // Create capabilities
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE EXISTS (SELECT g_1.e1 FROM pm1.g2 AS g_1 WHERE g_1.e1 = g_0.e1)", //$NON-NLS-1$
- "SELECT g_0.e1 FROM pm1.g3 AS g_0" }, //$NON-NLS-1$
- TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 1, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Same as above, but using a correlated variable based on an aggregate
- * @throws Exception
- */
- @Test public void testDontPushSubqueryBelowVirtual() throws Exception {
- String sql = "select g3.e1 from (select e1, max(e2) y from pm1.g1 group by e1) x, pm1.g3 where exists (select e1 from pm1.g2 where x.y = e1)"; //$NON-NLS-1$
-
- // Create capabilities
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
- null, capFinder,
- new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", //$NON-NLS-1$
- "SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0" }, //$NON-NLS-1$
- TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 1, // Grouping
- 1, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testPushCorrelatedSubquery1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- 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$
- 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);
- }
-
- @Test public void testPushCorrelatedSubquery2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setFunctionSupport(SourceSystemFunctions.CONCAT, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- String sqlIn =
- "SELECT c37n.intkey " + //$NON-NLS-1$
- "FROM bqt1.mediuma AS c37n, bqt1.smallb AS m37n " + //$NON-NLS-1$
- "WHERE (m37n.stringkey LIKE '%0') AND " + //$NON-NLS-1$
- "(c37n.stringkey = ('1' || (m37n.intkey || '0'))) AND " + //$NON-NLS-1$
- "(c37n.datevalue = (" + //$NON-NLS-1$
- "SELECT MAX(c37s.datevalue) " + //$NON-NLS-1$
- "FROM bqt1.mediuma AS c37s, bqt1.smallb AS m37s " + //$NON-NLS-1$
- "WHERE (m37s.stringkey LIKE '%0') AND " + //$NON-NLS-1$
- "(c37s.stringkey = ('1' || (m37s.intkey || '0'))) AND " + //$NON-NLS-1$
- "(m37s.stringkey = m37n.stringkey) ))"; //$NON-NLS-1$
-
- 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(),
- null, capFinder,
- new String[] { sqlOut }, SHOULD_SUCCEED);
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @Test public void testPushCorrelatedSubquery3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
- caps.setFunctionSupport("||", true); //$NON-NLS-1$
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- String sqlIn =
- "SELECT intkey " + //$NON-NLS-1$
- "FROM vqt.smalla AS e " + //$NON-NLS-1$
- "WHERE (stringkey = 'VOD.L') AND " + //$NON-NLS-1$
- "(datevalue = (" + //$NON-NLS-1$
- "SELECT MAX(datevalue) " + //$NON-NLS-1$
- "FROM vqt.smalla " + //$NON-NLS-1$
- "WHERE (stringkey = e.stringkey) ))"; //$NON-NLS-1$
-
- 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(),
- null, capFinder,
- new String[] { sqlOut }, SHOULD_SUCCEED);
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- /**
- * Check that scalar subquery in select is pushed
- */
- public void testPushSubqueryInSelectClause1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- 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$
- 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[] {
- 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 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$
- new String[] { "SELECT e1, pm1.g1.e2 FROM pm1.g1" }); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // 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 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$
- new String[] { "SELECT e1, pm1.g1.e2 FROM pm1.g1" }); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 1, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testCorrelatedSubqueryVirtualLayer1() {
- ProcessorPlan plan = helpPlan("Select e1 from vm1.g6 where e1 in (select e1 FROM pm2.g1 WHERE vm1.g6.e3 = pm2.g1.e2)", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // 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 testCorrelatedSubqueryVirtualLayer2() {
- ProcessorPlan plan = helpPlan("Select e1 from vm1.g6 where e1 in (select e1 FROM pm2.g1 WHERE vm1.g6.e4 = pm2.g1.e4)", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1, e2, e4 FROM pm1.g1" }); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // 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 testCorrelatedSubqueryVirtualLayer3() {
- ProcessorPlan plan = helpPlan("Select e1, (select e1 FROM pm2.g1 WHERE vm1.g6.e4 = pm2.g1.e4) from vm1.g6", example1(), //$NON-NLS-1$
- new String[] { "SELECT e1, e2, e4 FROM pm1.g1" }); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 1, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- @Test public void testCorrelatedSubqueryInTransformation2() {
- String sql = "Select * from vm1.g20"; //$NON-NLS-1$
- ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.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
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Check that subquery is not pushed if the subquery cannot all be pushed to the source.
- */
- @Test public void testNoPushSubqueryInWhereClause1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- 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$
- null, capFinder,
- new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Check that subquery is not pushed if the subquery is from a different model
- * than the outer query.
- */
- @Test public void testNoPushSubqueryInWhereClause2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- 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$
- null, capFinder,
- new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Do not support XML query as subquery
- * Check that subquery is not pushed if the subquery is not relational.
- */
- public void defer_testNoPushSubqueryInWhereClause3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- 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$
- null, capFinder,
- new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Check that subquery is not pushed if the subquery has a function that can't be pushed
- * in the SELECT clause
- */
- @Test public void testNoPushSubqueryInWhereClause4() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- 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$
- null, capFinder,
- new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Check that subquery is not pushed if the subquery selects a constant value
- */
- @Test public void testNoPushSubqueryInWhereClause5() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- 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$
- null, capFinder,
- new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Check that subquery is not pushed if the subquery does ORDER BY
- */
- @Test public void testNoPushSubqueryInWhereClause6() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- 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$
- null, capFinder,
- new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Check that subquery is not pushed if the subquery has a function that can't be pushed
- * in the SELECT clause
- */
- @Test public void testNoPushSubqueryInWhereClause7() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setFunctionSupport("ltrim", true); //$NON-NLS-1$
- 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$
- null, capFinder,
- new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Check that subquery is not pushed if the subquery holds non-query access node.
- */
- @Test public void testNoPushSubqueryInWhereClause8() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- 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$
- null, capFinder,
- new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Check that subquery is not pushed if the subquery is correlated and correlated not supported
- */
- @Test public void testNoPushSubqueryInWhereClause9() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- 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$
- null, capFinder,
- new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // 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 testPushMultipleCorrelatedSubquery1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_OR, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MIN, true);
- 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$
- 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);
- }
-
- /*
- * Expressions containing subqueries can be pushed down
- */
- @Test public void testProjectSubqueryPushdown() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setFunctionSupport("+", true); //$NON-NLS-1$
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan("select pm1.g1.e1, convert((select max(vm1.g1.e1) from vm1.g1), integer) + 1 from pm1.g1", metadata, //$NON-NLS-1$
- null, capFinder,
- new String[] { "SELECT g_0.e1, (convert((SELECT MAX(g_1.e1) FROM pm1.g1 AS g_1), integer) + 1) FROM pm1.g1 AS g_0" }, SHOULD_SUCCEED); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @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$
- new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 1, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * 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$
- 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$
- 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());
- }
-
- /**
- * 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());
- }
-
- /**
- * 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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @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());
- }
-
- /**
- * 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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @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());
- }
-
- /**
- * A join will not be used since the predicate cannot be applied after the grouping
- * @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());
- }
-
- @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());
- }
-
- /**
- * 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());
- }
-
- /**
- * A join will not be used here because of the all
- * @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());
- }
-
- @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());
- }
-
- /**
- * 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$
- 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
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 1, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkJoinCounts(plan, 1, 0);
- }
-
- /**
- * 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$
- new String[] { "SELECT g_0.e1, g_0.e2 FROM pm1.g2 AS g_0" }); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * 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$
- 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
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 1, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkJoinCounts(plan, 0, 1);
- }
-
- @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$
- 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
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 1, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkJoinCounts(plan, 0, 1);
- }
-
- @After public void tearDown() {
- System.setProperty(RuleMergeCriteria.UNNEST_DEFAULT, Boolean.FALSE.toString());
- }
-
- @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$
- 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
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 1, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkJoinCounts(plan, 0, 1);
- }
-
- void checkJoinCounts(ProcessorPlan plan, int semi, int antiSemi) {
- checkNodeTypes(plan, new int[] {semi, antiSemi}, new Class[] {SemiJoin.class, AntiSemiJoin.class});
- }
-
- @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$
- new String[] {}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
- checkNodeTypes(plan, new int[] {
- 0, // Access
- 0, // DependentAccess
- 1, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Test to ensure that we don't create an invalid semijoin query when attempting to convert the subquery to a semijoin
- */
- @Test public void testInvalidGeneratedSemijoinQuery() throws Exception {
- String sql = "SELECT intkey FROM BQT1.SmallA AS A WHERE convert(shortvalue, integer) = (SELECT MAX(convert(shortvalue, integer)) FROM (select * from BQT1.SmallA) AS B WHERE b.intnum = a.intnum) ORDER BY intkey";
- BasicSourceCapabilities bsc = getTypicalCapabilities();
- bsc.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- bsc.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
- TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.shortvalue, g_0.intnum, g_0.intkey FROM BQT1.SmallA AS g_0"}, new DefaultCapabilitiesFinder(bsc), ComparisonMode.EXACT_COMMAND_STRING);
- }
-
- @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());
- }
-
- @Test public void testCompareSubquery2() throws Exception {
- ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 <= some (select e1 FROM pm2.g1)", example1(), //$NON-NLS-1$
- new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 <= (SELECT MAX(X.e1) FROM (SELECT e1 FROM pm2.g1) AS X)" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
- }
-
- @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$
- 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
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- checkJoinCounts(plan, 0, 0);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1054 @@
+/*
+ * 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;
+
+import static org.teiid.query.optimizer.TestOptimizer.*;
+
+import org.junit.After;
+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;
+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.optimizer.relational.rules.RuleMergeCriteria;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.rewriter.TestQueryRewriter;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.translator.SourceSystemFunctions;
+
+ at SuppressWarnings("nls")
+public class TestSubqueryPushdown {
+
+ @Test public void testPushSubqueryBelowVirtual() throws Exception {
+ String sql = "select g3.e1 from (select e1, max(e2) y from pm1.g1 group by e1) x, pm1.g3 where exists (select e1 from pm1.g2 where x.e1 = e1)"; //$NON-NLS-1$
+
+ // Create capabilities
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ // Plan query
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
+ null, capFinder,
+ new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE EXISTS (SELECT g_1.e1 FROM pm1.g2 AS g_1 WHERE g_1.e1 = g_0.e1)", //$NON-NLS-1$
+ "SELECT g_0.e1 FROM pm1.g3 AS g_0" }, //$NON-NLS-1$
+ TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 1, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Same as above, but using a correlated variable based on an aggregate
+ * @throws Exception
+ */
+ @Test public void testDontPushSubqueryBelowVirtual() throws Exception {
+ String sql = "select g3.e1 from (select e1, max(e2) y from pm1.g1 group by e1) x, pm1.g3 where exists (select e1 from pm1.g2 where x.y = e1)"; //$NON-NLS-1$
+
+ // Create capabilities
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ // Plan query
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
+ null, capFinder,
+ new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", //$NON-NLS-1$
+ "SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0" }, //$NON-NLS-1$
+ TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 1, // Grouping
+ 1, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testPushCorrelatedSubquery1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ 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 )", 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);
+ }
+
+ @Test public void testPushCorrelatedSubquery2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setFunctionSupport(SourceSystemFunctions.CONCAT, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ String sqlIn =
+ "SELECT c37n.intkey " + //$NON-NLS-1$
+ "FROM bqt1.mediuma AS c37n, bqt1.smallb AS m37n " + //$NON-NLS-1$
+ "WHERE (m37n.stringkey LIKE '%0') AND " + //$NON-NLS-1$
+ "(c37n.stringkey = ('1' || (m37n.intkey || '0'))) AND " + //$NON-NLS-1$
+ "(c37n.datevalue = (" + //$NON-NLS-1$
+ "SELECT MAX(c37s.datevalue) " + //$NON-NLS-1$
+ "FROM bqt1.mediuma AS c37s, bqt1.smallb AS m37s " + //$NON-NLS-1$
+ "WHERE (m37s.stringkey LIKE '%0') AND " + //$NON-NLS-1$
+ "(c37s.stringkey = ('1' || (m37s.intkey || '0'))) AND " + //$NON-NLS-1$
+ "(m37s.stringkey = m37n.stringkey) ))"; //$NON-NLS-1$
+
+ 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, RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] { sqlOut }, SHOULD_SUCCEED);
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testPushCorrelatedSubquery3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+ caps.setFunctionSupport("||", true); //$NON-NLS-1$
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ String sqlIn =
+ "SELECT intkey " + //$NON-NLS-1$
+ "FROM vqt.smalla AS e " + //$NON-NLS-1$
+ "WHERE (stringkey = 'VOD.L') AND " + //$NON-NLS-1$
+ "(datevalue = (" + //$NON-NLS-1$
+ "SELECT MAX(datevalue) " + //$NON-NLS-1$
+ "FROM vqt.smalla " + //$NON-NLS-1$
+ "WHERE (stringkey = e.stringkey) ))"; //$NON-NLS-1$
+
+ 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, RealMetadataFactory.exampleBQTCached(),
+ null, capFinder,
+ new String[] { sqlOut }, SHOULD_SUCCEED);
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ /**
+ * Check that scalar subquery in select is pushed
+ */
+ public void testPushSubqueryInSelectClause1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ 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", 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[] {
+ 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 testCorrelatedSubquery1() {
+ 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
+ 0, // DependentAccess
+ 1, // 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 testCorrelatedSubquery2() {
+ 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 1, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testCorrelatedSubqueryVirtualLayer1() {
+ ProcessorPlan plan = helpPlan("Select e1 from vm1.g6 where e1 in (select e1 FROM pm2.g1 WHERE vm1.g6.e3 = pm2.g1.e2)", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // 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 testCorrelatedSubqueryVirtualLayer2() {
+ ProcessorPlan plan = helpPlan("Select e1 from vm1.g6 where e1 in (select e1 FROM pm2.g1 WHERE vm1.g6.e4 = pm2.g1.e4)", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1, e2, e4 FROM pm1.g1" }); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // 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 testCorrelatedSubqueryVirtualLayer3() {
+ ProcessorPlan plan = helpPlan("Select e1, (select e1 FROM pm2.g1 WHERE vm1.g6.e4 = pm2.g1.e4) from vm1.g6", example1(), //$NON-NLS-1$
+ new String[] { "SELECT e1, e2, e4 FROM pm1.g1" }); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 1, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ @Test public void testCorrelatedSubqueryInTransformation2() {
+ String sql = "Select * from vm1.g20"; //$NON-NLS-1$
+ 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
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Check that subquery is not pushed if the subquery cannot all be pushed to the source.
+ */
+ @Test public void testNoPushSubqueryInWhereClause1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ 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)", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Check that subquery is not pushed if the subquery is from a different model
+ * than the outer query.
+ */
+ @Test public void testNoPushSubqueryInWhereClause2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ 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)", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Do not support XML query as subquery
+ * Check that subquery is not pushed if the subquery is not relational.
+ */
+ public void defer_testNoPushSubqueryInWhereClause3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ 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)", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Check that subquery is not pushed if the subquery has a function that can't be pushed
+ * in the SELECT clause
+ */
+ @Test public void testNoPushSubqueryInWhereClause4() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ 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)", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Check that subquery is not pushed if the subquery selects a constant value
+ */
+ @Test public void testNoPushSubqueryInWhereClause5() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ 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)", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Check that subquery is not pushed if the subquery does ORDER BY
+ */
+ @Test public void testNoPushSubqueryInWhereClause6() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ 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)", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Check that subquery is not pushed if the subquery has a function that can't be pushed
+ * in the SELECT clause
+ */
+ @Test public void testNoPushSubqueryInWhereClause7() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setFunctionSupport("ltrim", true); //$NON-NLS-1$
+ 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)", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Check that subquery is not pushed if the subquery holds non-query access node.
+ */
+ @Test public void testNoPushSubqueryInWhereClause8() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ 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())", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Check that subquery is not pushed if the subquery is correlated and correlated not supported
+ */
+ @Test public void testNoPushSubqueryInWhereClause9() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ 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)", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 1, // 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 testPushMultipleCorrelatedSubquery1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_OR, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MIN, true);
+ 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 )", 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);
+ }
+
+ /*
+ * Expressions containing subqueries can be pushed down
+ */
+ @Test public void testProjectSubqueryPushdown() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setFunctionSupport("+", true); //$NON-NLS-1$
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan("select pm1.g1.e1, convert((select max(vm1.g1.e1) from vm1.g1), integer) + 1 from pm1.g1", metadata, //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT g_0.e1, (convert((SELECT MAX(g_1.e1) FROM pm1.g1 AS g_1), integer) + 1) FROM pm1.g1 AS g_0" }, SHOULD_SUCCEED); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testScalarSubquery2() {
+ 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 1, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * 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)", 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", 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", 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", 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", 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", 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", RealMetadataFactory.example4());
+ }
+
+ @Test public void testSubqueryRewriteToJoin2() throws Exception {
+ 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)", 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)", 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)", 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)", RealMetadataFactory.example4());
+ }
+
+ /**
+ * A join will not be used since the predicate cannot be applied after the grouping
+ * @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))", 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)", 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)", RealMetadataFactory.example4());
+ }
+
+ /**
+ * A join will not be used here because of the all
+ * @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)", 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)", 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)", 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 1, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkJoinCounts(plan, 1, 0);
+ }
+
+ /**
+ * 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))", 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
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * 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))", 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 1, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkJoinCounts(plan, 0, 1);
+ }
+
+ @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))", 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 1, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkJoinCounts(plan, 0, 1);
+ }
+
+ @After public void tearDown() {
+ System.setProperty(RuleMergeCriteria.UNNEST_DEFAULT, Boolean.FALSE.toString());
+ }
+
+ @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)", 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 1, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkJoinCounts(plan, 0, 1);
+ }
+
+ void checkJoinCounts(ProcessorPlan plan, int semi, int antiSemi) {
+ checkNodeTypes(plan, new int[] {semi, antiSemi}, new Class[] {SemiJoin.class, AntiSemiJoin.class});
+ }
+
+ @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)", RealMetadataFactory.example4(), //$NON-NLS-1$
+ new String[] {}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+ checkNodeTypes(plan, new int[] {
+ 0, // Access
+ 0, // DependentAccess
+ 1, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Test to ensure that we don't create an invalid semijoin query when attempting to convert the subquery to a semijoin
+ */
+ @Test public void testInvalidGeneratedSemijoinQuery() throws Exception {
+ String sql = "SELECT intkey FROM BQT1.SmallA AS A WHERE convert(shortvalue, integer) = (SELECT MAX(convert(shortvalue, integer)) FROM (select * from BQT1.SmallA) AS B WHERE b.intnum = a.intnum) ORDER BY intkey";
+ BasicSourceCapabilities bsc = getTypicalCapabilities();
+ bsc.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ bsc.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+ TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.shortvalue, g_0.intnum, g_0.intkey FROM BQT1.SmallA AS g_0"}, new DefaultCapabilitiesFinder(bsc), ComparisonMode.EXACT_COMMAND_STRING);
+ }
+
+ @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)", RealMetadataFactory.example4());
+ }
+
+ @Test public void testCompareSubquery2() throws Exception {
+ ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 <= some (select e1 FROM pm2.g1)", example1(), //$NON-NLS-1$
+ new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 <= (SELECT MAX(X.e1) FROM (SELECT e1 FROM pm2.g1) AS X)" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+ }
+
+ @Test public void testUncorrelatedSet() {
+ 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ checkJoinCounts(plan, 0, 0);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,258 +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.optimizer;
-
-import org.junit.Test;
-import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
-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.unittest.FakeMetadataFactory;
-
- at SuppressWarnings("nls")
-public class TestUnionPlanning {
-
- @Test public void testUnionPushDown() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- 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$
- 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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- /**
- * Here the change in the all causes us not to pushdown
- */
- @Test public void testUnionPushDown1() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- 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$
- 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[] {
- 3, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 2 // UnionAll
- });
- }
-
- @Test public void testUnionPushDown2() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- 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$
- 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[] {
- 3, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- public void testUnionPushDown3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- 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$
- 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[] {
- 3, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 0, // Project
- 0, // Select
- 0, // Sort
- 2 // UnionAll
- });
- }
-
- @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$
- 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);
-
- 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
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- @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$
- 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$
- 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);
-
- 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
- 0, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
- }
-
- @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$
- 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);
-
- 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
- });
- }
-
- @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$
- 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)",
- "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) ORDER BY c_0" }, ComparisonMode.EXACT_COMMAND_STRING);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 4, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 2 // UnionAll
- });
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,258 @@
+/*
+ * 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;
+
+import org.junit.Test;
+import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
+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.unittest.RealMetadataFactory;
+
+ at SuppressWarnings("nls")
+public class TestUnionPlanning {
+
+ @Test public void testUnionPushDown() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ 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", 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ /**
+ * Here the change in the all causes us not to pushdown
+ */
+ @Test public void testUnionPushDown1() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ 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", 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[] {
+ 3, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 2 // UnionAll
+ });
+ }
+
+ @Test public void testUnionPushDown2() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ 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", 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[] {
+ 3, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ public void testUnionPushDown3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ 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)", 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[] {
+ 3, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 2 // UnionAll
+ });
+ }
+
+ @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", 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);
+
+ 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
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ @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", 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)", 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);
+
+ 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
+ 0, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+ }
+
+ @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", 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);
+
+ 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
+ });
+ }
+
+ @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", 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)",
+ "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) ORDER BY c_0" }, ComparisonMode.EXACT_COMMAND_STRING);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 4, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 2 // UnionAll
+ });
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/proc/TestProcedurePlanner.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/proc/TestProcedurePlanner.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/proc/TestProcedurePlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,272 +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.optimizer.proc;
-
-import java.util.Collections;
-
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataID;
-import org.teiid.query.optimizer.QueryOptimizer;
-import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.rewriter.QueryRewriter;
-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.validator.Validator;
-import org.teiid.query.validator.ValidatorFailure;
-import org.teiid.query.validator.ValidatorReport;
-
- at SuppressWarnings("nls")
-public class TestProcedurePlanner {
-
- // ################ getReplacementClause tests ###################
-
- private ProcessorPlan helpPlanProcedure(String userQuery,
- String procedure,
- String procedureType) throws TeiidComponentException,
- QueryMetadataException, TeiidProcessingException {
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
-
- QueryParser parser = QueryParser.getQueryParser();
- Command userCommand = userQuery != null ? parser.parseCommand(userQuery) : parser.parseCommand(procedure);
-
- if (userCommand instanceof CreateUpdateProcedureCommand) {
- GroupSymbol gs = new GroupSymbol("proc");
- gs.setMetadataID(new TempMetadataID("proc", Collections.EMPTY_LIST));
- ((CreateUpdateProcedureCommand)userCommand).setVirtualGroup(gs);
- }
-
- QueryResolver.resolveCommand(userCommand, metadata);
- ValidatorReport report = Validator.validate(userCommand, metadata);
-
- if (report.hasItems()) {
- ValidatorFailure firstFailure = report.getItems().iterator().next();
- throw new QueryValidatorException(firstFailure.getMessage());
- }
- userCommand = QueryRewriter.rewrite(userCommand, metadata, null);
-
- AnalysisRecord analysisRecord = new AnalysisRecord(false, DEBUG);
-
- try {
- return QueryOptimizer.optimizePlan(userCommand, metadata, null, new DefaultCapabilitiesFinder(), analysisRecord, null);
- } finally {
- if(DEBUG) {
- System.out.println(analysisRecord.getDebugLog());
- }
- }
- }
-
- // =============================================================================
- // TESTS
- // =============================================================================
-
- @Test public void testCreateUpdateProcedure1() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Declare String var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 = 'x' or var1 = 'y')\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2, Input.e2, CHANGING.e2, CHANGING.e1 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = 1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "INSERT into vm1.g1 (e1) values('x')"; //$NON-NLS-1$
-
- helpPlanProcedure(userUpdateStr, procedure,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
- }
-
- // special variable CHANGING used with declared variable
- @Test public void testCreateUpdateProcedure2() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2, Input.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e1, pm1.g1.e2 = INPUT.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = 1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpPlanProcedure(userUpdateStr, procedure,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // special variable CHANGING and INPUT used in conpound criteria
- @Test public void testCreateUpdateProcedure3() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(CHANGING.e1='false' and INPUT.e1=1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2, Input.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e1, pm1.g1.e2 = INPUT.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = 1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpPlanProcedure(userUpdateStr, procedure,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // special variable CHANGING and INPUT used in conpound criteria, with declared variables
- @Test public void testCreateUpdateProcedure4() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(CHANGING.e4 ='true' and INPUT.e2=1 or var1 < 30)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2, Input.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e1, pm1.g1.e2 = INPUT.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = 1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpPlanProcedure(userUpdateStr, procedure,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // virtual group elements used in procedure(HAS CRITERIA)
- @Test public void testCreateUpdateProcedure5() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where HAS CRITERIA ON (vm1.g1.e1, vm1.g1.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpPlanProcedure(userUpdateStr, procedure,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // virtual group elements used in procedure in if statement(HAS CRITERIA)
- @Test public void testCreateUpdateProcedure6() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(HAS CRITERIA ON (vm1.g1.e1, vm1.g1.e1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where HAS CRITERIA ON (vm1.g1.e1, vm1.g1.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpPlanProcedure(userUpdateStr, procedure,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // testing rows updated incremented, Input and assignment statements
- @Test public void testCreateUpdateProcedure7() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e1, pm1.g1.e2 = INPUT.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = 1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e2=40"; //$NON-NLS-1$
-
- helpPlanProcedure(userUpdateStr, procedure,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // testing select into with virtual group in from clause
- @Test public void testCreateVirtualProcedure1() throws Exception {
- String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1 INTO #temptable FROM vm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1 FROM #temptable;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- helpPlanProcedure(null, procedure,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // testing select into with function in select clause
- @Test public void testCreateVirtualProcedure2() throws Exception {
- String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1, convert(e2, string) INTO #temptable FROM vm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1 FROM #temptable;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- helpPlanProcedure(null, procedure,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // testing select into with function in select clause
- @Test public void testCreateVirtualProcedure3() throws Exception {
- String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1, convert(e2, string) as a1 INTO #temptable FROM vm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1 FROM #temptable;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- helpPlanProcedure(null, procedure,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testCase4504() throws Exception {
- String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT y INTO #temptable FROM (select x.e1 as y from (select convert(pm1.g1.e1, date) e1 from pm1.g1) x) z;\n"; //$NON-NLS-1$
- procedure = procedure + "loop on (SELECT y FROM #temptable) as mycursor\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "select * from #temptable;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- helpPlanProcedure(null, procedure,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // =============================================================================
- // FRAMEWORK
- // =============================================================================
-
- private static boolean DEBUG = false;
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/proc/TestProcedurePlanner.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/proc/TestProcedurePlanner.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/proc/TestProcedurePlanner.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/proc/TestProcedurePlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,272 @@
+/*
+ * 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.proc;
+
+import java.util.Collections;
+
+import org.junit.Test;
+import org.teiid.api.exception.query.QueryMetadataException;
+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;
+import org.teiid.query.optimizer.QueryOptimizer;
+import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.rewriter.QueryRewriter;
+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.RealMetadataFactory;
+import org.teiid.query.validator.Validator;
+import org.teiid.query.validator.ValidatorFailure;
+import org.teiid.query.validator.ValidatorReport;
+
+ at SuppressWarnings("nls")
+public class TestProcedurePlanner {
+
+ // ################ getReplacementClause tests ###################
+
+ private ProcessorPlan helpPlanProcedure(String userQuery,
+ String procedure,
+ TriggerEvent procedureType) throws TeiidComponentException,
+ QueryMetadataException, TeiidProcessingException {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(procedureType, procedure);
+
+ QueryParser parser = QueryParser.getQueryParser();
+ Command userCommand = userQuery != null ? parser.parseCommand(userQuery) : parser.parseCommand(procedure);
+
+ if (userCommand instanceof CreateUpdateProcedureCommand) {
+ GroupSymbol gs = new GroupSymbol("proc");
+ gs.setMetadataID(new TempMetadataID("proc", Collections.EMPTY_LIST));
+ ((CreateUpdateProcedureCommand)userCommand).setVirtualGroup(gs);
+ }
+
+ QueryResolver.resolveCommand(userCommand, metadata);
+ ValidatorReport report = Validator.validate(userCommand, metadata);
+
+ if (report.hasItems()) {
+ ValidatorFailure firstFailure = report.getItems().iterator().next();
+ throw new QueryValidatorException(firstFailure.getMessage());
+ }
+ userCommand = QueryRewriter.rewrite(userCommand, metadata, null);
+
+ AnalysisRecord analysisRecord = new AnalysisRecord(false, DEBUG);
+
+ try {
+ return QueryOptimizer.optimizePlan(userCommand, metadata, null, new DefaultCapabilitiesFinder(), analysisRecord, null);
+ } finally {
+ if(DEBUG) {
+ System.out.println(analysisRecord.getDebugLog());
+ }
+ }
+ }
+
+ // =============================================================================
+ // TESTS
+ // =============================================================================
+
+ @Test public void testCreateUpdateProcedure1() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Declare String var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 = 'x' or var1 = 'y')\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2, Input.e2, CHANGING.e2, CHANGING.e1 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = 1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "INSERT into vm1.g1 (e1) values('x')"; //$NON-NLS-1$
+
+ helpPlanProcedure(userUpdateStr, procedure,
+ TriggerEvent.INSERT);
+ }
+
+ // special variable CHANGING used with declared variable
+ @Test public void testCreateUpdateProcedure2() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2, Input.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e1, pm1.g1.e2 = INPUT.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = 1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpPlanProcedure(userUpdateStr, procedure,
+ TriggerEvent.UPDATE);
+ }
+
+ // special variable CHANGING and INPUT used in conpound criteria
+ @Test public void testCreateUpdateProcedure3() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(CHANGING.e1='false' and INPUT.e1=1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2, Input.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e1, pm1.g1.e2 = INPUT.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = 1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpPlanProcedure(userUpdateStr, procedure,
+ TriggerEvent.UPDATE);
+ }
+
+ // special variable CHANGING and INPUT used in conpound criteria, with declared variables
+ @Test public void testCreateUpdateProcedure4() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(CHANGING.e4 ='true' and INPUT.e2=1 or var1 < 30)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2, Input.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e1, pm1.g1.e2 = INPUT.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = 1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpPlanProcedure(userUpdateStr, procedure,
+ TriggerEvent.UPDATE);
+ }
+
+ // virtual group elements used in procedure(HAS CRITERIA)
+ @Test public void testCreateUpdateProcedure5() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where HAS CRITERIA ON (vm1.g1.e1, vm1.g1.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpPlanProcedure(userUpdateStr, procedure,
+ TriggerEvent.UPDATE);
+ }
+
+ // virtual group elements used in procedure in if statement(HAS CRITERIA)
+ @Test public void testCreateUpdateProcedure6() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(HAS CRITERIA ON (vm1.g1.e1, vm1.g1.e1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where HAS CRITERIA ON (vm1.g1.e1, vm1.g1.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpPlanProcedure(userUpdateStr, procedure,
+ TriggerEvent.UPDATE);
+ }
+
+ // testing rows updated incremented, Input and assignment statements
+ @Test public void testCreateUpdateProcedure7() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e1, pm1.g1.e2 = INPUT.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = 1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e2=40"; //$NON-NLS-1$
+
+ helpPlanProcedure(userUpdateStr, procedure,
+ TriggerEvent.UPDATE);
+ }
+
+ // testing select into with virtual group in from clause
+ @Test public void testCreateVirtualProcedure1() throws Exception {
+ String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT e1 INTO #temptable FROM vm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT e1 FROM #temptable;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ helpPlanProcedure(null, procedure,
+ TriggerEvent.UPDATE);
+ }
+
+ // testing select into with function in select clause
+ @Test public void testCreateVirtualProcedure2() throws Exception {
+ String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT e1, convert(e2, string) INTO #temptable FROM vm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT e1 FROM #temptable;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ helpPlanProcedure(null, procedure,
+ TriggerEvent.UPDATE);
+ }
+
+ // testing select into with function in select clause
+ @Test public void testCreateVirtualProcedure3() throws Exception {
+ String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT e1, convert(e2, string) as a1 INTO #temptable FROM vm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT e1 FROM #temptable;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ helpPlanProcedure(null, procedure,
+ TriggerEvent.UPDATE);
+ }
+
+ @Test public void testCase4504() throws Exception {
+ String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT y INTO #temptable FROM (select x.e1 as y from (select convert(pm1.g1.e1, date) e1 from pm1.g1) x) z;\n"; //$NON-NLS-1$
+ procedure = procedure + "loop on (SELECT y FROM #temptable) as mycursor\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "select * from #temptable;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ helpPlanProcedure(null, procedure,
+ TriggerEvent.UPDATE);
+ }
+
+ // =============================================================================
+ // FRAMEWORK
+ // =============================================================================
+
+ private static boolean DEBUG = false;
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,170 +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.optimizer.relational;
-
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.dqp.internal.datamgr.LanguageBridgeFactory;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.resolver.TestResolver;
-import org.teiid.query.rewriter.QueryRewriter;
-import org.teiid.query.sql.lang.Command;
-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;
-
- at SuppressWarnings("nls")
-public class TestAliasGenerator {
-
- private Command helpTest(String sql,
- String expected,
- boolean aliasGroups,
- boolean stripColumnAliases, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException {
- Command command = TestResolver.helpResolve(sql, metadata);
- command = QueryRewriter.rewrite(command, metadata, null);
- command.acceptVisitor(new AliasGenerator(aliasGroups, stripColumnAliases));
- assertEquals(expected, command.toString());
- return command;
- }
-
- /**
- * Ensures that views are named with v_ even without metadata
- */
- @Test public void testViewAliasing() throws Exception {
- String sql = "select y.e1 from (select pm1.g1.e1 from pm1.g1) y"; //$NON-NLS-1$
- Query command = (Query)QueryParser.getQueryParser().parseCommand(sql);
- ((ElementSymbol)command.getSelect().getSymbol(0)).setGroupSymbol(new GroupSymbol("y")); //$NON-NLS-1$
- command.acceptVisitor(new AliasGenerator(true));
- assertEquals("SELECT v_0.c_0 FROM (SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0) AS v_0", command.toString()); //$NON-NLS-1$
- }
-
- @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());
- }
-
- @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());
- assertEquals(command.getOrderBy().getSortKeys().get(0).getName(), "e1"); //$NON-NLS-1$
- assertEquals(command.getProjectedSymbols().get(0).getShortName(), "e1"); //$NON-NLS-1$
- }
-
- @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());
- }
-
- @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());
- 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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @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());
- org.teiid.language.Command c = lbf.translate(command);
- assertEquals("SELECT SmallA.IntKey, SmallA.StringKey FROM SmallA ORDER BY SmallA.IntKey, SmallA.StringKey", c.toString());
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,170 @@
+/*
+ * 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.relational;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.dqp.internal.datamgr.LanguageBridgeFactory;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.resolver.TestResolver;
+import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.lang.Command;
+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.RealMetadataFactory;
+
+ at SuppressWarnings("nls")
+public class TestAliasGenerator {
+
+ private Command helpTest(String sql,
+ String expected,
+ boolean aliasGroups,
+ boolean stripColumnAliases, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException {
+ Command command = TestResolver.helpResolve(sql, metadata);
+ command = QueryRewriter.rewrite(command, metadata, null);
+ command.acceptVisitor(new AliasGenerator(aliasGroups, stripColumnAliases));
+ assertEquals(expected, command.toString());
+ return command;
+ }
+
+ /**
+ * Ensures that views are named with v_ even without metadata
+ */
+ @Test public void testViewAliasing() throws Exception {
+ String sql = "select y.e1 from (select pm1.g1.e1 from pm1.g1) y"; //$NON-NLS-1$
+ Query command = (Query)QueryParser.getQueryParser().parseCommand(sql);
+ ((ElementSymbol)command.getSelect().getSymbol(0)).setGroupSymbol(new GroupSymbol("y")); //$NON-NLS-1$
+ command.acceptVisitor(new AliasGenerator(true));
+ assertEquals("SELECT v_0.c_0 FROM (SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0) AS v_0", command.toString()); //$NON-NLS-1$
+ }
+
+ @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, 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, RealMetadataFactory.example1Cached());
+ assertEquals(command.getOrderBy().getSortKeys().get(0).getName(), "e1"); //$NON-NLS-1$
+ assertEquals(command.getProjectedSymbols().get(0).getShortName(), "e1"); //$NON-NLS-1$
+ }
+
+ @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, 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, 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());
+ }
+
+ @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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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());
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,780 +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.optimizer.relational.rules;
-
-import static org.junit.Assert.*;
-
-import java.util.Arrays;
-
-import org.junit.Ignore;
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryMetadataException;
-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.relational.RelationalPlanner;
-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.parser.QueryParser;
-import org.teiid.query.processor.TestVirtualDepJoin;
-import org.teiid.query.processor.relational.RelationalPlan;
-import org.teiid.query.resolver.QueryResolver;
-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.util.CommandContext;
-
- at SuppressWarnings("nls")
-public class TestCalculateCostUtil {
-
- // =====================================================================
- // HELPERS
- // =====================================================================
-
- private static Criteria helpGetCriteria(String critString, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException{
-
- Criteria result = QueryParser.getQueryParser().parseCriteria(critString);
- QueryResolver.resolveCriteria(result, metadata);
- result = QueryRewriter.rewriteCriteria(result, null, new CommandContext(), metadata);
-
- return result;
- }
-
- private static PlanNode helpGetJoinNode(float childCost1, float childCost2, JoinType joinType){
- PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- PlanNode child1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- PlanNode child2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
-
- joinNode.addLastChild(child1);
- joinNode.addLastChild(child2);
-
- child1.setProperty(NodeConstants.Info.EST_CARDINALITY, new Float(childCost1));
- child2.setProperty(NodeConstants.Info.EST_CARDINALITY, new Float(childCost2));
-
- joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, joinType);
-
- return joinNode;
- }
-
- void helpTestEstimateCost(String critString, float childCost, float expectedResult, QueryMetadataInterface metadata) throws Exception {
- Criteria crit = helpGetCriteria(critString, metadata);
- PlanNode select = RelationalPlanner.createSelectNode(crit, false);
-
- float resultCost = NewCalculateCostUtil.recursiveEstimateCostOfCriteria(childCost, select, crit, metadata);
- assertEquals((int)expectedResult, (int)resultCost);
- }
-
- // =====================================================================
- // TESTS
- // =====================================================================
-
- @Test public void testEstimateCostOfCriteria() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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();
- 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();
- String critString = "pm1.g1.e1 < '3'"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
- }
-
- /**
- * usesKey = false
- * NOT = false
- */
- @Test public void testEstimateCostOfMatchCriteria1() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm2.g3.e1 LIKE '#%'"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 300, 100, metadata);
- }
-
- /**
- * usesKey = false
- * NOT = true
- */
- @Test public void testEstimateCostOfMatchCriteria2() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm2.g3.e1 NOT LIKE '#_'"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 300, 233, metadata);
- }
-
- /**
- * usesKey = true
- * NOT = false
- */
- @Test public void testEstimateCostOfMatchCriteria3() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm1.g1.e1 LIKE '#_'"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 300, 50, metadata);
- }
-
- /**
- * usesKey = true
- * NOT = true
- */
- @Test public void testEstimateCostOfMatchCriteria4() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm1.g1.e1 NOT LIKE '#_'"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 300, 249, metadata);
- }
-
- /**
- * usesKey = false
- * NOT = false
- */
- @Test public void testEstimateCostOfIsNullCriteria1() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm2.g3.e1 IS NULL"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 300, 33, metadata);
- }
-
- /**
- * usesKey = false
- * NOT = true
- */
- @Test public void testEstimateCostOfIsNullCriteria2() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm2.g3.e1 IS NOT NULL"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 300, 266, metadata);
- }
-
- /**
- * usesKey = true
- * NOT = false
- */
- @Test public void testEstimateCostOfIsNullCriteria3() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm1.g1.e1 IS NULL"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 300, 1, metadata);
- }
-
- /**
- * usesKey = true
- * NOT = true
- */
- @Test public void testEstimateCostOfIsNullCriteria4() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm1.g1.e1 IS NOT NULL"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 300, 299, metadata);
- }
-
- /**
- * usesKey = false
- * known child cost = false
- * NOT = false
- */
- @Test public void testEstimateCostOfSetCriteria1() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm2.g3.e1 IN ('2', '3')"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
- }
-
- /**
- * usesKey = false
- * known child cost = false
- * NOT = true
- */
- @Test public void testEstimateCostOfSetCriteria2() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm2.g3.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
- }
-
- /**
- * usesKey = false
- * known child cost = true
- * NOT = false
- */
- @Test public void testEstimateCostOfSetCriteria3() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm2.g3.e1 IN ('2', '3')"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 300, 66, metadata);
- }
-
- /**
- * usesKey = false
- * known child cost = true
- * NOT = true
- */
- @Test public void testEstimateCostOfSetCriteria4() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm2.g3.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 300, 233, metadata);
- }
-
- /**
- * usesKey = true
- * known child cost = false
- * NOT = false
- */
- @Test public void testEstimateCostOfSetCriteria5() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm1.g1.e1 IN ('2', '3')"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
- }
-
- /**
- * usesKey = true
- * known child cost = false
- * NOT = true
- */
- @Test public void testEstimateCostOfSetCriteria6() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm1.g1.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
- }
-
- /**
- * usesKey = true
- * known child cost = true
- * NOT = false
- */
- @Test public void testEstimateCostOfSetCriteria7() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm1.g1.e1 IN ('2', '3')"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 200, 2, metadata);
- }
-
- /**
- * usesKey = true
- * known child cost = true
- * NOT = true
- */
- @Test public void testEstimateCostOfSetCriteria8() throws Exception{
- QueryMetadataInterface metadata = FakeMetadataFactory.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();
- PlanNode joinNode = helpGetJoinNode(NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, JoinType.JOIN_CROSS);
-
- float cost = NewCalculateCostUtil.computeCostForTree(joinNode, metadata);
- assertTrue(cost == NewCalculateCostUtil.UNKNOWN_VALUE);
- }
-
- @Ignore("this logic needs to be refined to work better")
- @Test public void testEstimateJoinNodeCostOneUnknown() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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);
- assertEquals(10000, cost, 0);
- }
-
- @Test public void testEstimateNdvPostJoin() throws Exception {
- String query = "SELECT account FROM US.Accounts, Europe.CustAccts, CustomerMaster.Customers where account + accid + CustomerMaster.Customers.id = 1000000"; //$NON-NLS-1$
-
- helpTestQuery(1E9f, query, new String[] {"SELECT g_0.accid FROM Europe.CustAccts AS g_0", "SELECT g_0.id FROM CustomerMaster.Customers AS g_0", "SELECT g_0.account FROM US.Accounts AS g_0"});
- }
-
- /**
- * cases 2159 and 2160, defect 14998
- *
- * e1 and e2 make up a single compound key
- */
- @Test public void testEstimateCostOfCriteriaCompoundKey() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm4.g1.e1 = '3' and pm4.g1.e2 = 2"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
- }
-
- /**
- * cases 2159 and 2160, defect 14998
- *
- * e1 and e2 make up a single compound key, so an OR criteria cannot be
- * predicted to reduce the cost of the join
- */
- @Test public void testEstimateCostOfCriteriaCompoundKey2() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm4.g1.e1 = '3' or pm4.g1.e2 = 2"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
- }
-
- /**
- * cases 2159 and 2160, defect 14998
- *
- * e1 and e2 make up a single compound key - this criteria does not
- * lower the cost due to the NOT
- */
- @Test public void testEstimateCostOfCriteriaCompoundKey3() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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);
- }
-
- /**
- * cases 2159 and 2160, defect 14998
- *
- * e1 and e2 make up a single compound key - this criteria does not
- * lower the cost due to the 0R
- */
- @Test public void testEstimateCostOfCriteriaCompoundKey4() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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);
- }
-
- /**
- * cases 2159 and 2160, defect 14998
- *
- * e1 and e2 make up a single compound key - this criteria does not
- * lower the cost due to the OR
- */
- @Test public void testEstimateCostOfCriteriaCompoundKey5() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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);
- }
-
- /**
- * cases 2159 and 2160, defect 14998
- *
- * e1 and e2 make up a single compound key - this criteria does not
- * lower the cost due to the OR
- */
- @Test public void testEstimateCostOfCriteriaCompoundKey6() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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);
- }
-
- /**
- * cases 2159 and 2160, defect 14998
- *
- * e1 and e2 make up a single compound key - this criteria covers that
- * key so the cost should be low
- */
- @Test public void testEstimateCostOfCriteriaCompoundKey8() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm4.g1.e1 LIKE '3%' and pm4.g1.e2 = 2"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
- }
-
- /**
- * cases 2159 and 2160, defect 14998
- *
- * e1 and e2 make up a single compound key - this criteria does not
- * lower the cost due to the NOT
- */
- @Test public void testEstimateCostOfCriteriaCompoundKey9() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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);
- }
-
- /**
- * cases 2159 and 2160, defect 14998
- *
- * e1 and e2 make up a single compound key - this criteria covers that
- * key so the cost should be low
- */
- @Test public void testEstimateCostOfCriteriaCompoundKey10() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "'3' LIKE pm4.g1.e1 and pm4.g1.e2 = 2"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
- }
-
- /**
- * cases 2159 and 2160, defect 14998
- *
- * e1 and e2 make up a single compound key - this criteria covers that
- * key so the cost should be low
- */
- @Test public void testEstimateCostOfCriteriaCompoundKey11() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm4.g1.e1 IS NULL and pm4.g1.e2 = 2"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
- }
-
- /**
- * cases 2159 and 2160, defect 14998
- *
- * e1 and e2 make up a single compound key - this criteria does not
- * lower the cost due to the NOT
- */
- @Test public void testEstimateCostOfCriteriaCompoundKey12() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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);
- }
-
- /**
- * cases 2159 and 2160, defect 14998
- *
- * e1 and e2 make up a single compound key - this criteria covers that
- * key so the cost should be low
- */
- @Test public void testEstimateCostOfCriteriaCompoundKey13() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm4.g1.e1 IN ('3', '4') and pm4.g1.e2 = 2"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
- }
-
- /**
- * cases 2159 and 2160, defect 14998
- *
- * e1 and e2 make up a single compound key - this criteria does not
- * lower the cost due to the NOT
- */
- @Test public void testEstimateCostOfCriteriaCompoundKey14() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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();
- 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);
- }
-
- /**
- * usesKey true
- */
- @Test public void testEstimateCostOfCriteriaMultiGroup() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm4.g1.e1 = pm1.g1.e1"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
- }
-
- /**
- * usesKey false
- */
- @Test public void testEstimateCostOfCriteriaMultiGroup1() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm2.g3.e1 = pm4.g1.e1"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
- }
-
- /**
- * usesKey true
- */
- @Test public void testEstimateCostOfCriteriaMultiGroup2() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm4.g1.e1 = pm1.g1.e1"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 100, 10, metadata);
- }
-
- /**
- * usesKey false
- */
- @Test public void testEstimateCostOfCriteriaMultiGroup3() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.example4();
- String critString = "pm2.g3.e1 = pm4.g1.e1"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 100, 33, metadata);
- }
-
- /**
- * Date Criteria - Case using valid max and min date strings. In the case of date,
- * 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$
- String critString = "pm3.g1.e2 <= {d'2008-04-03'}"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 100, 100, metadata);
- }
-
- /**
- * Date Criteria - Case using invalid max and min date strings. In the case of date,
- * 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$
- String critString = "pm3.g1.e2 <= {d'2008-04-03'}"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 100, 33, metadata);
- }
-
- /**
- * 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$
- String critString = "pm3.g1.e3 <= {t'11:11:11'}"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 100, 1, metadata);
- }
-
- /**
- * 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$
- String critString = "pm3.g1.e3 <= {t'11:11:11'}"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 100, 33, metadata);
- }
-
- /**
- * 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$
- String critString = "pm3.g1.e4 <= {ts'2007-04-03 12:12:12.10'}"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 100, 1, metadata);
- }
-
- /**
- * 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$
- String critString = "pm3.g1.e4 <= {ts'2007-04-03 12:12:12.10'}"; //$NON-NLS-1$
-
- helpTestEstimateCost(critString, 100, 33, metadata);
- }
-
- @Test public void testNDVEstimate() throws Exception {
- String crit = "US.accounts.account = 10"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 800, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testNDVEstimate1() throws Exception {
- String crit = "US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 800, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testCompoundCriteriaEstimate() throws Exception {
- String crit = "US.accounts.account = 10 and US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 640, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testCompoundCriteriaEstimate1() throws Exception {
- String crit = "US.accounts.account = 10 or US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 1000, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testNNVEstimate() throws Exception {
- String crit = "US.accounts.account is null"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testNNVEstimate1() throws Exception {
- String crit = "US.accounts.account is null"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, NewCalculateCostUtil.UNKNOWN_VALUE, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testCompoundCriteriaEstimate2() throws Exception {
- String crit = "US.accounts.account is null and US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testCompoundCriteriaEstimate3() throws Exception {
- String crit = "US.accounts.account is null or US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 801, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- //ensures that the ordering of criteria does not effect the costing calculation
- @Test public void testCompoundCriteriaEstimate4() throws Exception {
- String crit = "US.accounts.account = 10 and US.accounts.account = US.accounts.customer and US.accounts.customer < 100"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 64, TestVirtualDepJoin.exampleVirtualDepJoin());
-
- String crit1 = "US.accounts.account = US.accounts.customer and US.accounts.customer < 100 and US.accounts.account = 10"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit1, 1000, 64, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testCompoundCriteriaEstimate5() throws Exception {
- String crit = "US.accounts.account is null and US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, NewCalculateCostUtil.UNKNOWN_VALUE, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testCompoundCriteriaEstimate6() throws Exception {
- String crit = "US.accounts.account is null or US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- //min and max are not set, so the default estimate is returned
- @Test public void testRangeEstimate() throws Exception {
- String crit = "US.accounts.account < 100"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 333, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testRangeEstimate1() throws Exception {
- String crit = "US.accounts.customer < 100"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 100, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testRangeEstimate2() throws Exception {
- String crit = "US.accounts.customer > 100"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 900, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testRangeEstimate3() throws Exception {
- String crit = "US.accounts.customer >= 1600"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testRangeEstimate4() throws Exception {
- String crit = "US.accounts.customer < -1"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testRangeEstimate5() throws Exception {
- String crit = "US.accounts.customer >= -1"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 1000, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testRangeEstimate6() throws Exception {
- String crit = "US.accounts.pennies >= -2"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 1000, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @Test public void testRangeEstimate7() throws Exception {
- String crit = "US.accounts.pennies >= -6"; //$NON-NLS-1$
-
- helpTestEstimateCost(crit, 1000, 800, TestVirtualDepJoin.exampleVirtualDepJoin());
- }
-
- @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$
-
- assertEquals(new Float(2), plan.getRootNode().getEstimateNodeCardinality());
- }
-
- public void helpTestSetOp(String op, float cost) throws Exception {
- String query = "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$
- op +
- "SELECT id, convert(accid / 10000, long), mod(accid, 10000), convert(type, integer), amount, 'EU' from Europe.CustAccts"; //$NON-NLS-1$
-
- String[] expected = new String[] {"SELECT g_0.customer, g_0.account, g_0.txnid, g_0.txn, g_0.pennies FROM US.Accounts AS g_0 WHERE g_0.txn <> 'X'", "SELECT g_0.id, g_0.accid, g_0.type, g_0.amount FROM Europe.CustAccts AS g_0"};
-
- helpTestQuery(cost, query, expected);
- }
-
- private void helpTestQuery(float cost, String query, String[] expected)
- throws TeiidComponentException, TeiidProcessingException {
- RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(query, TestVirtualDepJoin.exampleVirtualDepJoin(), expected, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
-
- assertEquals(cost, plan.getRootNode().getEstimateNodeCardinality());
- }
-
- @Test public void testUnion() throws Exception {
- helpTestSetOp("UNION ", 1375000.0f); //$NON-NLS-1$
- }
-
- @Test public void testUnionALL() throws Exception {
- helpTestSetOp("UNION ALL ", 1750000.0f); //$NON-NLS-1$
- }
-
- @Test public void testExcept() throws Exception {
- helpTestSetOp("EXCEPT ", 250000.0f); //$NON-NLS-1$
- }
-
- @Test public void testIntersect() throws Exception {
- helpTestSetOp("INTERSECT ", 375000.0f); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,781 @@
+/*
+ * 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.relational.rules;
+
+import static org.junit.Assert.*;
+
+import java.util.Arrays;
+
+import org.junit.Ignore;
+import org.junit.Test;
+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;
+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.parser.QueryParser;
+import org.teiid.query.processor.TestVirtualDepJoin;
+import org.teiid.query.processor.relational.RelationalPlan;
+import org.teiid.query.resolver.QueryResolver;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+ at SuppressWarnings("nls")
+public class TestCalculateCostUtil {
+
+ // =====================================================================
+ // HELPERS
+ // =====================================================================
+
+ private static Criteria helpGetCriteria(String critString, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException{
+
+ Criteria result = QueryParser.getQueryParser().parseCriteria(critString);
+ QueryResolver.resolveCriteria(result, metadata);
+ result = QueryRewriter.rewriteCriteria(result, null, new CommandContext(), metadata);
+
+ return result;
+ }
+
+ private static PlanNode helpGetJoinNode(float childCost1, float childCost2, JoinType joinType){
+ PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+ PlanNode child1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ PlanNode child2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+
+ joinNode.addLastChild(child1);
+ joinNode.addLastChild(child2);
+
+ child1.setProperty(NodeConstants.Info.EST_CARDINALITY, new Float(childCost1));
+ child2.setProperty(NodeConstants.Info.EST_CARDINALITY, new Float(childCost2));
+
+ joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, joinType);
+
+ return joinNode;
+ }
+
+ void helpTestEstimateCost(String critString, float childCost, float expectedResult, QueryMetadataInterface metadata) throws Exception {
+ Criteria crit = helpGetCriteria(critString, metadata);
+ PlanNode select = RelationalPlanner.createSelectNode(crit, false);
+
+ float resultCost = NewCalculateCostUtil.recursiveEstimateCostOfCriteria(childCost, select, crit, metadata);
+ assertEquals((int)expectedResult, (int)resultCost);
+ }
+
+ // =====================================================================
+ // TESTS
+ // =====================================================================
+
+ @Test public void testEstimateCostOfCriteria() throws Exception {
+ 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 = 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 = RealMetadataFactory.example4();
+ String critString = "pm1.g1.e1 < '3'"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+ }
+
+ /**
+ * usesKey = false
+ * NOT = false
+ */
+ @Test public void testEstimateCostOfMatchCriteria1() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm2.g3.e1 LIKE '#%'"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, 300, 100, metadata);
+ }
+
+ /**
+ * usesKey = false
+ * NOT = true
+ */
+ @Test public void testEstimateCostOfMatchCriteria2() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm2.g3.e1 NOT LIKE '#_'"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, 300, 233, metadata);
+ }
+
+ /**
+ * usesKey = true
+ * NOT = false
+ */
+ @Test public void testEstimateCostOfMatchCriteria3() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm1.g1.e1 LIKE '#_'"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, 300, 50, metadata);
+ }
+
+ /**
+ * usesKey = true
+ * NOT = true
+ */
+ @Test public void testEstimateCostOfMatchCriteria4() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm1.g1.e1 NOT LIKE '#_'"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, 300, 249, metadata);
+ }
+
+ /**
+ * usesKey = false
+ * NOT = false
+ */
+ @Test public void testEstimateCostOfIsNullCriteria1() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm2.g3.e1 IS NULL"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, 300, 33, metadata);
+ }
+
+ /**
+ * usesKey = false
+ * NOT = true
+ */
+ @Test public void testEstimateCostOfIsNullCriteria2() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm2.g3.e1 IS NOT NULL"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, 300, 266, metadata);
+ }
+
+ /**
+ * usesKey = true
+ * NOT = false
+ */
+ @Test public void testEstimateCostOfIsNullCriteria3() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm1.g1.e1 IS NULL"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, 300, 1, metadata);
+ }
+
+ /**
+ * usesKey = true
+ * NOT = true
+ */
+ @Test public void testEstimateCostOfIsNullCriteria4() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm1.g1.e1 IS NOT NULL"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, 300, 299, metadata);
+ }
+
+ /**
+ * usesKey = false
+ * known child cost = false
+ * NOT = false
+ */
+ @Test public void testEstimateCostOfSetCriteria1() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm2.g3.e1 IN ('2', '3')"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+ }
+
+ /**
+ * usesKey = false
+ * known child cost = false
+ * NOT = true
+ */
+ @Test public void testEstimateCostOfSetCriteria2() throws Exception {
+ 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);
+ }
+
+ /**
+ * usesKey = false
+ * known child cost = true
+ * NOT = false
+ */
+ @Test public void testEstimateCostOfSetCriteria3() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm2.g3.e1 IN ('2', '3')"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, 300, 66, metadata);
+ }
+
+ /**
+ * usesKey = false
+ * known child cost = true
+ * NOT = true
+ */
+ @Test public void testEstimateCostOfSetCriteria4() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm2.g3.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, 300, 233, metadata);
+ }
+
+ /**
+ * usesKey = true
+ * known child cost = false
+ * NOT = false
+ */
+ @Test public void testEstimateCostOfSetCriteria5() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm1.g1.e1 IN ('2', '3')"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+ }
+
+ /**
+ * usesKey = true
+ * known child cost = false
+ * NOT = true
+ */
+ @Test public void testEstimateCostOfSetCriteria6() throws Exception {
+ 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);
+ }
+
+ /**
+ * usesKey = true
+ * known child cost = true
+ * NOT = false
+ */
+ @Test public void testEstimateCostOfSetCriteria7() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm1.g1.e1 IN ('2', '3')"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, 200, 2, metadata);
+ }
+
+ /**
+ * usesKey = true
+ * known child cost = true
+ * NOT = true
+ */
+ @Test public void testEstimateCostOfSetCriteria8() throws Exception{
+ 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 = RealMetadataFactory.example4();
+ PlanNode joinNode = helpGetJoinNode(NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, JoinType.JOIN_CROSS);
+
+ float cost = NewCalculateCostUtil.computeCostForTree(joinNode, metadata);
+ assertTrue(cost == NewCalculateCostUtil.UNKNOWN_VALUE);
+ }
+
+ @Ignore("this logic needs to be refined to work better")
+ @Test public void testEstimateJoinNodeCostOneUnknown() throws Exception {
+ 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);
+ assertEquals(10000, cost, 0);
+ }
+
+ @Test public void testEstimateNdvPostJoin() throws Exception {
+ String query = "SELECT account FROM US.Accounts, Europe.CustAccts, CustomerMaster.Customers where account + accid + CustomerMaster.Customers.id = 1000000"; //$NON-NLS-1$
+
+ helpTestQuery(1E9f, query, new String[] {"SELECT g_0.accid FROM Europe.CustAccts AS g_0", "SELECT g_0.id FROM CustomerMaster.Customers AS g_0", "SELECT g_0.account FROM US.Accounts AS g_0"});
+ }
+
+ /**
+ * cases 2159 and 2160, defect 14998
+ *
+ * e1 and e2 make up a single compound key
+ */
+ @Test public void testEstimateCostOfCriteriaCompoundKey() throws Exception {
+ 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);
+ }
+
+ /**
+ * cases 2159 and 2160, defect 14998
+ *
+ * e1 and e2 make up a single compound key, so an OR criteria cannot be
+ * predicted to reduce the cost of the join
+ */
+ @Test public void testEstimateCostOfCriteriaCompoundKey2() throws Exception {
+ 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);
+ }
+
+ /**
+ * cases 2159 and 2160, defect 14998
+ *
+ * e1 and e2 make up a single compound key - this criteria does not
+ * lower the cost due to the NOT
+ */
+ @Test public void testEstimateCostOfCriteriaCompoundKey3() throws Exception {
+ 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);
+ }
+
+ /**
+ * cases 2159 and 2160, defect 14998
+ *
+ * e1 and e2 make up a single compound key - this criteria does not
+ * lower the cost due to the 0R
+ */
+ @Test public void testEstimateCostOfCriteriaCompoundKey4() throws Exception {
+ 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);
+ }
+
+ /**
+ * cases 2159 and 2160, defect 14998
+ *
+ * e1 and e2 make up a single compound key - this criteria does not
+ * lower the cost due to the OR
+ */
+ @Test public void testEstimateCostOfCriteriaCompoundKey5() throws Exception {
+ 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);
+ }
+
+ /**
+ * cases 2159 and 2160, defect 14998
+ *
+ * e1 and e2 make up a single compound key - this criteria does not
+ * lower the cost due to the OR
+ */
+ @Test public void testEstimateCostOfCriteriaCompoundKey6() throws Exception {
+ 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);
+ }
+
+ /**
+ * cases 2159 and 2160, defect 14998
+ *
+ * e1 and e2 make up a single compound key - this criteria covers that
+ * key so the cost should be low
+ */
+ @Test public void testEstimateCostOfCriteriaCompoundKey8() throws Exception {
+ 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);
+ }
+
+ /**
+ * cases 2159 and 2160, defect 14998
+ *
+ * e1 and e2 make up a single compound key - this criteria does not
+ * lower the cost due to the NOT
+ */
+ @Test public void testEstimateCostOfCriteriaCompoundKey9() throws Exception {
+ 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);
+ }
+
+ /**
+ * cases 2159 and 2160, defect 14998
+ *
+ * e1 and e2 make up a single compound key - this criteria covers that
+ * key so the cost should be low
+ */
+ @Test public void testEstimateCostOfCriteriaCompoundKey10() throws Exception {
+ 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);
+ }
+
+ /**
+ * cases 2159 and 2160, defect 14998
+ *
+ * e1 and e2 make up a single compound key - this criteria covers that
+ * key so the cost should be low
+ */
+ @Test public void testEstimateCostOfCriteriaCompoundKey11() throws Exception {
+ 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);
+ }
+
+ /**
+ * cases 2159 and 2160, defect 14998
+ *
+ * e1 and e2 make up a single compound key - this criteria does not
+ * lower the cost due to the NOT
+ */
+ @Test public void testEstimateCostOfCriteriaCompoundKey12() throws Exception {
+ 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);
+ }
+
+ /**
+ * cases 2159 and 2160, defect 14998
+ *
+ * e1 and e2 make up a single compound key - this criteria covers that
+ * key so the cost should be low
+ */
+ @Test public void testEstimateCostOfCriteriaCompoundKey13() throws Exception {
+ 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);
+ }
+
+ /**
+ * cases 2159 and 2160, defect 14998
+ *
+ * e1 and e2 make up a single compound key - this criteria does not
+ * lower the cost due to the NOT
+ */
+ @Test public void testEstimateCostOfCriteriaCompoundKey14() throws Exception {
+ 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 = 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);
+ }
+
+ /**
+ * usesKey true
+ */
+ @Test public void testEstimateCostOfCriteriaMultiGroup() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm4.g1.e1 = pm1.g1.e1"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+ }
+
+ /**
+ * usesKey false
+ */
+ @Test public void testEstimateCostOfCriteriaMultiGroup1() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm2.g3.e1 = pm4.g1.e1"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+ }
+
+ /**
+ * usesKey true
+ */
+ @Test public void testEstimateCostOfCriteriaMultiGroup2() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm4.g1.e1 = pm1.g1.e1"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, 100, 10, metadata);
+ }
+
+ /**
+ * usesKey false
+ */
+ @Test public void testEstimateCostOfCriteriaMultiGroup3() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example4();
+ String critString = "pm2.g3.e1 = pm4.g1.e1"; //$NON-NLS-1$
+
+ helpTestEstimateCost(critString, 100, 33, metadata);
+ }
+
+ /**
+ * Date Criteria - Case using valid max and min date strings. In the case of date,
+ * the valid strings are timestamp format - since that is what our costing sets them as.
+ */
+ @Test public void testEstimateCostOfCriteriaDate1() throws Exception {
+ 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);
+ }
+
+ /**
+ * Date Criteria - Case using invalid max and min date strings. In the case of date,
+ * one example of invalid strings is date format - since our costing sets them to timestamp.
+ */
+ @Test public void testEstimateCostOfCriteriaDate2() throws Exception {
+ 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);
+ }
+
+ /**
+ * Time Criteria - case using valid max and min time strings.
+ */
+ @Test public void testEstimateCostOfCriteriaTime1() throws Exception {
+ 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);
+ }
+
+ /**
+ * Time Criteria - case using invalid max and min time strings
+ */
+ @Test public void testEstimateCostOfCriteriaTime2() throws Exception {
+ 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);
+ }
+
+ /**
+ * Timestamp Criteria - case using valid max and min timestamp strings
+ */
+ @Test public void testEstimateCostOfCriteriaTimestamp1() throws Exception {
+ 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);
+ }
+
+ /**
+ * Timestamp Criteria - case using invalid max and min timestamp strings
+ */
+ @Test public void testEstimateCostOfCriteriaTimestamp2() throws Exception {
+ 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);
+ }
+
+ @Test public void testNDVEstimate() throws Exception {
+ String crit = "US.accounts.account = 10"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 800, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testNDVEstimate1() throws Exception {
+ String crit = "US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 800, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testCompoundCriteriaEstimate() throws Exception {
+ String crit = "US.accounts.account = 10 and US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 640, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testCompoundCriteriaEstimate1() throws Exception {
+ String crit = "US.accounts.account = 10 or US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 1000, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testNNVEstimate() throws Exception {
+ String crit = "US.accounts.account is null"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testNNVEstimate1() throws Exception {
+ String crit = "US.accounts.account is null"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, NewCalculateCostUtil.UNKNOWN_VALUE, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testCompoundCriteriaEstimate2() throws Exception {
+ String crit = "US.accounts.account is null and US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testCompoundCriteriaEstimate3() throws Exception {
+ String crit = "US.accounts.account is null or US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 801, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ //ensures that the ordering of criteria does not effect the costing calculation
+ @Test public void testCompoundCriteriaEstimate4() throws Exception {
+ String crit = "US.accounts.account = 10 and US.accounts.account = US.accounts.customer and US.accounts.customer < 100"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 64, TestVirtualDepJoin.exampleVirtualDepJoin());
+
+ String crit1 = "US.accounts.account = US.accounts.customer and US.accounts.customer < 100 and US.accounts.account = 10"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit1, 1000, 64, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testCompoundCriteriaEstimate5() throws Exception {
+ String crit = "US.accounts.account is null and US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, NewCalculateCostUtil.UNKNOWN_VALUE, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testCompoundCriteriaEstimate6() throws Exception {
+ String crit = "US.accounts.account is null or US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ //min and max are not set, so the default estimate is returned
+ @Test public void testRangeEstimate() throws Exception {
+ String crit = "US.accounts.account < 100"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 333, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testRangeEstimate1() throws Exception {
+ String crit = "US.accounts.customer < 100"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 100, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testRangeEstimate2() throws Exception {
+ String crit = "US.accounts.customer > 100"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 900, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testRangeEstimate3() throws Exception {
+ String crit = "US.accounts.customer >= 1600"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testRangeEstimate4() throws Exception {
+ String crit = "US.accounts.customer < -1"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testRangeEstimate5() throws Exception {
+ String crit = "US.accounts.customer >= -1"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 1000, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testRangeEstimate6() throws Exception {
+ String crit = "US.accounts.pennies >= -2"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 1000, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testRangeEstimate7() throws Exception {
+ String crit = "US.accounts.pennies >= -6"; //$NON-NLS-1$
+
+ helpTestEstimateCost(crit, 1000, 800, TestVirtualDepJoin.exampleVirtualDepJoin());
+ }
+
+ @Test public void testLimitWithUnknownChildCardinality() throws Exception {
+ String query = "select e1 from pm1.g1 limit 2"; //$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());
+ }
+
+ public void helpTestSetOp(String op, float cost) throws Exception {
+ String query = "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$
+ op +
+ "SELECT id, convert(accid / 10000, long), mod(accid, 10000), convert(type, integer), amount, 'EU' from Europe.CustAccts"; //$NON-NLS-1$
+
+ String[] expected = new String[] {"SELECT g_0.customer, g_0.account, g_0.txnid, g_0.txn, g_0.pennies FROM US.Accounts AS g_0 WHERE g_0.txn <> 'X'", "SELECT g_0.id, g_0.accid, g_0.type, g_0.amount FROM Europe.CustAccts AS g_0"};
+
+ helpTestQuery(cost, query, expected);
+ }
+
+ private void helpTestQuery(float cost, String query, String[] expected)
+ throws TeiidComponentException, TeiidProcessingException {
+ RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(query, TestVirtualDepJoin.exampleVirtualDepJoin(), expected, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+
+ assertEquals(cost, plan.getRootNode().getEstimateNodeCardinality());
+ }
+
+ @Test public void testUnion() throws Exception {
+ helpTestSetOp("UNION ", 1375000.0f); //$NON-NLS-1$
+ }
+
+ @Test public void testUnionALL() throws Exception {
+ helpTestSetOp("UNION ALL ", 1750000.0f); //$NON-NLS-1$
+ }
+
+ @Test public void testExcept() throws Exception {
+ helpTestSetOp("EXCEPT ", 250000.0f); //$NON-NLS-1$
+ }
+
+ @Test public void testIntersect() throws Exception {
+ helpTestSetOp("INTERSECT ", 375000.0f); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCapabilitiesUtil.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCapabilitiesUtil.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCapabilitiesUtil.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,600 +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.optimizer.relational.rules;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-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.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;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.resolver.util.ResolverVisitor;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.SetQuery.Operation;
-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.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;
-
-
-/**
- */
-public class TestCapabilitiesUtil extends TestCase {
-
- /**
- * 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$
-
- // Set up capabilities
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
- sourceCaps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, supportsSelfJoin);
- sourceCaps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, supportsGroupAlias);
- finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
-
- // Test capabilities util
- boolean actual = CapabilitiesUtil.supportsSelfJoins(modelID, metadata, finder);
- assertEquals("Got wrong answer for supports", expectedValue, actual); //$NON-NLS-1$
- }
-
- public void testSupportsSelfJoin1() throws Exception {
- helpTestSupportsSelfJoin(false, true, false);
- }
-
- public void testSupportsSelfJoin2() throws Exception {
- helpTestSupportsSelfJoin(true, false, false);
- }
-
- public void testSupportsSelfJoin3() throws Exception {
- helpTestSupportsSelfJoin(true, true, true);
- }
-
- public void testSupportsSelfJoin4() throws Exception {
- // Set up metadata
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- // Test capabilities util
- boolean actual = CapabilitiesUtil.supportsSelfJoins(modelID, metadata, new DefaultCapabilitiesFinder());
- assertEquals("Got wrong answer for supports", false, actual); //$NON-NLS-1$
- }
-
-
- 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$
-
- // Set up capabilities
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
- sourceCaps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, capsSupportsOuterJoin);
- sourceCaps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, capsSupportsFullOuterJoin);
- finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
-
- // Test capabilities util
- boolean actual = CapabilitiesUtil.supportsJoin(modelID, joinType, metadata, finder);
- assertEquals("Got wrong answer for supports", expectedValue, actual); //$NON-NLS-1$
- }
-
- // Test where capabilities don't support outer joins
- 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 {
- helpTestSupportsOuterJoin(true, false, JoinType.JOIN_FULL_OUTER, false);
- }
-
- // Test where capabilities support outer joins
- 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 {
- 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$
-
- // Set up capabilities
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
- sourceCaps.setCapabilitySupport(Capability.QUERY_AGGREGATES, capsSupportsAggregates);
- sourceCaps.setCapabilitySupport(Capability.QUERY_FUNCTIONS_IN_GROUP_BY, supportsFunctionInGroupBy);
- finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
-
- // Test capabilities util
- boolean actual = CapabilitiesUtil.supportsAggregates(groupCols, modelID, metadata, finder);
- assertEquals("Got wrong answer for supports", capsSupportsAggregates, actual); //$NON-NLS-1$
- }
-
- // Test where capabilities supports aggregates
- public void testSupportsAggregates1() throws Exception {
- helpTestSupportsAggregates(true, true, null);
- }
-
- /**
- * Supports functions in group by is misleading. It should actually
- * be called supports expression in group by. Thus the example below
- * is not supported.
- */
- 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();
- cols.add(expr);
- helpTestSupportsAggregates(false, false, cols);
- }
-
- 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$
-
- // Set up capabilities
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- finder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Test capabilities util
- boolean actual = CapabilitiesUtil.supportsAggregateFunction(modelID, aggregate, metadata, finder);
- assertEquals("Got wrong answer for supports", expectedValue, actual); //$NON-NLS-1$
- }
-
- // Test where capabilities don't support aggregate functions
- public void testSupportsAggregate1() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, false);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.COUNT, false, null); //$NON-NLS-1$
-
- helpTestSupportsAggregateFunction(caps, aggregate, false);
- }
-
- // Test where capabilities don't support COUNT
- public void testSupportsAggregate2() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, false);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, false);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.COUNT, false, null); //$NON-NLS-1$
-
- helpTestSupportsAggregateFunction(caps, aggregate, false);
- }
-
- // Test where capabilities support only COUNT(*)
- public void testSupportsAggregate3() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, false);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.COUNT, false, null); //$NON-NLS-1$
-
- helpTestSupportsAggregateFunction(caps, aggregate, true);
- }
-
- // Test where capabilities support only COUNT(*)
- public void testSupportsAggregate4() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, false);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.COUNT, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
-
- helpTestSupportsAggregateFunction(caps, aggregate, false);
- }
-
- // Test where capabilities support only COUNT
- public void testSupportsAggregate5() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, false);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.COUNT, false, null); //$NON-NLS-1$
-
- helpTestSupportsAggregateFunction(caps, aggregate, false);
- }
-
- // Test where capabilities support only COUNT
- public void testSupportsAggregate6() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, false);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.COUNT, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
-
- helpTestSupportsAggregateFunction(caps, aggregate, true);
- }
-
- // Test where capabilities don't support SUM
- public void testSupportsAggregate7() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, false);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.SUM, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
-
- helpTestSupportsAggregateFunction(caps, aggregate, false);
- }
-
- // Test where capabilities support SUM
- public void testSupportsAggregate8() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.SUM, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
-
- helpTestSupportsAggregateFunction(caps, aggregate, true);
- }
-
- // Test where capabilities don't support AVG
- public void testSupportsAggregate9() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, false);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.AVG, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
-
- helpTestSupportsAggregateFunction(caps, aggregate, false);
- }
-
- // Test where capabilities support AVG
- public void testSupportsAggregate10() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.AVG, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
-
- helpTestSupportsAggregateFunction(caps, aggregate, true);
- }
-
- // Test where capabilities don't support MIN
- public void testSupportsAggregate11() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MIN, false);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.MIN, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
-
- helpTestSupportsAggregateFunction(caps, aggregate, false);
- }
-
- // Test where capabilities support MIN
- public void testSupportsAggregate12() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MIN, true);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.MIN, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
-
- helpTestSupportsAggregateFunction(caps, aggregate, true);
- }
-
- // Test where capabilities don't support MAX
- public void testSupportsAggregate13() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, false);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.MAX, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
-
- helpTestSupportsAggregateFunction(caps, aggregate, false);
- }
-
- // Test where capabilities support MAX
- public void testSupportsAggregate14() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.MAX, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
-
- helpTestSupportsAggregateFunction(caps, aggregate, true);
- }
-
- // Test where capabilities don't support DISTINCT
- public void testSupportsAggregate15() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_DISTINCT, false);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.MAX, true, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
-
- helpTestSupportsAggregateFunction(caps, aggregate, false);
- }
-
- // Test where capabilities support DISTINCT
- public void testSupportsAggregate16() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_DISTINCT, true);
-
- AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.MAX, true, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
-
- helpTestSupportsAggregateFunction(caps, aggregate, true);
- }
-
- 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$
-
- // Set up capabilities
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- finder.addCapabilities("pm1", caps); //$NON-NLS-1$
- ResolverVisitor.resolveLanguageObject(function, metadata);
- // Test capabilities util
- boolean actual = CapabilitiesUtil.supportsScalarFunction(modelID, function, metadata, finder);
- assertEquals("Got wrong answer for supports", expectedValue, actual); //$NON-NLS-1$
- }
-
- // Test where capabilities don't support scalar functions
- public void testSupportsScalar1() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
-
- Function func = new Function("+", new Expression[] { new Constant(1), new Constant(2) }); //$NON-NLS-1$
- helpTestSupportsScalar(caps, func, false);
- }
-
- // Test where capabilities doesn't support function
- public void testSupportsScalar3() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setFunctionSupport("now", false); //$NON-NLS-1$
-
- Function func = new Function("NOW", new Expression[] { }); //$NON-NLS-1$
- helpTestSupportsScalar(caps, func, false);
- }
-
- // Test where capabilities do support function
- public void testSupportsScalar4() throws Exception {
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setFunctionSupport("now", true); //$NON-NLS-1$
-
- Function func = new Function("NOW", new Expression[] { }); //$NON-NLS-1$
- helpTestSupportsScalar(caps, func, true);
- }
-
- public void testSupportsDistinct1() throws Exception {
- // Set up metadata
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- // Set up capabilities
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
- sourceCaps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, true);
- finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
-
- assertTrue(CapabilitiesUtil.supportsSelectDistinct(modelID, metadata, finder));
- }
-
- public void testSupportsDistinct2() throws Exception {
- // Set up metadata
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- // Set up capabilities
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
- sourceCaps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, false);
- finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
-
- // Test capabilities util
- boolean actual = CapabilitiesUtil.supportsSelectDistinct(modelID, metadata, finder);
- assertEquals("Got wrong answer for supports", false, actual); //$NON-NLS-1$
- }
-
- public void testSupportsOrderBy1() throws Exception {
- // Set up metadata
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- // Set up capabilities
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
- sourceCaps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
-
- // Test capabilities util
- boolean actual = CapabilitiesUtil.supportsOrderBy(modelID, metadata, finder);
- assertEquals("Got wrong answer for supports", true, actual); //$NON-NLS-1$
- }
-
- public void testSupportsOrderBy2() throws Exception {
- // Set up metadata
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- // Set up capabilities
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
- sourceCaps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
- finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
-
- // Test capabilities util
- boolean actual = CapabilitiesUtil.supportsOrderBy(modelID, metadata, finder);
- assertEquals("Got wrong answer for supports", false, actual); //$NON-NLS-1$
- }
-
- 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$
-
- // Set up capabilities
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
- sourceCaps.setCapabilitySupport(Capability.QUERY_UNION, supports);
- finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
-
- // Test capabilities util
- boolean actual = CapabilitiesUtil.supportsSetOp(modelID, Operation.UNION, metadata, finder);
- assertEquals("Got wrong answer for supports", supports, actual); //$NON-NLS-1$
- }
-
- public void testSupportsUnionTrue() throws Exception {
- helpTestSupportsUnion(true);
- }
-
- 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$
-
- // Set up capabilities
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
- sourceCaps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, supports);
- finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
-
- // Test capabilities util
- boolean actual = CapabilitiesUtil.supportsSelectExpression(modelID, metadata, finder);
- assertEquals("Got wrong answer for supports", supports, actual); //$NON-NLS-1$
- }
-
- public void testSupportsLiteralsTrue() throws Exception {
- helpTestSupportsLiterals(true);
- }
-
- 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$
-
- // Set up capabilities
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
- if(searched) {
- sourceCaps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, supports);
- } else {
- sourceCaps.setCapabilitySupport(Capability.QUERY_CASE, supports);
- }
- finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
-
- // Test capabilities util
- boolean actual = false;
- if(searched) {
- actual = CapabilitiesUtil.supportsSearchedCaseExpression(modelID, metadata, finder);
- } else {
- actual = CapabilitiesUtil.supportsCaseExpression(modelID, metadata, finder);
- }
- assertEquals("Got wrong answer for supports", supports, actual); //$NON-NLS-1$
- }
-
- public void testSupportsCaseTrue() throws Exception {
- helpTtestSupportsCaseExpression(true, false);
- }
-
- public void testSupportsCaseFalse() throws Exception {
- helpTtestSupportsCaseExpression(false, false);
- }
-
- public void testSupportsSearchedCaseTrue() throws Exception {
- helpTtestSupportsCaseExpression(true, true);
- }
-
- public void testSupportsSearchedCaseFalse() throws Exception {
- helpTtestSupportsCaseExpression(false, true);
- }
-
- private FakeCapabilitiesFinder getFinder(Capability property, boolean supported) {
- // Set up capabilities
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
- sourceCaps.setCapabilitySupport(property, supported);
- finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
- return finder;
- }
-
- public void testSupportRowLimit() throws Exception {
- // Set up metadata
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
- // Set up capabilities
- FakeCapabilitiesFinder finder = getFinder(Capability.ROW_LIMIT, false);
- // Test capabilities util
- assertEquals(false, CapabilitiesUtil.supportsRowLimit(modelID, metadata, finder));
-
- finder = getFinder(Capability.ROW_LIMIT, true);
- // Test capabilities util
- assertEquals(true, CapabilitiesUtil.supportsRowLimit(modelID, metadata, finder));
- }
-
- public void testSupportRowOffset() throws Exception {
- // Set up metadata
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
- // Set up capabilities
- FakeCapabilitiesFinder finder = getFinder(Capability.ROW_OFFSET, false);
- // Test capabilities util
- assertEquals(false, CapabilitiesUtil.supportsRowOffset(modelID, metadata, finder));
-
- finder = getFinder(Capability.ROW_OFFSET, true);
- // Test capabilities util
- assertEquals(true, CapabilitiesUtil.supportsRowOffset(modelID, metadata, finder));
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCapabilitiesUtil.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCapabilitiesUtil.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCapabilitiesUtil.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCapabilitiesUtil.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,594 @@
+/*
+ * 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.relational.rules;
+
+import static org.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.List;
+
+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;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.resolver.util.ResolverVisitor;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.lang.SetQuery.Operation;
+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.ExpressionSymbol;
+import org.teiid.query.sql.symbol.Function;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+
+/**
+ */
+ at SuppressWarnings("nls")
+public class TestCapabilitiesUtil {
+
+ public void helpTestSupportsSelfJoin(boolean supportsSelfJoin, boolean supportsGroupAlias, boolean expectedValue) throws QueryMetadataException, TeiidComponentException {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
+ sourceCaps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, supportsSelfJoin);
+ sourceCaps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, supportsGroupAlias);
+ finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
+
+ // Test capabilities util
+ boolean actual = CapabilitiesUtil.supportsSelfJoins(modelID, metadata, finder);
+ assertEquals("Got wrong answer for supports", expectedValue, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testSupportsSelfJoin1() throws Exception {
+ helpTestSupportsSelfJoin(false, true, false);
+ }
+
+ @Test public void testSupportsSelfJoin2() throws Exception {
+ helpTestSupportsSelfJoin(true, false, false);
+ }
+
+ @Test public void testSupportsSelfJoin3() throws Exception {
+ helpTestSupportsSelfJoin(true, true, true);
+ }
+
+ @Test public void testSupportsSelfJoin4() throws Exception {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ // Test capabilities util
+ boolean actual = CapabilitiesUtil.supportsSelfJoins(modelID, metadata, new DefaultCapabilitiesFinder());
+ assertEquals("Got wrong answer for supports", false, actual); //$NON-NLS-1$
+ }
+
+
+ public void helpTestSupportsOuterJoin(boolean capsSupportsOuterJoin, boolean capsSupportsFullOuterJoin, JoinType joinType, boolean expectedValue) throws QueryMetadataException, TeiidComponentException {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
+ sourceCaps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER, capsSupportsOuterJoin);
+ sourceCaps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_OUTER_FULL, capsSupportsFullOuterJoin);
+ finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
+
+ // Test capabilities util
+ boolean actual = CapabilitiesUtil.supportsJoin(modelID, joinType, metadata, finder);
+ assertEquals("Got wrong answer for supports", expectedValue, actual); //$NON-NLS-1$
+ }
+
+ // Test where capabilities don't support outer joins
+ @Test public void testSupportsOuterJoinFail1() throws Exception {
+ helpTestSupportsOuterJoin(false, false, JoinType.JOIN_RIGHT_OUTER, false);
+ }
+
+ // Test where capabilities don't support full outer joins
+ @Test public void testSupportsOuterJoinFail3() throws Exception {
+ helpTestSupportsOuterJoin(true, false, JoinType.JOIN_FULL_OUTER, false);
+ }
+
+ // Test where capabilities support outer joins
+ @Test public void testSupportsOuterJoin1() throws Exception {
+ helpTestSupportsOuterJoin(true, false, JoinType.JOIN_RIGHT_OUTER, true);
+ }
+
+ // Test where capabilities support full outer joins
+ @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
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
+ sourceCaps.setCapabilitySupport(Capability.QUERY_AGGREGATES, capsSupportsAggregates);
+ sourceCaps.setCapabilitySupport(Capability.QUERY_FUNCTIONS_IN_GROUP_BY, supportsFunctionInGroupBy);
+ finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
+
+ // Test capabilities util
+ boolean actual = CapabilitiesUtil.supportsAggregates(groupCols, modelID, metadata, finder);
+ assertEquals("Got wrong answer for supports", capsSupportsAggregates, actual); //$NON-NLS-1$
+ }
+
+ // Test where capabilities supports aggregates
+ @Test public void testSupportsAggregates1() throws Exception {
+ helpTestSupportsAggregates(true, true, null);
+ }
+
+ /**
+ * Supports functions in group by is misleading. It should actually
+ * be called supports expression in group by. Thus the example below
+ * is not supported.
+ */
+ @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();
+ cols.add(expr);
+ helpTestSupportsAggregates(false, false, cols);
+ }
+
+ public void helpTestSupportsAggregateFunction(SourceCapabilities caps, AggregateSymbol aggregate, boolean expectedValue) throws QueryMetadataException, TeiidComponentException {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ finder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Test capabilities util
+ boolean actual = CapabilitiesUtil.supportsAggregateFunction(modelID, aggregate, metadata, finder);
+ assertEquals("Got wrong answer for supports", expectedValue, actual); //$NON-NLS-1$
+ }
+
+ // Test where capabilities don't support aggregate functions
+ @Test public void testSupportsAggregate1() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, false);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.COUNT, false, null); //$NON-NLS-1$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, false);
+ }
+
+ // Test where capabilities don't support COUNT
+ @Test public void testSupportsAggregate2() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, false);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, false);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.COUNT, false, null); //$NON-NLS-1$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, false);
+ }
+
+ // Test where capabilities support only COUNT(*)
+ @Test public void testSupportsAggregate3() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, false);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.COUNT, false, null); //$NON-NLS-1$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, true);
+ }
+
+ // Test where capabilities support only COUNT(*)
+ @Test public void testSupportsAggregate4() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, false);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.COUNT, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, false);
+ }
+
+ // Test where capabilities support only COUNT
+ @Test public void testSupportsAggregate5() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, false);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.COUNT, false, null); //$NON-NLS-1$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, false);
+ }
+
+ // Test where capabilities support only COUNT
+ @Test public void testSupportsAggregate6() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, false);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.COUNT, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, true);
+ }
+
+ // Test where capabilities don't support SUM
+ @Test public void testSupportsAggregate7() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, false);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.SUM, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, false);
+ }
+
+ // Test where capabilities support SUM
+ @Test public void testSupportsAggregate8() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.SUM, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, true);
+ }
+
+ // Test where capabilities don't support AVG
+ @Test public void testSupportsAggregate9() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, false);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.AVG, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, false);
+ }
+
+ // Test where capabilities support AVG
+ @Test public void testSupportsAggregate10() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.AVG, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, true);
+ }
+
+ // Test where capabilities don't support MIN
+ @Test public void testSupportsAggregate11() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MIN, false);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.MIN, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, false);
+ }
+
+ // Test where capabilities support MIN
+ @Test public void testSupportsAggregate12() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MIN, true);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.MIN, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, true);
+ }
+
+ // Test where capabilities don't support MAX
+ @Test public void testSupportsAggregate13() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, false);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.MAX, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, false);
+ }
+
+ // Test where capabilities support MAX
+ @Test public void testSupportsAggregate14() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.MAX, false, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, true);
+ }
+
+ // Test where capabilities don't support DISTINCT
+ @Test public void testSupportsAggregate15() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_DISTINCT, false);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.MAX, true, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, false);
+ }
+
+ // Test where capabilities support DISTINCT
+ @Test public void testSupportsAggregate16() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_DISTINCT, true);
+
+ AggregateSymbol aggregate = new AggregateSymbol("expr", NonReserved.MAX, true, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ helpTestSupportsAggregateFunction(caps, aggregate, true);
+ }
+
+ public void helpTestSupportsScalar(SourceCapabilities caps, Function function, boolean expectedValue) throws QueryMetadataException, TeiidComponentException, QueryResolverException {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ finder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ ResolverVisitor.resolveLanguageObject(function, metadata);
+ // Test capabilities util
+ boolean actual = CapabilitiesUtil.supportsScalarFunction(modelID, function, metadata, finder);
+ assertEquals("Got wrong answer for supports", expectedValue, actual); //$NON-NLS-1$
+ }
+
+ // Test where capabilities don't support scalar functions
+ @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$
+ helpTestSupportsScalar(caps, func, false);
+ }
+
+ // Test where capabilities doesn't support function
+ @Test public void testSupportsScalar3() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setFunctionSupport("now", false); //$NON-NLS-1$
+
+ Function func = new Function("NOW", new Expression[] { }); //$NON-NLS-1$
+ helpTestSupportsScalar(caps, func, false);
+ }
+
+ // Test where capabilities do support function
+ @Test public void testSupportsScalar4() throws Exception {
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setFunctionSupport("now", true); //$NON-NLS-1$
+
+ Function func = new Function("NOW", new Expression[] { }); //$NON-NLS-1$
+ helpTestSupportsScalar(caps, func, true);
+ }
+
+ @Test public void testSupportsDistinct1() throws Exception {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
+ sourceCaps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, true);
+ finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
+
+ assertTrue(CapabilitiesUtil.supportsSelectDistinct(modelID, metadata, finder));
+ }
+
+ @Test public void testSupportsDistinct2() throws Exception {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
+ sourceCaps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, false);
+ finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
+
+ // Test capabilities util
+ boolean actual = CapabilitiesUtil.supportsSelectDistinct(modelID, metadata, finder);
+ assertEquals("Got wrong answer for supports", false, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testSupportsOrderBy1() throws Exception {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
+ sourceCaps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
+
+ // Test capabilities util
+ boolean actual = CapabilitiesUtil.supportsOrderBy(modelID, metadata, finder);
+ assertEquals("Got wrong answer for supports", true, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testSupportsOrderBy2() throws Exception {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
+ sourceCaps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
+
+ // Test capabilities util
+ boolean actual = CapabilitiesUtil.supportsOrderBy(modelID, metadata, finder);
+ assertEquals("Got wrong answer for supports", false, actual); //$NON-NLS-1$
+ }
+
+ public void helpTestSupportsUnion(boolean supports) throws QueryMetadataException, TeiidComponentException {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
+ sourceCaps.setCapabilitySupport(Capability.QUERY_UNION, supports);
+ finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
+
+ // Test capabilities util
+ boolean actual = CapabilitiesUtil.supportsSetOp(modelID, Operation.UNION, metadata, finder);
+ assertEquals("Got wrong answer for supports", supports, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testSupportsUnionTrue() throws Exception {
+ helpTestSupportsUnion(true);
+ }
+
+ @Test public void testSupportsUnionFalse() throws Exception {
+ helpTestSupportsUnion(false);
+ }
+
+ public void helpTestSupportsLiterals(boolean supports) throws QueryMetadataException, TeiidComponentException {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
+ sourceCaps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, supports);
+ finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
+
+ // Test capabilities util
+ boolean actual = CapabilitiesUtil.supportsSelectExpression(modelID, metadata, finder);
+ assertEquals("Got wrong answer for supports", supports, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testSupportsLiteralsTrue() throws Exception {
+ helpTestSupportsLiterals(true);
+ }
+
+ @Test public void testSupportsLiteralsFalse() throws Exception {
+ helpTestSupportsLiterals(false);
+ }
+
+ public void helpTtestSupportsCaseExpression(boolean supports, boolean searched) throws QueryMetadataException, TeiidComponentException {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
+ if(searched) {
+ sourceCaps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, supports);
+ } else {
+ sourceCaps.setCapabilitySupport(Capability.QUERY_CASE, supports);
+ }
+ finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
+
+ // Test capabilities util
+ boolean actual = false;
+ if(searched) {
+ actual = CapabilitiesUtil.supportsSearchedCaseExpression(modelID, metadata, finder);
+ } else {
+ actual = CapabilitiesUtil.supportsCaseExpression(modelID, metadata, finder);
+ }
+ assertEquals("Got wrong answer for supports", supports, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testSupportsCaseTrue() throws Exception {
+ helpTtestSupportsCaseExpression(true, false);
+ }
+
+ @Test public void testSupportsCaseFalse() throws Exception {
+ helpTtestSupportsCaseExpression(false, false);
+ }
+
+ @Test public void testSupportsSearchedCaseTrue() throws Exception {
+ helpTtestSupportsCaseExpression(true, true);
+ }
+
+ @Test public void testSupportsSearchedCaseFalse() throws Exception {
+ helpTtestSupportsCaseExpression(false, true);
+ }
+
+ private FakeCapabilitiesFinder getFinder(Capability property, boolean supported) {
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities sourceCaps = new BasicSourceCapabilities();
+ sourceCaps.setCapabilitySupport(property, supported);
+ finder.addCapabilities("pm1", sourceCaps); //$NON-NLS-1$
+ return finder;
+ }
+
+ @Test public void testSupportRowLimit() throws Exception {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = getFinder(Capability.ROW_LIMIT, false);
+ // Test capabilities util
+ assertEquals(false, CapabilitiesUtil.supportsRowLimit(modelID, metadata, finder));
+
+ finder = getFinder(Capability.ROW_LIMIT, true);
+ // Test capabilities util
+ assertEquals(true, CapabilitiesUtil.supportsRowLimit(modelID, metadata, finder));
+ }
+
+ @Test public void testSupportRowOffset() throws Exception {
+ // Set up metadata
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+ // Set up capabilities
+ FakeCapabilitiesFinder finder = getFinder(Capability.ROW_OFFSET, false);
+ // Test capabilities util
+ assertEquals(false, CapabilitiesUtil.supportsRowOffset(modelID, metadata, finder));
+
+ finder = getFinder(Capability.ROW_OFFSET, true);
+ // Test capabilities util
+ assertEquals(true, CapabilitiesUtil.supportsRowOffset(modelID, metadata, finder));
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCriteriaCapabilityValidatorVisitor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCriteriaCapabilityValidatorVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCriteriaCapabilityValidatorVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,888 +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.optimizer.relational.rules;
-
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.TeiidException;
-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 static org.junit.Assert.*;
-
-
-/**
- */
-public class TestCriteriaCapabilityValidatorVisitor {
-
- public void helpTestVisitor(String sql, Object modelID, FakeMetadataFacade metadata, CapabilitiesFinder capFinder, boolean isValid, boolean expectException) {
- try {
- Criteria criteria = QueryParser.getQueryParser().parseCriteria(sql);
-
- QueryResolver.resolveCriteria(criteria, metadata);
-
- assertEquals("Got incorrect isValid flag", isValid, CriteriaCapabilityValidatorVisitor.canPushLanguageObject(criteria, modelID, metadata, capFinder, null)); //$NON-NLS-1$
- } catch(QueryMetadataException e) {
- 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) {
- try {
- Command command = QueryParser.getQueryParser().parseCommand(sql);
-
- QueryResolver.resolveCommand(command, metadata);
-
- assertEquals("Got incorrect isValid flag", isValid, CriteriaCapabilityValidatorVisitor.canPushLanguageObject(command, modelID, metadata, capFinder, null)); //$NON-NLS-1$
- } catch(QueryMetadataException e) {
- if (!expectException) {
- throw new RuntimeException(e);
- }
- } catch(TeiidException e) {
- throw new RuntimeException(e);
- }
- }
-
- // has all capabilities
- @Test public void testCompareCriteriaSuccess() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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, true, false); //$NON-NLS-1$
- }
-
- // does not have where capability
- @Test public void testCompareCriteriaCapFail1() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
- }
-
- // does not have = capability
- @Test public void testCompareCriteriaOpCapFail1() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
- }
-
- // does not have <> capability
- @Test public void testCompareCriteriaOpCapFail2() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
- }
-
- // does not have < capability
- @Test public void testCompareCriteriaOpCapFail3() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
- }
-
- // does not have <= capability
- @Test public void testCompareCriteriaOpCapFail4() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
- }
-
- // does not have > capability
- @Test public void testCompareCriteriaOpCapFail5() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
- }
-
- // does not have >= capability
- @Test public void testCompareCriteriaOpCapFail6() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
- }
-
- // 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);
-
- 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$
- }
-
- // no caps
- @Test public void testCompareCriteriaNoCaps() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-
- helpTestVisitor("pm1.g1.e1 = 'x'", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
- }
-
- @Test public void testCompoundCriteriaAnd1() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
- }
-
- @Test public void testCompoundCriteriaAnd4() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-
- helpTestVisitor("pm1.g1.e1 = 'x' AND 0 = 1", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
- }
-
- @Test public void testCompoundCriteriaOr1() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- 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$
- }
-
- @Test public void testCompoundCriteriaOr2() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- 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$
- }
-
- @Test public void testCompoundCriteriaOr4() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-
- helpTestVisitor("pm1.g1.e1 = 'x' OR 0 = 1", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
- }
-
- @Test public void testScalarFunction1() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
-
- helpTestVisitor("curtime() = {t'10:00:00'}", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
- }
-
- /**
- * 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$
-
- 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$
-
- helpTestVisitor("1 + 1 = 2", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
- }
-
- /**
- * 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$
-
- 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$
-
- helpTestVisitor("curtime() = '{t'10:00:00'}", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
- }
-
- /**
- * 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$
-
- 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$
-
- helpTestVisitor("rand() = '1.0'", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
-
- @Test public void testIsNull1() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
- }
-
- @Test public void testIsNull2() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
- }
-
- @Test public void testIsNull3() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-
- helpTestVisitor("pm1.g1.e1 IS NULL", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
- }
-
- /**
- * 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);
-
- 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$
- }
-
- @Test public void testIsNull6() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_ISNULL, true);
- 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$
- }
-
- @Test public void testIsNull6fails() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
- }
-
- // has all capabilities
- @Test public void testMatchCriteriaSuccess() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
- }
-
- @Test public void testMatchCriteriaSuccess2() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
- 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$
- }
-
- // Test for NOT LIKE
- @Test public void testMatchCriteriaSuccess3() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
- 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$
- }
-
- @Test public void testMatchCriteriaSuccess3fails() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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 NOT LIKE 'x'", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // does not have compare capability
- @Test public void testMatchCriteriaCapFail1() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_LIKE, false);
- caps.setCapabilitySupport(Capability.CRITERIA_LIKE_ESCAPE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitor("pm1.g1.e1 LIKE 'x'", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
- caps.setCapabilitySupport(Capability.CRITERIA_LIKE_ESCAPE, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitor("pm1.g1.e1 LIKE 'x' ESCAPE '#'", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // 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);
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
- caps.setCapabilitySupport(Capability.CRITERIA_LIKE_ESCAPE, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitor("pm1.g1.e1 LIKE 'x'", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // no caps
- @Test public void testMatchCriteriaNoCaps() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_NOT, false);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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$
-
- 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);
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitor("pm1.g1.e1 IN ('x')", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- //Test for success NOT IN
- @Test public void testSetCriteria7() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(2));
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(2));
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitor("pm1.g1.e1 = case when pm1.g1.e2 = 1 then 1 else 2 end", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // has all capabilities
- @Test public void testSubqueryCompareCriteriaSuccess() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
- }
-
- // does not have where capability
- @Test public void testSubqueryCompareCriteriaCapFail1() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // does not have compare capability
- @Test public void testSubqueryCompareCriteriaCapFail2() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // does not have subquery capability
- @Test public void testSubqueryCompareCriteriaFail3() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, false);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ALL (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // does not have = capability
- @Test public void testSubqueryCompareCriteriaOpCapFail1() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // does not have <> capability
- @Test public void testSubqueryCompareCriteriaOpCapFail2() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 <> ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // does not have < capability
- @Test public void testSubqueryCompareCriteriaOpCapFail3() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 < ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // does not have <= capability
- @Test public void testSubqueryCompareCriteriaOpCapFail4() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 <= ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // does not have > capability
- @Test public void testSubqueryCompareCriteriaOpCapFail5() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 > ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // does not have >= capability
- @Test public void testSubqueryCompareCriteriaOpCapFail6() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 >= ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
- }
-
- // 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);
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE EXISTS(SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCriteriaCapabilityValidatorVisitor.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCriteriaCapabilityValidatorVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCriteriaCapabilityValidatorVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCriteriaCapabilityValidatorVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,888 @@
+/*
+ * 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.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.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.RealMetadataFactory;
+
+
+/**
+ */
+ at SuppressWarnings("nls")
+public class TestCriteriaCapabilityValidatorVisitor {
+
+ public void helpTestVisitor(String sql, Object modelID, TransformationMetadata metadata, CapabilitiesFinder capFinder, boolean isValid, boolean expectException) throws Exception {
+ try {
+ Criteria criteria = QueryParser.getQueryParser().parseCriteria(sql);
+
+ QueryResolver.resolveCriteria(criteria, metadata);
+
+ assertEquals("Got incorrect isValid flag", isValid, CriteriaCapabilityValidatorVisitor.canPushLanguageObject(criteria, modelID, metadata, capFinder, null)); //$NON-NLS-1$
+ } catch(QueryMetadataException e) {
+ if (!expectException) {
+ 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, TransformationMetadata metadata, CapabilitiesFinder capFinder, boolean isValid, boolean expectException) {
+ try {
+ Command command = QueryParser.getQueryParser().parseCommand(sql);
+
+ QueryResolver.resolveCommand(command, metadata);
+
+ assertEquals("Got incorrect isValid flag", isValid, CriteriaCapabilityValidatorVisitor.canPushLanguageObject(command, modelID, metadata, capFinder, null)); //$NON-NLS-1$
+ } catch(QueryMetadataException e) {
+ if (!expectException) {
+ throw new RuntimeException(e);
+ }
+ } catch(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ // has all capabilities
+ @Test public void testCompareCriteriaSuccess() 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'", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
+ }
+
+ // does not have where capability
+ @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);
+ }
+
+ // does not have = capability
+ @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);
+ }
+
+ // does not have <> capability
+ @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);
+ }
+
+ // does not have < capability
+ @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);
+ }
+
+ // does not have <= capability
+ @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);
+ }
+
+ // does not have > capability
+ @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);
+ }
+
+ // does not have >= capability
+ @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);
+ }
+
+ // element not searchable
+ @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);
+ }
+
+ // no caps
+ @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);
+ }
+
+ @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);
+ }
+
+ @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);
+ }
+
+ @Test public void testCompoundCriteriaOr1() 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.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);
+ }
+
+ @Test public void testCompoundCriteriaOr2() 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.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);
+ }
+
+ @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);
+ }
+
+ @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);
+
+ 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() 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);
+
+ 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() 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);
+
+ 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() 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);
+
+ helpTestVisitor("rand() = '1.0'", modelID, metadata, capFinder, false, false);
+ }
+
+
+ @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);
+ }
+
+ @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);
+ }
+
+ @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);
+ }
+
+ /**
+ * Is null is not a comparison operation
+ */
+ @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);
+ }
+
+ @Test public void testIsNull6() 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);
+ 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);
+ }
+
+ @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);
+ }
+
+ // has all capabilities
+ @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);
+ }
+
+ @Test public void testMatchCriteriaSuccess2() 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);
+ 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);
+ }
+
+ // Test for NOT LIKE
+ @Test public void testMatchCriteriaSuccess3() 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);
+ 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);
+ }
+
+ @Test public void testMatchCriteriaSuccess3fails() 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 NOT LIKE 'x'", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // does not have compare capability
+ @Test public void testMatchCriteriaCapFail1() 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, false);
+ caps.setCapabilitySupport(Capability.CRITERIA_LIKE_ESCAPE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("pm1.g1.e1 LIKE 'x'", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // does not have escape char capability
+ @Test public void testMatchCriteriaCapFail2() 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);
+ caps.setCapabilitySupport(Capability.CRITERIA_LIKE_ESCAPE, false);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("pm1.g1.e1 LIKE 'x' ESCAPE '#'", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // element not searchable
+ @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();
+ caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_LIKE_ESCAPE, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("pm1.g1.e1 LIKE 'x'", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // no caps
+ @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() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Object modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("NOT pm1.g1.e1 = 'x'", modelID, metadata, capFinder, true, false); //$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();
+ caps.setCapabilitySupport(Capability.CRITERIA_NOT, false);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("NOT pm1.g1.e1 = 'x'", modelID, metadata, capFinder, false, false); //$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();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("pm1.g1.e1 IN ('x')", modelID, metadata, capFinder, true, false); //$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();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, false);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("pm1.g1.e1 IN ('x')", modelID, metadata, capFinder, false, false); //$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() 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();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("pm1.g1.e1 IN ('x')", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ //Test for success NOT IN
+ @Test public void testSetCriteria7() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Object modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("pm1.g1.e1 NOT IN ('x')", modelID, metadata, capFinder, true, false); //$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();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("pm1.g1.e1 NOT IN ('x')", modelID, metadata, capFinder, false, false); //$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();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(2));
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("pm1.g1.e1 IN ('x', 'y', 'z')", modelID, metadata, capFinder, false, false); //$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();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(2));
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("pm1.g1.e1 IN ('x', 'y')", modelID, metadata, capFinder, true, false); //$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();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("pm1.g1.e1 IN (SELECT 'xyz' FROM pm1.g1)", modelID, metadata, capFinder, false, false); //$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();
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitor("pm1.g1.e1 = case when pm1.g1.e2 = 1 then 1 else 2 end", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // has all capabilities
+ @Test public void testSubqueryCompareCriteriaSuccess() 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.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
+ }
+
+ // does not have where capability
+ @Test public void testSubqueryCompareCriteriaCapFail1() 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$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // does not have compare capability
+ @Test public void testSubqueryCompareCriteriaCapFail2() 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$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // does not have subquery capability
+ @Test public void testSubqueryCompareCriteriaFail3() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Object modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, false);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // does not have quantified subquery comparison capability
+ @Test public void testSubqueryCompareCriteriaFail4() 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.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, false);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // does not have quantified subquery comparison capability for ANY
+ @Test public void testSubqueryCompareCriteriaFail5() 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.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, false);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // does not have quantified subquery comparison capability for ALL
+ @Test public void testSubqueryCompareCriteriaFail6() 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.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, false);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ALL (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // does not have = capability
+ @Test public void testSubqueryCompareCriteriaOpCapFail1() 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$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // does not have <> capability
+ @Test public void testSubqueryCompareCriteriaOpCapFail2() 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$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 <> ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // does not have < capability
+ @Test public void testSubqueryCompareCriteriaOpCapFail3() 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$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 < ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // does not have <= capability
+ @Test public void testSubqueryCompareCriteriaOpCapFail4() 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$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 <= ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // does not have > capability
+ @Test public void testSubqueryCompareCriteriaOpCapFail5() 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$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 > ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // does not have >= capability
+ @Test public void testSubqueryCompareCriteriaOpCapFail6() 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$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 >= ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+ }
+
+ // element not searchable
+ @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();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Object modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Object modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, false);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+ Object modelID = metadata.getMetadataStore().getSchema("PM1");
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE EXISTS(SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAccessPatternValidation.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAccessPatternValidation.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAccessPatternValidation.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,192 +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.optimizer.relational.rules;
-
-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.query.analysis.AnalysisRecord;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.TestOptimizer;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
-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.PlanNode;
-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.util.CommandContext;
-
-
-/**
- * Tests {@link RuleChooseAccessPattern}
- */
-public class TestRuleAccessPatternValidation {
-
- private static final FakeMetadataFacade METADATA = FakeMetadataFactory.example1Cached();
-
- private static final boolean DEBUG = false;
-
- private static CapabilitiesFinder FINDER = new DefaultCapabilitiesFinder(TestOptimizer.getTypicalCapabilities());
-
- /**
- * @param command the query to be turned into a test query plan
- * @param expectedChosenPredicates expected criteria predicates that should
- * be below the access node after the rule is run
- */
- private void helpTestAccessPatternValidation(String command) throws Exception {
- PlanNode node = this.helpPlan(command);
-
- if(DEBUG) {
- System.out.println("\nfinal plan node:\n"+node); //$NON-NLS-1$
- }
- }
-
-
- /**
- * Parses and resolves the command, creates a canonical relational plan,
- * and runs some of the optimizer rules, ending with the
- * RuleChooseAccessPattern.
- * @param command String command to parse, resolve and use for planning
- * @param rules empty RuleStack
- * @param groups Collection to add parsed and resolved GroupSymbols to
- * @return the root PlanNode of the query plan
- */
- private PlanNode helpPlan(String command) throws Exception {
- Command query = QueryParser.getQueryParser().parseCommand(command);
- QueryResolver.resolveCommand(query, METADATA);
-
- //Generate canonical plan
- RelationalPlanner p = new RelationalPlanner();
- p.initialize(query, null, METADATA, FINDER, null, new CommandContext());
- PlanNode planNode = p.generatePlan(query);
- RelationalPlanner planner = new RelationalPlanner();
- final RuleStack rules = planner.buildRules();
-
- PlanNode testPlan = helpExecuteRules(rules, planNode, METADATA, DEBUG);
-
- return testPlan;
- }
-
- /**
- * Simulate execution of the QueryOptimizer rules stack
- */
- private static PlanNode helpExecuteRules(RuleStack rules, PlanNode plan, QueryMetadataInterface metadata, boolean debug)
- throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
- CommandContext context = new CommandContext();
- while(! rules.isEmpty()) {
- if(debug) {
- System.out.println("\n============================================================================"); //$NON-NLS-1$
- }
- OptimizerRule rule = rules.pop();
- if(debug) {
- System.out.println("EXECUTING " + rule); //$NON-NLS-1$
- }
-
- plan = rule.execute(plan, metadata, FINDER, rules, new AnalysisRecord(false, debug), context);
- if(debug) {
- System.out.println("\nAFTER: \n" + plan); //$NON-NLS-1$
- }
- }
- return plan;
- }
-
-
- // ################################## ACTUAL TESTS ################################
-
- /**
- * This test demonstrates that APs are ignored for inserts
- * CASE 3966
- */
- @Test public void testInsertWithAccessPattern_Case3966() throws Exception {
- this.helpTestAccessPatternValidation( "insert into pm4.g1 (e1, e2, e3, e4) values('test', 1, convert('true', boolean) , convert('12', double) )" ); //$NON-NLS-1$
- }
-
- /**
- * This test demonstrates that a satisfied AP does not fail.
- * Found testing fix for 3966.
- */
- @Test public void testDeleteWithAccessPattern_Case3966() throws Exception {
- this.helpTestAccessPatternValidation( "delete from pm4.g1 where e1 = 'test' and e2 = 1" ); //$NON-NLS-1$
- }
-
- /**
- * This test demonstrates that unsatisfied AP fails.
- * Found testing fix for 3966.
- */
- @Test public void testDeleteWithAccessPattern_Case3966_2() throws Exception {
- try {
- this.helpTestAccessPatternValidation( "delete from pm4.g1" ); //$NON-NLS-1$
- fail("Expected QueryPlannerException, but did not get one"); //$NON-NLS-1$
- } catch (QueryPlannerException err) {
- //This SHOULD happen.
- final String msg = err.getMessage();
- final String expected = "Group has an access pattern which has not been met: group(s) [pm4.g1]; access pattern(s) [Access Pattern: Unsatisfied [pm4.g1.e1] History [[pm4.g1.e1]]]"; //$NON-NLS-1$
- assertEquals("Did not fail with expected QueryPlannerException", expected, msg); //$NON-NLS-1$
- }
- }
-
- @Test public void testUpdateWithAccessPattern_Case3966() throws Exception {
- this.helpTestAccessPatternValidation( "update pm4.g1 set e1 = 'test1' where e1 = 'test' and e2 = 1" ); //$NON-NLS-1$
- }
-
- /**
- * This test demonstrates that unsatisfied AP fails.
- * Found testing fix for 3966.
- */
- @Test public void testUpdateWithAccessPattern_Case3966_2() throws Exception {
- try {
- this.helpTestAccessPatternValidation( "update pm4.g1 set e1 = 'test'" ); //$NON-NLS-1$
- fail("Expected QueryPlannerException, but did not get one"); //$NON-NLS-1$
- } catch (QueryPlannerException err) {
- //This SHOULD happen.
- final String msg = err.getMessage();
- final String expected = "Group has an access pattern which has not been met: group(s) [pm4.g1]; access pattern(s) [Access Pattern: Unsatisfied [pm4.g1.e1] History [[pm4.g1.e1]]]"; //$NON-NLS-1$
- assertEquals("Did not fail with expected QueryPlannerException", expected, msg); //$NON-NLS-1$
- }
- }
-
- /**
- * This test demonstrates that APs are ignored for inserts through a virtual layer
- * CASE 3966
- */
- @Test public void testInsertWithAccessPattern_Case3966_VL() throws Exception {
- this.helpTestAccessPatternValidation( "insert into vm1.g37 (e1, e2, e3, e4) values('test', 1, convert('true', boolean) , convert('12', double) )" ); //$NON-NLS-1$
- }
-
- /**
- * This test demonstrates that a satisfied AP within a Delete
- * through a virtual layer does not fail.
- * Found testing fix for 3966.
- */
- @Test public void testDeleteWithAccessPattern_Case3966_VL() throws Exception {
- this.helpTestAccessPatternValidation( "delete from vm1.g37 where e1 = 'test' and e2 = 1" ); //$NON-NLS-1$
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAccessPatternValidation.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAccessPatternValidation.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAccessPatternValidation.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAccessPatternValidation.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,191 @@
+/*
+ * 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.relational.rules;
+
+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.query.analysis.AnalysisRecord;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.TestOptimizer;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
+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.PlanNode;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+
+/**
+ * Tests {@link RuleChooseAccessPattern}
+ */
+public class TestRuleAccessPatternValidation {
+
+ private static final QueryMetadataInterface METADATA = RealMetadataFactory.example1Cached();
+
+ private static final boolean DEBUG = false;
+
+ private static CapabilitiesFinder FINDER = new DefaultCapabilitiesFinder(TestOptimizer.getTypicalCapabilities());
+
+ /**
+ * @param command the query to be turned into a test query plan
+ * @param expectedChosenPredicates expected criteria predicates that should
+ * be below the access node after the rule is run
+ */
+ private void helpTestAccessPatternValidation(String command) throws Exception {
+ PlanNode node = this.helpPlan(command);
+
+ if(DEBUG) {
+ System.out.println("\nfinal plan node:\n"+node); //$NON-NLS-1$
+ }
+ }
+
+
+ /**
+ * Parses and resolves the command, creates a canonical relational plan,
+ * and runs some of the optimizer rules, ending with the
+ * RuleChooseAccessPattern.
+ * @param command String command to parse, resolve and use for planning
+ * @param rules empty RuleStack
+ * @param groups Collection to add parsed and resolved GroupSymbols to
+ * @return the root PlanNode of the query plan
+ */
+ private PlanNode helpPlan(String command) throws Exception {
+ Command query = QueryParser.getQueryParser().parseCommand(command);
+ QueryResolver.resolveCommand(query, METADATA);
+
+ //Generate canonical plan
+ RelationalPlanner p = new RelationalPlanner();
+ p.initialize(query, null, METADATA, FINDER, null, new CommandContext());
+ PlanNode planNode = p.generatePlan(query);
+ RelationalPlanner planner = new RelationalPlanner();
+ final RuleStack rules = planner.buildRules();
+
+ PlanNode testPlan = helpExecuteRules(rules, planNode, METADATA, DEBUG);
+
+ return testPlan;
+ }
+
+ /**
+ * Simulate execution of the QueryOptimizer rules stack
+ */
+ private static PlanNode helpExecuteRules(RuleStack rules, PlanNode plan, QueryMetadataInterface metadata, boolean debug)
+ throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+ CommandContext context = new CommandContext();
+ while(! rules.isEmpty()) {
+ if(debug) {
+ System.out.println("\n============================================================================"); //$NON-NLS-1$
+ }
+ OptimizerRule rule = rules.pop();
+ if(debug) {
+ System.out.println("EXECUTING " + rule); //$NON-NLS-1$
+ }
+
+ plan = rule.execute(plan, metadata, FINDER, rules, new AnalysisRecord(false, debug), context);
+ if(debug) {
+ System.out.println("\nAFTER: \n" + plan); //$NON-NLS-1$
+ }
+ }
+ return plan;
+ }
+
+
+ // ################################## ACTUAL TESTS ################################
+
+ /**
+ * This test demonstrates that APs are ignored for inserts
+ * CASE 3966
+ */
+ @Test public void testInsertWithAccessPattern_Case3966() throws Exception {
+ this.helpTestAccessPatternValidation( "insert into pm4.g1 (e1, e2, e3, e4) values('test', 1, convert('true', boolean) , convert('12', double) )" ); //$NON-NLS-1$
+ }
+
+ /**
+ * This test demonstrates that a satisfied AP does not fail.
+ * Found testing fix for 3966.
+ */
+ @Test public void testDeleteWithAccessPattern_Case3966() throws Exception {
+ this.helpTestAccessPatternValidation( "delete from pm4.g1 where e1 = 'test' and e2 = 1" ); //$NON-NLS-1$
+ }
+
+ /**
+ * This test demonstrates that unsatisfied AP fails.
+ * Found testing fix for 3966.
+ */
+ @Test public void testDeleteWithAccessPattern_Case3966_2() throws Exception {
+ try {
+ this.helpTestAccessPatternValidation( "delete from pm4.g1" ); //$NON-NLS-1$
+ fail("Expected QueryPlannerException, but did not get one"); //$NON-NLS-1$
+ } catch (QueryPlannerException err) {
+ //This SHOULD happen.
+ final String msg = err.getMessage();
+ final String expected = "Group has an access pattern which has not been met: group(s) [pm4.g1]; access pattern(s) [Access Pattern: Unsatisfied [pm4.g1.e1] History [[pm4.g1.e1]]]"; //$NON-NLS-1$
+ assertEquals("Did not fail with expected QueryPlannerException", expected, msg); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testUpdateWithAccessPattern_Case3966() throws Exception {
+ this.helpTestAccessPatternValidation( "update pm4.g1 set e1 = 'test1' where e1 = 'test' and e2 = 1" ); //$NON-NLS-1$
+ }
+
+ /**
+ * This test demonstrates that unsatisfied AP fails.
+ * Found testing fix for 3966.
+ */
+ @Test public void testUpdateWithAccessPattern_Case3966_2() throws Exception {
+ try {
+ this.helpTestAccessPatternValidation( "update pm4.g1 set e1 = 'test'" ); //$NON-NLS-1$
+ fail("Expected QueryPlannerException, but did not get one"); //$NON-NLS-1$
+ } catch (QueryPlannerException err) {
+ //This SHOULD happen.
+ final String msg = err.getMessage();
+ final String expected = "Group has an access pattern which has not been met: group(s) [pm4.g1]; access pattern(s) [Access Pattern: Unsatisfied [pm4.g1.e1] History [[pm4.g1.e1]]]"; //$NON-NLS-1$
+ assertEquals("Did not fail with expected QueryPlannerException", expected, msg); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * This test demonstrates that APs are ignored for inserts through a virtual layer
+ * CASE 3966
+ */
+ @Test public void testInsertWithAccessPattern_Case3966_VL() throws Exception {
+ this.helpTestAccessPatternValidation( "insert into vm1.g37 (e1, e2, e3, e4) values('test', 1, convert('true', boolean) , convert('12', double) )" ); //$NON-NLS-1$
+ }
+
+ /**
+ * This test demonstrates that a satisfied AP within a Delete
+ * through a virtual layer does not fail.
+ * Found testing fix for 3966.
+ */
+ @Test public void testDeleteWithAccessPattern_Case3966_VL() throws Exception {
+ this.helpTestAccessPatternValidation( "delete from vm1.g37 where e1 = 'test' and e2 = 1" ); //$NON-NLS-1$
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAssignOutputElements.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAssignOutputElements.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAssignOutputElements.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,115 +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.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 junit.framework.*;
-
-/**
- */
-public class TestRuleAssignOutputElements extends TestCase {
-
- /**
- * 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() {
- PlanNode projNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
- PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- projNode.addLastChild(accessNode);
-
- helpTestIsUnionNoAll(projNode, false);
- }
-
- 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);
- PlanNode projNode1 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
- PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- PlanNode projNode2 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
- PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
-
- unionNode.addLastChild(projNode1);
- projNode1.addLastChild(accessNode1);
- unionNode.addLastChild(projNode2);
- projNode2.addLastChild(accessNode2);
-
- helpTestIsUnionNoAll(unionNode, false);
- }
-
- 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);
- PlanNode projNode1 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
- PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- PlanNode projNode2 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
- PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
-
- unionNode.addLastChild(projNode1);
- projNode1.addLastChild(accessNode1);
- unionNode.addLastChild(projNode2);
- projNode2.addLastChild(accessNode2);
-
- helpTestIsUnionNoAll(unionNode, true);
- }
-
- 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);
- PlanNode unionNode2 = NodeFactory.getNewNode(NodeConstants.Types.SET_OP);
- unionNode2.setProperty(NodeConstants.Info.SET_OPERATION, Operation.UNION);
- unionNode2.setProperty(NodeConstants.Info.USE_ALL, Boolean.FALSE);
- PlanNode projNode1 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
- PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- PlanNode projNode2 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
- PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- PlanNode projNode3 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
- PlanNode accessNode3 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
-
- unionNode1.addLastChild(projNode1);
- projNode1.addLastChild(accessNode1);
- unionNode1.addLastChild(unionNode2);
- unionNode2.addLastChild(projNode2);
- projNode2.addLastChild(accessNode2);
- unionNode2.addLastChild(projNode3);
- projNode3.addLastChild(accessNode3);
-
- helpTestIsUnionNoAll(unionNode1, true);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAssignOutputElements.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAssignOutputElements.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAssignOutputElements.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAssignOutputElements.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,108 @@
+/*
+ * 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.relational.rules;
+
+import static org.junit.Assert.*;
+
+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 {
+
+ 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$
+ }
+
+ @Test public void testFindNoAllUnion1() {
+ PlanNode projNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+ PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ projNode.addLastChild(accessNode);
+
+ helpTestIsUnionNoAll(projNode, false);
+ }
+
+ @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);
+ PlanNode projNode1 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+ PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ PlanNode projNode2 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+ PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+
+ unionNode.addLastChild(projNode1);
+ projNode1.addLastChild(accessNode1);
+ unionNode.addLastChild(projNode2);
+ projNode2.addLastChild(accessNode2);
+
+ helpTestIsUnionNoAll(unionNode, false);
+ }
+
+ @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);
+ PlanNode projNode1 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+ PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ PlanNode projNode2 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+ PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+
+ unionNode.addLastChild(projNode1);
+ projNode1.addLastChild(accessNode1);
+ unionNode.addLastChild(projNode2);
+ projNode2.addLastChild(accessNode2);
+
+ helpTestIsUnionNoAll(unionNode, true);
+ }
+
+ @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);
+ PlanNode unionNode2 = NodeFactory.getNewNode(NodeConstants.Types.SET_OP);
+ unionNode2.setProperty(NodeConstants.Info.SET_OPERATION, Operation.UNION);
+ unionNode2.setProperty(NodeConstants.Info.USE_ALL, Boolean.FALSE);
+ PlanNode projNode1 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+ PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ PlanNode projNode2 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+ PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ PlanNode projNode3 = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+ PlanNode accessNode3 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+
+ unionNode1.addLastChild(projNode1);
+ projNode1.addLastChild(accessNode1);
+ unionNode1.addLastChild(unionNode2);
+ unionNode2.addLastChild(projNode2);
+ projNode2.addLastChild(accessNode2);
+ unionNode2.addLastChild(projNode3);
+ projNode3.addLastChild(accessNode3);
+
+ helpTestIsUnionNoAll(unionNode1, true);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleChooseDependent.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleChooseDependent.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleChooseDependent.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1158 +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.optimizer.relational.rules;
-
-import static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-
-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.query.analysis.AnalysisRecord;
-import org.teiid.query.optimizer.TestOptimizer;
-import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
-import org.teiid.query.optimizer.relational.RuleStack;
-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.processor.relational.JoinNode.JoinStrategyType;
-import org.teiid.query.rewriter.QueryRewriter;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.From;
-import org.teiid.query.sql.lang.IsNullCriteria;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.MatchCriteria;
-import org.teiid.query.sql.lang.NotCriteria;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.lang.SetCriteria;
-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.util.CommandContext;
-
- at SuppressWarnings("unchecked")
-public class TestRuleChooseDependent {
-
- /* Make Left Side Dependent */
- private static final int LEFT_SIDE = 1;
- /* Make Right Side Dependent */
- private static final int RIGHT_SIDE = 2;
- /* Make Neither Side Dependent */
- private static final int NEITHER_SIDE = 3;
-
- private FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- // ################################## TEST HELPERS ################################
-
- public PlanNode createAccessNode(Collection groupSymbols) {
- PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- PlanNode sourceNode = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
- joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_INNER);
- List crits = new ArrayList();
- crits.add(new CompareCriteria(getElementSymbol(1,1), CompareCriteria.EQ, getElementSymbol(2,1)));
- joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, crits);
- joinNode.addFirstChild(accessNode);
- accessNode.addFirstChild(sourceNode);
- Iterator i = groupSymbols.iterator();
- while (i.hasNext()) {
- GroupSymbol gs = (GroupSymbol)i.next();
- accessNode.addGroup(gs);
- sourceNode.addGroup(gs);
- }
- return accessNode;
- }
-
- public GroupSymbol getVirtualGroup() {
- GroupSymbol gs = new GroupSymbol("vm1.g1"); //$NON-NLS-1$
- gs.setMetadataID(this.metadata.getStore().findObject("vm1.g1", FakeMetadataObject.GROUP)); //$NON-NLS-1$
- return gs;
- }
-
- public GroupSymbol getPhysicalGroup(int num) {
- String id = "pm1.g" + num; //$NON-NLS-1$
- GroupSymbol gs = new GroupSymbol(id);
- gs.setMetadataID(this.metadata.getStore().findObject(id, FakeMetadataObject.GROUP));
- return gs;
- }
-
- public GroupSymbol getPhysicalGroup(int modelNum, int num) {
- 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));
- return gs;
- }
-
- public GroupSymbol getPhysicalGroupWithAlias(int num, String alias) {
- String id = "pm1.g" + num; //$NON-NLS-1$
- GroupSymbol gs = new GroupSymbol(alias, id);
- gs.setMetadataID(this.metadata.getStore().findObject(id, FakeMetadataObject.GROUP));
- return gs;
- }
-
- public ElementSymbol getElementSymbol(int groupNum, int elementNum) {
- 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.setGroupSymbol(getPhysicalGroup(groupNum));
- return es;
- }
-
- public ElementSymbol getElementSymbol(int modelNum, int groupNum, int elementNum) {
- 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.setGroupSymbol(getPhysicalGroup(modelNum, groupNum));
- return es;
- }
-
- public ElementSymbol getElementSymbolWithGroupAlias(int groupNum, int elementNum, String alias) {
- 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.setGroupSymbol(getPhysicalGroupWithAlias(groupNum, alias));
- return es;
- }
-
- public Query createBaseQuery() {
- Query query = new Query();
-
- Select select = new Select();
- select.addSymbol(getElementSymbol(1,1));
- query.setSelect(select);
-
- From from = new From();
- from.addGroup(getPhysicalGroup(1));
- query.setFrom(from);
-
- return query;
- }
-
- public void helpTestValidJoin(PlanNode joinNode, PlanNode accessNode, boolean expectedValid) {
- RuleChooseDependent rule = new RuleChooseDependent();
- RuleChooseJoinStrategy.chooseJoinStrategy(joinNode, metadata);
- boolean isValid = rule.isValidJoin(joinNode, accessNode, AnalysisRecord.createNonRecordingRecord());
- assertEquals("Valid join check is wrong ", expectedValid, isValid); //$NON-NLS-1$
- }
-
- /**
- * Tests choosing from two eligible sibling access nodes, and then tests marking
- * the chosen one dependent. This method sets up a bogus plan tree using a
- * bogus project parent node, an inner join node using the supplied join criteria, and
- * two access nodes using each of the groups and (optional) atomic criteria. Then
- * this method tests that, if an access node is chosen, it can be marked dependent,
- * and that the chosen one is the one which was expected to be marked dependent.
- * @param atomicRequestGroup1 GroupSymbol to select * from in atomic request 1
- * @param atomicRequestCrit1 optional, may be null
- * @param atomicRequestGroup2 GroupSymbol to select * from in atomic request 2
- * @param atomicRequestCrit2 optional, may be null
- * @param joinCriteria Collection of Criteria to add to join node
- * @param expectedMadeDependent one of the three outcome possibility class constants
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- * @throws QueryPlannerException
- */
- private void helpTestChooseSiblingAndMarkDependent(GroupSymbol atomicRequestGroup1,
- Criteria atomicRequestCrit1,
- GroupSymbol atomicRequestGroup2,
- Criteria atomicRequestCrit2,
- Collection joinCriteria,
- int expectedMadeDependent) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
- helpTestChooseSiblingAndMarkDependent(atomicRequestGroup1,
- atomicRequestCrit1,
- null,
- null,
- null,
- atomicRequestGroup2,
- atomicRequestCrit2,
- null,
- null,
- null,
- joinCriteria,
- expectedMadeDependent, null, null);
- }
-
- /**
- * Tests choosing from two eligible sibling access nodes, and then tests marking
- * the chosen one dependent. This method sets up a bogus plan tree using a
- * bogus project parent node, a join node using the supplied join criteria, and
- * two access nodes using each of the groups and (optional) atomic criteria and
- * join criteria. Then
- * this method tests that, if an access node is chosen, it is marked dependent,
- * and that the chosen one is the one which was expected to be marked dependent.
- * @param atomicRequestGroup1 GroupSymbol to select from in atomic request 1
- * @param atomicRequestCrit1 optional, may be null
- * @param atomicRequestGroup1a optional, may be null
- * @param atomicRequestCrit1a optional, may be null
- * @param atomicJoinCriteria1 optional, may be null
- * @param atomicRequestGroup2 GroupSymbol to select from in atomic request 2
- * @param atomicRequestCrit2 optional, may be null
- * @param atomicRequestGroup2a optional, may be null
- * @param atomicRequestCrit2a optional, may be null
- * @param atomicJoinCriteria2 optional, may be null
- * @param joinCriteria Collection of Criteria to add to outer join node
- * @param expectedMadeDependent one of the three outcome possibility class constants
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- * @throws QueryPlannerException
- */
- private void helpTestChooseSiblingAndMarkDependent(GroupSymbol atomicRequestGroup1,
- Criteria atomicRequestCrit1, //optional
- GroupSymbol atomicRequestGroup1a, //optional
- Criteria atomicRequestCrit1a, //optional
- Collection atomicJoinCriteria1, //optional
- GroupSymbol atomicRequestGroup2,
- Criteria atomicRequestCrit2, //optional
- GroupSymbol atomicRequestGroup2a, //optional
- Criteria atomicRequestCrit2a, //optional
- Collection atomicJoinCriteria2, //optional
- Collection joinCriteria,
- int expectedMadeDependent, Number expectedCost1, Number expectedCost2) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-//EXAMPLE:
-// Project(groups=[])
-// Join(groups=[], props={21=joinCriteria, 23=true, 22=INNER JOIN})
-// Access(groups=[atomicRequestGroup1], props={...})
-// Source(groups=[atomicRequestGroup1])
-// Access(groups=[atomicRequestGroup2, atomicRequestGroup2a], props={...})
-// Join(groups=[atomicRequestGroup2, atomicRequestGroup2a], props={21=[atomicJoinCriteria2], 23=true, 22=INNER JOIN})
-// Select(groups=[atomicRequestGroup2], props={40=atomicRequestCrit2})
-// Source(groups=[atomicRequestGroup2])
-// Source(groups=[atomicRequestGroup2a])
-
- PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- accessNode1.addGroup(atomicRequestGroup1);
- if (atomicRequestGroup1a != null){
- accessNode1.addGroup(atomicRequestGroup1a);
- }
-
- PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- accessNode2.addGroup(atomicRequestGroup2);
- if (atomicRequestGroup2a != null){
- accessNode2.addGroup(atomicRequestGroup2a);
- }
-
- PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_INNER);
- joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, joinCriteria);
- joinNode.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.NESTED_LOOP);
- joinNode.addLastChild(accessNode1);
- joinNode.addLastChild(accessNode2);
-
- PlanNode bogusParentNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
- bogusParentNode.addLastChild(joinNode);
-
- //FIRST (LEFT) BRANCH OF TREE
- PlanNode sourceNode1 = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
- sourceNode1.addGroup(atomicRequestGroup1);
- if (atomicRequestCrit1 != null){
- PlanNode selectNode1 = NodeFactory.getNewNode(NodeConstants.Types.SELECT);
- selectNode1.setProperty(NodeConstants.Info.SELECT_CRITERIA, atomicRequestCrit1);
- selectNode1.addGroup(atomicRequestGroup1);
- selectNode1.addFirstChild(sourceNode1);
- if (atomicRequestGroup1a != null){
- PlanNode atomicJoinNode1 = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- if (atomicJoinCriteria1.isEmpty()){
- atomicJoinNode1.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_CROSS);
- } else {
- atomicJoinNode1.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_INNER);
- atomicJoinNode1.setProperty(NodeConstants.Info.JOIN_CRITERIA, atomicJoinCriteria1);
- }
- atomicJoinNode1.addGroup(atomicRequestGroup1);
- atomicJoinNode1.addGroup(atomicRequestGroup1a);
- atomicJoinNode1.addLastChild(selectNode1);
-
- PlanNode sourceNode1a = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
- sourceNode1a.addGroup(atomicRequestGroup1a);
- if (atomicRequestCrit1a != null){
- PlanNode selectNode1a = NodeFactory.getNewNode(NodeConstants.Types.SELECT);
- selectNode1a.setProperty(NodeConstants.Info.SELECT_CRITERIA, atomicRequestCrit1a);
- selectNode1a.addGroup(atomicRequestGroup1a);
- selectNode1a.addFirstChild(sourceNode1a);
- atomicJoinNode1.addLastChild(selectNode1a);
- } else {
- atomicJoinNode1.addLastChild(sourceNode1a);
- }
- accessNode1.addLastChild(atomicJoinNode1);
- } else {
- accessNode1.addFirstChild(selectNode1);
- }
- } else {
- accessNode1.addFirstChild(sourceNode1);
- }
-
- //SECOND (RIGHT) BRANCH OF TREE
- PlanNode sourceNode2 = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
- sourceNode2.addGroup(atomicRequestGroup2);
- if (atomicRequestCrit2 != null){
- PlanNode selectNode2 = NodeFactory.getNewNode(NodeConstants.Types.SELECT);
- selectNode2.setProperty(NodeConstants.Info.SELECT_CRITERIA, atomicRequestCrit2);
- selectNode2.addGroup(atomicRequestGroup2);
- selectNode2.addFirstChild(sourceNode2);
- if (atomicRequestGroup2a != null){
- PlanNode atomicJoinNode2 = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- if (atomicJoinCriteria2.isEmpty()){
- atomicJoinNode2.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_CROSS);
- } else {
- atomicJoinNode2.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_INNER);
- atomicJoinNode2.setProperty(NodeConstants.Info.JOIN_CRITERIA, atomicJoinCriteria2);
- }
- atomicJoinNode2.addGroup(atomicRequestGroup2);
- atomicJoinNode2.addGroup(atomicRequestGroup2a);
- atomicJoinNode2.addLastChild(selectNode2);
-
- PlanNode sourceNode2a = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
- sourceNode2a.addGroup(atomicRequestGroup2a);
- if (atomicRequestCrit2a != null){
- PlanNode selectNode2a = NodeFactory.getNewNode(NodeConstants.Types.SELECT);
- selectNode2a.setProperty(NodeConstants.Info.SELECT_CRITERIA, atomicRequestCrit2a);
- selectNode2a.addGroup(atomicRequestGroup2a);
- selectNode2a.addFirstChild(sourceNode2a);
- atomicJoinNode2.addLastChild(selectNode2a);
- } else {
- atomicJoinNode2.addLastChild(sourceNode2a);
- }
- accessNode2.addLastChild(atomicJoinNode2);
- } else {
- accessNode2.addFirstChild(selectNode2);
- }
- } else {
- accessNode2.addFirstChild(sourceNode2);
- }
-
- //Add access pattern(s)
- RulePlaceAccess.addAccessPatternsProperty(accessNode1, metadata);
- RulePlaceAccess.addAccessPatternsProperty(accessNode2, metadata);
-
- if (DEBUG){
- System.out.println("Before."); //$NON-NLS-1$
- System.out.println(bogusParentNode);
- }
-
- RuleChooseDependent rule = new RuleChooseDependent();
- RuleChooseJoinStrategy.chooseJoinStrategy(joinNode, metadata);
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- capFinder.addCapabilities("pm1", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
- capFinder.addCapabilities("pm2", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
- capFinder.addCapabilities("pm3", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
- capFinder.addCapabilities("pm4", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
-
- rule.execute(bogusParentNode, metadata, capFinder, new RuleStack(), null, new CommandContext());
-
- if (DEBUG){
- System.out.println("Done."); //$NON-NLS-1$
- System.out.println(bogusParentNode);
- }
-
- Object prop1 = joinNode.getProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE);
-
- if (expectedMadeDependent == LEFT_SIDE){
- assertNotNull("Expected one side to be made dependent", prop1); //$NON-NLS-1$
- assertEquals(accessNode1, FrameUtil.findJoinSourceNode(joinNode.getLastChild()));
- } else if (expectedMadeDependent == RIGHT_SIDE){
- assertNotNull("Expected one side to be made dependent", prop1); //$NON-NLS-1$
- assertEquals(accessNode2, FrameUtil.findJoinSourceNode(joinNode.getLastChild()));
- } else if (expectedMadeDependent == NEITHER_SIDE){
- assertNull("Neither side should be dependent", prop1); //$NON-NLS-1$
- } else {
- fail("Invalid test constant " + expectedMadeDependent); //$NON-NLS-1$
- }
-
- Float cost1 = (Float)accessNode1.getProperty(NodeConstants.Info.EST_CARDINALITY);
- Float cost2 = (Float)accessNode2.getProperty(NodeConstants.Info.EST_CARDINALITY);
- assertNotNull(cost2);
- assertNotNull(cost1);
- if (expectedCost1 != null) {
- assertEquals(expectedCost1.longValue(), cost1.longValue());
- assertEquals(expectedCost2.longValue(), cost2.longValue());
- }
- }
-
- // ################################## ACTUAL TESTS ################################
-
- @Test public void testValidJoin1() {
- PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- accessNode.addGroup(getPhysicalGroup(1));
-
- PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_CROSS);
- joinNode.addFirstChild(accessNode);
-
- helpTestValidJoin(joinNode, accessNode, false);
- }
-
- @Test public void testValidJoin2() {
- PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- accessNode.addGroup(getPhysicalGroup(1));
-
- PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_FULL_OUTER);
- joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, Arrays.asList(QueryRewriter.FALSE_CRITERIA));
- joinNode.addFirstChild(accessNode);
-
- helpTestValidJoin(joinNode, accessNode, false);
- }
-
- @Test public void testValidJoin3() {
- PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- accessNode1.addGroup(getPhysicalGroup(1));
- accessNode2.addGroup(getPhysicalGroup(2));
-
- PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_RIGHT_OUTER);
- List crits = new ArrayList();
- crits.add(new CompareCriteria(getElementSymbol(1,1), CompareCriteria.EQ, getElementSymbol(2,1)));
- joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, crits);
- joinNode.addLastChild(accessNode1);
- joinNode.addLastChild(accessNode2);
-
- helpTestValidJoin(joinNode, accessNode1, true);
- }
-
- @Test public void testValidJoin4() {
- PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
-
- PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_RIGHT_OUTER);
- List crits = new ArrayList();
- crits.add(new CompareCriteria(getElementSymbol(1,1), CompareCriteria.EQ, getElementSymbol(2,1)));
- joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, crits);
- joinNode.addLastChild(accessNode1);
- joinNode.addLastChild(accessNode2);
-
- helpTestValidJoin(joinNode, accessNode2, false);
- }
-
- @Test public void testValidJoin5() {
- PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
-
- PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_LEFT_OUTER);
- List crits = new ArrayList();
- crits.add(new CompareCriteria(getElementSymbol(1,1), CompareCriteria.EQ, getElementSymbol(2,1)));
- joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, crits);
- joinNode.addLastChild(accessNode1);
- joinNode.addLastChild(accessNode2);
-
- helpTestValidJoin(joinNode, accessNode1, false);
- }
-
- @Test public void testValidJoin6() {
- PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- accessNode1.addGroup(getPhysicalGroup(1));
- accessNode2.addGroup(getPhysicalGroup(2));
-
- PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
- joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_LEFT_OUTER);
- List crits = new ArrayList();
- crits.add(new CompareCriteria(getElementSymbol(1,1), CompareCriteria.EQ, getElementSymbol(2,1)));
- joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, crits);
- joinNode.addLastChild(accessNode1);
- joinNode.addLastChild(accessNode2);
-
- helpTestValidJoin(joinNode, accessNode2, true);
- }
-
- /**
- * Tests that heuristics will take a primary key in the atomic criteria into account when
- * making a dependent join.
- */
- @Test public void testChooseKey() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(2,3);
- GroupSymbol group2 = getPhysicalGroup(3,3);
-
- //Join criteria
- ElementSymbol group1e1 = getElementSymbol(2,3,1);
- ElementSymbol group2e1 = getElementSymbol(3,3,1);
- CompareCriteria crit = new CompareCriteria(group2e1, CompareCriteria.EQ, group1e1);
- ArrayList crits = new ArrayList(1);
- crits.add(crit);
-
- Criteria atomicCrit1 = null;
- Criteria atomicCrit2 = new CompareCriteria(group2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
- int expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- /**
- * Neither side should be chosen since the left side lacks cardinality information and the right is not strong
- */
- @Test public void testChooseKey2() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(2,3); //no key
- GroupSymbol group1a = null;
- GroupSymbol group2 = getPhysicalGroup(3,3); //has key
- GroupSymbol group2a = getPhysicalGroup(3,2); //no key
-
- ElementSymbol group1e1 = getElementSymbol(2,3,1);
- ElementSymbol group2e1 = getElementSymbol(3,3,1);
- ElementSymbol group2e2 = getElementSymbol(3,3,2);
- ElementSymbol group2ae1 = getElementSymbol(3,2,1);
-
- //Outer Join criteria
- CompareCriteria crit = new CompareCriteria(group2e1, CompareCriteria.EQ, group1e1);
- ArrayList crits = new ArrayList(1);
- crits.add(crit);
-
- //atomic select criteria
- Criteria atomicCrit1 = null;
- Criteria atomicCrit1a = null;
- Criteria atomicCrit2 = new CompareCriteria(group2e2, CompareCriteria.EQ, new Constant(new Integer(5)));
- Criteria atomicCrit2a = null;
-
- //atomic Join criteria 1
- Collection atomicJoinCrits1 = null;
-
- //atomic Join criteria 2
- CompareCriteria atomicJoinCrit2 = new CompareCriteria(group2ae1, CompareCriteria.EQ, group2e1);
- ArrayList atomicJoinCrits2 = new ArrayList(1);
- atomicJoinCrits2.add(atomicJoinCrit2);
-
- int expected = NEITHER_SIDE;
-
- helpTestChooseSiblingAndMarkDependent(
- group1,
- atomicCrit1,
- group1a,
- atomicCrit1a,
- atomicJoinCrits1,
- group2,
- atomicCrit2,
- group2a,
- atomicCrit2a,
- atomicJoinCrits2,
- crits,
- expected, -1, 7930);
- }
-
- /**
- * Tests that heuristics will take cardinality of a group into account when
- * making a dependent join.
- */
- @Test public void testCardinality() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- GroupSymbol group2 = getPhysicalGroup(2,2);
-
- //Join criteria
- ElementSymbol pm1g2e1 = getElementSymbol(1,2,1);
- ElementSymbol pm2g2e1 = getElementSymbol(2,2,1);
- CompareCriteria crit = new CompareCriteria(pm2g2e1, CompareCriteria.EQ, pm1g2e1);
- ArrayList crits = new ArrayList(2);
- crits.add(crit);
- ElementSymbol pm1g2e2 = getElementSymbol(1,2,2);
- ElementSymbol pm2g2e2 = getElementSymbol(2,2,2);
- CompareCriteria crit2 = new CompareCriteria(pm1g2e2, CompareCriteria.EQ, pm2g2e2);
- crits.add(crit2);
-
- Criteria atomicCrit1 = null;
- Criteria atomicCrit2 = null;
- int expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- /**
- * Tests that heuristics will take cardinality of a group into account when
- * making a dependent join, and that this information supercedes a key
- * in the atomic criteria.
- */
- @Test public void testCardinalityAndKey() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- GroupSymbol group2 = getPhysicalGroup(2,2);
-
- //Join criteria
- ElementSymbol pm1g2e1 = getElementSymbol(1,2,1);
- ElementSymbol pm2g2e1 = getElementSymbol(2,2,1);
- CompareCriteria crit = new CompareCriteria(pm2g2e1, CompareCriteria.EQ, pm1g2e1);
- ArrayList crits = new ArrayList(1);
- crits.add(crit);
- ElementSymbol pm1g2e2 = getElementSymbol(1,2,2);
- ElementSymbol pm2g2e2 = getElementSymbol(2,2,2);
- CompareCriteria crit2 = new CompareCriteria(pm1g2e2, CompareCriteria.EQ, pm2g2e2);
- crits.add(crit2);
-
- Criteria atomicCrit1 = null;
- Criteria atomicCrit2 = null;
- int expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- @Test public void testCardinalityAndKeyNestedLoop() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- GroupSymbol group2 = getPhysicalGroup(2,2);
-
- //Join criteria
- ElementSymbol pm1g2e1 = getElementSymbol(1,2,1);
- ElementSymbol pm2g2e1 = getElementSymbol(2,2,1);
- CompareCriteria crit = new CompareCriteria(pm2g2e1, CompareCriteria.EQ, pm1g2e1);
- ArrayList crits = new ArrayList(1);
- crits.add(crit);
- ElementSymbol pm1g2e2 = getElementSymbol(1,2,2);
- ElementSymbol pm2g2e2 = getElementSymbol(2,2,2);
- CompareCriteria crit2 = new CompareCriteria(pm1g2e2, CompareCriteria.LT, pm2g2e2);
- crits.add(crit2);
-
- Criteria atomicCrit1 = null;
- Criteria atomicCrit2 = null;
- int expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- @Test public void testRejectDependentJoin() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(3,1);
- GroupSymbol group2 = getPhysicalGroup(3,2);
-
- //Join criteria
- ElementSymbol pm3g1e2 = getElementSymbol(3,1,2);
- ElementSymbol pm3g2e2 = getElementSymbol(3,2,2);
- CompareCriteria crit = new CompareCriteria(pm3g1e2, CompareCriteria.EQ, pm3g2e2);
- ArrayList crits = new ArrayList(1);
- crits.add(crit);
-
- Criteria atomicCrit1 = null;
- Criteria atomicCrit2 = null;
- int expected = NEITHER_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = NEITHER_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- /**
- * Tests that join side with larger cardinality will still have a lower
- * cost computed because it has a criteria including a primary key
- */
- @Test public void testCardinalityWithKeyCrit() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- ElementSymbol g1e2 = getElementSymbol(1,2,2);
-
- GroupSymbol group2 = getPhysicalGroup(3,3);
- ElementSymbol g2e1 = getElementSymbol(3,3,1);
- ElementSymbol g2e2 = getElementSymbol(3,3,2);
-
- //Join criteria
- ArrayList crits = new ArrayList(1);
- CompareCriteria crit2 = new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2);
- crits.add(crit2);
-
- Criteria atomicCrit1 = null;
- Criteria atomicCrit2 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
- int expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- /**
- * Tests that join side with larger cardinality will still have a lower
- * cost computed because it has a criteria including a primary key
- */
- @Test public void testCardinalityWithKeyCompoundCritAND() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- ElementSymbol g1e2 = getElementSymbol(1,2,2);
-
- GroupSymbol group2 = getPhysicalGroup(3,3);
- ElementSymbol g2e1 = getElementSymbol(3,3,1);
- ElementSymbol g2e2 = getElementSymbol(3,3,2);
-
- //Join criteria
- ArrayList crits = new ArrayList(1);
- crits.add(new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2));
-
- Criteria atomicCrit1 = null;
-
- Criteria crit1 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
- Criteria crit2 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(7)));
- CompoundCriteria atomicCrit2 = new CompoundCriteria(CompoundCriteria.AND, crit1, crit2);
-
- int expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- /**
- * Tests that join side with larger cardinality will still have a lower
- * cost computed because it has a criteria including a primary key.
- * Defect 8445
- */
- @Test public void testCardinalityWithKeyCompoundCritOR() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- ElementSymbol g1e2 = getElementSymbol(1,2,2);
-
- GroupSymbol group2 = getPhysicalGroup(3,3);
- ElementSymbol g2e1 = getElementSymbol(3,3,1);
- ElementSymbol g2e2 = getElementSymbol(3,3,2);
-
- //Join criteria
- ArrayList crits = new ArrayList(1);
- crits.add(new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2));
-
- Criteria atomicCrit1 = null;
-
- Criteria crit1 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
- Criteria crit2 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(7)));
- CompoundCriteria atomicCrit2 = new CompoundCriteria(CompoundCriteria.OR, crit1, crit2);
-
- int expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- /**
- * Tests SetCriteria against a key column in the atomic criteria
- */
- @Test public void testCardinalityWithKeySetCrit() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- ElementSymbol g1e2 = getElementSymbol(1,2,2);
-
- GroupSymbol group2 = getPhysicalGroup(3,3);
- ElementSymbol g2e1 = getElementSymbol(3,3,1);
- ElementSymbol g2e2 = getElementSymbol(3,3,2);
-
- //Join criteria
- ArrayList crits = new ArrayList(1);
- CompareCriteria crit2 = new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2);
- crits.add(crit2);
-
- Criteria atomicCrit1 = null;
- Collection values = new LinkedList();
- values.add(new Constant(new Integer(3)));
- values.add(new Constant(new Integer(4)));
- values.add(new Constant(new Integer(5)));
- Criteria atomicCrit2 = new SetCriteria(g2e1, values);
- int expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- /**
- * Tests SetCriteria in the atomic criteria
- */
- @Test public void testCardinalityWithKeyMatchCrit() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- ElementSymbol g1e2 = getElementSymbol(1,2,2);
-
- GroupSymbol group2 = getPhysicalGroup(3,3);
- ElementSymbol g2e1 = getElementSymbol(3,3,1);
- ElementSymbol g2e2 = getElementSymbol(3,3,2);
-
- //Join criteria
- ArrayList crits = new ArrayList(1);
- CompareCriteria crit2 = new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2);
- crits.add(crit2);
-
- Criteria atomicCrit1 = null;
- Criteria atomicCrit2 = new MatchCriteria(g2e1, new Constant(new String("ab%"))); //$NON-NLS-1$
- int expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- /**
- * Tests SetCriteria in the atomic criteria
- */
- @Test public void testCardinalityWithKeyIsNullCrit() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- ElementSymbol g1e2 = getElementSymbol(1,2,2);
-
- GroupSymbol group2 = getPhysicalGroup(3,3);
- ElementSymbol g2e1 = getElementSymbol(3,3,1);
- ElementSymbol g2e2 = getElementSymbol(3,3,2);
-
- //Join criteria
- ArrayList crits = new ArrayList(1);
- CompareCriteria crit2 = new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2);
- crits.add(crit2);
-
- Criteria atomicCrit1 = null;
- Criteria atomicCrit2 = new IsNullCriteria(g2e1);
- int expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- /**
- * Tests NotCriteria in the atomic criteria
- */
- @Test public void testCardinalityWithKeyNotCrit() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- ElementSymbol g1e2 = getElementSymbol(1,2,2);
-
- GroupSymbol group2 = getPhysicalGroup(3,3);
- ElementSymbol g2e1 = getElementSymbol(3,3,1);
- ElementSymbol g2e2 = getElementSymbol(3,3,2);
-
- //Join criteria
- ArrayList crits = new ArrayList(1);
- CompareCriteria crit2 = new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2);
- crits.add(crit2);
-
- Criteria atomicCrit1 = null;
- Criteria atomicCrit2 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
- atomicCrit2 = new NotCriteria(atomicCrit2);
- int expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- /**
- * Tests that join side with larger cardinality will still have a lower
- * cost computed because it has a criteria including a primary key
- */
- @Test public void testCardinalityWithKeyComplexCrit() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- ElementSymbol g1e2 = getElementSymbol(1,2,2);
-
- GroupSymbol group2 = getPhysicalGroup(3,3);
- ElementSymbol g2e1 = getElementSymbol(3,3,1);
- ElementSymbol g2e2 = getElementSymbol(3,3,2);
-
- //Join criteria
- ArrayList crits = new ArrayList(1);
- crits.add(new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2));
-
- Criteria atomicCrit1 = null;
-
- Criteria crit1 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
- Criteria crit2 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(7)));
- CompoundCriteria atomicCrit2 = new CompoundCriteria(CompoundCriteria.AND, crit1, crit2);
- Criteria crit3 = new MatchCriteria(g2e1, new Constant(new String("ab"))); //$NON-NLS-1$
- atomicCrit2 = new CompoundCriteria(CompoundCriteria.OR, atomicCrit2, crit3);
-
- int expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- @Test public void testCardinalityWithKeyComplexCrit2() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- ElementSymbol g1e2 = getElementSymbol(1,2,2);
-
- GroupSymbol group2 = getPhysicalGroup(3,3);
- ElementSymbol g2e1 = getElementSymbol(3,3,1);
- ElementSymbol g2e2 = getElementSymbol(3,3,2);
-
- //Join criteria
- ArrayList crits = new ArrayList(1);
- crits.add(new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2));
-
- Criteria atomicCrit1 = null;
-
- Criteria crit1 = new CompareCriteria(g2e1, CompareCriteria.GT, new Constant(new Integer(5)));
- Criteria crit2 = new CompareCriteria(g2e1, CompareCriteria.LT, new Constant(new Integer(7)));
- Criteria atomicCrit2 = new CompoundCriteria(CompoundCriteria.AND, crit1, crit2);
- Criteria crit3 = new MatchCriteria(g2e1, new Constant(new String("cd%"))); //$NON-NLS-1$
- atomicCrit2 = new CompoundCriteria(CompoundCriteria.OR, atomicCrit2, crit3);
- atomicCrit2 = new NotCriteria(atomicCrit2);
-
- int expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- @Test public void testCardinalityWithKeyComplexCrit3() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- ElementSymbol g1e2 = getElementSymbol(1,2,2);
-
- GroupSymbol group2 = getPhysicalGroup(3,3);
- ElementSymbol g2e1 = getElementSymbol(3,3,1);
- ElementSymbol g2e2 = getElementSymbol(3,3,2);
-
- //Join criteria
- ArrayList crits = new ArrayList(1);
- crits.add(new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2));
-
- Criteria atomicCrit1 = null;
-
- Criteria crit1 = new CompareCriteria(g2e1, CompareCriteria.GE, new Constant(new Integer(5)));
- Criteria crit2 = new CompareCriteria(g2e1, CompareCriteria.NE, new Constant(new Integer(7)));
- Criteria atomicCrit2 = new CompoundCriteria(CompoundCriteria.OR, crit1, crit2);
- atomicCrit2 = new NotCriteria(atomicCrit2);
- Criteria crit3 = new CompareCriteria(g2e1, CompareCriteria.LE, new Constant(new Integer(25)));
- atomicCrit2 = new CompoundCriteria(CompoundCriteria.AND, atomicCrit2, crit3);
-
- int expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- /**
- * Tests that join side with larger cardinality and non-key criteria
- * will be made dependent
- */
- @Test public void testCardinalityWithNonKeyCrit() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(1,2);
- ElementSymbol g1e1 = getElementSymbol(1,2,1);
-// ElementSymbol g1e2 = getElementSymbol(1,2,2);
-
- GroupSymbol group2 = getPhysicalGroup(3,3);
- ElementSymbol g2e1 = getElementSymbol(3,3,1);
- ElementSymbol g2e2 = getElementSymbol(3,3,2);
-
- //Join criteria
- ArrayList crits = new ArrayList(1);
- CompareCriteria crit2 = new CompareCriteria(g1e1, CompareCriteria.EQ, g2e1);
- crits.add(crit2);
-
- Criteria atomicCrit1 = null;
- Criteria atomicCrit2 = new CompareCriteria(g2e2, CompareCriteria.EQ, new Constant(new Integer(5)));
- int expected = RIGHT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
- expected = LEFT_SIDE;
- helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
- }
-
- /**
- * Tests that join side with larger cardinality will still have a lower
- * cost computed because it has a criteria including a primary key
- */
- @Test public void testCardinalityWithCriteriaAndJoin() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(2,2); //no key
- GroupSymbol group1a = null;
- GroupSymbol group2 = getPhysicalGroup(3,3); //has key
- GroupSymbol group2a = getPhysicalGroup(3,1); //has key
-
- ElementSymbol group1e1 = getElementSymbol(2,2,1);
- ElementSymbol group2e1 = getElementSymbol(3,3,1);
- ElementSymbol group2e2 = getElementSymbol(3,3,2);
- ElementSymbol group2ae1 = getElementSymbol(3,1,1);
- ElementSymbol group2ae2 = getElementSymbol(3,1,2);
-
- //Outer Join criteria
- CompareCriteria crit = new CompareCriteria(group2e1, CompareCriteria.EQ, group1e1);
- ArrayList crits = new ArrayList(1);
- crits.add(crit);
-
- //atomic select criteria
- Criteria atomicCrit1 = null;
- Criteria atomicCrit1a = null;
- Criteria atomicCrit2 = new CompareCriteria(group2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
- Criteria atomicCrit2a = new CompareCriteria(group2ae1, CompareCriteria.EQ, new Constant(new Integer(5)));
-
- //atomic Join criteria 1
- Collection atomicJoinCrits1 = null;
-
- //atomic Join criteria 2
- CompareCriteria atomicJoinCrit2 = new CompareCriteria(group2ae2, CompareCriteria.EQ, group2e2);
- ArrayList atomicJoinCrits2 = new ArrayList(1);
- atomicJoinCrits2.add(atomicJoinCrit2);
-
- int expected = LEFT_SIDE;
-
- helpTestChooseSiblingAndMarkDependent(
- group1,
- atomicCrit1,
- group1a,
- atomicCrit1a,
- atomicJoinCrits1,
- group2,
- atomicCrit2,
- group2a,
- atomicCrit2a,
- atomicJoinCrits2,
- crits,
- expected, 1000, 1);
- }
-
- @Test public void testCardinalityWithAtomicCrossJoin() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(2,2); //no key
- GroupSymbol group1a = null;
- GroupSymbol group2 = getPhysicalGroup(3,3); //has key
- GroupSymbol group2a = getPhysicalGroup(3,1); //has key
-
- ElementSymbol group1e1 = getElementSymbol(2,2,1);
- ElementSymbol group2e1 = getElementSymbol(3,3,1);
-
- //Outer Join criteria
- CompareCriteria crit = new CompareCriteria(group2e1, CompareCriteria.EQ, group1e1);
- ArrayList crits = new ArrayList(1);
- crits.add(crit);
-
- //atomic select criteria
- Criteria atomicCrit1 = null;
- Criteria atomicCrit1a = null;
- Criteria atomicCrit2 = new CompareCriteria(group2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
- Criteria atomicCrit2a = null;
-
- //atomic Join criteria 1
- Collection atomicJoinCrits1 = null;
-
- //atomic Join criteria 2
- List atomicJoinCrits2 = Collections.EMPTY_LIST; //INDICATES CROSS JOIN
-
- int expected = NEITHER_SIDE;
-
- helpTestChooseSiblingAndMarkDependent(
- group1,
- atomicCrit1,
- group1a,
- atomicCrit1a,
- atomicJoinCrits1,
- group2,
- atomicCrit2,
- group2a,
- atomicCrit2a,
- atomicJoinCrits2,
- crits,
- expected, 1000, 1E5);
- }
-
- @Test public void testCardinalityWithAtomicCrossJoin2() throws Exception {
- //override default metadata
- this.metadata = FakeMetadataFactory.example4();
-
- GroupSymbol group1 = getPhysicalGroup(2,2); //no key
- GroupSymbol group1a = null;
- GroupSymbol group2 = getPhysicalGroup(3,3); //has key
- GroupSymbol group2a = getPhysicalGroup(3,1); //has key
-
- ElementSymbol group1e1 = getElementSymbol(2,2,1);
- ElementSymbol group2e1 = getElementSymbol(3,3,1);
-
- //Outer Join criteria
- CompareCriteria crit = new CompareCriteria(group2e1, CompareCriteria.EQ, group1e1);
- ArrayList crits = new ArrayList(1);
- crits.add(crit);
-
- //atomic select criteria
- Criteria atomicCrit1 = null;
- Criteria atomicCrit1a = null;
- Criteria atomicCrit2 = new CompareCriteria(group2e1, CompareCriteria.NE, new Constant(new Integer(5)));
- Criteria atomicCrit2a = null;
-
- //atomic Join criteria 1
- Collection atomicJoinCrits1 = null;
-
- //atomic Join criteria 2
- List atomicJoinCrits2 = Collections.EMPTY_LIST; //INDICATES CROSS JOIN
-
- int expected = RIGHT_SIDE;
-
- helpTestChooseSiblingAndMarkDependent(
- group1,
- atomicCrit1,
- group1a,
- atomicCrit1a,
- atomicJoinCrits1,
- group2,
- atomicCrit2,
- group2a,
- atomicCrit2a,
- atomicJoinCrits2,
- crits,
- expected, 1000, 9999899648l);
- }
-
- // ################################## TEST SUITE ################################
-
- private static final boolean DEBUG = false;
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleChooseDependent.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleChooseDependent.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleChooseDependent.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleChooseDependent.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1158 @@
+/*
+ * 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.relational.rules;
+
+import static org.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+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.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;
+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.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;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.From;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.lang.MatchCriteria;
+import org.teiid.query.sql.lang.NotCriteria;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.SetCriteria;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+ at SuppressWarnings("unchecked")
+public class TestRuleChooseDependent {
+
+ /* Make Left Side Dependent */
+ private static final int LEFT_SIDE = 1;
+ /* Make Right Side Dependent */
+ private static final int RIGHT_SIDE = 2;
+ /* Make Neither Side Dependent */
+ private static final int NEITHER_SIDE = 3;
+
+ private QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ // ################################## TEST HELPERS ################################
+
+ 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);
+ joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_INNER);
+ List crits = new ArrayList();
+ crits.add(new CompareCriteria(getElementSymbol(1,1), CompareCriteria.EQ, getElementSymbol(2,1)));
+ joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, crits);
+ joinNode.addFirstChild(accessNode);
+ accessNode.addFirstChild(sourceNode);
+ Iterator i = groupSymbols.iterator();
+ while (i.hasNext()) {
+ GroupSymbol gs = (GroupSymbol)i.next();
+ accessNode.addGroup(gs);
+ sourceNode.addGroup(gs);
+ }
+ return accessNode;
+ }
+
+ public GroupSymbol getVirtualGroup() throws Exception {
+ GroupSymbol gs = new GroupSymbol("vm1.g1"); //$NON-NLS-1$
+ ResolverUtil.resolveGroup(gs, metadata);
+ return gs;
+ }
+
+ public GroupSymbol getPhysicalGroup(int num) throws Exception {
+ String id = "pm1.g" + num; //$NON-NLS-1$
+ GroupSymbol gs = new GroupSymbol(id);
+ ResolverUtil.resolveGroup(gs, metadata);
+ return gs;
+ }
+
+ 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);
+ ResolverUtil.resolveGroup(gs, metadata);
+ return gs;
+ }
+
+ public GroupSymbol getPhysicalGroupWithAlias(int num, String alias) throws Exception {
+ String id = "pm1.g" + num; //$NON-NLS-1$
+ GroupSymbol gs = new GroupSymbol(alias, id);
+ ResolverUtil.resolveGroup(gs, metadata);
+ return gs;
+ }
+
+ 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.getElementID(id));
+ es.setGroupSymbol(getPhysicalGroup(groupNum));
+ return es;
+ }
+
+ 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.getElementID(id));
+ es.setGroupSymbol(getPhysicalGroup(modelNum, groupNum));
+ return es;
+ }
+
+ 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.getElementID(id));
+ es.setGroupSymbol(getPhysicalGroupWithAlias(groupNum, alias));
+ return es;
+ }
+
+ public Query createBaseQuery() throws Exception {
+ Query query = new Query();
+
+ Select select = new Select();
+ select.addSymbol(getElementSymbol(1,1));
+ query.setSelect(select);
+
+ From from = new From();
+ from.addGroup(getPhysicalGroup(1));
+ query.setFrom(from);
+
+ return query;
+ }
+
+ public void helpTestValidJoin(PlanNode joinNode, PlanNode accessNode, boolean expectedValid) {
+ RuleChooseDependent rule = new RuleChooseDependent();
+ RuleChooseJoinStrategy.chooseJoinStrategy(joinNode, metadata);
+ boolean isValid = rule.isValidJoin(joinNode, accessNode, AnalysisRecord.createNonRecordingRecord());
+ assertEquals("Valid join check is wrong ", expectedValid, isValid); //$NON-NLS-1$
+ }
+
+ /**
+ * Tests choosing from two eligible sibling access nodes, and then tests marking
+ * the chosen one dependent. This method sets up a bogus plan tree using a
+ * bogus project parent node, an inner join node using the supplied join criteria, and
+ * two access nodes using each of the groups and (optional) atomic criteria. Then
+ * this method tests that, if an access node is chosen, it can be marked dependent,
+ * and that the chosen one is the one which was expected to be marked dependent.
+ * @param atomicRequestGroup1 GroupSymbol to select * from in atomic request 1
+ * @param atomicRequestCrit1 optional, may be null
+ * @param atomicRequestGroup2 GroupSymbol to select * from in atomic request 2
+ * @param atomicRequestCrit2 optional, may be null
+ * @param joinCriteria Collection of Criteria to add to join node
+ * @param expectedMadeDependent one of the three outcome possibility class constants
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ * @throws QueryPlannerException
+ */
+ private void helpTestChooseSiblingAndMarkDependent(GroupSymbol atomicRequestGroup1,
+ Criteria atomicRequestCrit1,
+ GroupSymbol atomicRequestGroup2,
+ Criteria atomicRequestCrit2,
+ Collection joinCriteria,
+ int expectedMadeDependent) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+ helpTestChooseSiblingAndMarkDependent(atomicRequestGroup1,
+ atomicRequestCrit1,
+ null,
+ null,
+ null,
+ atomicRequestGroup2,
+ atomicRequestCrit2,
+ null,
+ null,
+ null,
+ joinCriteria,
+ expectedMadeDependent, null, null);
+ }
+
+ /**
+ * Tests choosing from two eligible sibling access nodes, and then tests marking
+ * the chosen one dependent. This method sets up a bogus plan tree using a
+ * bogus project parent node, a join node using the supplied join criteria, and
+ * two access nodes using each of the groups and (optional) atomic criteria and
+ * join criteria. Then
+ * this method tests that, if an access node is chosen, it is marked dependent,
+ * and that the chosen one is the one which was expected to be marked dependent.
+ * @param atomicRequestGroup1 GroupSymbol to select from in atomic request 1
+ * @param atomicRequestCrit1 optional, may be null
+ * @param atomicRequestGroup1a optional, may be null
+ * @param atomicRequestCrit1a optional, may be null
+ * @param atomicJoinCriteria1 optional, may be null
+ * @param atomicRequestGroup2 GroupSymbol to select from in atomic request 2
+ * @param atomicRequestCrit2 optional, may be null
+ * @param atomicRequestGroup2a optional, may be null
+ * @param atomicRequestCrit2a optional, may be null
+ * @param atomicJoinCriteria2 optional, may be null
+ * @param joinCriteria Collection of Criteria to add to outer join node
+ * @param expectedMadeDependent one of the three outcome possibility class constants
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ * @throws QueryPlannerException
+ */
+ private void helpTestChooseSiblingAndMarkDependent(GroupSymbol atomicRequestGroup1,
+ Criteria atomicRequestCrit1, //optional
+ GroupSymbol atomicRequestGroup1a, //optional
+ Criteria atomicRequestCrit1a, //optional
+ Collection atomicJoinCriteria1, //optional
+ GroupSymbol atomicRequestGroup2,
+ Criteria atomicRequestCrit2, //optional
+ GroupSymbol atomicRequestGroup2a, //optional
+ Criteria atomicRequestCrit2a, //optional
+ Collection atomicJoinCriteria2, //optional
+ Collection joinCriteria,
+ int expectedMadeDependent, Number expectedCost1, Number expectedCost2) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+//EXAMPLE:
+// Project(groups=[])
+// Join(groups=[], props={21=joinCriteria, 23=true, 22=INNER JOIN})
+// Access(groups=[atomicRequestGroup1], props={...})
+// Source(groups=[atomicRequestGroup1])
+// Access(groups=[atomicRequestGroup2, atomicRequestGroup2a], props={...})
+// Join(groups=[atomicRequestGroup2, atomicRequestGroup2a], props={21=[atomicJoinCriteria2], 23=true, 22=INNER JOIN})
+// Select(groups=[atomicRequestGroup2], props={40=atomicRequestCrit2})
+// Source(groups=[atomicRequestGroup2])
+// Source(groups=[atomicRequestGroup2a])
+
+ PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ accessNode1.addGroup(atomicRequestGroup1);
+ if (atomicRequestGroup1a != null){
+ accessNode1.addGroup(atomicRequestGroup1a);
+ }
+
+ PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ accessNode2.addGroup(atomicRequestGroup2);
+ if (atomicRequestGroup2a != null){
+ accessNode2.addGroup(atomicRequestGroup2a);
+ }
+
+ PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+ joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_INNER);
+ joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, joinCriteria);
+ joinNode.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.NESTED_LOOP);
+ joinNode.addLastChild(accessNode1);
+ joinNode.addLastChild(accessNode2);
+
+ PlanNode bogusParentNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+ bogusParentNode.addLastChild(joinNode);
+
+ //FIRST (LEFT) BRANCH OF TREE
+ PlanNode sourceNode1 = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+ sourceNode1.addGroup(atomicRequestGroup1);
+ if (atomicRequestCrit1 != null){
+ PlanNode selectNode1 = NodeFactory.getNewNode(NodeConstants.Types.SELECT);
+ selectNode1.setProperty(NodeConstants.Info.SELECT_CRITERIA, atomicRequestCrit1);
+ selectNode1.addGroup(atomicRequestGroup1);
+ selectNode1.addFirstChild(sourceNode1);
+ if (atomicRequestGroup1a != null){
+ PlanNode atomicJoinNode1 = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+ if (atomicJoinCriteria1.isEmpty()){
+ atomicJoinNode1.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_CROSS);
+ } else {
+ atomicJoinNode1.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_INNER);
+ atomicJoinNode1.setProperty(NodeConstants.Info.JOIN_CRITERIA, atomicJoinCriteria1);
+ }
+ atomicJoinNode1.addGroup(atomicRequestGroup1);
+ atomicJoinNode1.addGroup(atomicRequestGroup1a);
+ atomicJoinNode1.addLastChild(selectNode1);
+
+ PlanNode sourceNode1a = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+ sourceNode1a.addGroup(atomicRequestGroup1a);
+ if (atomicRequestCrit1a != null){
+ PlanNode selectNode1a = NodeFactory.getNewNode(NodeConstants.Types.SELECT);
+ selectNode1a.setProperty(NodeConstants.Info.SELECT_CRITERIA, atomicRequestCrit1a);
+ selectNode1a.addGroup(atomicRequestGroup1a);
+ selectNode1a.addFirstChild(sourceNode1a);
+ atomicJoinNode1.addLastChild(selectNode1a);
+ } else {
+ atomicJoinNode1.addLastChild(sourceNode1a);
+ }
+ accessNode1.addLastChild(atomicJoinNode1);
+ } else {
+ accessNode1.addFirstChild(selectNode1);
+ }
+ } else {
+ accessNode1.addFirstChild(sourceNode1);
+ }
+
+ //SECOND (RIGHT) BRANCH OF TREE
+ PlanNode sourceNode2 = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+ sourceNode2.addGroup(atomicRequestGroup2);
+ if (atomicRequestCrit2 != null){
+ PlanNode selectNode2 = NodeFactory.getNewNode(NodeConstants.Types.SELECT);
+ selectNode2.setProperty(NodeConstants.Info.SELECT_CRITERIA, atomicRequestCrit2);
+ selectNode2.addGroup(atomicRequestGroup2);
+ selectNode2.addFirstChild(sourceNode2);
+ if (atomicRequestGroup2a != null){
+ PlanNode atomicJoinNode2 = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+ if (atomicJoinCriteria2.isEmpty()){
+ atomicJoinNode2.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_CROSS);
+ } else {
+ atomicJoinNode2.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_INNER);
+ atomicJoinNode2.setProperty(NodeConstants.Info.JOIN_CRITERIA, atomicJoinCriteria2);
+ }
+ atomicJoinNode2.addGroup(atomicRequestGroup2);
+ atomicJoinNode2.addGroup(atomicRequestGroup2a);
+ atomicJoinNode2.addLastChild(selectNode2);
+
+ PlanNode sourceNode2a = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
+ sourceNode2a.addGroup(atomicRequestGroup2a);
+ if (atomicRequestCrit2a != null){
+ PlanNode selectNode2a = NodeFactory.getNewNode(NodeConstants.Types.SELECT);
+ selectNode2a.setProperty(NodeConstants.Info.SELECT_CRITERIA, atomicRequestCrit2a);
+ selectNode2a.addGroup(atomicRequestGroup2a);
+ selectNode2a.addFirstChild(sourceNode2a);
+ atomicJoinNode2.addLastChild(selectNode2a);
+ } else {
+ atomicJoinNode2.addLastChild(sourceNode2a);
+ }
+ accessNode2.addLastChild(atomicJoinNode2);
+ } else {
+ accessNode2.addFirstChild(selectNode2);
+ }
+ } else {
+ accessNode2.addFirstChild(sourceNode2);
+ }
+
+ //Add access pattern(s)
+ RulePlaceAccess.addAccessPatternsProperty(accessNode1, metadata);
+ RulePlaceAccess.addAccessPatternsProperty(accessNode2, metadata);
+
+ if (DEBUG){
+ System.out.println("Before."); //$NON-NLS-1$
+ System.out.println(bogusParentNode);
+ }
+
+ RuleChooseDependent rule = new RuleChooseDependent();
+ RuleChooseJoinStrategy.chooseJoinStrategy(joinNode, metadata);
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ capFinder.addCapabilities("pm1", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
+ capFinder.addCapabilities("pm3", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
+ capFinder.addCapabilities("pm4", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
+
+ rule.execute(bogusParentNode, metadata, capFinder, new RuleStack(), null, new CommandContext());
+
+ if (DEBUG){
+ System.out.println("Done."); //$NON-NLS-1$
+ System.out.println(bogusParentNode);
+ }
+
+ Object prop1 = joinNode.getProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE);
+
+ if (expectedMadeDependent == LEFT_SIDE){
+ assertNotNull("Expected one side to be made dependent", prop1); //$NON-NLS-1$
+ assertEquals(accessNode1, FrameUtil.findJoinSourceNode(joinNode.getLastChild()));
+ } else if (expectedMadeDependent == RIGHT_SIDE){
+ assertNotNull("Expected one side to be made dependent", prop1); //$NON-NLS-1$
+ assertEquals(accessNode2, FrameUtil.findJoinSourceNode(joinNode.getLastChild()));
+ } else if (expectedMadeDependent == NEITHER_SIDE){
+ assertNull("Neither side should be dependent", prop1); //$NON-NLS-1$
+ } else {
+ fail("Invalid test constant " + expectedMadeDependent); //$NON-NLS-1$
+ }
+
+ Float cost1 = (Float)accessNode1.getProperty(NodeConstants.Info.EST_CARDINALITY);
+ Float cost2 = (Float)accessNode2.getProperty(NodeConstants.Info.EST_CARDINALITY);
+ assertNotNull(cost2);
+ assertNotNull(cost1);
+ if (expectedCost1 != null) {
+ assertEquals(expectedCost1.longValue(), cost1.longValue());
+ assertEquals(expectedCost2.longValue(), cost2.longValue());
+ }
+ }
+
+ // ################################## ACTUAL TESTS ################################
+
+ @Test public void testValidJoin1() throws Exception {
+ PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ accessNode.addGroup(getPhysicalGroup(1));
+
+ PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+ joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_CROSS);
+ joinNode.addFirstChild(accessNode);
+
+ helpTestValidJoin(joinNode, accessNode, false);
+ }
+
+ @Test public void testValidJoin2() throws Exception {
+ PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ accessNode.addGroup(getPhysicalGroup(1));
+
+ PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+ joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_FULL_OUTER);
+ joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, Arrays.asList(QueryRewriter.FALSE_CRITERIA));
+ joinNode.addFirstChild(accessNode);
+
+ helpTestValidJoin(joinNode, accessNode, false);
+ }
+
+ @Test public void testValidJoin3() throws Exception {
+ PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ accessNode1.addGroup(getPhysicalGroup(1));
+ accessNode2.addGroup(getPhysicalGroup(2));
+
+ PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+ joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_RIGHT_OUTER);
+ List crits = new ArrayList();
+ crits.add(new CompareCriteria(getElementSymbol(1,1), CompareCriteria.EQ, getElementSymbol(2,1)));
+ joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, crits);
+ joinNode.addLastChild(accessNode1);
+ joinNode.addLastChild(accessNode2);
+
+ helpTestValidJoin(joinNode, accessNode1, true);
+ }
+
+ @Test public void testValidJoin4() throws Exception {
+ PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+
+ PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+ joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_RIGHT_OUTER);
+ List crits = new ArrayList();
+ crits.add(new CompareCriteria(getElementSymbol(1,1), CompareCriteria.EQ, getElementSymbol(2,1)));
+ joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, crits);
+ joinNode.addLastChild(accessNode1);
+ joinNode.addLastChild(accessNode2);
+
+ helpTestValidJoin(joinNode, accessNode2, false);
+ }
+
+ @Test public void testValidJoin5() throws Exception {
+ PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+
+ PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+ joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_LEFT_OUTER);
+ List crits = new ArrayList();
+ crits.add(new CompareCriteria(getElementSymbol(1,1), CompareCriteria.EQ, getElementSymbol(2,1)));
+ joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, crits);
+ joinNode.addLastChild(accessNode1);
+ joinNode.addLastChild(accessNode2);
+
+ helpTestValidJoin(joinNode, accessNode1, false);
+ }
+
+ @Test public void testValidJoin6() throws Exception {
+ PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ accessNode1.addGroup(getPhysicalGroup(1));
+ accessNode2.addGroup(getPhysicalGroup(2));
+
+ PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+ joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, JoinType.JOIN_LEFT_OUTER);
+ List crits = new ArrayList();
+ crits.add(new CompareCriteria(getElementSymbol(1,1), CompareCriteria.EQ, getElementSymbol(2,1)));
+ joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, crits);
+ joinNode.addLastChild(accessNode1);
+ joinNode.addLastChild(accessNode2);
+
+ helpTestValidJoin(joinNode, accessNode2, true);
+ }
+
+ /**
+ * Tests that heuristics will take a primary key in the atomic criteria into account when
+ * making a dependent join.
+ */
+ @Test public void testChooseKey() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(2,3);
+ GroupSymbol group2 = getPhysicalGroup(3,3);
+
+ //Join criteria
+ ElementSymbol group1e1 = getElementSymbol(2,3,1);
+ ElementSymbol group2e1 = getElementSymbol(3,3,1);
+ CompareCriteria crit = new CompareCriteria(group2e1, CompareCriteria.EQ, group1e1);
+ ArrayList crits = new ArrayList(1);
+ crits.add(crit);
+
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit2 = new CompareCriteria(group2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
+ int expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ /**
+ * Neither side should be chosen since the left side lacks cardinality information and the right is not strong
+ */
+ @Test public void testChooseKey2() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(2,3); //no key
+ GroupSymbol group1a = null;
+ GroupSymbol group2 = getPhysicalGroup(3,3); //has key
+ GroupSymbol group2a = getPhysicalGroup(3,2); //no key
+
+ ElementSymbol group1e1 = getElementSymbol(2,3,1);
+ ElementSymbol group2e1 = getElementSymbol(3,3,1);
+ ElementSymbol group2e2 = getElementSymbol(3,3,2);
+ ElementSymbol group2ae1 = getElementSymbol(3,2,1);
+
+ //Outer Join criteria
+ CompareCriteria crit = new CompareCriteria(group2e1, CompareCriteria.EQ, group1e1);
+ ArrayList crits = new ArrayList(1);
+ crits.add(crit);
+
+ //atomic select criteria
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit1a = null;
+ Criteria atomicCrit2 = new CompareCriteria(group2e2, CompareCriteria.EQ, new Constant(new Integer(5)));
+ Criteria atomicCrit2a = null;
+
+ //atomic Join criteria 1
+ Collection atomicJoinCrits1 = null;
+
+ //atomic Join criteria 2
+ CompareCriteria atomicJoinCrit2 = new CompareCriteria(group2ae1, CompareCriteria.EQ, group2e1);
+ ArrayList atomicJoinCrits2 = new ArrayList(1);
+ atomicJoinCrits2.add(atomicJoinCrit2);
+
+ int expected = NEITHER_SIDE;
+
+ helpTestChooseSiblingAndMarkDependent(
+ group1,
+ atomicCrit1,
+ group1a,
+ atomicCrit1a,
+ atomicJoinCrits1,
+ group2,
+ atomicCrit2,
+ group2a,
+ atomicCrit2a,
+ atomicJoinCrits2,
+ crits,
+ expected, -1, 7930);
+ }
+
+ /**
+ * Tests that heuristics will take cardinality of a group into account when
+ * making a dependent join.
+ */
+ @Test public void testCardinality() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ GroupSymbol group2 = getPhysicalGroup(2,2);
+
+ //Join criteria
+ ElementSymbol pm1g2e1 = getElementSymbol(1,2,1);
+ ElementSymbol pm2g2e1 = getElementSymbol(2,2,1);
+ CompareCriteria crit = new CompareCriteria(pm2g2e1, CompareCriteria.EQ, pm1g2e1);
+ ArrayList crits = new ArrayList(2);
+ crits.add(crit);
+ ElementSymbol pm1g2e2 = getElementSymbol(1,2,2);
+ ElementSymbol pm2g2e2 = getElementSymbol(2,2,2);
+ CompareCriteria crit2 = new CompareCriteria(pm1g2e2, CompareCriteria.EQ, pm2g2e2);
+ crits.add(crit2);
+
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit2 = null;
+ int expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ /**
+ * Tests that heuristics will take cardinality of a group into account when
+ * making a dependent join, and that this information supercedes a key
+ * in the atomic criteria.
+ */
+ @Test public void testCardinalityAndKey() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ GroupSymbol group2 = getPhysicalGroup(2,2);
+
+ //Join criteria
+ ElementSymbol pm1g2e1 = getElementSymbol(1,2,1);
+ ElementSymbol pm2g2e1 = getElementSymbol(2,2,1);
+ CompareCriteria crit = new CompareCriteria(pm2g2e1, CompareCriteria.EQ, pm1g2e1);
+ ArrayList crits = new ArrayList(1);
+ crits.add(crit);
+ ElementSymbol pm1g2e2 = getElementSymbol(1,2,2);
+ ElementSymbol pm2g2e2 = getElementSymbol(2,2,2);
+ CompareCriteria crit2 = new CompareCriteria(pm1g2e2, CompareCriteria.EQ, pm2g2e2);
+ crits.add(crit2);
+
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit2 = null;
+ int expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ @Test public void testCardinalityAndKeyNestedLoop() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ GroupSymbol group2 = getPhysicalGroup(2,2);
+
+ //Join criteria
+ ElementSymbol pm1g2e1 = getElementSymbol(1,2,1);
+ ElementSymbol pm2g2e1 = getElementSymbol(2,2,1);
+ CompareCriteria crit = new CompareCriteria(pm2g2e1, CompareCriteria.EQ, pm1g2e1);
+ ArrayList crits = new ArrayList(1);
+ crits.add(crit);
+ ElementSymbol pm1g2e2 = getElementSymbol(1,2,2);
+ ElementSymbol pm2g2e2 = getElementSymbol(2,2,2);
+ CompareCriteria crit2 = new CompareCriteria(pm1g2e2, CompareCriteria.LT, pm2g2e2);
+ crits.add(crit2);
+
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit2 = null;
+ int expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ @Test public void testRejectDependentJoin() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(3,1);
+ GroupSymbol group2 = getPhysicalGroup(3,2);
+
+ //Join criteria
+ ElementSymbol pm3g1e2 = getElementSymbol(3,1,2);
+ ElementSymbol pm3g2e2 = getElementSymbol(3,2,2);
+ CompareCriteria crit = new CompareCriteria(pm3g1e2, CompareCriteria.EQ, pm3g2e2);
+ ArrayList crits = new ArrayList(1);
+ crits.add(crit);
+
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit2 = null;
+ int expected = NEITHER_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = NEITHER_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ /**
+ * Tests that join side with larger cardinality will still have a lower
+ * cost computed because it has a criteria including a primary key
+ */
+ @Test public void testCardinalityWithKeyCrit() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ ElementSymbol g1e2 = getElementSymbol(1,2,2);
+
+ GroupSymbol group2 = getPhysicalGroup(3,3);
+ ElementSymbol g2e1 = getElementSymbol(3,3,1);
+ ElementSymbol g2e2 = getElementSymbol(3,3,2);
+
+ //Join criteria
+ ArrayList crits = new ArrayList(1);
+ CompareCriteria crit2 = new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2);
+ crits.add(crit2);
+
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit2 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
+ int expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ /**
+ * Tests that join side with larger cardinality will still have a lower
+ * cost computed because it has a criteria including a primary key
+ */
+ @Test public void testCardinalityWithKeyCompoundCritAND() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ ElementSymbol g1e2 = getElementSymbol(1,2,2);
+
+ GroupSymbol group2 = getPhysicalGroup(3,3);
+ ElementSymbol g2e1 = getElementSymbol(3,3,1);
+ ElementSymbol g2e2 = getElementSymbol(3,3,2);
+
+ //Join criteria
+ ArrayList crits = new ArrayList(1);
+ crits.add(new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2));
+
+ Criteria atomicCrit1 = null;
+
+ Criteria crit1 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
+ Criteria crit2 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(7)));
+ CompoundCriteria atomicCrit2 = new CompoundCriteria(CompoundCriteria.AND, crit1, crit2);
+
+ int expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ /**
+ * Tests that join side with larger cardinality will still have a lower
+ * cost computed because it has a criteria including a primary key.
+ * Defect 8445
+ */
+ @Test public void testCardinalityWithKeyCompoundCritOR() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ ElementSymbol g1e2 = getElementSymbol(1,2,2);
+
+ GroupSymbol group2 = getPhysicalGroup(3,3);
+ ElementSymbol g2e1 = getElementSymbol(3,3,1);
+ ElementSymbol g2e2 = getElementSymbol(3,3,2);
+
+ //Join criteria
+ ArrayList crits = new ArrayList(1);
+ crits.add(new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2));
+
+ Criteria atomicCrit1 = null;
+
+ Criteria crit1 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
+ Criteria crit2 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(7)));
+ CompoundCriteria atomicCrit2 = new CompoundCriteria(CompoundCriteria.OR, crit1, crit2);
+
+ int expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ /**
+ * Tests SetCriteria against a key column in the atomic criteria
+ */
+ @Test public void testCardinalityWithKeySetCrit() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ ElementSymbol g1e2 = getElementSymbol(1,2,2);
+
+ GroupSymbol group2 = getPhysicalGroup(3,3);
+ ElementSymbol g2e1 = getElementSymbol(3,3,1);
+ ElementSymbol g2e2 = getElementSymbol(3,3,2);
+
+ //Join criteria
+ ArrayList crits = new ArrayList(1);
+ CompareCriteria crit2 = new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2);
+ crits.add(crit2);
+
+ Criteria atomicCrit1 = null;
+ Collection values = new LinkedList();
+ values.add(new Constant(new Integer(3)));
+ values.add(new Constant(new Integer(4)));
+ values.add(new Constant(new Integer(5)));
+ Criteria atomicCrit2 = new SetCriteria(g2e1, values);
+ int expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ /**
+ * Tests SetCriteria in the atomic criteria
+ */
+ @Test public void testCardinalityWithKeyMatchCrit() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ ElementSymbol g1e2 = getElementSymbol(1,2,2);
+
+ GroupSymbol group2 = getPhysicalGroup(3,3);
+ ElementSymbol g2e1 = getElementSymbol(3,3,1);
+ ElementSymbol g2e2 = getElementSymbol(3,3,2);
+
+ //Join criteria
+ ArrayList crits = new ArrayList(1);
+ CompareCriteria crit2 = new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2);
+ crits.add(crit2);
+
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit2 = new MatchCriteria(g2e1, new Constant(new String("ab%"))); //$NON-NLS-1$
+ int expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ /**
+ * Tests SetCriteria in the atomic criteria
+ */
+ @Test public void testCardinalityWithKeyIsNullCrit() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ ElementSymbol g1e2 = getElementSymbol(1,2,2);
+
+ GroupSymbol group2 = getPhysicalGroup(3,3);
+ ElementSymbol g2e1 = getElementSymbol(3,3,1);
+ ElementSymbol g2e2 = getElementSymbol(3,3,2);
+
+ //Join criteria
+ ArrayList crits = new ArrayList(1);
+ CompareCriteria crit2 = new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2);
+ crits.add(crit2);
+
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit2 = new IsNullCriteria(g2e1);
+ int expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ /**
+ * Tests NotCriteria in the atomic criteria
+ */
+ @Test public void testCardinalityWithKeyNotCrit() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ ElementSymbol g1e2 = getElementSymbol(1,2,2);
+
+ GroupSymbol group2 = getPhysicalGroup(3,3);
+ ElementSymbol g2e1 = getElementSymbol(3,3,1);
+ ElementSymbol g2e2 = getElementSymbol(3,3,2);
+
+ //Join criteria
+ ArrayList crits = new ArrayList(1);
+ CompareCriteria crit2 = new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2);
+ crits.add(crit2);
+
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit2 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
+ atomicCrit2 = new NotCriteria(atomicCrit2);
+ int expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ /**
+ * Tests that join side with larger cardinality will still have a lower
+ * cost computed because it has a criteria including a primary key
+ */
+ @Test public void testCardinalityWithKeyComplexCrit() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ ElementSymbol g1e2 = getElementSymbol(1,2,2);
+
+ GroupSymbol group2 = getPhysicalGroup(3,3);
+ ElementSymbol g2e1 = getElementSymbol(3,3,1);
+ ElementSymbol g2e2 = getElementSymbol(3,3,2);
+
+ //Join criteria
+ ArrayList crits = new ArrayList(1);
+ crits.add(new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2));
+
+ Criteria atomicCrit1 = null;
+
+ Criteria crit1 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
+ Criteria crit2 = new CompareCriteria(g2e1, CompareCriteria.EQ, new Constant(new Integer(7)));
+ CompoundCriteria atomicCrit2 = new CompoundCriteria(CompoundCriteria.AND, crit1, crit2);
+ Criteria crit3 = new MatchCriteria(g2e1, new Constant(new String("ab"))); //$NON-NLS-1$
+ atomicCrit2 = new CompoundCriteria(CompoundCriteria.OR, atomicCrit2, crit3);
+
+ int expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ @Test public void testCardinalityWithKeyComplexCrit2() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ ElementSymbol g1e2 = getElementSymbol(1,2,2);
+
+ GroupSymbol group2 = getPhysicalGroup(3,3);
+ ElementSymbol g2e1 = getElementSymbol(3,3,1);
+ ElementSymbol g2e2 = getElementSymbol(3,3,2);
+
+ //Join criteria
+ ArrayList crits = new ArrayList(1);
+ crits.add(new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2));
+
+ Criteria atomicCrit1 = null;
+
+ Criteria crit1 = new CompareCriteria(g2e1, CompareCriteria.GT, new Constant(new Integer(5)));
+ Criteria crit2 = new CompareCriteria(g2e1, CompareCriteria.LT, new Constant(new Integer(7)));
+ Criteria atomicCrit2 = new CompoundCriteria(CompoundCriteria.AND, crit1, crit2);
+ Criteria crit3 = new MatchCriteria(g2e1, new Constant(new String("cd%"))); //$NON-NLS-1$
+ atomicCrit2 = new CompoundCriteria(CompoundCriteria.OR, atomicCrit2, crit3);
+ atomicCrit2 = new NotCriteria(atomicCrit2);
+
+ int expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ @Test public void testCardinalityWithKeyComplexCrit3() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ ElementSymbol g1e2 = getElementSymbol(1,2,2);
+
+ GroupSymbol group2 = getPhysicalGroup(3,3);
+ ElementSymbol g2e1 = getElementSymbol(3,3,1);
+ ElementSymbol g2e2 = getElementSymbol(3,3,2);
+
+ //Join criteria
+ ArrayList crits = new ArrayList(1);
+ crits.add(new CompareCriteria(g1e2, CompareCriteria.EQ, g2e2));
+
+ Criteria atomicCrit1 = null;
+
+ Criteria crit1 = new CompareCriteria(g2e1, CompareCriteria.GE, new Constant(new Integer(5)));
+ Criteria crit2 = new CompareCriteria(g2e1, CompareCriteria.NE, new Constant(new Integer(7)));
+ Criteria atomicCrit2 = new CompoundCriteria(CompoundCriteria.OR, crit1, crit2);
+ atomicCrit2 = new NotCriteria(atomicCrit2);
+ Criteria crit3 = new CompareCriteria(g2e1, CompareCriteria.LE, new Constant(new Integer(25)));
+ atomicCrit2 = new CompoundCriteria(CompoundCriteria.AND, atomicCrit2, crit3);
+
+ int expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ /**
+ * Tests that join side with larger cardinality and non-key criteria
+ * will be made dependent
+ */
+ @Test public void testCardinalityWithNonKeyCrit() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(1,2);
+ ElementSymbol g1e1 = getElementSymbol(1,2,1);
+// ElementSymbol g1e2 = getElementSymbol(1,2,2);
+
+ GroupSymbol group2 = getPhysicalGroup(3,3);
+ ElementSymbol g2e1 = getElementSymbol(3,3,1);
+ ElementSymbol g2e2 = getElementSymbol(3,3,2);
+
+ //Join criteria
+ ArrayList crits = new ArrayList(1);
+ CompareCriteria crit2 = new CompareCriteria(g1e1, CompareCriteria.EQ, g2e1);
+ crits.add(crit2);
+
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit2 = new CompareCriteria(g2e2, CompareCriteria.EQ, new Constant(new Integer(5)));
+ int expected = RIGHT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group1, atomicCrit1, group2, atomicCrit2, crits, expected);
+ expected = LEFT_SIDE;
+ helpTestChooseSiblingAndMarkDependent(group2, atomicCrit2, group1, atomicCrit1, crits, expected);
+ }
+
+ /**
+ * Tests that join side with larger cardinality will still have a lower
+ * cost computed because it has a criteria including a primary key
+ */
+ @Test public void testCardinalityWithCriteriaAndJoin() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(2,2); //no key
+ GroupSymbol group1a = null;
+ GroupSymbol group2 = getPhysicalGroup(3,3); //has key
+ GroupSymbol group2a = getPhysicalGroup(3,1); //has key
+
+ ElementSymbol group1e1 = getElementSymbol(2,2,1);
+ ElementSymbol group2e1 = getElementSymbol(3,3,1);
+ ElementSymbol group2e2 = getElementSymbol(3,3,2);
+ ElementSymbol group2ae1 = getElementSymbol(3,1,1);
+ ElementSymbol group2ae2 = getElementSymbol(3,1,2);
+
+ //Outer Join criteria
+ CompareCriteria crit = new CompareCriteria(group2e1, CompareCriteria.EQ, group1e1);
+ ArrayList crits = new ArrayList(1);
+ crits.add(crit);
+
+ //atomic select criteria
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit1a = null;
+ Criteria atomicCrit2 = new CompareCriteria(group2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
+ Criteria atomicCrit2a = new CompareCriteria(group2ae1, CompareCriteria.EQ, new Constant(new Integer(5)));
+
+ //atomic Join criteria 1
+ Collection atomicJoinCrits1 = null;
+
+ //atomic Join criteria 2
+ CompareCriteria atomicJoinCrit2 = new CompareCriteria(group2ae2, CompareCriteria.EQ, group2e2);
+ ArrayList atomicJoinCrits2 = new ArrayList(1);
+ atomicJoinCrits2.add(atomicJoinCrit2);
+
+ int expected = LEFT_SIDE;
+
+ helpTestChooseSiblingAndMarkDependent(
+ group1,
+ atomicCrit1,
+ group1a,
+ atomicCrit1a,
+ atomicJoinCrits1,
+ group2,
+ atomicCrit2,
+ group2a,
+ atomicCrit2a,
+ atomicJoinCrits2,
+ crits,
+ expected, 1000, 1);
+ }
+
+ @Test public void testCardinalityWithAtomicCrossJoin() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(2,2); //no key
+ GroupSymbol group1a = null;
+ GroupSymbol group2 = getPhysicalGroup(3,3); //has key
+ GroupSymbol group2a = getPhysicalGroup(3,1); //has key
+
+ ElementSymbol group1e1 = getElementSymbol(2,2,1);
+ ElementSymbol group2e1 = getElementSymbol(3,3,1);
+
+ //Outer Join criteria
+ CompareCriteria crit = new CompareCriteria(group2e1, CompareCriteria.EQ, group1e1);
+ ArrayList crits = new ArrayList(1);
+ crits.add(crit);
+
+ //atomic select criteria
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit1a = null;
+ Criteria atomicCrit2 = new CompareCriteria(group2e1, CompareCriteria.EQ, new Constant(new Integer(5)));
+ Criteria atomicCrit2a = null;
+
+ //atomic Join criteria 1
+ Collection atomicJoinCrits1 = null;
+
+ //atomic Join criteria 2
+ List atomicJoinCrits2 = Collections.EMPTY_LIST; //INDICATES CROSS JOIN
+
+ int expected = NEITHER_SIDE;
+
+ helpTestChooseSiblingAndMarkDependent(
+ group1,
+ atomicCrit1,
+ group1a,
+ atomicCrit1a,
+ atomicJoinCrits1,
+ group2,
+ atomicCrit2,
+ group2a,
+ atomicCrit2a,
+ atomicJoinCrits2,
+ crits,
+ expected, 1000, 1E5);
+ }
+
+ @Test public void testCardinalityWithAtomicCrossJoin2() throws Exception {
+ //override default metadata
+ this.metadata = RealMetadataFactory.example4();
+
+ GroupSymbol group1 = getPhysicalGroup(2,2); //no key
+ GroupSymbol group1a = null;
+ GroupSymbol group2 = getPhysicalGroup(3,3); //has key
+ GroupSymbol group2a = getPhysicalGroup(3,1); //has key
+
+ ElementSymbol group1e1 = getElementSymbol(2,2,1);
+ ElementSymbol group2e1 = getElementSymbol(3,3,1);
+
+ //Outer Join criteria
+ CompareCriteria crit = new CompareCriteria(group2e1, CompareCriteria.EQ, group1e1);
+ ArrayList crits = new ArrayList(1);
+ crits.add(crit);
+
+ //atomic select criteria
+ Criteria atomicCrit1 = null;
+ Criteria atomicCrit1a = null;
+ Criteria atomicCrit2 = new CompareCriteria(group2e1, CompareCriteria.NE, new Constant(new Integer(5)));
+ Criteria atomicCrit2a = null;
+
+ //atomic Join criteria 1
+ Collection atomicJoinCrits1 = null;
+
+ //atomic Join criteria 2
+ List atomicJoinCrits2 = Collections.EMPTY_LIST; //INDICATES CROSS JOIN
+
+ int expected = RIGHT_SIDE;
+
+ helpTestChooseSiblingAndMarkDependent(
+ group1,
+ atomicCrit1,
+ group1a,
+ atomicCrit1a,
+ atomicJoinCrits1,
+ group2,
+ atomicCrit2,
+ group2a,
+ atomicCrit2a,
+ atomicJoinCrits2,
+ crits,
+ expected, 1000, 9999899648l);
+ }
+
+ // ################################## TEST SUITE ################################
+
+ private static final boolean DEBUG = false;
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePlaceAccess.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePlaceAccess.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePlaceAccess.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,87 +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.optimizer.relational.rules;
-
-import java.util.Collection;
-
-import org.teiid.query.metadata.QueryMetadataInterface;
-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.optimizer.relational.rules.RulePlaceAccess;
-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.GroupSymbol;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
-import junit.framework.TestCase;
-
-
-public class TestRulePlaceAccess extends TestCase {
-
- private static final QueryMetadataInterface METADATA = FakeMetadataFactory.example1Cached();
-
- // ################################## FRAMEWORK ################################
-
- /**
- * Constructor for TestRulePlaceAccess.
- * @param name
- */
- public TestRulePlaceAccess(String name) {
- super(name);
- }
-
- /**
- * Tests that any access patterns (a Collection of Collections of
- * Object element ids) for a physical group will be found and added
- * as a property of an ACCESS node.
- */
- public void testAddAccessPatterns2() throws Exception {
- Query query = new Query();
-
- From from = new From();
- GroupSymbol group = new GroupSymbol("pm4.g2"); //$NON-NLS-1$
- from.addGroup(group);
- query.setFrom(from);
-
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
-
- group.setMetadataID(METADATA.getGroupID("pm4.g2")); //$NON-NLS-1$
-
- PlanNode n1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- n1.setProperty(NodeConstants.Info.ATOMIC_REQUEST, query);
- n1.addGroup(group);
-
- RulePlaceAccess.addAccessPatternsProperty(n1, METADATA);
-
- Collection accessPatterns = (Collection)n1.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
- assertNotNull(accessPatterns);
- assertTrue("Expected two access patterns, got " + accessPatterns.size(), accessPatterns.size() == 2); //$NON-NLS-1$
- }
-
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePlaceAccess.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePlaceAccess.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePlaceAccess.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePlaceAccess.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,87 @@
+/*
+ * 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.relational.rules;
+
+import java.util.Collection;
+
+import org.teiid.query.metadata.QueryMetadataInterface;
+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.optimizer.relational.rules.RulePlaceAccess;
+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.GroupSymbol;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+import junit.framework.TestCase;
+
+
+public class TestRulePlaceAccess extends TestCase {
+
+ private static final QueryMetadataInterface METADATA = RealMetadataFactory.example1Cached();
+
+ // ################################## FRAMEWORK ################################
+
+ /**
+ * Constructor for TestRulePlaceAccess.
+ * @param name
+ */
+ public TestRulePlaceAccess(String name) {
+ super(name);
+ }
+
+ /**
+ * Tests that any access patterns (a Collection of Collections of
+ * Object element ids) for a physical group will be found and added
+ * as a property of an ACCESS node.
+ */
+ public void testAddAccessPatterns2() throws Exception {
+ Query query = new Query();
+
+ From from = new From();
+ GroupSymbol group = new GroupSymbol("pm4.g2"); //$NON-NLS-1$
+ from.addGroup(group);
+ query.setFrom(from);
+
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+
+ group.setMetadataID(METADATA.getGroupID("pm4.g2")); //$NON-NLS-1$
+
+ PlanNode n1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ n1.setProperty(NodeConstants.Info.ATOMIC_REQUEST, query);
+ n1.addGroup(group);
+
+ RulePlaceAccess.addAccessPatternsProperty(n1, METADATA);
+
+ Collection accessPatterns = (Collection)n1.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
+ assertNotNull(accessPatterns);
+ assertTrue("Expected two access patterns, got " + accessPatterns.size(), accessPatterns.size() == 2); //$NON-NLS-1$
+ }
+
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePushSelectCriteria.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePushSelectCriteria.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePushSelectCriteria.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,93 +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.optimizer.relational.rules;
-
-import static org.junit.Assert.*;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.junit.Test;
-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.TestOptimizer;
-import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
-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;
-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.parser.QueryParser;
-import org.teiid.query.sql.lang.Command;
-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.util.CommandContext;
-
-
-public class TestRulePushSelectCriteria {
-
- @Test public void testElementsInCritieria() throws Exception {
- String criteria = "e1 = '1' OR ((e1 = '2' OR e1 = '4') AND e2 = 3)"; //$NON-NLS-1$
- Set<ElementSymbol> expected = new HashSet<ElementSymbol>(Arrays.asList(new ElementSymbol("e1"))); //$NON-NLS-1$
- assertEquals(expected, RulePushSelectCriteria.getElementsIncriteria(QueryParser.getQueryParser().parseCriteria(criteria)));
- }
-
- @Test public void testElementsInCritieria1() throws Exception {
- String criteria = "e1 = '1' and ((e1 = '2' OR e1 = '4') AND e2 = 3) or e2 is null"; //$NON-NLS-1$
- Set<ElementSymbol> expected = new HashSet<ElementSymbol>(Arrays.asList(new ElementSymbol("e2"))); //$NON-NLS-1$
- assertEquals(expected, RulePushSelectCriteria.getElementsIncriteria(QueryParser.getQueryParser().parseCriteria(criteria)));
- }
-
- @Test public void testPushAcrossFrameWithAccessNode() throws Exception {
- QueryMetadataInterface metadata = new TempMetadataAdapter(FakeMetadataFactory.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();
- CommandContext cc = new CommandContext();
- p.initialize(command, null, metadata, null, null, cc);
- PlanNode root = p.generatePlan(command);
- PlanNode child = p.generatePlan(subCommand);
- PlanNode sourceNode = NodeEditor.findNodePreOrder(root, NodeConstants.Types.SOURCE);
- sourceNode.addFirstChild(child);
- sourceNode.setProperty(NodeConstants.Info.SYMBOL_MAP, SymbolMap.createSymbolMap(sourceNode.getGroups().iterator().next(), (List<SingleElementSymbol>)child.getFirstChild().getProperty(Info.PROJECT_COLS), metadata));
- //add a dummy access node
- PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
- accessNode.addGroups(child.getFirstChild().getGroups());
- child.getFirstChild().addAsParent(accessNode);
-
- new RulePushSelectCriteria().execute(root, metadata, new DefaultCapabilitiesFinder(), new RuleStack(), AnalysisRecord.createNonRecordingRecord(), cc);
- // the select node should still be above the access node
- accessNode = NodeEditor.findNodePreOrder(root, NodeConstants.Types.ACCESS);
- assertEquals(NodeConstants.Types.SELECT, accessNode.getParent().getType());
- assertNull(NodeEditor.findNodePreOrder(accessNode, NodeConstants.Types.SELECT));
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePushSelectCriteria.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePushSelectCriteria.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePushSelectCriteria.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePushSelectCriteria.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,93 @@
+/*
+ * 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.relational.rules;
+
+import static org.junit.Assert.*;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Test;
+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.TestOptimizer;
+import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
+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;
+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.parser.QueryParser;
+import org.teiid.query.sql.lang.Command;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+
+public class TestRulePushSelectCriteria {
+
+ @Test public void testElementsInCritieria() throws Exception {
+ String criteria = "e1 = '1' OR ((e1 = '2' OR e1 = '4') AND e2 = 3)"; //$NON-NLS-1$
+ Set<ElementSymbol> expected = new HashSet<ElementSymbol>(Arrays.asList(new ElementSymbol("e1"))); //$NON-NLS-1$
+ assertEquals(expected, RulePushSelectCriteria.getElementsIncriteria(QueryParser.getQueryParser().parseCriteria(criteria)));
+ }
+
+ @Test public void testElementsInCritieria1() throws Exception {
+ String criteria = "e1 = '1' and ((e1 = '2' OR e1 = '4') AND e2 = 3) or e2 is null"; //$NON-NLS-1$
+ Set<ElementSymbol> expected = new HashSet<ElementSymbol>(Arrays.asList(new ElementSymbol("e2"))); //$NON-NLS-1$
+ assertEquals(expected, RulePushSelectCriteria.getElementsIncriteria(QueryParser.getQueryParser().parseCriteria(criteria)));
+ }
+
+ @Test public void testPushAcrossFrameWithAccessNode() throws Exception {
+ 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();
+ CommandContext cc = new CommandContext();
+ p.initialize(command, null, metadata, null, null, cc);
+ PlanNode root = p.generatePlan(command);
+ PlanNode child = p.generatePlan(subCommand);
+ PlanNode sourceNode = NodeEditor.findNodePreOrder(root, NodeConstants.Types.SOURCE);
+ sourceNode.addFirstChild(child);
+ sourceNode.setProperty(NodeConstants.Info.SYMBOL_MAP, SymbolMap.createSymbolMap(sourceNode.getGroups().iterator().next(), (List<SingleElementSymbol>)child.getFirstChild().getProperty(Info.PROJECT_COLS), metadata));
+ //add a dummy access node
+ PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+ accessNode.addGroups(child.getFirstChild().getGroups());
+ child.getFirstChild().addAsParent(accessNode);
+
+ new RulePushSelectCriteria().execute(root, metadata, new DefaultCapabilitiesFinder(), new RuleStack(), AnalysisRecord.createNonRecordingRecord(), cc);
+ // the select node should still be above the access node
+ accessNode = NodeEditor.findNodePreOrder(root, NodeConstants.Types.ACCESS);
+ assertEquals(NodeConstants.Types.SELECT, accessNode.getParent().getType());
+ assertNull(NodeEditor.findNodePreOrder(accessNode, NodeConstants.Types.SELECT));
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleValidateWhereAll.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleValidateWhereAll.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleValidateWhereAll.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,99 +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.optimizer.relational.rules;
-
-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.FakeCapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.optimizer.relational.rules.RuleValidateWhereAll;
-import org.teiid.query.sql.lang.CompareCriteria;
-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 junit.framework.TestCase;
-
-
-public class TestRuleValidateWhereAll extends TestCase {
-
- public TestRuleValidateWhereAll(String name) {
- super(name);
- }
-
- public void testHasNoCriteria1() {
- assertEquals("Got incorrect answer checking for no criteria", false, RuleValidateWhereAll.hasNoCriteria(new Insert())); //$NON-NLS-1$
- }
-
- public void testHasNoCriteria2() {
- Query query = new Query();
- CompareCriteria crit = new CompareCriteria(new Constant("a"), CompareCriteria.EQ, new Constant("b")); //$NON-NLS-1$ //$NON-NLS-2$
- query.setCriteria(crit);
- assertEquals("Got incorrect answer checking for no criteria", false, RuleValidateWhereAll.hasNoCriteria(query)); //$NON-NLS-1$
- }
-
- public void testHasNoCriteria3() {
- assertEquals("Got incorrect answer checking for no criteria", true, RuleValidateWhereAll.hasNoCriteria(new Query())); //$NON-NLS-1$
- }
-
- private FakeCapabilitiesFinder getWhereAllCapabilities() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.REQUIRES_CRITERIA, true);
- capFinder.addCapabilities("pm1", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
- capFinder.addCapabilities("pm6", caps); //$NON-NLS-1$
- return capFinder;
- }
-
- public void testDefect21982_3() {
- TestOptimizer.helpPlan(
- "SELECT * FROM vm1.g38", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, getWhereAllCapabilities(),
- new String[0],
- false);
- }
-
- public void testWhereAll1() {
- TestOptimizer.helpPlan(
- "SELECT * FROM pm6.g1", //$NON-NLS-1$
- FakeMetadataFactory.example1Cached(),
- null, getWhereAllCapabilities(),
- new String[0],
- false);
- }
-
- 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(),
- 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$
- },
- ComparisonMode.EXACT_COMMAND_STRING);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleValidateWhereAll.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleValidateWhereAll.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleValidateWhereAll.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleValidateWhereAll.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.optimizer.relational.rules;
+
+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.FakeCapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.optimizer.relational.rules.RuleValidateWhereAll;
+import org.teiid.query.sql.lang.CompareCriteria;
+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.RealMetadataFactory;
+
+import junit.framework.TestCase;
+
+
+public class TestRuleValidateWhereAll extends TestCase {
+
+ public TestRuleValidateWhereAll(String name) {
+ super(name);
+ }
+
+ public void testHasNoCriteria1() {
+ assertEquals("Got incorrect answer checking for no criteria", false, RuleValidateWhereAll.hasNoCriteria(new Insert())); //$NON-NLS-1$
+ }
+
+ public void testHasNoCriteria2() {
+ Query query = new Query();
+ CompareCriteria crit = new CompareCriteria(new Constant("a"), CompareCriteria.EQ, new Constant("b")); //$NON-NLS-1$ //$NON-NLS-2$
+ query.setCriteria(crit);
+ assertEquals("Got incorrect answer checking for no criteria", false, RuleValidateWhereAll.hasNoCriteria(query)); //$NON-NLS-1$
+ }
+
+ public void testHasNoCriteria3() {
+ assertEquals("Got incorrect answer checking for no criteria", true, RuleValidateWhereAll.hasNoCriteria(new Query())); //$NON-NLS-1$
+ }
+
+ private FakeCapabilitiesFinder getWhereAllCapabilities() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.REQUIRES_CRITERIA, true);
+ capFinder.addCapabilities("pm1", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
+ capFinder.addCapabilities("pm6", caps); //$NON-NLS-1$
+ return capFinder;
+ }
+
+ public void testDefect21982_3() {
+ TestOptimizer.helpPlan(
+ "SELECT * FROM vm1.g38", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, getWhereAllCapabilities(),
+ new String[0],
+ false);
+ }
+
+ public void testWhereAll1() {
+ TestOptimizer.helpPlan(
+ "SELECT * FROM pm6.g1", //$NON-NLS-1$
+ RealMetadataFactory.example1Cached(),
+ null, getWhereAllCapabilities(),
+ new String[0],
+ false);
+ }
+
+ 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$
+ 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$
+ },
+ ComparisonMode.EXACT_COMMAND_STRING);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestMarkExcludeVisitor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/xml/TestMarkExcludeVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestMarkExcludeVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,366 +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.optimizer.xml;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.Collection;
-
-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.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();
- Query query = (Query)TestXMLProcessor.helpGetCommand(sql, metadata);
-
- Collection groups = GroupCollectorVisitor.getGroups(query, true);
- GroupSymbol group = (GroupSymbol) groups.iterator().next();
-
- MappingDocument docOrig = (MappingDocument)metadata.getMappingNode(metadata.getGroupID(group.getName()));
- MappingDocument doc = (MappingDocument)docOrig.clone();
-
- doc = XMLPlanner.preMarkExcluded(query, doc);
- XMLPlanner.removeExcluded(doc);
-
- MappingOutputter out = new MappingOutputter();
- StringWriter sw = new StringWriter();
- out.write(doc, new PrintWriter(sw));
- String actual = sw.toString();
-
- expected = expected.replaceAll("\\s*<", "<"); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals(expected, actual);
- }
-
- public void testAttribute() throws Exception {
- String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
- "<xmlMapping>" + //$NON-NLS-1$
- "<documentEncoding>UTF-8</documentEncoding>" + //$NON-NLS-1$
- "<formattedDocument>true</formattedDocument>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Catalogs</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Catalog</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Items</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Item</name>" + //$NON-NLS-1$
- " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
- " <source>xmltest.group.items</source>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>ItemID</name>" + //$NON-NLS-1$
- " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
- " <symbol>xmltest.group.items.itemNum</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- "</xmlMapping>"; //$NON-NLS-1$
-
- helpTest("SELECT Catalogs.Catalog.Items.Item. at ItemID FROM xmltest.doc9", expected); //$NON-NLS-1$
- }
-
-
- public void testGroupNode() throws Exception{
- String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
- "<xmlMapping>" + //$NON-NLS-1$
- "<documentEncoding>UTF-8</documentEncoding>" + //$NON-NLS-1$
- "<formattedDocument>true</formattedDocument>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Catalogs</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Catalog</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Items</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Item</name>" + //$NON-NLS-1$
- " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
- " <source>xmltest.group.items</source>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Suppliers</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Supplier</name>" + //$NON-NLS-1$
- " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
- " <source>xmltest.suppliers</source>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>SupplierID</name>" + //$NON-NLS-1$
- " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
- " <symbol>xmltest.suppliers.supplierNum</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Name</name>" + //$NON-NLS-1$
- " <symbol>xmltest.suppliers.supplierName</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Zip</name>" + //$NON-NLS-1$
- " <symbol>xmltest.suppliers.supplierZipCode</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Orders</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Order</name>" + //$NON-NLS-1$
- " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
- " <source>xmltest.orders</source>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>OrderID</name>" + //$NON-NLS-1$
- " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
- " <symbol>xmltest.orders.orderNum</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>OrderDate</name>" + //$NON-NLS-1$
- " <symbol>xmltest.orders.orderDate</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>OrderQuantity</name>" + //$NON-NLS-1$
- " <symbol>xmltest.orders.orderQty</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>OrderStatus</name>" + //$NON-NLS-1$
- " <minOccurs>0</minOccurs>" + //$NON-NLS-1$
- " <symbol>xmltest.orders.orderStatus</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- "</xmlMapping>"; //$NON-NLS-1$
-
- helpTest("SELECT Catalogs.Catalog.Items.Item.Suppliers.Supplier.* FROM xmltest.doc9", expected); //$NON-NLS-1$
- helpTest("SELECT Supplier.* FROM xmltest.doc9", expected); //$NON-NLS-1$
- }
-
- public void testElements() throws Exception {
- String expected="<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
- "<xmlMapping>" + //$NON-NLS-1$
- "<documentEncoding>UTF-8</documentEncoding>" + //$NON-NLS-1$
- "<formattedDocument>true</formattedDocument>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Catalogs</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Catalog</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Items</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Item</name>" + //$NON-NLS-1$
- " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
- " <source>xmltest.group.items</source>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>ItemID</name>" + //$NON-NLS-1$
- " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
- " <symbol>xmltest.group.items.itemNum</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Suppliers</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Supplier</name>" + //$NON-NLS-1$
- " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
- " <source>xmltest.suppliers</source>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>SupplierID</name>" + //$NON-NLS-1$
- " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
- " <symbol>xmltest.suppliers.supplierNum</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Orders</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Order</name>" + //$NON-NLS-1$
- " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
- " <source>xmltest.orders</source>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>OrderID</name>" + //$NON-NLS-1$
- " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
- " <symbol>xmltest.orders.orderNum</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>OrderQuantity</name>" + //$NON-NLS-1$
- " <symbol>xmltest.orders.orderQty</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- "</xmlMapping>"; //$NON-NLS-1$
-
- helpTest("SELECT OrderQuantity, SupplierID, ItemID, OrderID FROM xmltest.doc9" + //$NON-NLS-1$
- " ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC," + //$NON-NLS-1$
- " OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expected); //$NON-NLS-1$
- }
-
- public void testSelectAll() throws Exception {
- String expected= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
- "<xmlMapping>" + //$NON-NLS-1$
- "<documentEncoding>UTF-8</documentEncoding>" + //$NON-NLS-1$
- "<formattedDocument>true</formattedDocument>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Catalogs</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Catalog</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Items</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Item</name>" + //$NON-NLS-1$
- " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
- " <source>xmltest.group.items</source>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>ItemID</name>" + //$NON-NLS-1$
- " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
- " <symbol>xmltest.group.items.itemNum</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Name</name>" + //$NON-NLS-1$
- " <symbol>xmltest.group.items.itemName</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Quantity</name>" + //$NON-NLS-1$
- " <symbol>xmltest.group.items.itemQuantity</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Suppliers</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Supplier</name>" + //$NON-NLS-1$
- " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
- " <source>xmltest.suppliers</source>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>SupplierID</name>" + //$NON-NLS-1$
- " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
- " <symbol>xmltest.suppliers.supplierNum</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Name</name>" + //$NON-NLS-1$
- " <symbol>xmltest.suppliers.supplierName</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Zip</name>" + //$NON-NLS-1$
- " <symbol>xmltest.suppliers.supplierZipCode</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Orders</name>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>Order</name>" + //$NON-NLS-1$
- " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
- " <source>xmltest.orders</source>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>OrderID</name>" + //$NON-NLS-1$
- " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
- " <symbol>xmltest.orders.orderNum</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>OrderDate</name>" + //$NON-NLS-1$
- " <symbol>xmltest.orders.orderDate</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>OrderQuantity</name>" + //$NON-NLS-1$
- " <symbol>xmltest.orders.orderQty</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " <mappingNode>" + //$NON-NLS-1$
- " <name>OrderStatus</name>" + //$NON-NLS-1$
- " <minOccurs>0</minOccurs>" + //$NON-NLS-1$
- " <symbol>xmltest.orders.orderStatus</symbol>" + //$NON-NLS-1$
- " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- " </mappingNode>" + //$NON-NLS-1$
- "</xmlMapping>" ; //$NON-NLS-1$
-
- // everything as it is..
- helpTest("SELECT * FROM xmltest.doc9", expected); //$NON-NLS-1$
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestMarkExcludeVisitor.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/xml/TestMarkExcludeVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestMarkExcludeVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestMarkExcludeVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,365 @@
+/*
+ * 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.io.PrintWriter;
+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.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;
+
+
+
+/**
+ *
+ */
+public class TestMarkExcludeVisitor extends TestCase {
+
+ void helpTest(String sql, String expected) throws Exception{
+ QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
+ Query query = (Query)TestXMLProcessor.helpGetCommand(sql, metadata);
+
+ Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(query, true);
+ GroupSymbol group = groups.iterator().next();
+
+ MappingDocument docOrig = (MappingDocument)metadata.getMappingNode(metadata.getGroupID(group.getName()));
+ MappingDocument doc = docOrig.clone();
+
+ doc = XMLPlanner.preMarkExcluded(query, doc);
+ XMLPlanner.removeExcluded(doc);
+
+ MappingOutputter out = new MappingOutputter();
+ StringWriter sw = new StringWriter();
+ out.write(doc, new PrintWriter(sw));
+ String actual = sw.toString();
+
+ expected = expected.replaceAll("\\s*<", "<"); //$NON-NLS-1$ //$NON-NLS-2$
+ assertEquals(expected, actual);
+ }
+
+ public void testAttribute() throws Exception {
+ String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
+ "<xmlMapping>" + //$NON-NLS-1$
+ "<documentEncoding>UTF-8</documentEncoding>" + //$NON-NLS-1$
+ "<formattedDocument>true</formattedDocument>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Catalogs</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Catalog</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Items</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Item</name>" + //$NON-NLS-1$
+ " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
+ " <source>xmltest.group.items</source>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>ItemID</name>" + //$NON-NLS-1$
+ " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
+ " <symbol>xmltest.group.items.itemNum</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ "</xmlMapping>"; //$NON-NLS-1$
+
+ helpTest("SELECT Catalogs.Catalog.Items.Item. at ItemID FROM xmltest.doc9", expected); //$NON-NLS-1$
+ }
+
+
+ public void testGroupNode() throws Exception{
+ String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
+ "<xmlMapping>" + //$NON-NLS-1$
+ "<documentEncoding>UTF-8</documentEncoding>" + //$NON-NLS-1$
+ "<formattedDocument>true</formattedDocument>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Catalogs</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Catalog</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Items</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Item</name>" + //$NON-NLS-1$
+ " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
+ " <source>xmltest.group.items</source>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Suppliers</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Supplier</name>" + //$NON-NLS-1$
+ " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
+ " <source>xmltest.suppliers</source>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>SupplierID</name>" + //$NON-NLS-1$
+ " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
+ " <symbol>xmltest.suppliers.supplierNum</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Name</name>" + //$NON-NLS-1$
+ " <symbol>xmltest.suppliers.supplierName</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Zip</name>" + //$NON-NLS-1$
+ " <symbol>xmltest.suppliers.supplierZipCode</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Orders</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Order</name>" + //$NON-NLS-1$
+ " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
+ " <source>xmltest.orders</source>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>OrderID</name>" + //$NON-NLS-1$
+ " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
+ " <symbol>xmltest.orders.orderNum</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>OrderDate</name>" + //$NON-NLS-1$
+ " <symbol>xmltest.orders.orderDate</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>OrderQuantity</name>" + //$NON-NLS-1$
+ " <symbol>xmltest.orders.orderQty</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>OrderStatus</name>" + //$NON-NLS-1$
+ " <minOccurs>0</minOccurs>" + //$NON-NLS-1$
+ " <symbol>xmltest.orders.orderStatus</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ "</xmlMapping>"; //$NON-NLS-1$
+
+ helpTest("SELECT Catalogs.Catalog.Items.Item.Suppliers.Supplier.* FROM xmltest.doc9", expected); //$NON-NLS-1$
+ helpTest("SELECT Supplier.* FROM xmltest.doc9", expected); //$NON-NLS-1$
+ }
+
+ public void testElements() throws Exception {
+ String expected="<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
+ "<xmlMapping>" + //$NON-NLS-1$
+ "<documentEncoding>UTF-8</documentEncoding>" + //$NON-NLS-1$
+ "<formattedDocument>true</formattedDocument>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Catalogs</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Catalog</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Items</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Item</name>" + //$NON-NLS-1$
+ " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
+ " <source>xmltest.group.items</source>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>ItemID</name>" + //$NON-NLS-1$
+ " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
+ " <symbol>xmltest.group.items.itemNum</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Suppliers</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Supplier</name>" + //$NON-NLS-1$
+ " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
+ " <source>xmltest.suppliers</source>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>SupplierID</name>" + //$NON-NLS-1$
+ " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
+ " <symbol>xmltest.suppliers.supplierNum</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Orders</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Order</name>" + //$NON-NLS-1$
+ " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
+ " <source>xmltest.orders</source>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>OrderID</name>" + //$NON-NLS-1$
+ " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
+ " <symbol>xmltest.orders.orderNum</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>OrderQuantity</name>" + //$NON-NLS-1$
+ " <symbol>xmltest.orders.orderQty</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ "</xmlMapping>"; //$NON-NLS-1$
+
+ helpTest("SELECT OrderQuantity, SupplierID, ItemID, OrderID FROM xmltest.doc9" + //$NON-NLS-1$
+ " ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC," + //$NON-NLS-1$
+ " OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expected); //$NON-NLS-1$
+ }
+
+ public void testSelectAll() throws Exception {
+ String expected= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
+ "<xmlMapping>" + //$NON-NLS-1$
+ "<documentEncoding>UTF-8</documentEncoding>" + //$NON-NLS-1$
+ "<formattedDocument>true</formattedDocument>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Catalogs</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Catalog</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Items</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Item</name>" + //$NON-NLS-1$
+ " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
+ " <source>xmltest.group.items</source>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>ItemID</name>" + //$NON-NLS-1$
+ " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
+ " <symbol>xmltest.group.items.itemNum</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Name</name>" + //$NON-NLS-1$
+ " <symbol>xmltest.group.items.itemName</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Quantity</name>" + //$NON-NLS-1$
+ " <symbol>xmltest.group.items.itemQuantity</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Suppliers</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Supplier</name>" + //$NON-NLS-1$
+ " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
+ " <source>xmltest.suppliers</source>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>SupplierID</name>" + //$NON-NLS-1$
+ " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
+ " <symbol>xmltest.suppliers.supplierNum</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Name</name>" + //$NON-NLS-1$
+ " <symbol>xmltest.suppliers.supplierName</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Zip</name>" + //$NON-NLS-1$
+ " <symbol>xmltest.suppliers.supplierZipCode</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Orders</name>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>Order</name>" + //$NON-NLS-1$
+ " <maxOccurs>-1</maxOccurs>" + //$NON-NLS-1$
+ " <source>xmltest.orders</source>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>OrderID</name>" + //$NON-NLS-1$
+ " <nodeType>attribute</nodeType>" + //$NON-NLS-1$
+ " <symbol>xmltest.orders.orderNum</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>"+ //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>OrderDate</name>" + //$NON-NLS-1$
+ " <symbol>xmltest.orders.orderDate</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>OrderQuantity</name>" + //$NON-NLS-1$
+ " <symbol>xmltest.orders.orderQty</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " <mappingNode>" + //$NON-NLS-1$
+ " <name>OrderStatus</name>" + //$NON-NLS-1$
+ " <minOccurs>0</minOccurs>" + //$NON-NLS-1$
+ " <symbol>xmltest.orders.orderStatus</symbol>" + //$NON-NLS-1$
+ " <includeAlways>false</includeAlways>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ " </mappingNode>" + //$NON-NLS-1$
+ "</xmlMapping>" ; //$NON-NLS-1$
+
+ // everything as it is..
+ helpTest("SELECT * FROM xmltest.doc9", expected); //$NON-NLS-1$
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestNameInSourceResolverVisitor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/xml/TestNameInSourceResolverVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestNameInSourceResolverVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,179 +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.optimizer.xml;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.teiid.core.TeiidComponentException;
-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.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.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;
-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.sql.visitor.GroupCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFacade;
-
-import junit.framework.TestCase;
-
-
-
-/**
- *
- */
-public class TestNameInSourceResolverVisitor extends TestCase {
- static HashMap infos = new HashMap();
-
- XMLPlannerEnvironment getEnv(String sql) throws Exception{
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
- Query query = (Query)TestXMLProcessor.helpGetCommand(sql, metadata);
-
- Collection groups = GroupCollectorVisitor.getGroups(query, true);
- GroupSymbol group = (GroupSymbol) groups.iterator().next();
-
- MappingDocument docOrig = (MappingDocument)metadata.getMappingNode(metadata.getGroupID(group.getName()));
- MappingDocument doc = (MappingDocument)docOrig.clone();
-
- XMLPlannerEnvironment env = new XMLPlannerEnvironment(metadata);
- env.mappingDoc = doc;
-
- setResultInfo("xmltest.group.items", new DummyCommand("xmltest.group.items", new String[] {"itemNum", "itemName", "itemQuantity", "itemStatus"})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- setResultInfo("xmltest.suppliers", new DummyCommand("xmltest.suppliers", new String[] {"supplierNum", "supplierName", "supplierZipCode", "itemNum"})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- setResultInfo("xmltest.orders", new DummyCommand("xmltest.orders", new String[] {"orderNum", "orderDate", "orderQty", "orderStatus"})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-
- return env;
- }
-
- private static void setResultInfo(String groupName, Command command) {
- ResultSetInfo rsInfo = new ResultSetInfo(groupName);
- rsInfo.setCommand(command);
- infos.put(groupName, rsInfo);
- }
-
- private static ResultSetInfo getResultInfo(String groupName) {
- return (ResultSetInfo)infos.get(groupName);
- }
-
- public void testResolve() throws Exception {
- XMLPlannerEnvironment env = getEnv("SELECT * FROM xmltest.doc9"); //$NON-NLS-1$
- MappingDocument doc = env.mappingDoc;
-
- // we should expect to fail
- doc.acceptVisitor(new NameValidator(false));
-
- doc = SourceNodeGenaratorVisitor.extractSourceNodes(doc);
- doc.acceptVisitor(new Navigator(true, new SourceFixer()));
- NameInSourceResolverVisitor.resolveElements(doc, env);
-
- // now we pass
- doc.acceptVisitor(new NameValidator(true));
- }
-
-
- static class SourceFixer extends MappingVisitor{
- public void visit(MappingSourceNode sourceNode) {
- ResultSetInfo info = getResultInfo(sourceNode.getResultName());
- Map symbolMap = new HashMap();
- for (Iterator i = info.getCommand().getProjectedSymbols().iterator(); i.hasNext();) {
- ElementSymbol element = (ElementSymbol)i.next();
- symbolMap.put(element, element);
- }
- sourceNode.setSymbolMap(symbolMap);
- sourceNode.setResultSetInfo(info);
- }
- }
-
- static class NameValidator extends MappingVisitor{
- boolean shouldPass;
-
- public NameValidator(boolean pass) {
- this.shouldPass = pass;
- }
-
- public void visit(MappingAttribute attribute) {
- if (attribute.getNameInSource() != null) {
- if (this.shouldPass) {
- assertNotNull(attribute.getElementSymbol());
- }
- else {
- assertNull(attribute.getElementSymbol());
- }
- }
- }
-
- public void visit(MappingElement element) {
- if (element.getNameInSource() != null) {
- if (this.shouldPass) {
- assertNotNull(element.getElementSymbol());
- }
- else {
- assertNull(element.getElementSymbol());
- }
- }
- }
- }
-
- static class DummyCommand extends Command{
- List list = new ArrayList();
-
- DummyCommand(String groupName, String[] symbols){
- for (int i= 0; i < symbols.length; i++) {
- list.add(new ElementSymbol(groupName+"."+symbols[i])); //$NON-NLS-1$
- }
- }
- public List getProjectedSymbols() {
- return list;
- }
-
- public boolean areResultsCachable() {
- return false;
- }
-
- public Object clone() {
- return null;
- }
-
- public int getType() {
- return 0;
- }
-
- public void acceptVisitor(LanguageVisitor visitor) {
- }
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestNameInSourceResolverVisitor.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/xml/TestNameInSourceResolverVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestNameInSourceResolverVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestNameInSourceResolverVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,174 @@
+/*
+ * 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.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+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;
+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.QueryMetadataInterface;
+import org.teiid.query.processor.xml.TestXMLProcessor;
+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.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.visitor.GroupCollectorVisitor;
+
+
+
+/**
+ *
+ */
+public class TestNameInSourceResolverVisitor extends TestCase {
+ static HashMap infos = new HashMap();
+
+ XMLPlannerEnvironment getEnv(String sql) throws Exception{
+ QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
+ Query query = (Query)TestXMLProcessor.helpGetCommand(sql, metadata);
+
+ Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(query, true);
+ GroupSymbol group = groups.iterator().next();
+
+ MappingDocument docOrig = (MappingDocument)metadata.getMappingNode(metadata.getGroupID(group.getName()));
+ MappingDocument doc = docOrig.clone();
+
+ XMLPlannerEnvironment env = new XMLPlannerEnvironment(metadata);
+ env.mappingDoc = doc;
+
+ setResultInfo("xmltest.group.items", new DummyCommand("xmltest.group.items", new String[] {"itemNum", "itemName", "itemQuantity", "itemStatus"})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ setResultInfo("xmltest.suppliers", new DummyCommand("xmltest.suppliers", new String[] {"supplierNum", "supplierName", "supplierZipCode", "itemNum"})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ setResultInfo("xmltest.orders", new DummyCommand("xmltest.orders", new String[] {"orderNum", "orderDate", "orderQty", "orderStatus"})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+
+ return env;
+ }
+
+ private static void setResultInfo(String groupName, Command command) {
+ ResultSetInfo rsInfo = new ResultSetInfo(groupName);
+ rsInfo.setCommand(command);
+ infos.put(groupName, rsInfo);
+ }
+
+ private static ResultSetInfo getResultInfo(String groupName) {
+ return (ResultSetInfo)infos.get(groupName);
+ }
+
+ public void testResolve() throws Exception {
+ XMLPlannerEnvironment env = getEnv("SELECT * FROM xmltest.doc9"); //$NON-NLS-1$
+ MappingDocument doc = env.mappingDoc;
+
+ // we should expect to fail
+ doc.acceptVisitor(new NameValidator(false));
+
+ doc = SourceNodeGenaratorVisitor.extractSourceNodes(doc);
+ doc.acceptVisitor(new Navigator(true, new SourceFixer()));
+ NameInSourceResolverVisitor.resolveElements(doc, env);
+
+ // now we pass
+ doc.acceptVisitor(new NameValidator(true));
+ }
+
+
+ static class SourceFixer extends MappingVisitor{
+ public void visit(MappingSourceNode sourceNode) {
+ ResultSetInfo info = getResultInfo(sourceNode.getResultName());
+ Map symbolMap = new HashMap();
+ for (Iterator i = info.getCommand().getProjectedSymbols().iterator(); i.hasNext();) {
+ ElementSymbol element = (ElementSymbol)i.next();
+ symbolMap.put(element, element);
+ }
+ sourceNode.setSymbolMap(symbolMap);
+ sourceNode.setResultSetInfo(info);
+ }
+ }
+
+ static class NameValidator extends MappingVisitor{
+ boolean shouldPass;
+
+ public NameValidator(boolean pass) {
+ this.shouldPass = pass;
+ }
+
+ public void visit(MappingAttribute attribute) {
+ if (attribute.getNameInSource() != null) {
+ if (this.shouldPass) {
+ assertNotNull(attribute.getElementSymbol());
+ }
+ else {
+ assertNull(attribute.getElementSymbol());
+ }
+ }
+ }
+
+ public void visit(MappingElement element) {
+ if (element.getNameInSource() != null) {
+ if (this.shouldPass) {
+ assertNotNull(element.getElementSymbol());
+ }
+ else {
+ assertNull(element.getElementSymbol());
+ }
+ }
+ }
+ }
+
+ static class DummyCommand extends Command{
+ List list = new ArrayList();
+
+ DummyCommand(String groupName, String[] symbols){
+ for (int i= 0; i < symbols.length; i++) {
+ list.add(new ElementSymbol(groupName+"."+symbols[i])); //$NON-NLS-1$
+ }
+ }
+ public List getProjectedSymbols() {
+ return list;
+ }
+
+ public boolean areResultsCachable() {
+ return false;
+ }
+
+ public Object clone() {
+ return null;
+ }
+
+ public int getType() {
+ return 0;
+ }
+
+ public void acceptVisitor(LanguageVisitor visitor) {
+ }
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLNodeMappingVisitor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLNodeMappingVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLNodeMappingVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.optimizer.xml;
-
-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.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 {
-
- /**
- * Constructor for TestXMLNodeMappingVisitor.
- * @param arg0
- */
- public TestXMLNodeMappingVisitor(String arg0) {
- super(arg0);
- }
-
- public void helpTestMapping(Criteria crit, String expectedCritString, MappingDocument mappingDoc, QueryMetadataInterface metadata) throws QueryPlannerException, TeiidComponentException {
- crit = XMLNodeMappingVisitor.convertCriteria(crit, mappingDoc, metadata);
- String actualCritString = crit.toString();
-
- assertEquals("Got incorrect converted string: ", expectedCritString, actualCritString); //$NON-NLS-1$
- }
-
- public void testMappingCriteria() throws Exception {
- FakeMetadataFacade 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$
- 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$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLNodeMappingVisitor.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLNodeMappingVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLNodeMappingVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLNodeMappingVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,76 @@
+/*
+ * 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 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.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;
+
+
+/**
+ */
+public class TestXMLNodeMappingVisitor extends TestCase {
+
+ /**
+ * Constructor for TestXMLNodeMappingVisitor.
+ * @param arg0
+ */
+ public TestXMLNodeMappingVisitor(String arg0) {
+ super(arg0);
+ }
+
+ public void helpTestMapping(Criteria crit, String expectedCritString, MappingDocument mappingDoc, QueryMetadataInterface metadata) throws QueryPlannerException, TeiidComponentException {
+ crit = XMLNodeMappingVisitor.convertCriteria(crit, mappingDoc, metadata);
+ String actualCritString = crit.toString();
+
+ assertEquals("Got incorrect converted string: ", expectedCritString, actualCritString); //$NON-NLS-1$
+ }
+
+ public void testMappingCriteria() throws Exception {
+ 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", 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$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLPlanner.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLPlanner.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLPlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,923 +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.optimizer.xml;
-
-import java.util.ArrayList;
-import java.util.List;
-
-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.query.analysis.AnalysisRecord;
-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.mapping.xml.Namespace;
-import org.teiid.query.metadata.QueryMetadataInterface;
-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;
-import org.teiid.query.processor.xml.ExecSqlInstruction;
-import org.teiid.query.processor.xml.ExecStagingTableInstruction;
-import org.teiid.query.processor.xml.MoveCursorInstruction;
-import org.teiid.query.processor.xml.Program;
-import org.teiid.query.processor.xml.TestXMLProcessor;
-import org.teiid.query.processor.xml.WhileInstruction;
-import org.teiid.query.processor.xml.XMLPlan;
-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.util.CommandContext;
-
-import junit.framework.TestCase;
-
-
-public class TestXMLPlanner extends TestCase {
-
- // ################################## FRAMEWORK ################################
-
- public TestXMLPlanner(String name) {
- super(name);
- }
-
- // ################################## TEST HELPERS ################################
-
- public static XMLPlan helpPlan(String sql, QueryMetadataInterface md) throws Exception {
- Command command = TestXMLProcessor.helpGetCommand(sql, md);
- return preparePlan(command, md, TestOptimizer.getGenericFinder(), null);
- }
-
- private void helpPlanException(String sql, QueryMetadataInterface md) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
- Command command = TestXMLProcessor.helpGetCommand(sql, md);
-
- try {
- preparePlan(command, md, TestOptimizer.getGenericFinder(), null);
- fail("Expected exception for planning " + sql); //$NON-NLS-1$
- } catch (QueryPlannerException e) {
- // this is expected
- }
- }
-
- public static FakeMetadataFacade example1() {
- // Create models
- FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
- FakeMetadataObject vm1 = FakeMetadataFactory.createVirtualModel("vm1"); //$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$
-
- // Create physical elements
- 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 });
- List pm1g2e =
- FakeMetadataFactory.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,
- 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,
- 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 pm1g5e =
- FakeMetadataFactory.createElements(
- pm1g5,
- 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 tm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
- //selects from temp group
- FakeMetadataObject vm1g1 =
- FakeMetadataFactory.createVirtualGroup("vm1.g1", vm1, vm1g1n1); //$NON-NLS-1$
-
- QueryNode vm1g2n1 =
- new QueryNode("SELECT * FROM pm1.g2 where pm1.g2.e1=?"); //$NON-NLS-1$ //$NON-NLS-2$
- vm1g2n1.addBinding("vm1.g1.e1"); //$NON-NLS-1$
- FakeMetadataObject vm1g2 =
- FakeMetadataFactory.createVirtualGroup("vm1.g2", vm1, vm1g2n1); //$NON-NLS-1$
-
- QueryNode vm1g3n1 =
- new QueryNode("SELECT * FROM pm1.g3 where pm1.g3.e1=?"); //$NON-NLS-1$ //$NON-NLS-2$
- vm1g3n1.addBinding("vm1.g2.e1"); //$NON-NLS-1$
- FakeMetadataObject vm1g3 =
- FakeMetadataFactory.createVirtualGroup("vm1.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 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$
-
- 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$
-
- // Create virtual elements
- List vm1g1e =
- FakeMetadataFactory.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,
- 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,
- 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,
- 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 vm1g5e =
- FakeMetadataFactory.createElements(
- vm1g5,
- 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 tm1g1e =
- FakeMetadataFactory.createElements(
- tm1g1,
- 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 documents
- // DOC 1
- FakeMetadataObject doc1 =
- FakeMetadataFactory.createVirtualGroup("vm1.doc1", vm1, doc1()); //$NON-NLS-1$
- List docE1 =
- FakeMetadataFactory.createElements(
- doc1,
- new String[] {
- "a0", //$NON-NLS-1$
- "a0.a1", //$NON-NLS-1$
- "a0.a1.a1", //$NON-NLS-1$
- "a0.a1.b1", //$NON-NLS-1$
- "a0.a1.c1" }, //$NON-NLS-1$
- new String[] {
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING });
-
- // DOC 2
- FakeMetadataObject doc2 =
- FakeMetadataFactory.createVirtualGroup("vm1.doc2", vm1, doc2()); //$NON-NLS-1$
- List docE2 =
- FakeMetadataFactory.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(
- doc3,
- new String[] {
- "root", //$NON-NLS-1$
- "root.n1", //$NON-NLS-1$
- "root.n1.m1", //$NON-NLS-1$
- "root.n1.m1.n2", //$NON-NLS-1$
- "root.n1.m1.n2.leaf1" }, //$NON-NLS-1$
- new String[] {
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING });
-
- // DOC 4
- FakeMetadataObject doc4 =
- FakeMetadataFactory.createVirtualGroup("vm1.doc4", vm1, doc4()); //$NON-NLS-1$
- List docE4 =
- FakeMetadataFactory.createElements(
- doc4,
- new String[] {
- "root", //$NON-NLS-1$
- "root.n4a", //$NON-NLS-1$
- "root.n4a.n4b", //$NON-NLS-1$
- "root.n4a.n4c", //$NON-NLS-1$
- "root.n4a.fake", //$NON-NLS-1$
- "root.n4a.n4c.n4d", //$NON-NLS-1$
- "root.n4a.n4c.n4e", //$NON-NLS-1$
- "root.n4a.n4c.n4e.n4f" }, //$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 });
-
- // DOC 5
- FakeMetadataObject doc5 =
- FakeMetadataFactory.createVirtualGroup("vm1.doc5", vm1, doc5()); //$NON-NLS-1$
- List docE5 =
- FakeMetadataFactory.createElements(
- doc5,
- new String[] {
- "root", //$NON-NLS-1$
- "root.nodea", //$NON-NLS-1$
- "root.nodea.nodeb", //$NON-NLS-1$
- "root.nodea.nodec", //$NON-NLS-1$
- "root.nodea.nodec.noded", //$NON-NLS-1$
- "root.nodea.nodec.nodee", //$NON-NLS-1$
- "root.nodea.nodec.nodee.nodef", //$NON-NLS-1$
- "root.nodea.nodec.nodee.nodeg", //$NON-NLS-1$
- "root.nodea.nodec.nodee.nodeg.nodeh", //$NON-NLS-1$
- "root.nodea.nodec.nodee.nodeg.nodeI", //$NON-NLS-1$
- "root.nodea.nodec.nodee.nodeg.nodeI.nodeJ" }, //$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 });
-
- // DOC 6
- FakeMetadataObject doc6 =
- FakeMetadataFactory.createVirtualGroup("vm1.doc6", vm1, doc6()); //$NON-NLS-1$
- List docE6 =
- FakeMetadataFactory.createElements(
- doc6,
- new String[] { "tempGroupTest" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING });
-
- // DOC with excluded fragment
- FakeMetadataObject docWithExcluded =
- FakeMetadataFactory.createVirtualGroup(
- "vm1.docWithExcluded", //$NON-NLS-1$
- vm1,
- docWithExcluded());
- List docWithExcludedElements =
- FakeMetadataFactory.createElements(
- docWithExcluded,
- new String[] {
- "root", //$NON-NLS-1$
- "root.n1", //$NON-NLS-1$
- "root.n1.m1", //$NON-NLS-1$
- "root.n1.m1.n2", //$NON-NLS-1$
- "root.n1.m1.n2.leaf1" }, //$NON-NLS-1$
- new String[] {
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING });
-
- // DOC 2 with excluded fragment
- FakeMetadataObject doc2WithExcluded =
- FakeMetadataFactory.createVirtualGroup(
- "vm1.docWithExcluded2", //$NON-NLS-1$
- vm1,
- docWithExcluded2());
- List doc2WithExcludedElements =
- FakeMetadataFactory.createElements(
- doc2WithExcluded,
- new String[] {
- "root", //$NON-NLS-1$
- "root.n1", //$NON-NLS-1$
- "root.n1.m1", //$NON-NLS-1$
- "root.n1.m2", //$NON-NLS-1$
- "root.n1.m3" }, //$NON-NLS-1$
- new String[] {
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING });
-
-
- // DOC with attribute
- FakeMetadataObject docWithAttribute =
- FakeMetadataFactory.createVirtualGroup(
- "vm1.docWithAttribute", //$NON-NLS-1$
- vm1,
- docTestConvertCriteriaWithAttribute());
- FakeMetadataObject docWithAttribute3 =
- FakeMetadataFactory.createVirtualGroup(
- "vm1.docWithAttribute3", //$NON-NLS-1$
- vm1,
- docTestCriteriaWithAttribute());
- List docWithAttributeElements =
- FakeMetadataFactory.createElements(
- docWithAttribute,
- new String[] {
- "root", //$NON-NLS-1$
- "root.myElement", //$NON-NLS-1$
- "root. at myAttribute"}, //$NON-NLS-1$
- new String[] {
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING });
- // DOC with attribute2
- FakeMetadataObject docWithAttribute2 =
- FakeMetadataFactory.createVirtualGroup(
- "vm1.docWithAttribute2", //$NON-NLS-1$
- vm1,
- docTestConvertCriteriaWithAttribute2());
- List docWithAttributeElements2 =
- FakeMetadataFactory.createElements(
- docWithAttribute2,
- new String[] {
- "root", //$NON-NLS-1$
- "root.myElement", //$NON-NLS-1$
- "root. at myAttribute"}, //$NON-NLS-1$
- new String[] {
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.STRING });
-
- List docWithAttributeElements3 =
- FakeMetadataFactory.createElements(
- docWithAttribute3,
- new String[] {
- "root", //$NON-NLS-1$
- "root.myElement", //$NON-NLS-1$
- "root. at type"}, //$NON-NLS-1$
- new String[] {
- DataTypeManager.DefaultDataTypes.STRING,
- 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);
- }
-
- private static MappingDocument doc1() {
- // DOC 1
- MappingDocument doc = new MappingDocument(false);
-
- MappingElement node= doc.addChildElement(new MappingElement("a0")); //$NON-NLS-1$
-
- MappingElement sourceNode = node.addChildElement(new MappingElement("a1")); //$NON-NLS-1$
- sourceNode.setSource("vm1.g1"); //$NON-NLS-1$
-
- sourceNode.addStagingTable("tm1.g1"); //$NON-NLS-1$
-
- sourceNode.addChildElement(new MappingElement("a1", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
- sourceNode.addChildElement(new MappingElement("b1", "vm1.g1.e2")); //$NON-NLS-1$ //$NON-NLS-2$
- sourceNode.addChildElement(new MappingElement("c1", "vm1.g1.e3")); //$NON-NLS-1$ //$NON-NLS-2$
- return doc;
- }
-
- private static MappingDocument doc2() {
- MappingDocument doc = new MappingDocument(false);
- MappingElement A1 = doc.addChildElement(new MappingElement("a1", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
- A1.setSource("vm1.g1"); //$NON-NLS-1$
- return doc;
- }
-
- private static MappingDocument docTestConvertCriteriaWithAttribute() {
- MappingDocument doc = new MappingDocument(false);
-
- MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
- root.setSource("vm1.g1"); //$NON-NLS-1$
-
- root.addChildElement(new MappingElement("myElement", "vm1.g1.e2")); //$NON-NLS-1$ //$NON-NLS-2$
- root.addAttribute(new MappingAttribute("myAttribute", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
- return doc;
- }
-
- private static MappingDocument docTestConvertCriteriaWithAttribute2() {
- MappingDocument doc = new MappingDocument(false);
-
- MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
- root.setSource("vm1.g1"); //$NON-NLS-1$
- root.addAttribute(new MappingAttribute("myAttribute", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());
- seq.addChildElement(new MappingElement("myElement", "vm1.g1.e2")); //$NON-NLS-1$ //$NON-NLS-2$
- return doc;
- }
-
- /*
- * Note: this should fail when validator starts verifying that vm1.g1 cannot
- * be executed before the temp group tm1.g1 is, since it selects from that
- * group but is not in it's scope
- */
- private static MappingDocument doc3() {
- MappingDocument doc = new MappingDocument(false);
-
- MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
- MappingElement n1 = root.addChildElement(new MappingElement("n1")); //$NON-NLS-1$
- n1.setSource("vm1.g1"); //$NON-NLS-1$
-
- MappingElement m1 = n1.addChildElement(new MappingElement("m1")); //$NON-NLS-1$
-
- MappingElement n2 = m1.addChildElement(new MappingElement("n2")); //$NON-NLS-1$
- n2.setSource("vm1.g2"); //$NON-NLS-1$
- n2.addStagingTable("tm1.g1"); //$NON-NLS-1$
-
- n2.addChildElement(new MappingElement("leaf1", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-
- return doc;
- }
-
- private static MappingDocument doc4() {
-
- MappingDocument doc = new MappingDocument(false);
-
- MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
- MappingElement n4a = root.addChildElement(new MappingElement("n4a")); //$NON-NLS-1$
- n4a.setMaxOccurrs(-1);
- n4a.setSource("vm1.g1"); //$NON-NLS-1$
- n4a.addStagingTable("tm1.g1"); //$NON-NLS-1$
- n4a.addChildElement(new MappingElement("n4b", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement n4c = n4a.addChildElement(new MappingElement("n4c")); //$NON-NLS-1$
- n4c.setMaxOccurrs(-1);
- n4c.setSource("vm1.g2"); //$NON-NLS-1$
-
- //this node can't be used for anything but searching through mapping doc for this property
- MappingElement fake = n4a.addChildElement(new MappingElement("fake")); //$NON-NLS-1$
- fake.setSource("fakeResultSet"); //$NON-NLS-1$
-
- n4c.addChildElement(new MappingElement("n4d", "vm1.g2.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement n4e = n4c.addChildElement(new MappingElement("n4e")); //$NON-NLS-1$
- n4e.setSource("vm1.g3"); //$NON-NLS-1$
- n4e.setMaxOccurrs(-1);
- n4e.addChildElement(new MappingElement("n4f", "vm1.g3.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-
- return doc;
- }
-
- private static MappingDocument doc5() {
-
- MappingDocument doc = new MappingDocument(false);
-
- MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
- MappingElement nodea = root.addChildElement(new MappingElement("nodea")); //$NON-NLS-1$
- nodea.setSource("vm1.g1"); //$NON-NLS-1$
- nodea.addStagingTable("tm1.g1"); //$NON-NLS-1$
- nodea.setMaxOccurrs(-1);
-
- nodea.addChildElement(new MappingElement("nodeb", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement nodec = nodea.addChildElement(new MappingElement("nodec")); //$NON-NLS-1$
- nodec.setMaxOccurrs(-1);
- nodec.setSource("vm1.g2"); //$NON-NLS-1$
-
- nodec.addChildElement(new MappingElement("noded", "vm1.g2.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement nodee = nodec.addChildElement(new MappingElement("nodee")); //$NON-NLS-1$
- nodee.setSource("vm1.g3"); //$NON-NLS-1$
- nodee.setMaxOccurrs(-1);
-
- nodee.addChildElement(new MappingElement("nodef", "vm1.g3.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement nodeg = nodee.addChildElement(new MappingElement("nodeg")); //$NON-NLS-1$
- nodeg.setSource("vm1.g4"); //$NON-NLS-1$
- nodeg.setMaxOccurrs(-1);
-
- nodeg.addChildElement(new MappingElement("nodeh", "vm1.g4.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement nodeI = nodeg.addChildElement(new MappingElement("nodeI")); //$NON-NLS-1$
- nodeI.setMaxOccurrs(-1);
- nodeI.setSource("vm1.g5"); //$NON-NLS-1$
- nodeI.addChildElement(new MappingElement("nodeJ", "vm1.g5.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-
- return doc;
- }
-
- private static MappingDocument doc6() {
- MappingDocument doc = new MappingDocument(false);
-
- MappingElement simpleRoot = doc.addChildElement(new MappingElement("tempGroupTest")); //$NON-NLS-1$
- simpleRoot.setSource("vm1.g1"); //$NON-NLS-1$
- simpleRoot.addStagingTable("tm1.g1"); //$NON-NLS-1$
- return doc;
- }
-
- private static MappingDocument docWithExcluded() {
-
- MappingDocument doc = new MappingDocument(false);
- MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
- MappingElement n1 = root.addChildElement(new MappingElement("n1")); //$NON-NLS-1$
- n1.setSource("vm1.g1"); //$NON-NLS-1$
-
- MappingElement m1 = n1.addChildElement(new MappingElement("m1", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement n2 = m1.addChildElement(new MappingElement("n2")); //$NON-NLS-1$
- n2.setSource("vm1.g2"); //$NON-NLS-1$
- n2.setExclude(true);
- n2.addChildElement(new MappingElement("leaf1", "vm1.g2.e2")); //$NON-NLS-1$ //$NON-NLS-2$
- return doc;
- }
-
- private static MappingDocument docWithExcluded2() {
-
- MappingDocument doc = new MappingDocument(false);
- MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
- MappingElement n1 = root.addChildElement(new MappingElement("n1")); //$NON-NLS-1$
- n1.setSource("vm1.g1"); //$NON-NLS-1$
-
- n1.addChildElement(new MappingElement("m1", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement m2 = n1.addChildElement(new MappingElement("m2", "vm1.g1.e2")); //$NON-NLS-1$ //$NON-NLS-2$
- m2.setExclude(true);
-
- n1.addChildElement(new MappingElement("m3", "vm1.g1.e3")); //$NON-NLS-1$ //$NON-NLS-2$
-
- return doc;
- }
-
- private static MappingDocument docTestCriteriaWithAttribute() {
-
- MappingDocument doc = new MappingDocument(false);
-
- MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
- root.setSource("vm1.g1"); //$NON-NLS-1$
- root.addAttribute(new MappingAttribute("type", new Namespace("xsi", ""))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- root.addAttribute(new MappingAttribute("type", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
- root.addChildElement(new MappingElement("myElement", "vm1.g1.e2")); //$NON-NLS-1$ //$NON-NLS-2$
- return doc;
- }
-
-
- public void test1() throws Exception {
- helpPlan("SELECT * FROM vm1.doc1", example1()); //$NON-NLS-1$
- }
-
- /**
- * Tests that a user cannot cite an invalid XML node in criteria
- * (a node that is not mapped to data)
- * (Also duplicate defect 8130)
- */
- public void test1_defect7341() throws Exception {
- helpPlanException("SELECT * FROM vm1.doc1 WHERE a0 = '3'", example1()); //$NON-NLS-1$
- }
-
- /**
- * Tests that a user cannot cite an invalid XML node in criteria
- * (a node that is not mapped to data)
- * (Also duplicate defect 8130)
- */
- 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 {
- helpPlan("SELECT * FROM vm1.doc2", example1()); //$NON-NLS-1$
- }
-
- public void test3() throws Exception {
- helpPlan("SELECT * FROM vm1.doc1 where a0.a1.a1='x'", example1()); //$NON-NLS-1$
- }
-
- /**
- * Note: this should fail when validator starts verifying that vm1.g1 cannot
- * 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 {
- helpPlan("SELECT * FROM vm1.doc3", example1()); //$NON-NLS-1$
- }
-
- public void testTempGroupPlan() throws Exception {
- QueryMetadataInterface qmi = example1();
-
- XMLPlan plan = helpPlan("SELECT * FROM vm1.doc6", qmi); //$NON-NLS-1$
-
- Program program = plan.getOriginalProgram();
-
- int i = 0;
- assertTrue(program.getInstructionAt(i++) instanceof ExecStagingTableInstruction);
- assertTrue(program.getInstructionAt(i++) instanceof ExecSqlInstruction);
- assertTrue(program.getInstructionAt(i++) instanceof BlockInstruction);
- assertTrue(program.getInstructionAt(i++) instanceof MoveCursorInstruction);
- assertTrue(program.getInstructionAt(i++) instanceof WhileInstruction);
- assertTrue(program.getInstructionAt(i++) instanceof EndBlockInstruction);
- assertTrue(program.getInstructionAt(i++) instanceof ExecStagingTableInstruction);
- }
-
- 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 {
- helpPlan(
- "SELECT root. at myAttribute FROM vm1.docWithAttribute", //$NON-NLS-1$
- example1());
- }
-
- /**
- * This method takes in a Command object of the user's query and returns a XML plan
- * as a XMLNode object.
- * @param command The Command object for which query plan is to be returned
- * @param metadata The metadata needed for planning
- * @return The XML plan returned as an XMLPlan object
- * @throws QueryPlannerException
- * @throws QueryMetadataException
- * @throws TeiidComponentException
- */
- 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) {
- System.out.println("\n####################################\n" + command); //$NON-NLS-1$
- }
- return XMLPlanner.preparePlan(command, metadata, analysis, new XMLPlannerEnvironment(metadata), idGenerator, capFinder, context);
- } finally {
- if (DEBUG) {
- System.out.println(analysis.getDebugLog());
- }
- }
- }
-
- public void testDefect18227() throws Exception {
- QueryMetadataInterface metadata = example1();
- String sql = "select * from vm1.docWithAttribute3 where root. at type = '3'"; //$NON-NLS-1$
-
- Query query = (Query)TestXMLProcessor.helpGetCommand(sql, metadata);
-
- try {
- preparePlan(query, metadata, TestOptimizer.getGenericFinder(), new CommandContext());
- fail("Expected to get error about criteria against unmapped type attribute"); //$NON-NLS-1$
- } catch(QueryPlannerException e) {
- // Expect to get exception about criteria against xsi:type
- }
- }
-
- public void testDefect21983() throws Exception {
- QueryMetadataInterface metadata = example1();
- String sql = "select root. at type from vm1.docWithAttribute3"; //$NON-NLS-1$
-
- Query query = (Query)TestXMLProcessor.helpGetCommand(sql, metadata);
-
- //here's the test
- preparePlan(query, metadata, TestOptimizer.getGenericFinder(), new CommandContext());
- }
-
- /**
- * Test that if non-fully-qualified staging table name is used in user criteria, that fully-qualified
- * name is returned by XMLPlanner
- * @throws Exception
- */
- public void testRootStagingTableCase4308() throws Exception{
-
- String sql = "select * from vm1.doc1 where stagingTable2.e1 IN ('a', 'b', 'c')"; //$NON-NLS-1$
-
- QueryMetadataInterface metadata = exampleCase4308();
-
- Query query = (Query)new QueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(query, metadata);
-
- String expectedStagingTableResultSet = "tm1.stagingTable2"; //$NON-NLS-1$
- String actualStagingTableResultSet = CriteriaPlanner.getStagingTableForConjunct(query.getCriteria(), metadata);
-
- assertEquals(expectedStagingTableResultSet, actualStagingTableResultSet);
-
- }
-
- private FakeMetadataFacade exampleCase4308(){
-
- // Create models
- FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
- FakeMetadataObject vm1 = FakeMetadataFactory.createVirtualModel("vm1"); //$NON-NLS-1$
-
- // Create physical groups
- FakeMetadataObject pm1g1 =
- FakeMetadataFactory.createPhysicalGroup("pm1.g1", pm1); //$NON-NLS-1$
-
- // Create physical elements
- 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 });
-
-
- 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$
-
-
- List stagingTableElements =
- FakeMetadataFactory.createElements(
- stagingTable,
- 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 });
-
- MappingDocument doc = new MappingDocument(false);
-
- 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);
-
-
- // Create virtual documents
- // DOC 1
- FakeMetadataObject doc1 =
- FakeMetadataFactory.createVirtualGroup(
- "vm1.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);
- }
-
- private static final boolean DEBUG = false;
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLPlanner.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLPlanner.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLPlanner.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLPlanner.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,802 @@
+/*
+ * 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 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;
+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.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.parser.QueryParser;
+import org.teiid.query.processor.xml.BlockInstruction;
+import org.teiid.query.processor.xml.EndBlockInstruction;
+import org.teiid.query.processor.xml.ExecSqlInstruction;
+import org.teiid.query.processor.xml.ExecStagingTableInstruction;
+import org.teiid.query.processor.xml.MoveCursorInstruction;
+import org.teiid.query.processor.xml.Program;
+import org.teiid.query.processor.xml.TestXMLProcessor;
+import org.teiid.query.processor.xml.WhileInstruction;
+import org.teiid.query.processor.xml.XMLPlan;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+ at SuppressWarnings("nls")
+public class TestXMLPlanner {
+
+ // ################################## TEST HELPERS ################################
+
+ public static XMLPlan helpPlan(String sql, QueryMetadataInterface md) throws Exception {
+ Command command = TestXMLProcessor.helpGetCommand(sql, md);
+ return preparePlan(command, md, TestOptimizer.getGenericFinder(), null);
+ }
+
+ private void helpPlanException(String sql, QueryMetadataInterface md) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+ Command command = TestXMLProcessor.helpGetCommand(sql, md);
+
+ try {
+ preparePlan(command, md, TestOptimizer.getGenericFinder(), null);
+ fail("Expected exception for planning " + sql); //$NON-NLS-1$
+ } catch (QueryPlannerException e) {
+ // this is expected
+ }
+ }
+
+ public static TransformationMetadata example1() {
+ 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$
+ 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
+ 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 });
+ 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 });
+ 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 });
+ 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 });
+ RealMetadataFactory.createElements(
+ pm1g5,
+ 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 tm1.g1"); //$NON-NLS-1$
+ //selects from temp group
+ 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$
+ vm1g2n1.addBinding("vm1.g1.e1"); //$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$
+ vm1g3n1.addBinding("vm1.g2.e1"); //$NON-NLS-1$
+ Table vm1g3 = RealMetadataFactory.createVirtualGroup("g3", vm1, vm1g3n1); //$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$
+ Table vm1g5 = RealMetadataFactory.createVirtualGroup("g5", vm1, vm1g5n1); //$NON-NLS-1$
+
+ QueryNode tempGroup1 =
+ 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
+ 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 });
+ 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 });
+ 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 });
+ RealMetadataFactory.createElements(
+ 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 });
+ RealMetadataFactory.createElements(
+ vm1g5,
+ 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 });
+ RealMetadataFactory.createElements(
+ tm1g1,
+ 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 documents
+ // DOC 1
+ Table doc1 = RealMetadataFactory.createXmlDocument("doc1", vm1, doc1()); //$NON-NLS-1$
+ RealMetadataFactory.createElements(
+ doc1,
+ new String[] {
+ "a0", //$NON-NLS-1$
+ "a0.a1", //$NON-NLS-1$
+ "a0.a1.a1", //$NON-NLS-1$
+ "a0.a1.b1", //$NON-NLS-1$
+ "a0.a1.c1" }, //$NON-NLS-1$
+ new String[] {
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING });
+
+ // DOC 2
+ 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
+ Table doc3 = RealMetadataFactory.createXmlDocument("doc3", vm1, doc3()); //$NON-NLS-1$
+ RealMetadataFactory.createElements(
+ doc3,
+ new String[] {
+ "root", //$NON-NLS-1$
+ "root.n1", //$NON-NLS-1$
+ "root.n1.m1", //$NON-NLS-1$
+ "root.n1.m1.n2", //$NON-NLS-1$
+ "root.n1.m1.n2.leaf1" }, //$NON-NLS-1$
+ new String[] {
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING });
+
+ // DOC 4
+ Table doc4 = RealMetadataFactory.createXmlDocument("doc4", vm1, doc4()); //$NON-NLS-1$
+ RealMetadataFactory.createElements(
+ doc4,
+ new String[] {
+ "root", //$NON-NLS-1$
+ "root.n4a", //$NON-NLS-1$
+ "root.n4a.n4b", //$NON-NLS-1$
+ "root.n4a.n4c", //$NON-NLS-1$
+ "root.n4a.fake", //$NON-NLS-1$
+ "root.n4a.n4c.n4d", //$NON-NLS-1$
+ "root.n4a.n4c.n4e", //$NON-NLS-1$
+ "root.n4a.n4c.n4e.n4f" }, //$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 });
+
+ // DOC 5
+ Table doc5 = RealMetadataFactory.createXmlDocument("doc5", vm1, doc5()); //$NON-NLS-1$
+ RealMetadataFactory.createElements(
+ doc5,
+ new String[] {
+ "root", //$NON-NLS-1$
+ "root.nodea", //$NON-NLS-1$
+ "root.nodea.nodeb", //$NON-NLS-1$
+ "root.nodea.nodec", //$NON-NLS-1$
+ "root.nodea.nodec.noded", //$NON-NLS-1$
+ "root.nodea.nodec.nodee", //$NON-NLS-1$
+ "root.nodea.nodec.nodee.nodef", //$NON-NLS-1$
+ "root.nodea.nodec.nodee.nodeg", //$NON-NLS-1$
+ "root.nodea.nodec.nodee.nodeg.nodeh", //$NON-NLS-1$
+ "root.nodea.nodec.nodee.nodeg.nodeI", //$NON-NLS-1$
+ "root.nodea.nodec.nodee.nodeg.nodeI.nodeJ" }, //$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 });
+
+ // DOC 6
+ 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
+ Table docWithExcluded = RealMetadataFactory.createXmlDocument(
+ "vm1.docWithExcluded", //$NON-NLS-1$
+ vm1,
+ docWithExcluded());
+ RealMetadataFactory.createElements(
+ docWithExcluded,
+ new String[] {
+ "root", //$NON-NLS-1$
+ "root.n1", //$NON-NLS-1$
+ "root.n1.m1", //$NON-NLS-1$
+ "root.n1.m1.n2", //$NON-NLS-1$
+ "root.n1.m1.n2.leaf1" }, //$NON-NLS-1$
+ new String[] {
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING });
+
+ // DOC 2 with excluded fragment
+ Table doc2WithExcluded = RealMetadataFactory.createXmlDocument(
+ "vm1.docWithExcluded2", //$NON-NLS-1$
+ vm1,
+ docWithExcluded2());
+ RealMetadataFactory.createElements(
+ doc2WithExcluded,
+ new String[] {
+ "root", //$NON-NLS-1$
+ "root.n1", //$NON-NLS-1$
+ "root.n1.m1", //$NON-NLS-1$
+ "root.n1.m2", //$NON-NLS-1$
+ "root.n1.m3" }, //$NON-NLS-1$
+ new String[] {
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING });
+
+
+ // DOC with attribute
+ Table docWithAttribute = RealMetadataFactory.createXmlDocument(
+ "vm1.docWithAttribute", //$NON-NLS-1$
+ vm1,
+ docTestConvertCriteriaWithAttribute());
+ Table docWithAttribute3 = RealMetadataFactory.createXmlDocument(
+ "vm1.docWithAttribute3", //$NON-NLS-1$
+ vm1,
+ docTestCriteriaWithAttribute());
+ RealMetadataFactory.createElements(
+ docWithAttribute,
+ new String[] {
+ "root", //$NON-NLS-1$
+ "root.myElement", //$NON-NLS-1$
+ "root. at myAttribute"}, //$NON-NLS-1$
+ new String[] {
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING });
+ // DOC with attribute2
+ Table docWithAttribute2 = RealMetadataFactory.createXmlDocument(
+ "vm1.docWithAttribute2", //$NON-NLS-1$
+ vm1,
+ docTestConvertCriteriaWithAttribute2());
+ RealMetadataFactory.createElements(
+ docWithAttribute2,
+ new String[] {
+ "root", //$NON-NLS-1$
+ "root.myElement", //$NON-NLS-1$
+ "root. at myAttribute"}, //$NON-NLS-1$
+ new String[] {
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING });
+
+ RealMetadataFactory.createElements(
+ docWithAttribute3,
+ new String[] {
+ "root", //$NON-NLS-1$
+ "root.myElement", //$NON-NLS-1$
+ "root. at type"}, //$NON-NLS-1$
+ new String[] {
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.STRING });
+
+ // Create the facade from the store
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "example1");
+ }
+
+ private static MappingDocument doc1() {
+ // DOC 1
+ MappingDocument doc = new MappingDocument(false);
+
+ MappingElement node= doc.addChildElement(new MappingElement("a0")); //$NON-NLS-1$
+
+ MappingElement sourceNode = node.addChildElement(new MappingElement("a1")); //$NON-NLS-1$
+ sourceNode.setSource("vm1.g1"); //$NON-NLS-1$
+
+ sourceNode.addStagingTable("tm1.g1"); //$NON-NLS-1$
+
+ sourceNode.addChildElement(new MappingElement("a1", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+ sourceNode.addChildElement(new MappingElement("b1", "vm1.g1.e2")); //$NON-NLS-1$ //$NON-NLS-2$
+ sourceNode.addChildElement(new MappingElement("c1", "vm1.g1.e3")); //$NON-NLS-1$ //$NON-NLS-2$
+ return doc;
+ }
+
+ private static MappingDocument doc2() {
+ MappingDocument doc = new MappingDocument(false);
+ MappingElement A1 = doc.addChildElement(new MappingElement("a1", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+ A1.setSource("vm1.g1"); //$NON-NLS-1$
+ return doc;
+ }
+
+ private static MappingDocument docTestConvertCriteriaWithAttribute() {
+ MappingDocument doc = new MappingDocument(false);
+
+ MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+ root.setSource("vm1.g1"); //$NON-NLS-1$
+
+ root.addChildElement(new MappingElement("myElement", "vm1.g1.e2")); //$NON-NLS-1$ //$NON-NLS-2$
+ root.addAttribute(new MappingAttribute("myAttribute", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+ return doc;
+ }
+
+ private static MappingDocument docTestConvertCriteriaWithAttribute2() {
+ MappingDocument doc = new MappingDocument(false);
+
+ MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+ root.setSource("vm1.g1"); //$NON-NLS-1$
+ root.addAttribute(new MappingAttribute("myAttribute", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());
+ seq.addChildElement(new MappingElement("myElement", "vm1.g1.e2")); //$NON-NLS-1$ //$NON-NLS-2$
+ return doc;
+ }
+
+ /*
+ * Note: this should fail when validator starts verifying that vm1.g1 cannot
+ * be executed before the temp group tm1.g1 is, since it selects from that
+ * group but is not in it's scope
+ */
+ private static MappingDocument doc3() {
+ MappingDocument doc = new MappingDocument(false);
+
+ MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+ MappingElement n1 = root.addChildElement(new MappingElement("n1")); //$NON-NLS-1$
+ n1.setSource("vm1.g1"); //$NON-NLS-1$
+
+ MappingElement m1 = n1.addChildElement(new MappingElement("m1")); //$NON-NLS-1$
+
+ MappingElement n2 = m1.addChildElement(new MappingElement("n2")); //$NON-NLS-1$
+ n2.setSource("vm1.g2"); //$NON-NLS-1$
+ n2.addStagingTable("tm1.g1"); //$NON-NLS-1$
+
+ n2.addChildElement(new MappingElement("leaf1", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ return doc;
+ }
+
+ private static MappingDocument doc4() {
+
+ MappingDocument doc = new MappingDocument(false);
+
+ MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+ MappingElement n4a = root.addChildElement(new MappingElement("n4a")); //$NON-NLS-1$
+ n4a.setMaxOccurrs(-1);
+ n4a.setSource("vm1.g1"); //$NON-NLS-1$
+ n4a.addStagingTable("tm1.g1"); //$NON-NLS-1$
+ n4a.addChildElement(new MappingElement("n4b", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement n4c = n4a.addChildElement(new MappingElement("n4c")); //$NON-NLS-1$
+ n4c.setMaxOccurrs(-1);
+ n4c.setSource("vm1.g2"); //$NON-NLS-1$
+
+ //this node can't be used for anything but searching through mapping doc for this property
+ MappingElement fake = n4a.addChildElement(new MappingElement("fake")); //$NON-NLS-1$
+ fake.setSource("fakeResultSet"); //$NON-NLS-1$
+
+ n4c.addChildElement(new MappingElement("n4d", "vm1.g2.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement n4e = n4c.addChildElement(new MappingElement("n4e")); //$NON-NLS-1$
+ n4e.setSource("vm1.g3"); //$NON-NLS-1$
+ n4e.setMaxOccurrs(-1);
+ n4e.addChildElement(new MappingElement("n4f", "vm1.g3.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ return doc;
+ }
+
+ private static MappingDocument doc5() {
+
+ MappingDocument doc = new MappingDocument(false);
+
+ MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+ MappingElement nodea = root.addChildElement(new MappingElement("nodea")); //$NON-NLS-1$
+ nodea.setSource("vm1.g1"); //$NON-NLS-1$
+ nodea.addStagingTable("tm1.g1"); //$NON-NLS-1$
+ nodea.setMaxOccurrs(-1);
+
+ nodea.addChildElement(new MappingElement("nodeb", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement nodec = nodea.addChildElement(new MappingElement("nodec")); //$NON-NLS-1$
+ nodec.setMaxOccurrs(-1);
+ nodec.setSource("vm1.g2"); //$NON-NLS-1$
+
+ nodec.addChildElement(new MappingElement("noded", "vm1.g2.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement nodee = nodec.addChildElement(new MappingElement("nodee")); //$NON-NLS-1$
+ nodee.setSource("vm1.g3"); //$NON-NLS-1$
+ nodee.setMaxOccurrs(-1);
+
+ nodee.addChildElement(new MappingElement("nodef", "vm1.g3.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement nodeg = nodee.addChildElement(new MappingElement("nodeg")); //$NON-NLS-1$
+ nodeg.setSource("vm1.g4"); //$NON-NLS-1$
+ nodeg.setMaxOccurrs(-1);
+
+ nodeg.addChildElement(new MappingElement("nodeh", "vm1.g4.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement nodeI = nodeg.addChildElement(new MappingElement("nodeI")); //$NON-NLS-1$
+ nodeI.setMaxOccurrs(-1);
+ nodeI.setSource("vm1.g5"); //$NON-NLS-1$
+ nodeI.addChildElement(new MappingElement("nodeJ", "vm1.g5.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ return doc;
+ }
+
+ private static MappingDocument doc6() {
+ MappingDocument doc = new MappingDocument(false);
+
+ MappingElement simpleRoot = doc.addChildElement(new MappingElement("tempGroupTest")); //$NON-NLS-1$
+ simpleRoot.setSource("vm1.g1"); //$NON-NLS-1$
+ simpleRoot.addStagingTable("tm1.g1"); //$NON-NLS-1$
+ return doc;
+ }
+
+ private static MappingDocument docWithExcluded() {
+
+ MappingDocument doc = new MappingDocument(false);
+ MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+ MappingElement n1 = root.addChildElement(new MappingElement("n1")); //$NON-NLS-1$
+ n1.setSource("vm1.g1"); //$NON-NLS-1$
+
+ MappingElement m1 = n1.addChildElement(new MappingElement("m1", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement n2 = m1.addChildElement(new MappingElement("n2")); //$NON-NLS-1$
+ n2.setSource("vm1.g2"); //$NON-NLS-1$
+ n2.setExclude(true);
+ n2.addChildElement(new MappingElement("leaf1", "vm1.g2.e2")); //$NON-NLS-1$ //$NON-NLS-2$
+ return doc;
+ }
+
+ private static MappingDocument docWithExcluded2() {
+
+ MappingDocument doc = new MappingDocument(false);
+ MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+ MappingElement n1 = root.addChildElement(new MappingElement("n1")); //$NON-NLS-1$
+ n1.setSource("vm1.g1"); //$NON-NLS-1$
+
+ n1.addChildElement(new MappingElement("m1", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement m2 = n1.addChildElement(new MappingElement("m2", "vm1.g1.e2")); //$NON-NLS-1$ //$NON-NLS-2$
+ m2.setExclude(true);
+
+ n1.addChildElement(new MappingElement("m3", "vm1.g1.e3")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ return doc;
+ }
+
+ private static MappingDocument docTestCriteriaWithAttribute() {
+
+ MappingDocument doc = new MappingDocument(false);
+
+ MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+ root.setSource("vm1.g1"); //$NON-NLS-1$
+ root.addAttribute(new MappingAttribute("type", new Namespace("xsi", ""))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ root.addAttribute(new MappingAttribute("type", "vm1.g1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+ root.addChildElement(new MappingElement("myElement", "vm1.g1.e2")); //$NON-NLS-1$ //$NON-NLS-2$
+ return doc;
+ }
+
+
+ @Test public void test1() throws Exception {
+ helpPlan("SELECT * FROM vm1.doc1", example1()); //$NON-NLS-1$
+ }
+
+ /**
+ * Tests that a user cannot cite an invalid XML node in criteria
+ * (a node that is not mapped to data)
+ * (Also duplicate defect 8130)
+ */
+ @Test public void test1_defect7341() throws Exception {
+ helpPlanException("SELECT * FROM vm1.doc1 WHERE a0 = '3'", example1()); //$NON-NLS-1$
+ }
+
+ /**
+ * Tests that a user cannot cite an invalid XML node in criteria
+ * (a node that is not mapped to data)
+ * (Also duplicate defect 8130)
+ */
+ @Test public void test1_defect7341_a() throws Exception {
+ helpPlanException(
+ "SELECT * FROM vm1.doc3 WHERE context(m1, m1) = '3'", //$NON-NLS-1$
+ example1());
+ }
+
+ @Test public void test2() throws Exception {
+ helpPlan("SELECT * FROM vm1.doc2", example1()); //$NON-NLS-1$
+ }
+
+ @Test public void test3() throws Exception {
+ helpPlan("SELECT * FROM vm1.doc1 where a0.a1.a1='x'", example1()); //$NON-NLS-1$
+ }
+
+ /**
+ * Note: this should fail when validator starts verifying that vm1.g1 cannot
+ * be executed before the temp group tm1.g1 is, since it selects from that
+ * group but is not in it's scope
+ */
+ @Test public void test4() throws Exception {
+ helpPlan("SELECT * FROM vm1.doc3", example1()); //$NON-NLS-1$
+ }
+
+ @Test public void testTempGroupPlan() throws Exception {
+ QueryMetadataInterface qmi = example1();
+
+ XMLPlan plan = helpPlan("SELECT * FROM vm1.doc6", qmi); //$NON-NLS-1$
+
+ Program program = plan.getOriginalProgram();
+
+ int i = 0;
+ assertTrue(program.getInstructionAt(i++) instanceof ExecStagingTableInstruction);
+ assertTrue(program.getInstructionAt(i++) instanceof ExecSqlInstruction);
+ assertTrue(program.getInstructionAt(i++) instanceof BlockInstruction);
+ assertTrue(program.getInstructionAt(i++) instanceof MoveCursorInstruction);
+ assertTrue(program.getInstructionAt(i++) instanceof WhileInstruction);
+ assertTrue(program.getInstructionAt(i++) instanceof EndBlockInstruction);
+ assertTrue(program.getInstructionAt(i++) instanceof ExecStagingTableInstruction);
+ }
+
+ @Test public void testPreparePlan() throws Exception {
+ helpPlan(
+ "SELECT * FROM vm1.doc1 ORDER BY vm1.doc1.a0.a1.c1", //$NON-NLS-1$
+ example1());
+ }
+
+ @Test public void testPreparePlan2() throws Exception {
+ helpPlan(
+ "SELECT root. at myAttribute FROM vm1.docWithAttribute", //$NON-NLS-1$
+ example1());
+ }
+
+ /**
+ * This method takes in a Command object of the user's query and returns a XML plan
+ * as a XMLNode object.
+ * @param command The Command object for which query plan is to be returned
+ * @param metadata The metadata needed for planning
+ * @return The XML plan returned as an XMLPlan object
+ * @throws QueryPlannerException
+ * @throws QueryMetadataException
+ * @throws TeiidComponentException
+ */
+ 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) {
+ System.out.println("\n####################################\n" + command); //$NON-NLS-1$
+ }
+ return XMLPlanner.preparePlan(command, metadata, analysis, new XMLPlannerEnvironment(metadata), idGenerator, capFinder, context);
+ } finally {
+ if (DEBUG) {
+ System.out.println(analysis.getDebugLog());
+ }
+ }
+ }
+
+ @Test public void testDefect18227() throws Exception {
+ QueryMetadataInterface metadata = example1();
+ String sql = "select * from vm1.docWithAttribute3 where root. at type = '3'"; //$NON-NLS-1$
+
+ Query query = (Query)TestXMLProcessor.helpGetCommand(sql, metadata);
+
+ try {
+ preparePlan(query, metadata, TestOptimizer.getGenericFinder(), new CommandContext());
+ fail("Expected to get error about criteria against unmapped type attribute"); //$NON-NLS-1$
+ } catch(QueryPlannerException e) {
+ // Expect to get exception about criteria against xsi:type
+ }
+ }
+
+ @Test public void testDefect21983() throws Exception {
+ QueryMetadataInterface metadata = example1();
+ String sql = "select root. at type from vm1.docWithAttribute3"; //$NON-NLS-1$
+
+ Query query = (Query)TestXMLProcessor.helpGetCommand(sql, metadata);
+
+ //here's the test
+ preparePlan(query, metadata, TestOptimizer.getGenericFinder(), new CommandContext());
+ }
+
+ /**
+ * Test that if non-fully-qualified staging table name is used in user criteria, that fully-qualified
+ * name is returned by XMLPlanner
+ * @throws Exception
+ */
+ @Test public void testRootStagingTableCase4308() throws Exception{
+
+ String sql = "select * from vm1.doc1 where stagingTable2.e1 IN ('a', 'b', 'c')"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = exampleCase4308();
+
+ Query query = (Query)new QueryParser().parseCommand(sql);
+ QueryResolver.resolveCommand(query, metadata);
+
+ String expectedStagingTableResultSet = "vm1.doc1.stagingTable2"; //$NON-NLS-1$
+ String actualStagingTableResultSet = CriteriaPlanner.getStagingTableForConjunct(query.getCriteria(), metadata);
+
+ assertEquals(expectedStagingTableResultSet, actualStagingTableResultSet);
+
+ }
+
+ private TransformationMetadata exampleCase4308(){
+ 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$
+
+ // Create physical elements
+ 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 });
+
+
+ QueryNode stagingTableNode =
+ new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$
+ Table stagingTable = RealMetadataFactory.createXmlStagingTable("doc1.stagingTable2", vm1, stagingTableNode); //$NON-NLS-1$
+
+ RealMetadataFactory.createElements(
+ stagingTable,
+ 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 });
+
+ MappingDocument doc = new MappingDocument(false);
+
+ MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+ root.addStagingTable("vm1.doc1.stagingTable2");
+
+ // Create virtual documents
+ // DOC 1
+ RealMetadataFactory.createXmlDocument(
+ "doc1", //$NON-NLS-1$
+ vm1,
+ doc);
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "case4308");
+ }
+
+ private static final boolean DEBUG = false;
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestOptionsAndHints.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/parser/TestOptionsAndHints.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestOptionsAndHints.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1159 +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.parser;
-
-import static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.query.sql.lang.AbstractCompareCriteria;
-import org.teiid.query.sql.lang.CacheHint;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.From;
-import org.teiid.query.sql.lang.FromClause;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.JoinPredicate;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.Option;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.SubqueryFromClause;
-import org.teiid.query.sql.lang.UnaryFromClause;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.lang.SetQuery.Operation;
-import org.teiid.query.sql.proc.AssignmentStatement;
-import org.teiid.query.sql.proc.Block;
-import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
-import org.teiid.query.sql.proc.CriteriaSelector;
-import org.teiid.query.sql.proc.DeclareStatement;
-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.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.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.Reference;
-
- at SuppressWarnings("nls")
-public class TestOptionsAndHints {
-
- /*+* Select a From db.g1 MAKENOTDEP, db.g2 MAKENOTDEP WHERE a = b */
- @Test public void testOptionMakeNotDepInline4(){
- GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
- GroupSymbol g2 = new GroupSymbol("c", "db.g2"); //$NON-NLS-1$ //$NON-NLS-2$
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
-
- CompareCriteria crit = new CompareCriteria(a, CompareCriteria.EQ, b);
-
- From from = new From();
- FromClause clause = new UnaryFromClause(g1);
- clause.setMakeNotDep(true);
- from.addClause(clause);
- FromClause clause1 = new UnaryFromClause(g2);
- clause1.setMakeNotDep(true);
- from.addClause(clause1);
-
- Select select = new Select();
- select.addSymbol(a);
-
- Query query = new Query();
- query.setSelect(select);
- 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$
- query);
- }
-
- /*+* Select a From db.g1 JOIN db.g2 MAKEDEP ON a = b */
- @Test public void testOptionMakeDepInline1(){
- GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
- GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
-
- List crits = new ArrayList();
- crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
- JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
- jp.getRightClause().setMakeDep(true);
- From from = new From();
- from.addClause(jp);
-
- Select select = new Select();
- select.addSymbol(a);
-
- Query query = new Query();
- 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$
- query);
- }
-
- /*+* Select a From db.g1 MAKEDEP JOIN db.g2 ON a = b */
- @Test public void testOptionMakeDepInline2(){
- GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
- GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
-
- List crits = new ArrayList();
- crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
- JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
- jp.getLeftClause().setMakeDep(true);
- From from = new From();
- from.addClause(jp);
-
- Select select = new Select();
- select.addSymbol(a);
-
- Query query = new Query();
- 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$
- query);
- }
-
- /*+* Select a From (db.g1 MAKEDEP JOIN db.g2 ON a = b) LEFT OUTER JOIN db.g3 MAKEDEP ON a = c */
- @Test public void testOptionMakeDepInline3(){
- GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
- GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
- GroupSymbol g3 = new GroupSymbol("db.g3"); //$NON-NLS-1$
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
- ElementSymbol c = new ElementSymbol("c"); //$NON-NLS-1$
-
- List crits = new ArrayList();
- crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
- JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
- jp.getLeftClause().setMakeDep(true);
- List crits2 = new ArrayList();
- crits2.add(new CompareCriteria(a, CompareCriteria.EQ, c));
- JoinPredicate jp2 = new JoinPredicate(jp, new UnaryFromClause(g3), JoinType.JOIN_LEFT_OUTER, crits2);
- jp2.getRightClause().setMakeDep(true);
- From from = new From();
- from.addClause(jp2);
-
- Select select = new Select();
- select.addSymbol(a);
-
- Query query = new Query();
- 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$
- query);
- }
-
- /*+* Select a From db.g1 MAKEDEP, db.g2 MAKEDEP WHERE a = b */
- @Test public void testOptionMakeDepInline4(){
- GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
- GroupSymbol g2 = new GroupSymbol("c", "db.g2"); //$NON-NLS-1$ //$NON-NLS-2$
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
-
- CompareCriteria crit = new CompareCriteria(a, CompareCriteria.EQ, b);
-
- From from = new From();
- FromClause clause = new UnaryFromClause(g1);
- clause.setMakeDep(true);
- from.addClause(clause);
- FromClause clause1 = new UnaryFromClause(g2);
- clause1.setMakeDep(true);
- from.addClause(clause1);
-
- Select select = new Select();
- select.addSymbol(a);
-
- Query query = new Query();
- query.setSelect(select);
- 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$
- query);
- }
-
- @Test public void testOptionMakedep() throws Exception {
- String sql = "SELECT A.alert_id " + //$NON-NLS-1$
- "FROM (FSK_ALERT AS A MAKEDEP INNER JOIN Core.FSC_PARTY_DIM AS C ON A.primary_entity_key = C.PARTY_KEY) " +//$NON-NLS-1$
- "LEFT OUTER JOIN FSK_SCENARIO AS S ON A.scenario_id = S.scenario_id ";//$NON-NLS-1$
- Query command = (Query)new QueryParser().parseCommand(sql);
- JoinPredicate predicate = (JoinPredicate)command.getFrom().getClauses().get(0);
- assertTrue(((JoinPredicate)predicate.getLeftClause()).getLeftClause().isMakeDep());
- }
-
- /*+* Select a From db.g1 JOIN db.g2 MAKENOTDEP ON a = b */
- @Test public void testOptionMakeNotDepInline1(){
- GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
- GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
-
- List crits = new ArrayList();
- crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
- JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
- jp.getRightClause().setMakeNotDep(true);
- From from = new From();
- from.addClause(jp);
-
- Select select = new Select();
- select.addSymbol(a);
-
- Query query = new Query();
- 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$
- query);
- }
-
- /*+* Select a From db.g1 MAKENOTDEP JOIN db.g2 ON a = b */
- @Test public void testOptionMakeNotDepInline2(){
- GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
- GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
-
- List crits = new ArrayList();
- crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
- JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
- jp.getLeftClause().setMakeNotDep(true);
- From from = new From();
- from.addClause(jp);
-
- Select select = new Select();
- select.addSymbol(a);
-
- Query query = new Query();
- 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$
- query);
- }
-
- /*+* Select a From (db.g1 MAKENOTDEP JOIN db.g2 ON a = b) LEFT OUTER JOIN db.g3 MAKENOTDEP ON a = c */
- @Test public void testOptionMakeNotDepInline3(){
- GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
- GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
- GroupSymbol g3 = new GroupSymbol("db.g3"); //$NON-NLS-1$
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
- ElementSymbol c = new ElementSymbol("c"); //$NON-NLS-1$
-
- List crits = new ArrayList();
- crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
- JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
- jp.getLeftClause().setMakeNotDep(true);
- List crits2 = new ArrayList();
- crits2.add(new CompareCriteria(a, CompareCriteria.EQ, c));
- JoinPredicate jp2 = new JoinPredicate(jp, new UnaryFromClause(g3), JoinType.JOIN_LEFT_OUTER, crits2);
- jp2.getRightClause().setMakeNotDep(true);
- From from = new From();
- from.addClause(jp2);
-
- Select select = new Select();
- select.addSymbol(a);
-
- Query query = new Query();
- 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$
- query);
- }
-
- @Test public void testDepOptions2() {
- GroupSymbol a = new GroupSymbol("a"); //$NON-NLS-1$
- GroupSymbol b = new GroupSymbol("b"); //$NON-NLS-1$
- ElementSymbol x = new ElementSymbol("a.x", true); //$NON-NLS-1$
- ElementSymbol y = new ElementSymbol("b.y", true); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(x, CompareCriteria.EQ, new Function("func", new Expression[] {y})); //$NON-NLS-1$
- JoinPredicate predicate = new JoinPredicate(new UnaryFromClause(a), new UnaryFromClause(b), JoinType.JOIN_INNER, Arrays.asList(new Object[] {criteria}));
- 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}));
-
- 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$
- query);
- }
-
- @Test public void testOptionNoCache1(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Option option = new Option();
- option.setNoCache(true);
- option.addNoCacheGroup("a.b.c"); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setOption(option);
- TestParser.helpTest("Select a From db.g Option nocache a.b.c", //$NON-NLS-1$
- "SELECT a FROM db.g OPTION NOCACHE a.b.c", //$NON-NLS-1$
- query);
- }
-
- @Test public void testOptionNoCache2(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Option option = new Option();
- option.setNoCache(true);
- option.addNoCacheGroup("a.b.c"); //$NON-NLS-1$
- option.addNoCacheGroup("d.e.f"); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setOption(option);
- TestParser.helpTest("Select a From db.g Option nocache a.b.c, d.e.f", //$NON-NLS-1$
- "SELECT a FROM db.g OPTION NOCACHE a.b.c, d.e.f", //$NON-NLS-1$
- query);
- }
-
-// related to defect 14423
- @Test public void testOptionNoCache3(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Option option = new Option();
- option.setNoCache(true);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setOption(option);
- TestParser.helpTest("Select a From db.g Option nocache", //$NON-NLS-1$
- "SELECT a FROM db.g OPTION NOCACHE", //$NON-NLS-1$
- query);
- }
-
- /*+* SELECT a from g OPTION xyx */
- @Test public void testFailsIllegalOption(){
- TestParser.helpException("SELECT a from g OPTION xyx"); //$NON-NLS-1$
- }
-
- @Test public void testInsertWithOption() {
- Insert insert = new Insert();
- insert.setGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- List vars = new ArrayList();
- vars.add(new ElementSymbol("a")); //$NON-NLS-1$
- insert.setVariables(vars);
- List values = new ArrayList();
- values.add(new Reference(0));
- insert.setValues(values);
- Option option = new Option();
- option.setNoCache(true);
- insert.setOption(option);
- TestParser.helpTest("INSERT INTO m.g (a) VALUES (?) OPTION NOCACHE", //$NON-NLS-1$
- "INSERT INTO m.g (a) VALUES (?) OPTION NOCACHE", //$NON-NLS-1$
- insert);
- }
-
- @Test public void testDeleteWithOption() {
- Delete delete = new Delete();
- delete.setGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- Option option = new Option();
- option.setNoCache(true);
- delete.setOption(option);
- TestParser.helpTest("DELETE FROM m.g OPTION NOCACHE", //$NON-NLS-1$
- "DELETE FROM m.g OPTION NOCACHE", //$NON-NLS-1$
- delete);
- }
-
- @Test public void testUpdateWithOption() {
- Update update = new Update();
- update.setGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- update.addChange(new ElementSymbol("a"), new Reference(0));
- Option option = new Option();
- option.setNoCache(true);
- Criteria crit = new CompareCriteria(new ElementSymbol("b"), CompareCriteria.EQ, new Reference(1)); //$NON-NLS-1$
- update.setCriteria(crit);
- TestParser.helpTest("UPDATE m.g SET a = ? WHERE b = ? OPTION NOCACHE", //$NON-NLS-1$
- "UPDATE m.g SET a = ? WHERE b = ? OPTION NOCACHE", //$NON-NLS-1$
- update);
- }
-
- @Test public void testOptionalFromClause1() {
- String sql = "SELECT * FROM /*+ optional */ t1, t2"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- UnaryFromClause ufc = new UnaryFromClause();
- ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- ufc.setOptional(true);
- from.addClause(ufc);
- from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1, t2", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause1_1() {
- String sql = "SELECT * FROM /*+ optional*/ t1, t2"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- UnaryFromClause ufc = new UnaryFromClause();
- ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- ufc.setOptional(true);
- from.addClause(ufc);
- from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1, t2", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause1_2() {
- String sql = "SELECT * FROM /*+optional */ t1, t2"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- UnaryFromClause ufc = new UnaryFromClause();
- ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- ufc.setOptional(true);
- from.addClause(ufc);
- from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1, t2", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause1_3() {
- String sql = "SELECT * FROM /*+ optional */ t1, t2"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- UnaryFromClause ufc = new UnaryFromClause();
- ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- ufc.setOptional(true);
- from.addClause(ufc);
- from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1, t2", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause1_4() {
- String sql = "SELECT * /*+ optional */ FROM /*+ OptiOnal */ t1, t2"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- UnaryFromClause ufc = new UnaryFromClause();
- ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- ufc.setOptional(true);
- from.addClause(ufc);
- from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1, t2", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause1_5() {
- String sql = "SELECT * FROM /*+ OptiOnal */ t1, t2"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- UnaryFromClause ufc = new UnaryFromClause();
- ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- ufc.setOptional(true);
- from.addClause(ufc);
- from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1, t2", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause2() {
- String sql = "SELECT * FROM t1, /*+ optional */ t2"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- from.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- UnaryFromClause ufc = new UnaryFromClause();
- ufc.setGroup(new GroupSymbol("t2")); //$NON-NLS-1$
- ufc.setOptional(true);
- from.addClause(ufc);
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT * FROM t1, /*+ optional */ t2", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause3() {
- String sql = "SELECT * FROM /*+ optional */ t1 AS a, t2"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- UnaryFromClause ufc = new UnaryFromClause();
- ufc.setGroup(new GroupSymbol("a", "t1")); //$NON-NLS-1$ //$NON-NLS-2$
- ufc.setOptional(true);
- from.addClause(ufc);
- from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1 AS a, t2", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause4() {
- String sql = "SELECT * FROM t1, /*+ optional */ t2 as a"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- from.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- UnaryFromClause ufc = new UnaryFromClause();
- ufc.setGroup(new GroupSymbol("a", "t2")); //$NON-NLS-1$ //$NON-NLS-2$
- ufc.setOptional(true);
- from.addClause(ufc);
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT * FROM t1, /*+ optional */ t2 AS a", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause5() {
- String sql = "SELECT * FROM t1, /*+ optional */ (select * from t1, t2) as x"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
-
- Query query2 = new Query();
- select = new Select();
- select.addSymbol(new AllSymbol());
- query2.setSelect(select);
- From from2 = new From();
- from2.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- from2.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
- query2.setFrom(from2);
-
- SubqueryFromClause sfc = new SubqueryFromClause("x", query2);//$NON-NLS-1$
- sfc.setOptional(true);
- from.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- from.addClause(sfc);
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT * FROM t1, /*+ optional */ (SELECT * FROM t1, t2) AS x", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause6() {
- String sql = "SELECT * FROM t1 INNER JOIN /*+ optional */ (select a from t1, t2) AS x ON t1.a=x.a"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
-
- Query query2 = new Query();
- select = new Select();
- select.addSymbol(new ElementSymbol("a"));//$NON-NLS-1$
- From from2 = new From();
- from2.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- from2.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
- query2.setSelect(select);
- query2.setFrom(from2);
-
- UnaryFromClause ufc = new UnaryFromClause();
- ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
-
- SubqueryFromClause sfc = new SubqueryFromClause("x", query2);//$NON-NLS-1$
- sfc.setOptional(true);
-
- List criteria = new ArrayList();
- criteria.add(new CompareCriteria(new ElementSymbol("t1.a"), AbstractCompareCriteria.EQ, new ElementSymbol("x.a")));//$NON-NLS-1$//$NON-NLS-2$
- JoinPredicate joinPredicate = new JoinPredicate(ufc, sfc, JoinType.JOIN_INNER, criteria);
- from.addClause(joinPredicate);
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT * FROM t1 INNER JOIN /*+ optional */ (SELECT a FROM t1, t2) AS x ON t1.a = x.a", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause7() {
- String sql = "SELECT b FROM t1, /*+ optional */ (t2 INNER JOIN t3 ON t2.a = t3.a)"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new ElementSymbol("b"));//$NON-NLS-1$
- query.setSelect(select);
- From from = new From();
-
- UnaryFromClause ufc = new UnaryFromClause();
- ufc.setGroup(new GroupSymbol("t2")); //$NON-NLS-1$
-
- UnaryFromClause ufc2 = new UnaryFromClause();
- ufc2.setGroup(new GroupSymbol("t3")); //$NON-NLS-1$
-
- List criteria = new ArrayList();
- criteria.add(new CompareCriteria(new ElementSymbol("t2.a"), AbstractCompareCriteria.EQ, new ElementSymbol("t3.a")));//$NON-NLS-1$//$NON-NLS-2$
- JoinPredicate joinPredicate = new JoinPredicate(ufc, ufc2, JoinType.JOIN_INNER, criteria);
- joinPredicate.setOptional(true);
-
- UnaryFromClause ufc3 = new UnaryFromClause();
- ufc3.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- from.addClause(ufc3);
- from.addClause(joinPredicate);
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT b FROM t1, /*+ optional */ (t2 INNER JOIN t3 ON t2.a = t3.a)", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause8() {
- String sql = "SELECT b FROM t1, /*+ optional */ (/*+ optional */ (SELECT * FROM t1, t2) AS x INNER JOIN t3 ON x.a = t3.a)"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new ElementSymbol("b"));//$NON-NLS-1$
- query.setSelect(select);
- From from = new From();
-
-
- Query query2 = new Query();
- select = new Select();
- select.addSymbol(new AllSymbol());
- From from2 = new From();
- from2.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- from2.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
- query2.setSelect(select);
- query2.setFrom(from2);
- SubqueryFromClause sfc = new SubqueryFromClause("x", query2);//$NON-NLS-1$
- sfc.setOptional(true);
-
- UnaryFromClause ufc2 = new UnaryFromClause();
- ufc2.setGroup(new GroupSymbol("t3")); //$NON-NLS-1$
-
- List criteria = new ArrayList();
- criteria.add(new CompareCriteria(new ElementSymbol("x.a"), AbstractCompareCriteria.EQ, new ElementSymbol("t3.a")));//$NON-NLS-1$//$NON-NLS-2$
- JoinPredicate joinPredicate = new JoinPredicate(sfc, ufc2, JoinType.JOIN_INNER, criteria);
- joinPredicate.setOptional(true);
-
- UnaryFromClause ufc3 = new UnaryFromClause();
- ufc3.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- from.addClause(ufc3);
- from.addClause(joinPredicate);
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT b FROM t1, /*+ optional */ (/*+ optional */ (SELECT * FROM t1, t2) AS x INNER JOIN t3 ON x.a = t3.a)", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause9() {
- String sql = "SELECT b FROM (t1 LEFT OUTER JOIN /*+ optional */t2 on t1.a = t2.a) LEFT OUTER JOIN /*+ optional */t3 on t1.a = t3.a"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new ElementSymbol("b"));//$NON-NLS-1$
- query.setSelect(select);
- From from = new From();
-
- UnaryFromClause ufc = new UnaryFromClause();
- ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
-
- UnaryFromClause ufc2 = new UnaryFromClause();
- ufc2.setGroup(new GroupSymbol("t2")); //$NON-NLS-1$
- ufc2.setOptional(true);
-
- List criteria = new ArrayList();
- criteria.add(new CompareCriteria(new ElementSymbol("t1.a"), AbstractCompareCriteria.EQ, new ElementSymbol("t2.a")));//$NON-NLS-1$//$NON-NLS-2$
- JoinPredicate joinPredicate = new JoinPredicate(ufc, ufc2, JoinType.JOIN_LEFT_OUTER, criteria);
-
- UnaryFromClause ufc3 = new UnaryFromClause();
- ufc3.setGroup(new GroupSymbol("t3")); //$NON-NLS-1$
- ufc3.setOptional(true);
-
- criteria = new ArrayList();
- criteria.add(new CompareCriteria(new ElementSymbol("t1.a"), AbstractCompareCriteria.EQ, new ElementSymbol("t3.a")));//$NON-NLS-1$//$NON-NLS-2$
- JoinPredicate joinPredicate2 = new JoinPredicate(joinPredicate, ufc3, JoinType.JOIN_LEFT_OUTER, criteria);
-
- from.addClause(joinPredicate2);
- query.setFrom(from);
-
- TestParser.helpTest(sql, "SELECT b FROM (t1 LEFT OUTER JOIN /*+ optional */ t2 ON t1.a = t2.a) LEFT OUTER JOIN /*+ optional */ t3 ON t1.a = t3.a", query); //$NON-NLS-1$
- }
-
- @Test public void testOptionalFromClause10(){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- From elseFrom = (From)from.clone();
- UnaryFromClause ufc = new UnaryFromClause();
- ufc.setGroup(new GroupSymbol("h")); //$NON-NLS-1$
- ufc.setOptional(true);
- elseFrom.addClause(ufc);
- elseQuery.setFrom(elseFrom);
- elseQuery.setCriteria(criteria);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- //has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.IN);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
-
- Block block = new Block();
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- TestParser.helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
- " IF(HAS IN CRITERIA ON (a)) BEGIN var1 = (SELECT a1 FROM g WHERE a2 = 5); END"+ //$NON-NLS-1$
- " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g, /*+ optional */ h WHERE a2 = 5; END" + //$NON-NLS-1$
- " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- "IF(HAS IN CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g, /*+ optional */ h WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- @Test public void testStoredQueryWithOption(){
- StoredProcedure storedQuery = new StoredProcedure();
- storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
- Option option = new Option();
- option.setNoCache(true);
- storedQuery.setOption(option);
- TestParser.helpTest("exec proc1() option nocache", "EXEC proc1() OPTION NOCACHE", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /*+* Select a From db.g Option SHOWPLAN */
- /*+* Select a From db.g Option makedep a.b.c */
- @Test public void testOptionMakeDependent1(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Option option = new Option();
- option.addDependentGroup("a.b.c"); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setOption(option);
- TestParser.helpTest("Select a From db.g Option makedep a.b.c", //$NON-NLS-1$
- "SELECT a FROM db.g OPTION MAKEDEP a.b.c", //$NON-NLS-1$
- query);
- }
-
- /*+* Select a From db.g Option makedep a.b.c, d.e.f showplan */
- @Test public void testOptionMakeDependent2(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Option option = new Option();
- option.addDependentGroup("a.b.c"); //$NON-NLS-1$
- option.addDependentGroup("d.e.f"); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setOption(option);
- TestParser.helpTest("Select a From db.g Option makedep a.b.c, d.e.f", //$NON-NLS-1$
- "SELECT a FROM db.g OPTION MAKEDEP a.b.c, d.e.f", //$NON-NLS-1$
- query);
- }
-
- /*+* Select a From db.g Option makedep a.b.c, d.e.f, x.y.z */
- @Test public void testOptionMakeDependent3(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Option option = new Option();
- option.addDependentGroup("a.b.c"); //$NON-NLS-1$
- option.addDependentGroup("d.e.f"); //$NON-NLS-1$
- option.addDependentGroup("x.y.z"); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setOption(option);
- TestParser.helpTest("Select a From db.g Option makedep a.b.c, d.e.f, x.y.z", //$NON-NLS-1$
- "SELECT a FROM db.g OPTION MAKEDEP a.b.c, d.e.f, x.y.z", //$NON-NLS-1$
- query);
- }
-
- /*+* Select a From db.g Option makenotdep a.b.c */
- @Test public void testOptionMakeNotDependent1(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Option option = new Option();
- option.addNotDependentGroup("a.b.c"); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setOption(option);
- TestParser.helpTest("Select a From db.g Option makenotdep a.b.c", //$NON-NLS-1$
- "SELECT a FROM db.g OPTION MAKENOTDEP a.b.c", //$NON-NLS-1$
- query);
- }
-
- /*+* Select a From db.g Option makenotdep a.b.c, d.e.f showplan */
- @Test public void testOptionMakeNotDependent2(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Option option = new Option();
- option.addNotDependentGroup("a.b.c"); //$NON-NLS-1$
- option.addNotDependentGroup("d.e.f"); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setOption(option);
- TestParser.helpTest("Select a From db.g Option makeNOTdep a.b.c, d.e.f", //$NON-NLS-1$
- "SELECT a FROM db.g OPTION MAKENOTDEP a.b.c, d.e.f", //$NON-NLS-1$
- query);
- }
-
- /*+* Select a From db.g Option makenotdep a.b.c, d.e.f, x.y.z */
- @Test public void testOptionMakeNotDependent3(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Option option = new Option();
- option.addNotDependentGroup("a.b.c"); //$NON-NLS-1$
- option.addNotDependentGroup("d.e.f"); //$NON-NLS-1$
- option.addNotDependentGroup("x.y.z"); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setOption(option);
- TestParser.helpTest("Select a From db.g Option makenotdep a.b.c, d.e.f, x.y.z", //$NON-NLS-1$
- "SELECT a FROM db.g OPTION MAKENOTDEP a.b.c, d.e.f, x.y.z", //$NON-NLS-1$
- query);
- }
-
- @Test public void testDepOptions1() {
- GroupSymbol a = new GroupSymbol("a"); //$NON-NLS-1$
- GroupSymbol b = new GroupSymbol("b"); //$NON-NLS-1$
- ElementSymbol x = new ElementSymbol("a.x", true); //$NON-NLS-1$
- ElementSymbol y = new ElementSymbol("b.y", true); //$NON-NLS-1$
-
- From from = new From(Arrays.asList(new UnaryFromClause(a), new UnaryFromClause(b)));
-
- Option option = new Option();
- option.addDependentGroup("a"); //$NON-NLS-1$
- option.addNotDependentGroup("b"); //$NON-NLS-1$
-
- Select select = new Select(Arrays.asList(new Object[] {x, y}));
-
- Criteria criteria = new CompareCriteria(x, CompareCriteria.EQ, y);
- Query query = new Query(select, from, criteria, null, null, null, option);
- TestParser.helpTest("Select a.x, b.y From a, b WHERE a.x = b.y option makedep a makenotdep b", //$NON-NLS-1$
- "SELECT a.x, b.y FROM a, b WHERE a.x = b.y OPTION MAKEDEP a MAKENOTDEP b", //$NON-NLS-1$
- query);
- }
-
- @Test public void testOptionMakeDepInline5(){
- GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
- GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
- GroupSymbol g3 = new GroupSymbol("db.g3"); //$NON-NLS-1$
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
- ElementSymbol c = new ElementSymbol("c"); //$NON-NLS-1$
-
- List crits = new ArrayList();
- crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
- JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
- jp.setMakeDep(true);
- List crits2 = new ArrayList();
- crits2.add(new CompareCriteria(a, CompareCriteria.EQ, c));
- JoinPredicate jp2 = new JoinPredicate(jp, new UnaryFromClause(g3), JoinType.JOIN_LEFT_OUTER, crits2);
- From from = new From();
- from.addClause(jp2);
-
- Select select = new Select();
- select.addSymbol(a);
-
- Query query = new Query();
- 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$
- query);
-
- //ensure that the new string form is parsable
- TestParser.helpTest(query.toString(), query.toString(), query);
- }
-
- @Test public void testCache() {
- String sql = "/*+ cache */ SELECT * FROM t1"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- UnaryFromClause ufc = new UnaryFromClause();
- from.addClause(ufc);
- ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- query.setFrom(from);
- query.setCacheHint(new CacheHint());
- TestParser.helpTest(sql, "/*+ cache */ SELECT * FROM t1", query); //$NON-NLS-1$
- }
-
- @Test public void testCacheScope() {
- String sql = "/*+ cache(pref_mem scope:session) */ SELECT * FROM t1"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- UnaryFromClause ufc = new UnaryFromClause();
- from.addClause(ufc);
- ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- query.setFrom(from);
- CacheHint hint = new CacheHint();
- hint.setScope("session");
- hint.setPrefersMemory(true);
- query.setCacheHint(hint);
- TestParser.helpTest(sql, "/*+ cache(pref_mem scope:session) */ SELECT * FROM t1", query); //$NON-NLS-1$
- }
-
- @Test public void testCache1() {
- String sql = "/*+ cache */ execute foo()"; //$NON-NLS-1$
-
- StoredProcedure sp = new StoredProcedure();
- sp.setCacheHint(new CacheHint());
- sp.setProcedureName("foo"); //$NON-NLS-1$
-
- TestParser.helpTest(sql, "/*+ cache */ EXEC foo()", sp); //$NON-NLS-1$
- }
-
- @Test public void testExpandedCacheHint() {
- String sql = "/*+ cache( pref_mem ttl:2000) */ SELECT * FROM t1"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- UnaryFromClause ufc = new UnaryFromClause();
- from.addClause(ufc);
- ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- query.setFrom(from);
- CacheHint hint = new CacheHint();
- hint.setPrefersMemory(true);
- hint.setTtl(Long.valueOf(2000));
- query.setCacheHint(hint);
- TestParser.helpTest(sql, "/*+ cache(pref_mem ttl:2000) */ SELECT * FROM t1", query); //$NON-NLS-1$
- }
-
- @Test public void testCacheHintUnion() {
- String sql = "/*+ cache( pref_mem) */ SELECT * FROM t1 union select * from t2"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- UnaryFromClause ufc = new UnaryFromClause();
- from.addClause(ufc);
- ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
- query.setFrom(from);
-
- Query query1 = new Query();
- select = new Select();
- select.addSymbol(new AllSymbol());
- query1.setSelect(select);
- from = new From();
- ufc = new UnaryFromClause();
- from.addClause(ufc);
- ufc.setGroup(new GroupSymbol("t2")); //$NON-NLS-1$
- query1.setFrom(from);
-
- SetQuery sq = new SetQuery(Operation.UNION, false, query, query1);
- CacheHint hint = new CacheHint();
- hint.setPrefersMemory(true);
- sq.setCacheHint(hint);
- TestParser.helpTest(sql, "/*+ cache(pref_mem) */ SELECT * FROM t1 UNION SELECT * FROM t2", sq); //$NON-NLS-1$
- }
-
- @Test public void testCacheHintCallableStatement() {
- String sql = "/*+ cache */ { ? = call proc() }"; //$NON-NLS-1$
- StoredProcedure sp = new StoredProcedure();
- SPParameter param = new SPParameter(1, null);
- param.setParameterType(SPParameter.RETURN_VALUE);
- sp.setParameter(param);
- sp.setProcedureName("proc");
- sp.setCallableStatement(true);
- CacheHint hint = new CacheHint();
- sp.setCacheHint(hint);
- TestParser.helpTest(sql, "/*+ cache */ ? = EXEC proc()", sp); //$NON-NLS-1$
- }
-
- @Test public void testMergeJoinHint() {
- String sql = "SELECT e1 FROM m.g2 WHERE EXISTS /*+ MJ */ (SELECT e1 FROM m.g1)"; //$NON-NLS-1$
- Query q = TestParser.exampleExists(true);
- TestParser.helpTest(sql, "SELECT e1 FROM m.g2 WHERE EXISTS /*+ MJ */ (SELECT e1 FROM m.g1)", q); //$NON-NLS-1$
- }
-
- @Test public void testMergeJoinHint1() {
- String sql = "SELECT a FROM db.g WHERE b IN /*+ MJ */ (SELECT a FROM db.g WHERE a2 = 5)"; //$NON-NLS-1$
- Query q = TestParser.exampleIn(true);
- TestParser.helpTest(sql, "SELECT a FROM db.g WHERE b IN /*+ MJ */ (SELECT a FROM db.g WHERE a2 = 5)", q); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestOptionsAndHints.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/parser/TestOptionsAndHints.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestOptionsAndHints.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestOptionsAndHints.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1159 @@
+/*
+ * 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.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.query.sql.lang.AbstractCompareCriteria;
+import org.teiid.query.sql.lang.CacheHint;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.From;
+import org.teiid.query.sql.lang.FromClause;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.JoinPredicate;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.lang.Option;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.SubqueryFromClause;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.lang.SetQuery.Operation;
+import org.teiid.query.sql.proc.AssignmentStatement;
+import org.teiid.query.sql.proc.Block;
+import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
+import org.teiid.query.sql.proc.CriteriaSelector;
+import org.teiid.query.sql.proc.DeclareStatement;
+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.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.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.Reference;
+
+ at SuppressWarnings("nls")
+public class TestOptionsAndHints {
+
+ /*+* Select a From db.g1 MAKENOTDEP, db.g2 MAKENOTDEP WHERE a = b */
+ @Test public void testOptionMakeNotDepInline4(){
+ GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
+ GroupSymbol g2 = new GroupSymbol("c", "db.g2"); //$NON-NLS-1$ //$NON-NLS-2$
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
+
+ CompareCriteria crit = new CompareCriteria(a, CompareCriteria.EQ, b);
+
+ From from = new From();
+ FromClause clause = new UnaryFromClause(g1);
+ clause.setMakeNotDep(true);
+ from.addClause(clause);
+ FromClause clause1 = new UnaryFromClause(g2);
+ clause1.setMakeNotDep(true);
+ from.addClause(clause1);
+
+ Select select = new Select();
+ select.addSymbol(a);
+
+ Query query = new Query();
+ query.setSelect(select);
+ 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 /*+ MAKENOTDEP */ db.g1, /*+ MAKENOTDEP */ db.g2 AS c WHERE a = b", //$NON-NLS-1$
+ query);
+ }
+
+ /*+* Select a From db.g1 JOIN db.g2 MAKEDEP ON a = b */
+ @Test public void testOptionMakeDepInline1(){
+ GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
+ GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
+
+ List crits = new ArrayList();
+ crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
+ JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
+ jp.getRightClause().setMakeDep(true);
+ From from = new From();
+ from.addClause(jp);
+
+ Select select = new Select();
+ select.addSymbol(a);
+
+ Query query = new Query();
+ 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 /*+ MAKEDEP */ db.g2 ON a = b", //$NON-NLS-1$
+ query);
+ }
+
+ /*+* Select a From db.g1 MAKEDEP JOIN db.g2 ON a = b */
+ @Test public void testOptionMakeDepInline2(){
+ GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
+ GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
+
+ List crits = new ArrayList();
+ crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
+ JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
+ jp.getLeftClause().setMakeDep(true);
+ From from = new From();
+ from.addClause(jp);
+
+ Select select = new Select();
+ select.addSymbol(a);
+
+ Query query = new Query();
+ 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 /*+ MAKEDEP */ db.g1 INNER JOIN db.g2 ON a = b", //$NON-NLS-1$
+ query);
+ }
+
+ /*+* Select a From (db.g1 MAKEDEP JOIN db.g2 ON a = b) LEFT OUTER JOIN db.g3 MAKEDEP ON a = c */
+ @Test public void testOptionMakeDepInline3(){
+ GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
+ GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
+ GroupSymbol g3 = new GroupSymbol("db.g3"); //$NON-NLS-1$
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
+ ElementSymbol c = new ElementSymbol("c"); //$NON-NLS-1$
+
+ List crits = new ArrayList();
+ crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
+ JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
+ jp.getLeftClause().setMakeDep(true);
+ List crits2 = new ArrayList();
+ crits2.add(new CompareCriteria(a, CompareCriteria.EQ, c));
+ JoinPredicate jp2 = new JoinPredicate(jp, new UnaryFromClause(g3), JoinType.JOIN_LEFT_OUTER, crits2);
+ jp2.getRightClause().setMakeDep(true);
+ From from = new From();
+ from.addClause(jp2);
+
+ Select select = new Select();
+ select.addSymbol(a);
+
+ Query query = new Query();
+ 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 (/*+ MAKEDEP */ db.g1 INNER JOIN db.g2 ON a = b) LEFT OUTER JOIN /*+ MAKEDEP */ db.g3 ON a = c", //$NON-NLS-1$
+ query);
+ }
+
+ /*+* Select a From db.g1 MAKEDEP, db.g2 MAKEDEP WHERE a = b */
+ @Test public void testOptionMakeDepInline4(){
+ GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
+ GroupSymbol g2 = new GroupSymbol("c", "db.g2"); //$NON-NLS-1$ //$NON-NLS-2$
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
+
+ CompareCriteria crit = new CompareCriteria(a, CompareCriteria.EQ, b);
+
+ From from = new From();
+ FromClause clause = new UnaryFromClause(g1);
+ clause.setMakeDep(true);
+ from.addClause(clause);
+ FromClause clause1 = new UnaryFromClause(g2);
+ clause1.setMakeDep(true);
+ from.addClause(clause1);
+
+ Select select = new Select();
+ select.addSymbol(a);
+
+ Query query = new Query();
+ query.setSelect(select);
+ 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 /*+ MAKEDEP */ db.g1, /*+ MAKEDEP */ db.g2 AS c WHERE a = b", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testOptionMakedep() throws Exception {
+ String sql = "SELECT A.alert_id " + //$NON-NLS-1$
+ "FROM (FSK_ALERT AS A MAKEDEP INNER JOIN Core.FSC_PARTY_DIM AS C ON A.primary_entity_key = C.PARTY_KEY) " +//$NON-NLS-1$
+ "LEFT OUTER JOIN FSK_SCENARIO AS S ON A.scenario_id = S.scenario_id ";//$NON-NLS-1$
+ Query command = (Query)new QueryParser().parseCommand(sql);
+ JoinPredicate predicate = (JoinPredicate)command.getFrom().getClauses().get(0);
+ assertTrue(((JoinPredicate)predicate.getLeftClause()).getLeftClause().isMakeDep());
+ }
+
+ /*+* Select a From db.g1 JOIN db.g2 MAKENOTDEP ON a = b */
+ @Test public void testOptionMakeNotDepInline1(){
+ GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
+ GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
+
+ List crits = new ArrayList();
+ crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
+ JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
+ jp.getRightClause().setMakeNotDep(true);
+ From from = new From();
+ from.addClause(jp);
+
+ Select select = new Select();
+ select.addSymbol(a);
+
+ Query query = new Query();
+ 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 /*+ MAKENOTDEP */ db.g2 ON a = b", //$NON-NLS-1$
+ query);
+ }
+
+ /*+* Select a From db.g1 MAKENOTDEP JOIN db.g2 ON a = b */
+ @Test public void testOptionMakeNotDepInline2(){
+ GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
+ GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
+
+ List crits = new ArrayList();
+ crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
+ JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
+ jp.getLeftClause().setMakeNotDep(true);
+ From from = new From();
+ from.addClause(jp);
+
+ Select select = new Select();
+ select.addSymbol(a);
+
+ Query query = new Query();
+ 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 /*+ MAKENOTDEP */ db.g1 INNER JOIN db.g2 ON a = b", //$NON-NLS-1$
+ query);
+ }
+
+ /*+* Select a From (db.g1 MAKENOTDEP JOIN db.g2 ON a = b) LEFT OUTER JOIN db.g3 MAKENOTDEP ON a = c */
+ @Test public void testOptionMakeNotDepInline3(){
+ GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
+ GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
+ GroupSymbol g3 = new GroupSymbol("db.g3"); //$NON-NLS-1$
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
+ ElementSymbol c = new ElementSymbol("c"); //$NON-NLS-1$
+
+ List crits = new ArrayList();
+ crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
+ JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
+ jp.getLeftClause().setMakeNotDep(true);
+ List crits2 = new ArrayList();
+ crits2.add(new CompareCriteria(a, CompareCriteria.EQ, c));
+ JoinPredicate jp2 = new JoinPredicate(jp, new UnaryFromClause(g3), JoinType.JOIN_LEFT_OUTER, crits2);
+ jp2.getRightClause().setMakeNotDep(true);
+ From from = new From();
+ from.addClause(jp2);
+
+ Select select = new Select();
+ select.addSymbol(a);
+
+ Query query = new Query();
+ 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 (/*+ MAKENOTDEP */ db.g1 INNER JOIN db.g2 ON a = b) LEFT OUTER JOIN /*+ MAKENOTDEP */ db.g3 ON a = c", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testDepOptions2() {
+ GroupSymbol a = new GroupSymbol("a"); //$NON-NLS-1$
+ GroupSymbol b = new GroupSymbol("b"); //$NON-NLS-1$
+ ElementSymbol x = new ElementSymbol("a.x", true); //$NON-NLS-1$
+ ElementSymbol y = new ElementSymbol("b.y", true); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(x, CompareCriteria.EQ, new Function("func", new Expression[] {y})); //$NON-NLS-1$
+ JoinPredicate predicate = new JoinPredicate(new UnaryFromClause(a), new UnaryFromClause(b), JoinType.JOIN_INNER, Arrays.asList(new Object[] {criteria}));
+ From from = new From(Arrays.asList(predicate));
+ predicate.getLeftClause().setMakeNotDep(true);
+ predicate.getRightClause().setMakeDep(true);
+ 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 /*+ MAKENOTDEP */ a INNER JOIN /*+ MAKEDEP */ b ON a.x = func(b.y)", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testOptionNoCache1(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Option option = new Option();
+ option.setNoCache(true);
+ option.addNoCacheGroup("a.b.c"); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setOption(option);
+ TestParser.helpTest("Select a From db.g Option nocache a.b.c", //$NON-NLS-1$
+ "SELECT a FROM db.g OPTION NOCACHE a.b.c", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testOptionNoCache2(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Option option = new Option();
+ option.setNoCache(true);
+ option.addNoCacheGroup("a.b.c"); //$NON-NLS-1$
+ option.addNoCacheGroup("d.e.f"); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setOption(option);
+ TestParser.helpTest("Select a From db.g Option nocache a.b.c, d.e.f", //$NON-NLS-1$
+ "SELECT a FROM db.g OPTION NOCACHE a.b.c, d.e.f", //$NON-NLS-1$
+ query);
+ }
+
+// related to defect 14423
+ @Test public void testOptionNoCache3(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Option option = new Option();
+ option.setNoCache(true);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setOption(option);
+ TestParser.helpTest("Select a From db.g Option nocache", //$NON-NLS-1$
+ "SELECT a FROM db.g OPTION NOCACHE", //$NON-NLS-1$
+ query);
+ }
+
+ /*+* SELECT a from g OPTION xyx */
+ @Test public void testFailsIllegalOption(){
+ TestParser.helpException("SELECT a from g OPTION xyx"); //$NON-NLS-1$
+ }
+
+ @Test public void testInsertWithOption() {
+ Insert insert = new Insert();
+ insert.setGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ List vars = new ArrayList();
+ vars.add(new ElementSymbol("a")); //$NON-NLS-1$
+ insert.setVariables(vars);
+ List values = new ArrayList();
+ values.add(new Reference(0));
+ insert.setValues(values);
+ Option option = new Option();
+ option.setNoCache(true);
+ insert.setOption(option);
+ TestParser.helpTest("INSERT INTO m.g (a) VALUES (?) OPTION NOCACHE", //$NON-NLS-1$
+ "INSERT INTO m.g (a) VALUES (?) OPTION NOCACHE", //$NON-NLS-1$
+ insert);
+ }
+
+ @Test public void testDeleteWithOption() {
+ Delete delete = new Delete();
+ delete.setGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ Option option = new Option();
+ option.setNoCache(true);
+ delete.setOption(option);
+ TestParser.helpTest("DELETE FROM m.g OPTION NOCACHE", //$NON-NLS-1$
+ "DELETE FROM m.g OPTION NOCACHE", //$NON-NLS-1$
+ delete);
+ }
+
+ @Test public void testUpdateWithOption() {
+ Update update = new Update();
+ update.setGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ update.addChange(new ElementSymbol("a"), new Reference(0));
+ Option option = new Option();
+ option.setNoCache(true);
+ Criteria crit = new CompareCriteria(new ElementSymbol("b"), CompareCriteria.EQ, new Reference(1)); //$NON-NLS-1$
+ update.setCriteria(crit);
+ TestParser.helpTest("UPDATE m.g SET a = ? WHERE b = ? OPTION NOCACHE", //$NON-NLS-1$
+ "UPDATE m.g SET a = ? WHERE b = ? OPTION NOCACHE", //$NON-NLS-1$
+ update);
+ }
+
+ @Test public void testOptionalFromClause1() {
+ String sql = "SELECT * FROM /*+ optional */ t1, t2"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ UnaryFromClause ufc = new UnaryFromClause();
+ ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ ufc.setOptional(true);
+ from.addClause(ufc);
+ from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1, t2", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause1_1() {
+ String sql = "SELECT * FROM /*+ optional*/ t1, t2"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ UnaryFromClause ufc = new UnaryFromClause();
+ ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ ufc.setOptional(true);
+ from.addClause(ufc);
+ from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1, t2", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause1_2() {
+ String sql = "SELECT * FROM /*+optional */ t1, t2"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ UnaryFromClause ufc = new UnaryFromClause();
+ ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ ufc.setOptional(true);
+ from.addClause(ufc);
+ from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1, t2", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause1_3() {
+ String sql = "SELECT * FROM /*+ optional */ t1, t2"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ UnaryFromClause ufc = new UnaryFromClause();
+ ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ ufc.setOptional(true);
+ from.addClause(ufc);
+ from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1, t2", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause1_4() {
+ String sql = "SELECT * /*+ optional */ FROM /*+ OptiOnal */ t1, t2"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ UnaryFromClause ufc = new UnaryFromClause();
+ ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ ufc.setOptional(true);
+ from.addClause(ufc);
+ from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1, t2", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause1_5() {
+ String sql = "SELECT * FROM /*+ OptiOnal */ t1, t2"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ UnaryFromClause ufc = new UnaryFromClause();
+ ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ ufc.setOptional(true);
+ from.addClause(ufc);
+ from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1, t2", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause2() {
+ String sql = "SELECT * FROM t1, /*+ optional */ t2"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ from.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ UnaryFromClause ufc = new UnaryFromClause();
+ ufc.setGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+ ufc.setOptional(true);
+ from.addClause(ufc);
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT * FROM t1, /*+ optional */ t2", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause3() {
+ String sql = "SELECT * FROM /*+ optional */ t1 AS a, t2"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ UnaryFromClause ufc = new UnaryFromClause();
+ ufc.setGroup(new GroupSymbol("a", "t1")); //$NON-NLS-1$ //$NON-NLS-2$
+ ufc.setOptional(true);
+ from.addClause(ufc);
+ from.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT * FROM /*+ optional */ t1 AS a, t2", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause4() {
+ String sql = "SELECT * FROM t1, /*+ optional */ t2 as a"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ from.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ UnaryFromClause ufc = new UnaryFromClause();
+ ufc.setGroup(new GroupSymbol("a", "t2")); //$NON-NLS-1$ //$NON-NLS-2$
+ ufc.setOptional(true);
+ from.addClause(ufc);
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT * FROM t1, /*+ optional */ t2 AS a", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause5() {
+ String sql = "SELECT * FROM t1, /*+ optional */ (select * from t1, t2) as x"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+
+ Query query2 = new Query();
+ select = new Select();
+ select.addSymbol(new AllSymbol());
+ query2.setSelect(select);
+ From from2 = new From();
+ from2.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ from2.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+ query2.setFrom(from2);
+
+ SubqueryFromClause sfc = new SubqueryFromClause("x", query2);//$NON-NLS-1$
+ sfc.setOptional(true);
+ from.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ from.addClause(sfc);
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT * FROM t1, /*+ optional */ (SELECT * FROM t1, t2) AS x", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause6() {
+ String sql = "SELECT * FROM t1 INNER JOIN /*+ optional */ (select a from t1, t2) AS x ON t1.a=x.a"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+
+ Query query2 = new Query();
+ select = new Select();
+ select.addSymbol(new ElementSymbol("a"));//$NON-NLS-1$
+ From from2 = new From();
+ from2.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ from2.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+ query2.setSelect(select);
+ query2.setFrom(from2);
+
+ UnaryFromClause ufc = new UnaryFromClause();
+ ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+
+ SubqueryFromClause sfc = new SubqueryFromClause("x", query2);//$NON-NLS-1$
+ sfc.setOptional(true);
+
+ List criteria = new ArrayList();
+ criteria.add(new CompareCriteria(new ElementSymbol("t1.a"), AbstractCompareCriteria.EQ, new ElementSymbol("x.a")));//$NON-NLS-1$//$NON-NLS-2$
+ JoinPredicate joinPredicate = new JoinPredicate(ufc, sfc, JoinType.JOIN_INNER, criteria);
+ from.addClause(joinPredicate);
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT * FROM t1 INNER JOIN /*+ optional */ (SELECT a FROM t1, t2) AS x ON t1.a = x.a", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause7() {
+ String sql = "SELECT b FROM t1, /*+ optional */ (t2 INNER JOIN t3 ON t2.a = t3.a)"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("b"));//$NON-NLS-1$
+ query.setSelect(select);
+ From from = new From();
+
+ UnaryFromClause ufc = new UnaryFromClause();
+ ufc.setGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+
+ UnaryFromClause ufc2 = new UnaryFromClause();
+ ufc2.setGroup(new GroupSymbol("t3")); //$NON-NLS-1$
+
+ List criteria = new ArrayList();
+ criteria.add(new CompareCriteria(new ElementSymbol("t2.a"), AbstractCompareCriteria.EQ, new ElementSymbol("t3.a")));//$NON-NLS-1$//$NON-NLS-2$
+ JoinPredicate joinPredicate = new JoinPredicate(ufc, ufc2, JoinType.JOIN_INNER, criteria);
+ joinPredicate.setOptional(true);
+
+ UnaryFromClause ufc3 = new UnaryFromClause();
+ ufc3.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ from.addClause(ufc3);
+ from.addClause(joinPredicate);
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT b FROM t1, /*+ optional */ (t2 INNER JOIN t3 ON t2.a = t3.a)", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause8() {
+ String sql = "SELECT b FROM t1, /*+ optional */ (/*+ optional */ (SELECT * FROM t1, t2) AS x INNER JOIN t3 ON x.a = t3.a)"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("b"));//$NON-NLS-1$
+ query.setSelect(select);
+ From from = new From();
+
+
+ Query query2 = new Query();
+ select = new Select();
+ select.addSymbol(new AllSymbol());
+ From from2 = new From();
+ from2.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ from2.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+ query2.setSelect(select);
+ query2.setFrom(from2);
+ SubqueryFromClause sfc = new SubqueryFromClause("x", query2);//$NON-NLS-1$
+ sfc.setOptional(true);
+
+ UnaryFromClause ufc2 = new UnaryFromClause();
+ ufc2.setGroup(new GroupSymbol("t3")); //$NON-NLS-1$
+
+ List criteria = new ArrayList();
+ criteria.add(new CompareCriteria(new ElementSymbol("x.a"), AbstractCompareCriteria.EQ, new ElementSymbol("t3.a")));//$NON-NLS-1$//$NON-NLS-2$
+ JoinPredicate joinPredicate = new JoinPredicate(sfc, ufc2, JoinType.JOIN_INNER, criteria);
+ joinPredicate.setOptional(true);
+
+ UnaryFromClause ufc3 = new UnaryFromClause();
+ ufc3.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ from.addClause(ufc3);
+ from.addClause(joinPredicate);
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT b FROM t1, /*+ optional */ (/*+ optional */ (SELECT * FROM t1, t2) AS x INNER JOIN t3 ON x.a = t3.a)", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause9() {
+ String sql = "SELECT b FROM (t1 LEFT OUTER JOIN /*+ optional */t2 on t1.a = t2.a) LEFT OUTER JOIN /*+ optional */t3 on t1.a = t3.a"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("b"));//$NON-NLS-1$
+ query.setSelect(select);
+ From from = new From();
+
+ UnaryFromClause ufc = new UnaryFromClause();
+ ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+
+ UnaryFromClause ufc2 = new UnaryFromClause();
+ ufc2.setGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+ ufc2.setOptional(true);
+
+ List criteria = new ArrayList();
+ criteria.add(new CompareCriteria(new ElementSymbol("t1.a"), AbstractCompareCriteria.EQ, new ElementSymbol("t2.a")));//$NON-NLS-1$//$NON-NLS-2$
+ JoinPredicate joinPredicate = new JoinPredicate(ufc, ufc2, JoinType.JOIN_LEFT_OUTER, criteria);
+
+ UnaryFromClause ufc3 = new UnaryFromClause();
+ ufc3.setGroup(new GroupSymbol("t3")); //$NON-NLS-1$
+ ufc3.setOptional(true);
+
+ criteria = new ArrayList();
+ criteria.add(new CompareCriteria(new ElementSymbol("t1.a"), AbstractCompareCriteria.EQ, new ElementSymbol("t3.a")));//$NON-NLS-1$//$NON-NLS-2$
+ JoinPredicate joinPredicate2 = new JoinPredicate(joinPredicate, ufc3, JoinType.JOIN_LEFT_OUTER, criteria);
+
+ from.addClause(joinPredicate2);
+ query.setFrom(from);
+
+ TestParser.helpTest(sql, "SELECT b FROM (t1 LEFT OUTER JOIN /*+ optional */ t2 ON t1.a = t2.a) LEFT OUTER JOIN /*+ optional */ t3 ON t1.a = t3.a", query); //$NON-NLS-1$
+ }
+
+ @Test public void testOptionalFromClause10(){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ From elseFrom = (From)from.clone();
+ UnaryFromClause ufc = new UnaryFromClause();
+ ufc.setGroup(new GroupSymbol("h")); //$NON-NLS-1$
+ ufc.setOptional(true);
+ elseFrom.addClause(ufc);
+ elseQuery.setFrom(elseFrom);
+ elseQuery.setCriteria(criteria);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ //has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.IN);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
+
+ Block block = new Block();
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ TestParser.helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
+ " IF(HAS IN CRITERIA ON (a)) BEGIN var1 = (SELECT a1 FROM g WHERE a2 = 5); END"+ //$NON-NLS-1$
+ " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g, /*+ optional */ h WHERE a2 = 5; END" + //$NON-NLS-1$
+ " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "IF(HAS IN CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g, /*+ optional */ h WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ @Test public void testStoredQueryWithOption(){
+ StoredProcedure storedQuery = new StoredProcedure();
+ storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
+ Option option = new Option();
+ option.setNoCache(true);
+ storedQuery.setOption(option);
+ TestParser.helpTest("exec proc1() option nocache", "EXEC proc1() OPTION NOCACHE", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /*+* Select a From db.g Option SHOWPLAN */
+ /*+* Select a From db.g Option makedep a.b.c */
+ @Test public void testOptionMakeDependent1(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Option option = new Option();
+ option.addDependentGroup("a.b.c"); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setOption(option);
+ TestParser.helpTest("Select a From db.g Option makedep a.b.c", //$NON-NLS-1$
+ "SELECT a FROM db.g OPTION MAKEDEP a.b.c", //$NON-NLS-1$
+ query);
+ }
+
+ /*+* Select a From db.g Option makedep a.b.c, d.e.f showplan */
+ @Test public void testOptionMakeDependent2(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Option option = new Option();
+ option.addDependentGroup("a.b.c"); //$NON-NLS-1$
+ option.addDependentGroup("d.e.f"); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setOption(option);
+ TestParser.helpTest("Select a From db.g Option makedep a.b.c, d.e.f", //$NON-NLS-1$
+ "SELECT a FROM db.g OPTION MAKEDEP a.b.c, d.e.f", //$NON-NLS-1$
+ query);
+ }
+
+ /*+* Select a From db.g Option makedep a.b.c, d.e.f, x.y.z */
+ @Test public void testOptionMakeDependent3(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Option option = new Option();
+ option.addDependentGroup("a.b.c"); //$NON-NLS-1$
+ option.addDependentGroup("d.e.f"); //$NON-NLS-1$
+ option.addDependentGroup("x.y.z"); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setOption(option);
+ TestParser.helpTest("Select a From db.g Option makedep a.b.c, d.e.f, x.y.z", //$NON-NLS-1$
+ "SELECT a FROM db.g OPTION MAKEDEP a.b.c, d.e.f, x.y.z", //$NON-NLS-1$
+ query);
+ }
+
+ /*+* Select a From db.g Option makenotdep a.b.c */
+ @Test public void testOptionMakeNotDependent1(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Option option = new Option();
+ option.addNotDependentGroup("a.b.c"); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setOption(option);
+ TestParser.helpTest("Select a From db.g Option makenotdep a.b.c", //$NON-NLS-1$
+ "SELECT a FROM db.g OPTION MAKENOTDEP a.b.c", //$NON-NLS-1$
+ query);
+ }
+
+ /*+* Select a From db.g Option makenotdep a.b.c, d.e.f showplan */
+ @Test public void testOptionMakeNotDependent2(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Option option = new Option();
+ option.addNotDependentGroup("a.b.c"); //$NON-NLS-1$
+ option.addNotDependentGroup("d.e.f"); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setOption(option);
+ TestParser.helpTest("Select a From db.g Option makeNOTdep a.b.c, d.e.f", //$NON-NLS-1$
+ "SELECT a FROM db.g OPTION MAKENOTDEP a.b.c, d.e.f", //$NON-NLS-1$
+ query);
+ }
+
+ /*+* Select a From db.g Option makenotdep a.b.c, d.e.f, x.y.z */
+ @Test public void testOptionMakeNotDependent3(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Option option = new Option();
+ option.addNotDependentGroup("a.b.c"); //$NON-NLS-1$
+ option.addNotDependentGroup("d.e.f"); //$NON-NLS-1$
+ option.addNotDependentGroup("x.y.z"); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setOption(option);
+ TestParser.helpTest("Select a From db.g Option makenotdep a.b.c, d.e.f, x.y.z", //$NON-NLS-1$
+ "SELECT a FROM db.g OPTION MAKENOTDEP a.b.c, d.e.f, x.y.z", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testDepOptions1() {
+ GroupSymbol a = new GroupSymbol("a"); //$NON-NLS-1$
+ GroupSymbol b = new GroupSymbol("b"); //$NON-NLS-1$
+ ElementSymbol x = new ElementSymbol("a.x", true); //$NON-NLS-1$
+ ElementSymbol y = new ElementSymbol("b.y", true); //$NON-NLS-1$
+
+ From from = new From(Arrays.asList(new UnaryFromClause(a), new UnaryFromClause(b)));
+
+ Option option = new Option();
+ option.addDependentGroup("a"); //$NON-NLS-1$
+ option.addNotDependentGroup("b"); //$NON-NLS-1$
+
+ 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);
+ TestParser.helpTest("Select a.x, b.y From a, b WHERE a.x = b.y option makedep a makenotdep b", //$NON-NLS-1$
+ "SELECT a.x, b.y FROM a, b WHERE a.x = b.y OPTION MAKEDEP a MAKENOTDEP b", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testOptionMakeDepInline5(){
+ GroupSymbol g1 = new GroupSymbol("db.g1"); //$NON-NLS-1$
+ GroupSymbol g2 = new GroupSymbol("db.g2"); //$NON-NLS-1$
+ GroupSymbol g3 = new GroupSymbol("db.g3"); //$NON-NLS-1$
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
+ ElementSymbol c = new ElementSymbol("c"); //$NON-NLS-1$
+
+ List crits = new ArrayList();
+ crits.add(new CompareCriteria(a, CompareCriteria.EQ, b));
+ JoinPredicate jp = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, crits);
+ jp.setMakeDep(true);
+ List crits2 = new ArrayList();
+ crits2.add(new CompareCriteria(a, CompareCriteria.EQ, c));
+ JoinPredicate jp2 = new JoinPredicate(jp, new UnaryFromClause(g3), JoinType.JOIN_LEFT_OUTER, crits2);
+ From from = new From();
+ from.addClause(jp2);
+
+ Select select = new Select();
+ select.addSymbol(a);
+
+ Query query = new Query();
+ 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 /*+ 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
+ TestParser.helpTest(query.toString(), query.toString(), query);
+ }
+
+ @Test public void testCache() {
+ String sql = "/*+ cache */ SELECT * FROM t1"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ UnaryFromClause ufc = new UnaryFromClause();
+ from.addClause(ufc);
+ ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ query.setFrom(from);
+ query.setCacheHint(new CacheHint());
+ TestParser.helpTest(sql, "/*+ cache */ SELECT * FROM t1", query); //$NON-NLS-1$
+ }
+
+ @Test public void testCacheScope() {
+ String sql = "/*+ cache(pref_mem scope:session) */ SELECT * FROM t1"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ UnaryFromClause ufc = new UnaryFromClause();
+ from.addClause(ufc);
+ ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ query.setFrom(from);
+ CacheHint hint = new CacheHint();
+ hint.setScope("session");
+ hint.setPrefersMemory(true);
+ query.setCacheHint(hint);
+ TestParser.helpTest(sql, "/*+ cache(pref_mem scope:session) */ SELECT * FROM t1", query); //$NON-NLS-1$
+ }
+
+ @Test public void testCache1() {
+ String sql = "/*+ cache */ execute foo()"; //$NON-NLS-1$
+
+ StoredProcedure sp = new StoredProcedure();
+ sp.setCacheHint(new CacheHint());
+ sp.setProcedureName("foo"); //$NON-NLS-1$
+
+ TestParser.helpTest(sql, "/*+ cache */ EXEC foo()", sp); //$NON-NLS-1$
+ }
+
+ @Test public void testExpandedCacheHint() {
+ String sql = "/*+ cache( pref_mem ttl:2000) */ SELECT * FROM t1"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ UnaryFromClause ufc = new UnaryFromClause();
+ from.addClause(ufc);
+ ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ query.setFrom(from);
+ CacheHint hint = new CacheHint();
+ hint.setPrefersMemory(true);
+ hint.setTtl(Long.valueOf(2000));
+ query.setCacheHint(hint);
+ TestParser.helpTest(sql, "/*+ cache(pref_mem ttl:2000) */ SELECT * FROM t1", query); //$NON-NLS-1$
+ }
+
+ @Test public void testCacheHintUnion() {
+ String sql = "/*+ cache( pref_mem) */ SELECT * FROM t1 union select * from t2"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ UnaryFromClause ufc = new UnaryFromClause();
+ from.addClause(ufc);
+ ufc.setGroup(new GroupSymbol("t1")); //$NON-NLS-1$
+ query.setFrom(from);
+
+ Query query1 = new Query();
+ select = new Select();
+ select.addSymbol(new AllSymbol());
+ query1.setSelect(select);
+ from = new From();
+ ufc = new UnaryFromClause();
+ from.addClause(ufc);
+ ufc.setGroup(new GroupSymbol("t2")); //$NON-NLS-1$
+ query1.setFrom(from);
+
+ SetQuery sq = new SetQuery(Operation.UNION, false, query, query1);
+ CacheHint hint = new CacheHint();
+ hint.setPrefersMemory(true);
+ sq.setCacheHint(hint);
+ TestParser.helpTest(sql, "/*+ cache(pref_mem) */ SELECT * FROM t1 UNION SELECT * FROM t2", sq); //$NON-NLS-1$
+ }
+
+ @Test public void testCacheHintCallableStatement() {
+ String sql = "/*+ cache */ { ? = call proc() }"; //$NON-NLS-1$
+ StoredProcedure sp = new StoredProcedure();
+ SPParameter param = new SPParameter(1, null);
+ param.setParameterType(SPParameter.RETURN_VALUE);
+ sp.setParameter(param);
+ sp.setProcedureName("proc");
+ sp.setCallableStatement(true);
+ CacheHint hint = new CacheHint();
+ sp.setCacheHint(hint);
+ TestParser.helpTest(sql, "/*+ cache */ ? = EXEC proc()", sp); //$NON-NLS-1$
+ }
+
+ @Test public void testMergeJoinHint() {
+ String sql = "SELECT e1 FROM m.g2 WHERE EXISTS /*+ MJ */ (SELECT e1 FROM m.g1)"; //$NON-NLS-1$
+ Query q = TestParser.exampleExists(true);
+ TestParser.helpTest(sql, "SELECT e1 FROM m.g2 WHERE EXISTS /*+ MJ */ (SELECT e1 FROM m.g1)", q); //$NON-NLS-1$
+ }
+
+ @Test public void testMergeJoinHint1() {
+ String sql = "SELECT a FROM db.g WHERE b IN /*+ MJ */ (SELECT a FROM db.g WHERE a2 = 5)"; //$NON-NLS-1$
+ Query q = TestParser.exampleIn(true);
+ TestParser.helpTest(sql, "SELECT a FROM db.g WHERE b IN /*+ MJ */ (SELECT a FROM db.g WHERE a2 = 5)", q); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestParser.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/parser/TestParser.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestParser.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,6907 +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.parser;
-
-import static org.junit.Assert.*;
-
-import java.io.StringReader;
-import java.io.UnsupportedEncodingException;
-import java.math.BigInteger;
-import java.sql.Date;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryParserException;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.core.TeiidException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.language.SQLConstants.NonReserved;
-import org.teiid.language.SQLConstants.Reserved;
-import org.teiid.language.SortSpecification.NullOrdering;
-import org.teiid.query.sql.lang.ArrayTable;
-import org.teiid.query.sql.lang.BetweenCriteria;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Create;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.Drop;
-import org.teiid.query.sql.lang.DynamicCommand;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.ExpressionCriteria;
-import org.teiid.query.sql.lang.From;
-import org.teiid.query.sql.lang.FromClause;
-import org.teiid.query.sql.lang.GroupBy;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.Into;
-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;
-import org.teiid.query.sql.lang.OrderByItem;
-import org.teiid.query.sql.lang.PredicateCriteria;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.lang.SetClauseList;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.SubqueryCompareCriteria;
-import org.teiid.query.sql.lang.SubqueryFromClause;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.lang.TableFunctionReference;
-import org.teiid.query.sql.lang.TextTable;
-import org.teiid.query.sql.lang.UnaryFromClause;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.lang.WithQueryCommand;
-import org.teiid.query.sql.lang.XMLTable;
-import org.teiid.query.sql.lang.SetQuery.Operation;
-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.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;
-import org.teiid.query.sql.proc.HasCriteria;
-import org.teiid.query.sql.proc.IfStatement;
-import org.teiid.query.sql.proc.LoopStatement;
-import org.teiid.query.sql.proc.RaiseErrorStatement;
-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.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;
-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.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.XMLAttributes;
-import org.teiid.query.sql.symbol.XMLElement;
-import org.teiid.query.sql.symbol.XMLForest;
-import org.teiid.query.sql.symbol.XMLNamespaces;
-import org.teiid.query.sql.symbol.XMLParse;
-import org.teiid.query.sql.symbol.XMLQuery;
-import org.teiid.query.sql.symbol.XMLSerialize;
-
- at SuppressWarnings("nls")
-public class TestParser {
-
- static void helpTest(String sql, String expectedString, Command expectedCommand) {
- helpTest(sql, expectedString, expectedCommand, new ParseInfo());
- }
- static void helpTest(String sql, String expectedString, Command expectedCommand, ParseInfo info) {
- Command actualCommand = null;
- String actualString = null;
- try {
- actualCommand = QueryParser.getQueryParser().parseCommand(sql, info);
- actualString = actualCommand.toString();
- } catch(Throwable e) {
- throw new RuntimeException(e);
- }
-
- assertEquals("Parse string does not match: ", expectedString, actualString); //$NON-NLS-1$
- assertEquals("Command objects do not match: ", expectedCommand, actualCommand); //$NON-NLS-1$
- assertEquals("Cloned command objects do not match: ", expectedCommand, actualCommand.clone()); //$NON-NLS-1$
- }
-
- static void helpTestExpression(String sql, String expectedString, Expression expected) throws QueryParserException {
- Expression actual = QueryParser.getQueryParser().parseExpression(sql);
- String actualString = actual.toString();
-
- assertEquals("Parse string does not match: ", expectedString, actualString); //$NON-NLS-1$
- assertEquals("Command objects do not match: ", expected, actual); //$NON-NLS-1$
- assertEquals("Cloned command objects do not match: ", expected, actual.clone()); //$NON-NLS-1$
- }
-
- static void helpException(String sql) {
- helpException(sql, null);
- }
-
- static void helpException(String sql, String expected){
- try {
- QueryParser.getQueryParser().parseCommand(sql);
- fail("Expected exception for parsing " + sql); //$NON-NLS-1$
- } catch(TeiidException e) {
- if (expected != null) {
- assertEquals(expected, e.getMessage());
- }
- }
- }
-
- private void helpBlockTest(String block, String expectedString, Block expectedBlock) throws ParseException {
- Block actualBlock = new SQLParser(new StringReader(block)).block(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$
- }
-
- private void helpCriteriaSelectorTest(String selector, String expectedString, CriteriaSelector expectedSelector) throws ParseException {
- CriteriaSelector actualSelector = new SQLParser(new StringReader(selector)).criteriaSelector();
- String actualString = actualSelector.toString();
- assertEquals("Parse string does not match: ", expectedString, actualString); //$NON-NLS-1$
- assertEquals("CriteriaSelector does not match: ", expectedSelector, actualSelector); //$NON-NLS-1$
- }
-
- private void helpCriteriaTest(String crit, String expectedString, Criteria expectedCrit) throws QueryParserException {
- Criteria actualCrit = QueryParser.getQueryParser().parseCriteria(crit);
- String actualString = actualCrit.toString();
- assertEquals("Parse string does not match: ", expectedString, actualString); //$NON-NLS-1$
- assertEquals("Criteria does not match: ", expectedCrit, actualCrit); //$NON-NLS-1$
- }
-
- private void helpStmtTest(String stmt, String expectedString, Statement expectedStmt) throws ParseException {
- Statement actualStmt = new SQLParser(new StringReader(stmt)).statement(new ParseInfo());
- String actualString = actualStmt.toString();
- assertEquals("Parse string does not match: ", expectedString, actualString); //$NON-NLS-1$
- assertEquals("Language objects do not match: ", expectedStmt, actualStmt); //$NON-NLS-1$
- }
-
- // ################################## ACTUAL TESTS ################################
-
- // ======================== Joins ===============================================
-
- /** SELECT * FROM g1 inner join g2 on g1.a1=g2.a2 */
- @Test public void testInnerJoin() {
- UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
- UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
- CompareCriteria jcrit = new CompareCriteria(
- new ElementSymbol("g1.a1"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new ElementSymbol("g2.a2")); //$NON-NLS-1$
- ArrayList<Criteria> crits = new ArrayList<Criteria>();
- crits.add(jcrit);
- JoinPredicate jp = new JoinPredicate(g1, g2, JoinType.JOIN_INNER, crits);
- From from = new From();
- from.addClause(jp);
-
- AllSymbol all = new AllSymbol();
- Select select = new Select();
- select.addSymbol(all);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT * FROM g1 inner join g2 on g1.a1=g2.a2", //$NON-NLS-1$
- "SELECT * FROM g1 INNER JOIN g2 ON g1.a1 = g2.a2", //$NON-NLS-1$
- query);
- }
-
- /** SELECT * FROM g1 cross join g2 */
- @Test public void testCrossJoin() {
- UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
- UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
- JoinPredicate jp = new JoinPredicate(g1, g2, JoinType.JOIN_CROSS);
- From from = new From();
- from.addClause(jp);
-
- AllSymbol all = new AllSymbol();
- Select select = new Select();
- select.addSymbol(all);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT * FROM g1 cross join g2", //$NON-NLS-1$
- "SELECT * FROM g1 CROSS JOIN g2", //$NON-NLS-1$
- query);
- }
-
- /** SELECT * FROM (g1 cross join g2), g3 */
- @Test public void testFromClauses() {
- UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
- UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
- JoinPredicate jp = new JoinPredicate(g1, g2, JoinType.JOIN_CROSS);
- From from = new From();
- from.addClause(jp);
- from.addClause(new UnaryFromClause(new GroupSymbol("g3"))); //$NON-NLS-1$
-
- AllSymbol all = new AllSymbol();
- Select select = new Select();
- select.addSymbol(all);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT * FROM (g1 cross join g2), g3", //$NON-NLS-1$
- "SELECT * FROM g1 CROSS JOIN g2, g3", //$NON-NLS-1$
- query);
- }
-
- /** SELECT * FROM g1 inner join g2 */
- @Test public void testInvalidInnerJoin() {
- helpException("SELECT * FROM g1 inner join g2"); //$NON-NLS-1$
- }
-
- /** SELECT * FROM (g1 cross join g2) cross join g3 */
- @Test public void testMultiCrossJoin() {
- UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
- UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
- JoinPredicate jp = new JoinPredicate(g1, g2, JoinType.JOIN_CROSS);
- JoinPredicate jp2 = new JoinPredicate(jp, new UnaryFromClause(new GroupSymbol("g3")), JoinType.JOIN_CROSS); //$NON-NLS-1$
- From from = new From();
- from.addClause(jp2);
-
- AllSymbol all = new AllSymbol();
- Select select = new Select();
- select.addSymbol(all);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT * FROM (g1 cross join g2) cross join g3", //$NON-NLS-1$
- "SELECT * FROM (g1 CROSS JOIN g2) CROSS JOIN g3", //$NON-NLS-1$
- query);
- }
-
- /** SELECT * FROM (g1 cross join g2) cross join (g3 cross join g4) */
- @Test public void testMultiCrossJoin2() {
- UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
- UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
- JoinPredicate jp = new JoinPredicate(g1, g2, JoinType.JOIN_CROSS);
- UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("g3")); //$NON-NLS-1$
- UnaryFromClause g4 = new UnaryFromClause(new GroupSymbol("g4")); //$NON-NLS-1$
- JoinPredicate jp2 = new JoinPredicate(g3, g4, JoinType.JOIN_CROSS);
- JoinPredicate jp3 = new JoinPredicate(jp, jp2, JoinType.JOIN_CROSS);
- From from = new From();
- from.addClause(jp3);
-
- AllSymbol all = new AllSymbol();
- Select select = new Select();
- select.addSymbol(all);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT * FROM (g1 cross join g2) cross join (g3 cross join g4)", //$NON-NLS-1$
- "SELECT * FROM (g1 CROSS JOIN g2) CROSS JOIN (g3 CROSS JOIN g4)", //$NON-NLS-1$
- query);
- }
-
- /** SELECT * FROM g1 cross join (g2 cross join g3) */
- @Test public void testMultiCrossJoin3() {
- UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
- UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
- UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("g3")); //$NON-NLS-1$
- JoinPredicate jp = new JoinPredicate(g2, g3, JoinType.JOIN_CROSS);
- JoinPredicate jp2 = new JoinPredicate(g1, jp, JoinType.JOIN_CROSS);
- From from = new From();
- from.addClause(jp2);
-
- AllSymbol all = new AllSymbol();
- Select select = new Select();
- select.addSymbol(all);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT * FROM g1 cross join (g2 cross join g3)", //$NON-NLS-1$
- "SELECT * FROM g1 CROSS JOIN (g2 CROSS JOIN g3)", //$NON-NLS-1$
- query);
- }
-
- /** SELECT * FROM g1 cross join (g2 cross join g3), g4 */
- @Test public void testMixedJoin() {
- UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
- UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
- UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("g3")); //$NON-NLS-1$
- JoinPredicate jp = new JoinPredicate(g2, g3, JoinType.JOIN_CROSS);
- JoinPredicate jp2 = new JoinPredicate(g1, jp, JoinType.JOIN_CROSS);
- From from = new From();
- from.addClause(jp2);
- from.addClause(new UnaryFromClause(new GroupSymbol("g4"))); //$NON-NLS-1$
-
- AllSymbol all = new AllSymbol();
- Select select = new Select();
- select.addSymbol(all);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT * FROM g1 cross join (g2 cross join g3), g4", //$NON-NLS-1$
- "SELECT * FROM g1 CROSS JOIN (g2 CROSS JOIN g3), g4", //$NON-NLS-1$
- query);
- }
-
- /** SELECT * FROM g1 cross join (g2 cross join g3), g4, g5 cross join g6 */
- @Test public void testMixedJoin2() {
- UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
- UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
- UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("g3")); //$NON-NLS-1$
- UnaryFromClause g4 = new UnaryFromClause(new GroupSymbol("g4")); //$NON-NLS-1$
- UnaryFromClause g5 = new UnaryFromClause(new GroupSymbol("g5")); //$NON-NLS-1$
- UnaryFromClause g6 = new UnaryFromClause(new GroupSymbol("g6")); //$NON-NLS-1$
- JoinPredicate jp = new JoinPredicate(g2, g3, JoinType.JOIN_CROSS);
- JoinPredicate jp2 = new JoinPredicate(g1, jp, JoinType.JOIN_CROSS);
- JoinPredicate jp3 = new JoinPredicate(g5, g6, JoinType.JOIN_CROSS);
- From from = new From();
- from.addClause(jp2);
- from.addClause(g4);
- from.addClause(jp3);
-
- AllSymbol all = new AllSymbol();
- Select select = new Select();
- select.addSymbol(all);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT * FROM g1 cross join (g2 cross join g3), g4, g5 cross join g6", //$NON-NLS-1$
- "SELECT * FROM g1 CROSS JOIN (g2 CROSS JOIN g3), g4, g5 CROSS JOIN g6", //$NON-NLS-1$
- query);
- }
-
- /** SELECT * FROM g1, g2 inner join g3 on g2.a=g3.a */
- @Test public void testMixedJoin3() {
- UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
- UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
- UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("g3")); //$NON-NLS-1$
- CompareCriteria jcrit = new CompareCriteria(
- new ElementSymbol("g2.a"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new ElementSymbol("g3.a")); //$NON-NLS-1$
- ArrayList<Criteria> crits = new ArrayList<Criteria>();
- crits.add(jcrit);
- JoinPredicate jp = new JoinPredicate(g2, g3, JoinType.JOIN_INNER, crits);
- From from = new From();
- from.addClause(g1);
- from.addClause(jp);
-
- AllSymbol all = new AllSymbol();
- Select select = new Select();
- select.addSymbol(all);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT * FROM g1, g2 inner join g3 on g2.a=g3.a", //$NON-NLS-1$
- "SELECT * FROM g1, g2 INNER JOIN g3 ON g2.a = g3.a", //$NON-NLS-1$
- query);
- }
-
- /** Select myG.a myA, myH.b from g myG right outer join h myH on myG.x=myH.x */
- @Test public void testRightOuterJoinWithAliases() {
- UnaryFromClause g = new UnaryFromClause(new GroupSymbol("myG", "g")); //$NON-NLS-1$ //$NON-NLS-2$
- UnaryFromClause h = new UnaryFromClause(new GroupSymbol("myH", "h")); //$NON-NLS-1$ //$NON-NLS-2$
- CompareCriteria jcrit = new CompareCriteria(
- new ElementSymbol("myG.x"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new ElementSymbol("myH.x")); //$NON-NLS-1$
- ArrayList<Criteria> crits = new ArrayList<Criteria>();
- crits.add(jcrit);
- JoinPredicate jp = new JoinPredicate(g, h, JoinType.JOIN_RIGHT_OUTER, crits);
- From from = new From();
- from.addClause(jp);
-
- AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("myG.a")); //$NON-NLS-1$ //$NON-NLS-2$
- Select select = new Select();
- select.addSymbol(as);
- select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("Select myG.a myA, myH.b from g myG right outer join h myH on myG.x=myH.x", //$NON-NLS-1$
- "SELECT myG.a AS myA, myH.b FROM g AS myG RIGHT OUTER JOIN h AS myH ON myG.x = myH.x", //$NON-NLS-1$
- query);
- }
-
- /** Select myG.x myX, myH.y from g myG right join h myH on myG.x=myH.x */
- @Test public void testRightJoinWithAliases() {
- UnaryFromClause g = new UnaryFromClause(new GroupSymbol("myG", "g")); //$NON-NLS-1$ //$NON-NLS-2$
- UnaryFromClause h = new UnaryFromClause(new GroupSymbol("myH", "h")); //$NON-NLS-1$ //$NON-NLS-2$
- CompareCriteria jcrit = new CompareCriteria(
- new ElementSymbol("myG.x"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new ElementSymbol("myH.x")); //$NON-NLS-1$
- ArrayList<Criteria> crits = new ArrayList<Criteria>();
- crits.add(jcrit);
- JoinPredicate jp = new JoinPredicate(g, h, JoinType.JOIN_RIGHT_OUTER, crits);
- From from = new From();
- from.addClause(jp);
-
- AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("myG.a")); //$NON-NLS-1$ //$NON-NLS-2$
- Select select = new Select();
- select.addSymbol(as);
- select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("Select myG.a myA, myH.b from g myG right join h myH on myG.x=myH.x", //$NON-NLS-1$
- "SELECT myG.a AS myA, myH.b FROM g AS myG RIGHT OUTER JOIN h AS myH ON myG.x = myH.x", //$NON-NLS-1$
- query);
- }
-
- /** Select myG.a myA, myH.b from g myG left outer join h myH on myG.x=myH.x */
- @Test public void testLeftOuterJoinWithAliases() {
- UnaryFromClause g = new UnaryFromClause(new GroupSymbol("myG", "g")); //$NON-NLS-1$ //$NON-NLS-2$
- UnaryFromClause h = new UnaryFromClause(new GroupSymbol("myH", "h")); //$NON-NLS-1$ //$NON-NLS-2$
- CompareCriteria jcrit = new CompareCriteria(
- new ElementSymbol("myG.x"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new ElementSymbol("myH.x")); //$NON-NLS-1$
- ArrayList<Criteria> crits = new ArrayList<Criteria>();
- crits.add(jcrit);
- JoinPredicate jp = new JoinPredicate(g, h, JoinType.JOIN_LEFT_OUTER, crits);
- From from = new From();
- from.addClause(jp);
-
- AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("myG.a")); //$NON-NLS-1$ //$NON-NLS-2$
- Select select = new Select();
- select.addSymbol(as);
- select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("Select myG.a myA, myH.b from g myG left outer join h myH on myG.x=myH.x", //$NON-NLS-1$
- "SELECT myG.a AS myA, myH.b FROM g AS myG LEFT OUTER JOIN h AS myH ON myG.x = myH.x", //$NON-NLS-1$
- query);
- }
-
- /** Select myG.a myA, myH.b from g myG left join h myH on myG.x=myH.x */
- @Test public void testLeftJoinWithAliases() {
- UnaryFromClause g = new UnaryFromClause(new GroupSymbol("myG", "g")); //$NON-NLS-1$ //$NON-NLS-2$
- UnaryFromClause h = new UnaryFromClause(new GroupSymbol("myH", "h")); //$NON-NLS-1$ //$NON-NLS-2$
- CompareCriteria jcrit = new CompareCriteria(
- new ElementSymbol("myG.x"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new ElementSymbol("myH.x")); //$NON-NLS-1$
- ArrayList<Criteria> crits = new ArrayList<Criteria>();
- crits.add(jcrit);
- JoinPredicate jp = new JoinPredicate(g, h, JoinType.JOIN_LEFT_OUTER, crits);
- From from = new From();
- from.addClause(jp);
-
- AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("myG.a")); //$NON-NLS-1$ //$NON-NLS-2$
- Select select = new Select();
- select.addSymbol(as);
- select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("Select myG.a myA, myH.b from g myG left join h myH on myG.x=myH.x", //$NON-NLS-1$
- "SELECT myG.a AS myA, myH.b FROM g AS myG LEFT OUTER JOIN h AS myH ON myG.x = myH.x", //$NON-NLS-1$
- query);
- }
-
- /** Select myG.a myA, myH.b from g myG full outer join h myH on myG.x=myH.x */
- @Test public void testFullOuterJoinWithAliases() {
- UnaryFromClause g = new UnaryFromClause(new GroupSymbol("myG", "g")); //$NON-NLS-1$ //$NON-NLS-2$
- UnaryFromClause h = new UnaryFromClause(new GroupSymbol("myH", "h")); //$NON-NLS-1$ //$NON-NLS-2$
- CompareCriteria jcrit = new CompareCriteria(
- new ElementSymbol("myG.x"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new ElementSymbol("myH.x")); //$NON-NLS-1$
- ArrayList<Criteria> crits = new ArrayList<Criteria>();
- crits.add(jcrit);
- JoinPredicate jp = new JoinPredicate(g, h, JoinType.JOIN_FULL_OUTER, crits);
- From from = new From();
- from.addClause(jp);
-
- AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("myG.a")); //$NON-NLS-1$ //$NON-NLS-2$
- Select select = new Select();
- select.addSymbol(as);
- select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("Select myG.a myA, myH.b from g myG full outer join h myH on myG.x=myH.x", //$NON-NLS-1$
- "SELECT myG.a AS myA, myH.b FROM g AS myG FULL OUTER JOIN h AS myH ON myG.x = myH.x", //$NON-NLS-1$
- query);
- }
-
- /** Select g.a, h.b from g full join h on g.x=h.x */
- @Test public void testFullJoin() {
- UnaryFromClause g = new UnaryFromClause(new GroupSymbol("g")); //$NON-NLS-1$
- UnaryFromClause h = new UnaryFromClause(new GroupSymbol("h")); //$NON-NLS-1$
- CompareCriteria jcrit = new CompareCriteria(
- new ElementSymbol("g.x"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new ElementSymbol("h.x")); //$NON-NLS-1$
- ArrayList<Criteria> crits = new ArrayList<Criteria>();
- crits.add(jcrit);
- JoinPredicate jp = new JoinPredicate(g, h, JoinType.JOIN_FULL_OUTER, crits);
- From from = new From();
- from.addClause(jp);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("g.a")); //$NON-NLS-1$
- select.addSymbol(new ElementSymbol("h.b")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("Select g.a, h.b from g full join h on g.x=h.x", //$NON-NLS-1$
- "SELECT g.a, h.b FROM g FULL OUTER JOIN h ON g.x = h.x", //$NON-NLS-1$
- query);
- }
-
- // ======================= Convert ==============================================
-
- /** SELECT CONVERT(a, string) FROM g */
- @Test public void testConversionFunction() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("CONVERT", new Expression[] {new ElementSymbol("a", false), new Constant("string")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT CONVERT(a, string) FROM g", //$NON-NLS-1$
- "SELECT CONVERT(a, string) FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT CONVERT(CONVERT(a, timestamp), string) FROM g */
- @Test public void testConversionFunction2() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("CONVERT", new Expression[] {new ElementSymbol("a", false), new Constant("timestamp")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Function f2 = new Function("CONVERT", new Expression[] {f, new Constant("string")}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT CONVERT(CONVERT(a, timestamp), string) FROM g", //$NON-NLS-1$
- "SELECT CONVERT(CONVERT(a, timestamp), string) FROM g", //$NON-NLS-1$
- query);
- }
-
- // ======================= Functions ==============================================
-
- /** SELECT 5 + length(concat(a, 'x')) FROM g */
- @Test public void testMultiFunction() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("concat", new Expression[] {new ElementSymbol("a", false), new Constant("x")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Function f2 = new Function("length", new Expression[] {f}); //$NON-NLS-1$
- Function f3 = new Function("+", new Expression[] {new Constant(new Integer(5)), f2}); //$NON-NLS-1$
- ExpressionSymbol es = new ExpressionSymbol("expr", f3); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT 5 + length(concat(a, 'x')) FROM g", //$NON-NLS-1$
- "SELECT (5 + length(concat(a, 'x'))) FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT REPLACE(a, 'x', 'y') AS y FROM g */
- @Test public void testAliasedFunction() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("replace", new Expression[] {new ElementSymbol("a", false), new Constant("x"), new Constant("y")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- ExpressionSymbol es = new ExpressionSymbol("y", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("y", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT REPLACE(a, 'x', 'y') AS y FROM g", //$NON-NLS-1$
- "SELECT REPLACE(a, 'x', 'y') AS y FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT cast(a as string) FROM g */
- @Test public void testCastFunction() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("cast", new Expression[] {new ElementSymbol("a", false), new Constant("string")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT cast(a as string) FROM g", //$NON-NLS-1$
- "SELECT cast(a AS string) FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT cast(cast(a as timestamp) as string) FROM g */
- @Test public void testMultiCastFunction() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("cast", new Expression[] {new ElementSymbol("a", false), new Constant("timestamp")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Function f2 = new Function("cast", new Expression[] {f, new Constant("string")}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT cast(cast(a as timestamp) as string) FROM g", //$NON-NLS-1$
- "SELECT cast(cast(a AS timestamp) AS string) FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT left(fullname, 3) as x FROM sys.groups */
- @Test public void testLeftFunction() {
- GroupSymbol g = new GroupSymbol("sys.groups"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("left", new Expression[] {new ElementSymbol("fullname", false), new Constant(new Integer(3))}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT left(fullname, 3) as x FROM sys.groups", //$NON-NLS-1$
- "SELECT left(fullname, 3) AS x FROM sys.groups", //$NON-NLS-1$
- query);
- }
-
- /** SELECT right(fullname, 3) as x FROM sys.groups */
- @Test public void testRightFunction() {
- GroupSymbol g = new GroupSymbol("sys.groups"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("right", new Expression[] {new ElementSymbol("fullname", false), new Constant(new Integer(3))}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT right(fullname, 3) as x FROM sys.groups", //$NON-NLS-1$
- "SELECT right(fullname, 3) AS x FROM sys.groups", //$NON-NLS-1$
- query);
- }
-
- /** SELECT char('x') AS x FROM sys.groups */
- @Test public void testCharFunction() {
- GroupSymbol g = new GroupSymbol("sys.groups"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("char", new Expression[] { new Constant("x")}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT char('x') AS x FROM sys.groups", //$NON-NLS-1$
- "SELECT char('x') AS x FROM sys.groups", //$NON-NLS-1$
- query);
- }
-
- /** SELECT insert('x', 1, 'a') as x FROM sys.groups */
- @Test public void testInsertFunction() {
- GroupSymbol g = new GroupSymbol("sys.groups"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("insert", new Expression[] { new Constant("x"), new Constant(new Integer(1)), new Constant("a")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT insert('x', 1, 'a') AS x FROM sys.groups", //$NON-NLS-1$
- "SELECT insert('x', 1, 'a') AS x FROM sys.groups", //$NON-NLS-1$
- query);
- }
-
-
-
- @Test public void testInsertIntoSelect() {
- GroupSymbol g = new GroupSymbol("sys.groups"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Insert insert = new Insert();
- GroupSymbol groupSymbol = new GroupSymbol( "tempA" ); //$NON-NLS-1$
- insert.setGroup(groupSymbol);
-
- Select select = new Select();
-// select.addSymbol( new ExpressionSymbol( new Constant( new Integer(1) ) ) );
- select.addSymbol( new ExpressionSymbol( "exp", new Constant( new Integer(1) ) ) ); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
-
- insert.setQueryExpression( query );
-
- helpTest("insert into tempA SELECT 1", //$NON-NLS-1$
- "INSERT INTO tempA SELECT 1", //$NON-NLS-1$
- insert);
- }
-
- /** SELECT translate('x', 'x', 'y') FROM sys.groups */
- @Test public void testTranslateFunction() {
- GroupSymbol g = new GroupSymbol("sys.groups"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("translate", new Expression[] { new Constant("x"), new Constant("x"), new Constant("y")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT translate('x', 'x', 'y') FROM sys.groups", //$NON-NLS-1$
- "SELECT translate('x', 'x', 'y') FROM sys.groups", //$NON-NLS-1$
- query);
- }
-
- /** SELECT timestampadd(SQL_TSI_FRAC_SECOND, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
- @Test public void testTimestampaddFunctionFracSecond() {
- GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
- new Constant("SQL_TSI_FRAC_SECOND"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT timestampadd(SQL_TSI_FRAC_SECOND, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- "SELECT timestampadd(SQL_TSI_FRAC_SECOND, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT timestampadd(SQL_TSI_SECOND, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
- @Test public void testTimestampaddFunctionSecond() {
- GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
- new Constant("SQL_TSI_SECOND"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT timestampadd(SQL_TSI_SECOND, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- "SELECT timestampadd(SQL_TSI_SECOND, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT timestampadd(SQL_TSI_MINUTE, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
- @Test public void testTimestampaddFunctionMinute() {
- GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
- new Constant("SQL_TSI_MINUTE"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT timestampadd(SQL_TSI_MINUTE, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- "SELECT timestampadd(SQL_TSI_MINUTE, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT timestampadd(SQL_TSI_HOUR, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
- @Test public void testTimestampaddFunctionHour() {
- GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
- new Constant("SQL_TSI_HOUR"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT timestampadd(SQL_TSI_HOUR, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- "SELECT timestampadd(SQL_TSI_HOUR, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT timestampadd(SQL_TSI_DAY, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
- @Test public void testTimestampaddFunctionDay() {
- GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
- new Constant("SQL_TSI_DAY"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT timestampadd(SQL_TSI_DAY, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- "SELECT timestampadd(SQL_TSI_DAY, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT timestampadd(SQL_TSI_WEEK, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
- @Test public void testTimestampaddFunctionWeek() {
- GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
- new Constant("SQL_TSI_WEEK"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT timestampadd(SQL_TSI_WEEK, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- "SELECT timestampadd(SQL_TSI_WEEK, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT timestampadd(SQL_TSI_QUARTER, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
- @Test public void testTimestampaddFunctionQuarter() {
- GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
- new Constant("SQL_TSI_QUARTER"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT timestampadd(SQL_TSI_QUARTER, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- "SELECT timestampadd(SQL_TSI_QUARTER, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT timestampadd(SQL_TSI_YEAR, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
- @Test public void testTimestampaddFunctionYear() {
- GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
- new Constant("SQL_TSI_YEAR"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT timestampadd(SQL_TSI_YEAR, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- "SELECT timestampadd(SQL_TSI_YEAR, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT timestampdiff(SQL_TSI_FRAC_SECOND, '2003-05-01 10:20:10', '2003-05-01 10:20:30') as x FROM my.group1 */
- @Test public void testTimestampdiffFunctionFracSecond() {
- GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("timestampdiff", new Expression[] { //$NON-NLS-1$
- new Constant("SQL_TSI_FRAC_SECOND"), new Constant("2003-05-01 10:20:10"), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT timestampdiff(SQL_TSI_FRAC_SECOND, '2003-05-01 10:20:10', '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- "SELECT timestampdiff(SQL_TSI_FRAC_SECOND, '2003-05-01 10:20:10', '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 5 + 2 + 3 FROM g */
- @Test public void testArithmeticOperatorPrecedence1() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("+", new Expression[] {new Constant(new Integer(5)), new Constant(new Integer(2))}); //$NON-NLS-1$
- Function f2 = new Function("+", new Expression[] {f, new Constant(new Integer(3))}); //$NON-NLS-1$
- ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT 5 + 2 + 3 FROM g", //$NON-NLS-1$
- "SELECT ((5 + 2) + 3) FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 5 + 2 - 3 FROM g */
- @Test public void testArithmeticOperatorPrecedence2() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("+", new Expression[] {new Constant(new Integer(5)), new Constant(new Integer(2))}); //$NON-NLS-1$
- Function f2 = new Function("-", new Expression[] {f, new Constant(new Integer(3))}); //$NON-NLS-1$
- ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT 5 + 2 - 3 FROM g", //$NON-NLS-1$
- "SELECT ((5 + 2) - 3) FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 5 + 2 * 3 FROM g */
- @Test public void testArithmeticOperatorPrecedence3() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("*", new Expression[] {new Constant(new Integer(2)), new Constant(new Integer(3))}); //$NON-NLS-1$
- Function f2 = new Function("+", new Expression[] {new Constant(new Integer(5)), f}); //$NON-NLS-1$
-
- ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT 5 + 2 * 3 FROM g", //$NON-NLS-1$
- "SELECT (5 + (2 * 3)) FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 5 * 2 + 3 FROM g */
- @Test public void testArithmeticOperatorPrecedence4() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("*", new Expression[] {new Constant(new Integer(5)), new Constant(new Integer(2))}); //$NON-NLS-1$
- Function f2 = new Function("+", new Expression[] {f, new Constant(new Integer(3))}); //$NON-NLS-1$
- ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT 5 * 2 + 3 FROM g", //$NON-NLS-1$
- "SELECT ((5 * 2) + 3) FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 5 * 2 * 3 FROM g */
- @Test public void testArithmeticOperatorPrecedence5() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("*", new Expression[] {new Constant(new Integer(5)), new Constant(new Integer(2))}); //$NON-NLS-1$
- Function f2 = new Function("*", new Expression[] {f, new Constant(new Integer(3))}); //$NON-NLS-1$
- ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT 5 * 2 * 3 FROM g", //$NON-NLS-1$
- "SELECT ((5 * 2) * 3) FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 1 + 2 * 3 + 4 * 5 FROM g */
- @Test public void testArithmeticOperatorPrecedenceMixed1() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("*", new Expression[] {new Constant(new Integer(2)), new Constant(new Integer(3))}); //$NON-NLS-1$
- Function f2 = new Function("*", new Expression[] {new Constant(new Integer(4)), new Constant(new Integer(5))}); //$NON-NLS-1$
- Function f3 = new Function("+", new Expression[] {new Constant(new Integer(1)), f}); //$NON-NLS-1$
- Function f4 = new Function("+", new Expression[] {f3, f2}); //$NON-NLS-1$
- ExpressionSymbol es = new ExpressionSymbol("expr", f4); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT 1 + 2 * 3 + 4 * 5 FROM g", //$NON-NLS-1$
- "SELECT ((1 + (2 * 3)) + (4 * 5)) FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 1 * 2 + 3 * 4 + 5 FROM g */
- @Test public void testArithmeticOperatorPrecedenceMixed2() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("*", new Expression[] {new Constant(new Integer(1)), new Constant(new Integer(2))}); //$NON-NLS-1$
- Function f2 = new Function("*", new Expression[] {new Constant(new Integer(3)), new Constant(new Integer(4))}); //$NON-NLS-1$
- Function f3 = new Function("+", new Expression[] {f, f2}); //$NON-NLS-1$
- Function f4 = new Function("+", new Expression[] {f3, new Constant(new Integer(5))}); //$NON-NLS-1$
- ExpressionSymbol es = new ExpressionSymbol("expr", f4); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT 1 * 2 + 3 * 4 + 5 FROM g", //$NON-NLS-1$
- "SELECT (((1 * 2) + (3 * 4)) + 5) FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 5 - 4 - 3 - 2 FROM g --> SELECT ((5 - 4) - 3) - 2 FROM g */
- @Test public void testLeftAssociativeExpressions1() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("-", new Expression[] {new Constant(new Integer(5)), new Constant(new Integer(4))}); //$NON-NLS-1$
- Function f2 = new Function("-", new Expression[] {f, new Constant(new Integer(3))}); //$NON-NLS-1$
- Function f3 = new Function("-", new Expression[] {f2, new Constant(new Integer(2))}); //$NON-NLS-1$
- ExpressionSymbol es = new ExpressionSymbol("expr", f3); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT 5 - 4 - 3 - 2 FROM g", //$NON-NLS-1$
- "SELECT (((5 - 4) - 3) - 2) FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 5 / 4 / 3 / 2 FROM g --> SELECT ((5 / 4) / 3) / 2 FROM g */
- @Test public void testLeftAssociativeExpressions2() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("/", new Expression[] {new Constant(new Integer(5)), new Constant(new Integer(4))}); //$NON-NLS-1$
- Function f2 = new Function("/", new Expression[] {f, new Constant(new Integer(3))}); //$NON-NLS-1$
- Function f3 = new Function("/", new Expression[] {f2, new Constant(new Integer(2))}); //$NON-NLS-1$
- ExpressionSymbol es = new ExpressionSymbol("expr", f3); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT 5 / 4 / 3 / 2 FROM g", //$NON-NLS-1$
- "SELECT (((5 / 4) / 3) / 2) FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 'a' || 'b' || 'c' FROM g */
- @Test public void testConcatOperator1() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("||", new Expression[] {new Constant("a"), new Constant("b")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Function f2 = new Function("||", new Expression[] {f, new Constant("c")}); //$NON-NLS-1$ //$NON-NLS-2$
- ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT 'a' || 'b' || 'c' FROM g", //$NON-NLS-1$
- "SELECT (('a' || 'b') || 'c') FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 2 + 3 || 5 + 1 * 2 FROM g */
- @Test public void testMixedOperators1() {
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Function f = new Function("*", new Expression[] {new Constant(new Integer(1)), new Constant(new Integer(2))}); //$NON-NLS-1$
- Function f2 = new Function("+", new Expression[] {new Constant(new Integer(5)), f}); //$NON-NLS-1$
- Function f3 = new Function("+", new Expression[] {new Constant(new Integer(2)), new Constant(new Integer(3))}); //$NON-NLS-1$
- Function f4 = new Function("||", new Expression[] {f3, f2}); //$NON-NLS-1$
- ExpressionSymbol es = new ExpressionSymbol("expr", f4); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(es);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT 2 + 3 || 5 + 1 * 2 FROM g", //$NON-NLS-1$
- "SELECT ((2 + 3) || (5 + (1 * 2))) FROM g", //$NON-NLS-1$
- query);
- }
-
- // ======================= Group By ==============================================
-
- /** SELECT a FROM m.g GROUP BY b, c */
- @Test public void testGroupBy() {
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("a", false)); //$NON-NLS-1$
-
- GroupBy groupBy = new GroupBy();
- groupBy.addSymbol(new ElementSymbol("b", false)); //$NON-NLS-1$
- groupBy.addSymbol(new ElementSymbol("c", false)); //$NON-NLS-1$
-
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setGroupBy(groupBy);
- helpTest("SELECT a FROM m.g GROUP BY b, c", //$NON-NLS-1$
- "SELECT a FROM m.g GROUP BY b, c", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a FROM m.g GROUP BY b, c HAVING b=5*/
- @Test public void testGroupByHaving() {
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("a", false)); //$NON-NLS-1$
-
- GroupBy groupBy = new GroupBy();
- groupBy.addSymbol(new ElementSymbol("b", false)); //$NON-NLS-1$
- groupBy.addSymbol(new ElementSymbol("c", false)); //$NON-NLS-1$
-
- CompareCriteria having = new CompareCriteria(new ElementSymbol("b", false), CompareCriteria.EQ, new Constant(new Integer(5))); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setGroupBy(groupBy);
- query.setHaving(having);
- helpTest("SELECT a FROM m.g GROUP BY b, c HAVING b=5", //$NON-NLS-1$
- "SELECT a FROM m.g GROUP BY b, c HAVING b = 5", //$NON-NLS-1$
- query);
- }
-
- /** SELECT COUNT(a) AS c FROM m.g */
- @Test public void testAggregateFunction() {
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new AliasSymbol("c", //$NON-NLS-1$
- new AggregateSymbol("c", "COUNT", false, new ElementSymbol("a", false)))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT COUNT(a) AS c FROM m.g", //$NON-NLS-1$
- "SELECT COUNT(a) AS c FROM m.g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT (COUNT(a)) AS c FROM m.g - this kind of query is generated by ODBC sometimes */
- @Test public void testAggregateFunctionWithParens() {
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new AliasSymbol("c", //$NON-NLS-1$
- new AggregateSymbol("c", "COUNT", false, new ElementSymbol("a", false)))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT (COUNT(a)) AS c FROM m.g", //$NON-NLS-1$
- "SELECT COUNT(a) AS c FROM m.g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a FROM m.g GROUP BY a HAVING COUNT(b) > 0*/
- @Test public void testHavingFunction() {
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
-
- GroupBy groupBy = new GroupBy();
- groupBy.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
-
- Criteria having = new CompareCriteria(
- new AggregateSymbol("count", "COUNT", false, new ElementSymbol("b", false)), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- CompareCriteria.GT,
- new Constant(new Integer(0)) );
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setGroupBy(groupBy);
- query.setHaving(having);
-
- helpTest("SELECT a FROM m.g GROUP BY a HAVING COUNT(b) > 0", //$NON-NLS-1$
- "SELECT a FROM m.g GROUP BY a HAVING COUNT(b) > 0", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a FROM m.g GROUP BY a, b HAVING COUNT(b) > 0 AND b+5 > 0 */
- @Test public void testCompoundHaving() {
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
-
- GroupBy groupBy = new GroupBy();
- groupBy.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
- groupBy.addSymbol(new ElementSymbol("b")); //$NON-NLS-1$
-
- CompoundCriteria having = new CompoundCriteria();
- having.setOperator(CompoundCriteria.AND);
- having.addCriteria(new CompareCriteria(
- new AggregateSymbol("count", "COUNT", false, new ElementSymbol("b", false)), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- CompareCriteria.GT,
- new Constant(new Integer(0)) ));
- having.addCriteria(new CompareCriteria(
- new Function("+", new Expression[] { new ElementSymbol("b", false), new Constant(new Integer(5)) }), //$NON-NLS-1$ //$NON-NLS-2$
- CompareCriteria.GT,
- new Constant(new Integer(0)) ));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setGroupBy(groupBy);
- query.setHaving(having);
-
- helpTest("SELECT a FROM m.g GROUP BY a, b HAVING COUNT(b) > 0 AND b+5 > 0", //$NON-NLS-1$
- "SELECT a FROM m.g GROUP BY a, b HAVING (COUNT(b) > 0) AND ((b + 5) > 0)", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a FROM m.g GROUP BY a, b HAVING COUNT(AVG(b)) */
- @Test public void testFailNestedAggregateInHaving() {
- helpException("SELECT a FROM m.g GROUP BY a, b HAVING COUNT(b) AS x = 5"); //$NON-NLS-1$
- }
-
- /** SELECT a FROM m.g GROUP BY a, b AS x */
- @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() {
- 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$
- //}
- }
- }
-
-
-
- @Test public void testFunctionOfAggregates() {
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- AggregateSymbol agg1 = new AggregateSymbol("count", "COUNT", false, new ElementSymbol("a", false)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- AggregateSymbol agg2 = new AggregateSymbol("sum", "SUM", false, new ElementSymbol("a", false)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Function f = new Function("*", new Expression[] { agg1, agg2 }); //$NON-NLS-1$
- ExpressionSymbol expr = new ExpressionSymbol("expr", f); //$NON-NLS-1$
- AliasSymbol alias = new AliasSymbol("c", expr); //$NON-NLS-1$
- select.addSymbol(alias);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT COUNT(a) * SUM(a) AS c FROM m.g", //$NON-NLS-1$
- "SELECT (COUNT(a) * SUM(a)) AS c FROM m.g", //$NON-NLS-1$
- query);
-
- }
-
- /** SELECT 5-null, a.g1.c1 FROM a.g1 */
- @Test public void testArithmeticNullFunction() {
- GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol(
- "expr", //$NON-NLS-1$
- new Function("-", new Expression[] { new Constant(new Integer(5)), new Constant(null) }) ) ); //$NON-NLS-1$
- select.addSymbol(new ElementSymbol("a.g1.c1")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT 5-null, a.g1.c1 FROM a.g1", //$NON-NLS-1$
- "SELECT (5 - null), a.g1.c1 FROM a.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 'abc' FROM a.g1 */
- @Test public void testStringLiteral() {
- GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant("abc"))); //$NON-NLS-1$ //$NON-NLS-2$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT 'abc' FROM a.g1", //$NON-NLS-1$
- "SELECT 'abc' FROM a.g1", //$NON-NLS-1$
- query);
- }
-
-
- /** SELECT 'O''Leary' FROM a.g1 */
- @Test public void testStringLiteralEscapedTick() {
- GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant("O'Leary"))); //$NON-NLS-1$ //$NON-NLS-2$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT 'O''Leary' FROM a.g1", //$NON-NLS-1$
- "SELECT 'O''Leary' FROM a.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT '''abc''' FROM a.g1 */
- @Test public void testStringLiteralEscapedTick2() {
- GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant("'abc'"))); //$NON-NLS-1$ //$NON-NLS-2$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT '''abc''' FROM a.g1", //$NON-NLS-1$
- "SELECT '''abc''' FROM a.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 'a''b''c' FROM a.g1 */
- @Test public void testStringLiteralEscapedTick3() {
- GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant("a'b'c"))); //$NON-NLS-1$ //$NON-NLS-2$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT 'a''b''c' FROM a.g1", //$NON-NLS-1$
- "SELECT 'a''b''c' FROM a.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT " "" " FROM a.g1 */
- @Test public void testStringLiteralEscapedTick4() {
- GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol(" \" ")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT \" \"\" \" FROM a.g1", //$NON-NLS-1$
- "SELECT \" \"\" \" FROM a.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 123456789012 FROM a.g1 */
- @Test public void testLongLiteral() {
- GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant(new Long(123456789012L)))); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT 123456789012 FROM a.g1", //$NON-NLS-1$
- "SELECT 123456789012 FROM a.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 1000000000000000000000000 FROM a.g1 */
- @Test public void testBigIntegerLiteral() {
- GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant(new BigInteger("1000000000000000000000000")))); //$NON-NLS-1$ //$NON-NLS-2$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT 1000000000000000000000000 FROM a.g1", //$NON-NLS-1$
- "SELECT 1000000000000000000000000 FROM a.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT 1.3e8 FROM a.g1 */
- @Test public void testFloatWithE() {
- GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant(new Double(1.3e8)))); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT 1.3e8 FROM a.g1", //$NON-NLS-1$
- "SELECT 1.3E8 FROM a.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT -1.3e-6 FROM a.g1 */
- @Test public void testFloatWithMinusE() {
- GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant(new Double(-1.3e-6)))); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT -1.3e-6 FROM a.g1", //$NON-NLS-1$
- "SELECT -1.3E-6 FROM a.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT -1.3e+8 FROM a.g1 */
- @Test public void testFloatWithPlusE() {
- GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant(new Double(-1.3e+8)))); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT -1.3e+8 FROM a.g1", //$NON-NLS-1$
- "SELECT -1.3E8 FROM a.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT {d'2002-10-02'} FROM m.g1 */
- @Test public void testDateLiteral1() {
- GroupSymbol g = new GroupSymbol("m.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant(java.sql.Date.valueOf("2002-10-02")))); //$NON-NLS-1$ //$NON-NLS-2$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT {d'2002-10-02'} FROM m.g1", //$NON-NLS-1$
- "SELECT {d'2002-10-02'} FROM m.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT {d'2002-9-1'} FROM m.g1 */
- @Test public void testDateLiteral2() {
- GroupSymbol g = new GroupSymbol("m.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant(java.sql.Date.valueOf("2002-09-01")))); //$NON-NLS-1$ //$NON-NLS-2$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT {d'2002-09-01'} FROM m.g1", //$NON-NLS-1$
- "SELECT {d'2002-09-01'} FROM m.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT {d'bad'} FROM m.g1 */
- @Test public void testDateLiteralFail() {
- helpException("SELECT {d'bad'} FROM m.g1"); //$NON-NLS-1$
- }
-
- /** SELECT {t '11:10:00' } FROM m.g1 */
- @Test public void testTimeLiteral1() {
- GroupSymbol g = new GroupSymbol("m.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant(java.sql.Time.valueOf("11:10:00")))); //$NON-NLS-1$ //$NON-NLS-2$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT {t '11:10:00' } FROM m.g1", //$NON-NLS-1$
- "SELECT {t'11:10:00'} FROM m.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT {t '5:10:00'} FROM m.g1 */
- @Test public void testTimeLiteral2() {
- GroupSymbol g = new GroupSymbol("m.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant(java.sql.Time.valueOf("5:10:00")))); //$NON-NLS-1$ //$NON-NLS-2$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT {t '05:10:00'} FROM m.g1", //$NON-NLS-1$
- "SELECT {t'05:10:00'} FROM m.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT {t 'xyz'} FROM m.g1 */
- @Test public void testTimeLiteralFail() {
- helpException("SELECT {t 'xyz'} FROM m.g1"); //$NON-NLS-1$
- }
-
- /** SELECT {ts'2002-10-02 19:00:02.50'} FROM m.g1 */
- @Test public void testTimestampLiteral() {
- GroupSymbol g = new GroupSymbol("m.g1"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant(java.sql.Timestamp.valueOf("2002-10-02 19:00:02.50")))); //$NON-NLS-1$ //$NON-NLS-2$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT {ts'2002-10-02 19:00:02.50'} FROM m.g1", //$NON-NLS-1$
- "SELECT {ts'2002-10-02 19:00:02.5'} FROM m.g1", //$NON-NLS-1$
- query);
- }
-
- /** SELECT {b'true'} FROM m.g1 */
- @Test public void testBooleanLiteralTrue() {
- Boolean expected = Boolean.TRUE;
- Class<?> expectedType = DataTypeManager.DefaultDataClasses.BOOLEAN;
- String sql = "SELECT {b'true'}"; //$NON-NLS-1$
- String expectedSql = "SELECT TRUE"; //$NON-NLS-1$
-
- helpTestLiteral(expected, expectedType, sql, expectedSql);
- }
-
- private void helpTestLiteral(Boolean expected, Class<?> expectedType,
- String sql, String expectedSql) {
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant(expected, expectedType))); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
-
- helpTest(sql,
- expectedSql,
- query);
- }
- /** SELECT TRUE FROM m.g1 */
- @Test public void testBooleanLiteralTrue2() {
- Boolean expected = Boolean.TRUE;
- Class<?> expectedType = DataTypeManager.DefaultDataClasses.BOOLEAN;
- String sql = "SELECT TRUE"; //$NON-NLS-1$
- String expectedSql = "SELECT TRUE"; //$NON-NLS-1$
-
- helpTestLiteral(expected, expectedType, sql, expectedSql);
- }
-
- /** SELECT {b'false'} FROM m.g1 */
- @Test public void testBooleanLiteralFalse() {
- Boolean expected = Boolean.FALSE;
- Class<?> expectedType = DataTypeManager.DefaultDataClasses.BOOLEAN;
- String sql = "SELECT {b'false'}"; //$NON-NLS-1$
- String expectedSql = "SELECT FALSE"; //$NON-NLS-1$
-
- helpTestLiteral(expected, expectedType, sql, expectedSql);
- }
-
- /** SELECT FALSE FROM m.g1 */
- @Test public void testBooleanLiteralFalse2() {
- Boolean expected = Boolean.FALSE;
- Class<?> expectedType = DataTypeManager.DefaultDataClasses.BOOLEAN;
- String sql = "SELECT {b'false'}"; //$NON-NLS-1$
- String expectedSql = "SELECT FALSE"; //$NON-NLS-1$
-
- helpTestLiteral(expected, expectedType, sql, expectedSql);
- }
-
- @Test public void testBooleanLiteralUnknown() {
- Boolean expected = null;
- Class<?> expectedType = DataTypeManager.DefaultDataClasses.BOOLEAN;
- String sql = "SELECT {b'unknown'}"; //$NON-NLS-1$
- String expectedSql = "SELECT UNKNOWN"; //$NON-NLS-1$
-
- helpTestLiteral(expected, expectedType, sql, expectedSql);
- }
-
- @Test public void testBooleanLiteralUnknown2() {
- Boolean expected = null;
- Class<?> expectedType = DataTypeManager.DefaultDataClasses.BOOLEAN;
- String sql = "SELECT UNKNOWN"; //$NON-NLS-1$
- String expectedSql = "SELECT UNKNOWN"; //$NON-NLS-1$
-
- helpTestLiteral(expected, expectedType, sql, expectedSql);
- }
-
- /** SELECT DISTINCT a FROM g */
- @Test public void testSelectDistinct(){
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
- select.setDistinct(true);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT DISTINCT a FROM g", //$NON-NLS-1$
- "SELECT DISTINCT a FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT ALL a FROM g */
- @Test public void testSelectAll(){
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
- select.setDistinct(false);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT ALL a FROM g", //$NON-NLS-1$
- "SELECT a FROM g", //$NON-NLS-1$
- query);
- }
-
- //=========================Aliasing==============================================
-
- /** SELECT a AS myA, b FROM g */
- @Test public void testAliasInSelect(){
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("a")); //$NON-NLS-1$ //$NON-NLS-2$
- Select select = new Select();
- select.addSymbol(as);
- select.addSymbol(new ElementSymbol("b")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT a AS myA, b FROM g", //$NON-NLS-1$
- "SELECT a AS myA, b FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a myA, b FROM g, h */
- @Test public void testAliasInSelect2(){
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- GroupSymbol h = new GroupSymbol("h"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
- from.addGroup(h);
-
- AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("a")); //$NON-NLS-1$ //$NON-NLS-2$
- Select select = new Select();
- select.addSymbol(as);
- select.addSymbol(new ElementSymbol("b")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT a myA, b FROM g, h", //$NON-NLS-1$
- "SELECT a AS myA, b FROM g, h", //$NON-NLS-1$
- query);
- }
-
- /** SELECT myG.a FROM g AS myG */
- @Test public void testAliasInFrom(){
- GroupSymbol g = new GroupSymbol("myG", "g"); //$NON-NLS-1$ //$NON-NLS-2$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("myG.a")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT myG.a FROM g AS myG", //$NON-NLS-1$
- "SELECT myG.a FROM g AS myG", //$NON-NLS-1$
- query);
- }
-
- /** SELECT myG.*, myH.b FROM g AS myG, h AS myH */
- @Test public void testAliasesInFrom(){
- GroupSymbol g = new GroupSymbol("myG", "g"); //$NON-NLS-1$ //$NON-NLS-2$
- GroupSymbol h = new GroupSymbol("myH", "h"); //$NON-NLS-1$ //$NON-NLS-2$
- From from = new From();
- from.addGroup(g);
- from.addGroup(h);
-
- Select select = new Select();
- AllInGroupSymbol myG = new AllInGroupSymbol("myG.*"); //$NON-NLS-1$
- select.addSymbol(myG);
- select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT myG.*, myH.b FROM g AS myG, h AS myH", //$NON-NLS-1$
- "SELECT myG.*, myH.b FROM g AS myG, h AS myH", //$NON-NLS-1$
- query);
- }
-
- /** SELECT myG.a, myH.b FROM g myG, h myH */
- @Test public void testHiddenAliasesInFrom(){
- GroupSymbol g = new GroupSymbol("myG", "g"); //$NON-NLS-1$ //$NON-NLS-2$
- GroupSymbol h = new GroupSymbol("myH", "h"); //$NON-NLS-1$ //$NON-NLS-2$
- From from = new From();
- from.addGroup(g);
- from.addGroup(h);
-
- Select select = new Select();
- AllInGroupSymbol myG = new AllInGroupSymbol("myG.*"); //$NON-NLS-1$
- select.addSymbol(myG);
- select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT myG.*, myH.b FROM g myG, h myH", //$NON-NLS-1$
- "SELECT myG.*, myH.b FROM g AS myG, h AS myH", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a AS or FROM g */
- @Test public void testAliasInSelectUsingKeywordFails(){
- helpException("SELECT a AS or FROM g"); //$NON-NLS-1$
- }
-
- /** SELECT or.a FROM g AS or */
- @Test public void testAliasInFromUsingKeywordFails(){
- helpException("SELECT or.a FROM g AS or"); //$NON-NLS-1$
- }
-
- // ======================= Misc ==============================================
-
- /** Select a From db.g Where a IS NULL */
- @Test public void testIsNullCriteria1(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Criteria crit = new IsNullCriteria(a);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("Select a From db.g Where a IS NULL", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE a IS NULL", //$NON-NLS-1$
- query);
- }
-
- /** Select a From db.g Where a IS NOT NULL */
- @Test public void testIsNullCriteria2(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- IsNullCriteria crit = new IsNullCriteria(a);
- crit.setNegated(true);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("Select a From db.g Where a IS NOT NULL", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE a IS NOT NULL", //$NON-NLS-1$
- query);
- }
-
- /** Select a From db.g Where Not a IS NULL */
- @Test public void testNotIsNullCriteria(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Criteria crit = new NotCriteria(new IsNullCriteria(a));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("Select a From db.g Where Not a IS NULL", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE NOT (a IS NULL)", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db.g where a <> "value" */
- @Test public void testStringNotEqualDoubleTicks(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Expression ex = new ElementSymbol("value"); //$NON-NLS-1$
- Criteria crit = new CompareCriteria(a, CompareCriteria.NE, ex);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a from db.g where a <> \"value\"", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE a <> \"value\"", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db.g where a != "value" */
- @Test public void testNotEquals2(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Expression constant = new Constant("value"); //$NON-NLS-1$
- Criteria crit = new CompareCriteria(a, CompareCriteria.NE, constant);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a from db.g where a != 'value'", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE a <> 'value'", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db."g" where a = 5 */
- @Test public void testPartlyQuotedGroup(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Criteria crit = new CompareCriteria(a, CompareCriteria.EQ, new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a from db.\"g\" where a = 5", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE a = 5", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from "db"."g" where a = 5 */
- @Test public void testFullyQuotedGroup(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Criteria crit = new CompareCriteria(a, CompareCriteria.EQ, new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a from \"db\".\"g\" where a = 5", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE a = 5", //$NON-NLS-1$
- query);
- }
-
- /** SELECT "db".g.a from db.g */
- @Test public void testPartlyQuotedElement1(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("db.g.a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT \"db\".g.a from db.g", //$NON-NLS-1$
- "SELECT db.g.a FROM db.g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT "db"."g".a from db.g */
- @Test public void testPartlyQuotedElement2(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("db.g.a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT \"db\".\"g\".a from db.g", //$NON-NLS-1$
- "SELECT db.g.a FROM db.g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT "db"."g"."a" from db.g */
- @Test public void testPartlyQuotedElement3(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("db.g.a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT \"db\".\"g\".\"a\" from db.g", //$NON-NLS-1$
- "SELECT db.g.a FROM db.g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT ""g"".""a" from db.g */
- @Test public void testStringLiteralLikeQuotedElement(){
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("g\".\"a")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT \"g\"\".\"\"a\" from g", //$NON-NLS-1$
- "SELECT \"g\"\"\".\"\"\"a\" FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT ""g"".""a" from db.g */
- @Test public void testStringLiteralLikeQuotedElement1(){
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", new Constant("g\".\"a"))); //$NON-NLS-1$ //$NON-NLS-2$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- ParseInfo info = new ParseInfo();
- info.ansiQuotedIdentifiers = false;
- helpTest("SELECT \"g\"\".\"\"a\" from g", //$NON-NLS-1$
- "SELECT 'g\".\"a' FROM g", //$NON-NLS-1$
- query, info);
- }
-
- /** SELECT g.x AS "select" FROM g */
- @Test public void testQuotedAlias(){
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- AliasSymbol a = new AliasSymbol("select", new ElementSymbol("g.x")); //$NON-NLS-1$ //$NON-NLS-2$
- select.addSymbol(a);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT g.x AS \"select\" FROM g", //$NON-NLS-1$
- "SELECT g.x AS \"select\" FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT g.x AS year FROM g */
- @Test public void testQuotedAlias2(){
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- AliasSymbol a = new AliasSymbol("year", new ElementSymbol("g.x")); //$NON-NLS-1$ //$NON-NLS-2$
- select.addSymbol(a);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT g.x AS \"year\" FROM g", //$NON-NLS-1$
- "SELECT g.x AS \"year\" FROM g", //$NON-NLS-1$
- query);
- }
-
- @Test public void testQuotedAlias3(){
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- AliasSymbol a = new AliasSymbol("some year", new ElementSymbol("g.x")); //$NON-NLS-1$ //$NON-NLS-2$
- select.addSymbol(a);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT g.x AS \"some year\" FROM g", //$NON-NLS-1$
- "SELECT g.x AS \"some year\" FROM g", //$NON-NLS-1$
- query);
- }
-
-
- /** SELECT g."select" FROM g */
- @Test public void testReservedWordElement1(){
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("g.select"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT g.\"select\" FROM g", //$NON-NLS-1$
- "SELECT g.\"select\" FROM g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet.x FROM newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet */
- @Test public void testReservedWordElement2() {
- GroupSymbol g = new GroupSymbol("newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet.x"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet.x FROM newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet", //$NON-NLS-1$
- "SELECT newModel5.ResultSetDocument.MappingClasses.\"from\".\"from\".Query1InputSet.x FROM newModel5.ResultSetDocument.MappingClasses.\"from\".\"from\".Query1InputSet", //$NON-NLS-1$
- query);
- }
-
- /** SELECT * FROM newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet */
- @Test public void testReservedWordGroup1(){
- GroupSymbol g = new GroupSymbol("newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new AllSymbol());
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT * FROM newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet", //$NON-NLS-1$
- "SELECT * FROM newModel5.ResultSetDocument.MappingClasses.\"from\".\"from\".Query1InputSet", //$NON-NLS-1$
- query);
- }
-
- /** SELECT * FROM newModel5."ResultSetDocument.MappingClasses.from.from.Query1InputSet" */
- @Test public void testReservedWordGroup2(){
- GroupSymbol g = new GroupSymbol("newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new AllSymbol());
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT * FROM newModel5.\"ResultSetDocument.MappingClasses.from.from.Query1InputSet\"", //$NON-NLS-1$
- "SELECT * FROM newModel5.ResultSetDocument.MappingClasses.\"from\".\"from\".Query1InputSet", //$NON-NLS-1$
- query);
- }
-
- /** SELECT * FROM model.doc WHERE ab.cd. at ef = 'abc' */
- @Test public void testXMLCriteriaWithAttribute() {
- GroupSymbol g = new GroupSymbol("model.doc"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new AllSymbol());
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- ElementSymbol elem = new ElementSymbol("ab.cd. at ef"); //$NON-NLS-1$
- query.setCriteria(new CompareCriteria(elem, CompareCriteria.EQ, new Constant("abc"))); //$NON-NLS-1$
-
- helpTest("SELECT * FROM model.doc WHERE ab.cd. at ef = 'abc'", //$NON-NLS-1$
- "SELECT * FROM model.doc WHERE ab.cd. at ef = 'abc'", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db.g where a <> 'value' */
- @Test public void testStringNotEqual(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Expression constant = new Constant("value"); //$NON-NLS-1$
- Criteria crit = new CompareCriteria(a, CompareCriteria.NE, constant);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a from db.g where a <> 'value'", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE a <> 'value'", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db.g where a BETWEEN 1000 AND 2000 */
- @Test public void testBetween1(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Expression constant1 = new Constant(new Integer(1000));
- Expression constant2 = new Constant(new Integer(2000));
- Criteria crit = new BetweenCriteria(a, constant1, constant2);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a from db.g where a BETWEEN 1000 AND 2000", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE a BETWEEN 1000 AND 2000", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db.g where a NOT BETWEEN 1000 AND 2000 */
- @Test public void testBetween2(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Expression constant1 = new Constant(new Integer(1000));
- Expression constant2 = new Constant(new Integer(2000));
- BetweenCriteria crit = new BetweenCriteria(a, constant1, constant2);
- crit.setNegated(true);
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a from db.g where a NOT BETWEEN 1000 AND 2000", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE a NOT BETWEEN 1000 AND 2000", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db.g where a < 1000 */
- @Test public void testCompareLT(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Expression constant = new Constant(new Integer(1000));
- Criteria crit = new CompareCriteria(a, CompareCriteria.LT, constant);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a from db.g where a < 1000", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE a < 1000", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db.g where a > 1000 */
- @Test public void testCompareGT(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Expression constant = new Constant(new Integer(1000));
- Criteria crit = new CompareCriteria(a, CompareCriteria.GT, constant);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a from db.g where a > 1000", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE a > 1000", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db.g where a <= 1000 */
- @Test public void testCompareLE(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Expression constant = new Constant(new Integer(1000));
- Criteria crit = new CompareCriteria(a, CompareCriteria.LE, constant);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a from db.g where a <= 1000", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE a <= 1000", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db.g where a >= 1000 */
- @Test public void testCompareGE(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Expression constant = new Constant(new Integer(1000));
- Criteria crit = new CompareCriteria(a, CompareCriteria.GE, constant);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a from db.g where a >= 1000", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE a >= 1000", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db.g where b = x and a = 1000 */
- @Test public void testCompoundCompare1(){
- helpTestCompoundCompare("SELECT a from db.g where b = x and a = 1000"); //$NON-NLS-1$
- }
-
- /** SELECT a from db.g where (b = x and a = 1000) */
- @Test public void testCompoundCompare2(){
- helpTestCompoundCompare("SELECT a from db.g where (b = x and a = 1000)"); //$NON-NLS-1$
- }
-
- /** SELECT a from db.g where ((b = x) and (a = 1000)) */
- @Test public void testCompoundCompare3(){
- helpTestCompoundCompare("SELECT a from db.g where ((b = x) and (a = 1000))"); //$NON-NLS-1$
- }
-
- /** SELECT a from db.g where (((b = x) and (a = 1000))) */
- @Test public void testCompoundCompare4(){
- helpTestCompoundCompare("SELECT a from db.g where (((b = x) and (a = 1000)))"); //$NON-NLS-1$
- }
-
- /** SELECT a FROM db.g WHERE (b = x) AND (a = 1000) */
- private void helpTestCompoundCompare(String testSQL){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Criteria crit1 = new CompareCriteria(new ElementSymbol("b"), CompareCriteria.EQ, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
- Expression constant = new Constant(new Integer(1000));
- Criteria crit2 = new CompareCriteria(a, CompareCriteria.EQ, constant);
- Criteria crit = new CompoundCriteria(CompoundCriteria.AND, crit1, crit2);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest(testSQL,
- "SELECT a FROM db.g WHERE (b = x) AND (a = 1000)", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a FROM db.g WHERE b IN (1000,5000)*/
- @Test public void testSetCriteria0(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
-
- Expression constant1 = new Constant(new Integer(1000));
- Expression constant2 = new Constant(new Integer(5000));
- Collection constants = new ArrayList(2);
- constants.add(constant1);
- constants.add(constant2);
- Criteria crit = new SetCriteria(new ElementSymbol("b"), constants); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a FROM db.g WHERE b IN (1000,5000)", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b IN (1000, 5000)", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a FROM db.g WHERE b NOT IN (1000,5000)*/
- @Test public void testSetCriteria1(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
-
- Expression constant1 = new Constant(new Integer(1000));
- Expression constant2 = new Constant(new Integer(5000));
- Collection constants = new ArrayList(2);
- constants.add(constant1);
- constants.add(constant2);
- SetCriteria crit = new SetCriteria(new ElementSymbol("b"), constants); //$NON-NLS-1$
- crit.setNegated(true);
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a FROM db.g WHERE b NOT IN (1000,5000)", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b NOT IN (1000, 5000)", //$NON-NLS-1$
- query);
- }
-
- // ================================== order by ==================================
-
- /** SELECT a FROM db.g WHERE b = aString order by c*/
- @Test public void testOrderBy(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Criteria crit = new CompareCriteria(new ElementSymbol("b"), CompareCriteria.EQ, new ElementSymbol("aString")); //$NON-NLS-1$ //$NON-NLS-2$
-
- ArrayList elements = new ArrayList();
- elements.add(new ElementSymbol("c")); //$NON-NLS-1$
- OrderBy orderBy = new OrderBy(elements);
-
- Query query = new Query(select, from, crit, orderBy, null);
- helpTest("SELECT a FROM db.g WHERE b = aString ORDER BY c", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b = aString ORDER BY c", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a FROM db.g WHERE b = aString order by c desc*/
- @Test public void testOrderByDesc(){
- ArrayList elements = new ArrayList();
- elements.add(new ElementSymbol("c")); //$NON-NLS-1$
- ArrayList orderTypes = new ArrayList();
- orderTypes.add(Boolean.FALSE);
- OrderBy orderBy = new OrderBy(elements, orderTypes);
-
- Query query = getOrderByQuery(orderBy);
- helpTest("SELECT a FROM db.g WHERE b = aString ORDER BY c desc", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b = aString ORDER BY c DESC", //$NON-NLS-1$
- query);
- }
- private Query getOrderByQuery(OrderBy orderBy) {
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Criteria crit = new CompareCriteria(new ElementSymbol("b"), CompareCriteria.EQ, new ElementSymbol("aString")); //$NON-NLS-1$ //$NON-NLS-2$
-
- Query query = new Query(select, from, crit, orderBy, null);
- return query;
- }
-
- /** SELECT a FROM db.g WHERE b = aString order by c,d*/
- @Test public void testOrderBys(){
- ArrayList elements = new ArrayList();
- elements.add(new ElementSymbol("c")); //$NON-NLS-1$
- elements.add(new ElementSymbol("d")); //$NON-NLS-1$
- OrderBy orderBy = new OrderBy(elements);
-
- Query query = getOrderByQuery(orderBy);
- helpTest("SELECT a FROM db.g WHERE b = aString ORDER BY c,d", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b = aString ORDER BY c, d", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a FROM db.g WHERE b = aString order by c desc,d desc*/
- @Test public void testOrderBysDesc(){
- ArrayList elements = new ArrayList();
- elements.add(new ElementSymbol("c")); //$NON-NLS-1$
- elements.add(new ElementSymbol("d")); //$NON-NLS-1$
- ArrayList orderTypes = new ArrayList();
- orderTypes.add(Boolean.FALSE);
- orderTypes.add(Boolean.FALSE);
- OrderBy orderBy = new OrderBy(elements, orderTypes);
-
- Query query = getOrderByQuery(orderBy);
- helpTest("SELECT a FROM db.g WHERE b = aString ORDER BY c desc,d desc", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b = aString ORDER BY c DESC, d DESC", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a FROM db.g WHERE b = aString order by c desc,d*/
- @Test public void testMixedOrderBys(){
- ArrayList elements = new ArrayList();
- elements.add(new ElementSymbol("c")); //$NON-NLS-1$
- elements.add(new ElementSymbol("d")); //$NON-NLS-1$
- ArrayList orderTypes = new ArrayList();
- orderTypes.add(Boolean.FALSE);
- orderTypes.add(Boolean.TRUE);
- OrderBy orderBy = new OrderBy(elements, orderTypes);
-
- Query query = getOrderByQuery(orderBy);
- helpTest("SELECT a FROM db.g WHERE b = aString ORDER BY c desc,d", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b = aString ORDER BY c DESC, d", //$NON-NLS-1$
- query);
- }
-
- @Test public void testOrderByNullOrdering(){
- OrderBy orderBy = new OrderBy();
- OrderByItem item = new OrderByItem(new ElementSymbol("c"), true);
- item.setNullOrdering(NullOrdering.FIRST);
- orderBy.getOrderByItems().add(item);
- item = new OrderByItem(new ElementSymbol("d"), false);
- item.setNullOrdering(NullOrdering.LAST);
- orderBy.getOrderByItems().add(item);
-
- Query query = getOrderByQuery(orderBy);
- helpTest("SELECT a FROM db.g WHERE b = aString ORDER BY c NULLS FIRST,d desc nulls last", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b = aString ORDER BY c NULLS FIRST, d DESC NULLS LAST", //$NON-NLS-1$
- query);
- }
-
- // ================================== match ====================================
-
- /** SELECT a FROM db.g WHERE b LIKE 'aString'*/
- @Test public void testLike0(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Expression string1 = new Constant("aString"); //$NON-NLS-1$
- Criteria crit = new MatchCriteria(new ElementSymbol("b"), string1); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a FROM db.g WHERE b LIKE 'aString'", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b LIKE 'aString'", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a FROM db.g WHERE b NOT LIKE 'aString'*/
- @Test public void testLike1(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Expression string1 = new Constant("aString"); //$NON-NLS-1$
- MatchCriteria crit = new MatchCriteria(new ElementSymbol("b"), string1); //$NON-NLS-1$
- crit.setNegated(true);
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a FROM db.g WHERE b NOT LIKE 'aString'", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b NOT LIKE 'aString'", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db.g where b like '#String' escape '#'*/
- @Test public void testLikeWithEscape(){
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Expression string1 = new Constant("#String"); //$NON-NLS-1$
- Criteria crit = new MatchCriteria(new ElementSymbol("b"), string1, '#'); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a from db.g where b like '#String' escape '#'", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b LIKE '#String' ESCAPE '#'", //$NON-NLS-1$
- query);
- }
-
- @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$
- }
-
- /** SELECT "date"."time" from db.g */
- @Test public void testReservedWordsInElement() {
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("date.time"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT \"date\".\"time\" from db.g", //$NON-NLS-1$
- "SELECT \"date\".\"time\" FROM db.g", //$NON-NLS-1$
- query);
-
- }
-
- /** SELECT a */
- @Test public void testNoFromClause(){
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- ExpressionSymbol b = new ExpressionSymbol("expr", new Constant(new Integer(5), Integer.class)); //$NON-NLS-1$
- select.addSymbol(a);
- select.addSymbol(b);
- Query query = new Query();
- query.setSelect(select);
- helpTest("SELECT a, 5", "SELECT a, 5", query); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // ==================== misc queries that should fail ===========================
-
- /** FROM g WHERE a = 'aString' */
- @Test public void testFailsNoSelectClause(){
- helpException("FROM g WHERE a = 'aString'"); //$NON-NLS-1$
- }
-
- /** SELECT a WHERE a = 'aString' */
- @Test public void testFailsNoFromClause(){
- helpException("SELECT a WHERE a = 'aString'"); //$NON-NLS-1$
- }
-
- /** SELECT xx.yy%.a from xx.yy */
- @Test public void testFailsWildcardInSelect(){
- helpException("SELECT xx.yy%.a from xx.yy"); //$NON-NLS-1$
- }
-
- /** SELECT a or b from g */
- @Test public void testOrInSelect(){
- Query query = new Query();
- query.setSelect(new Select(Arrays.asList(new ExpressionSymbol("foo", new CompoundCriteria(CompoundCriteria.OR, Arrays.asList(new ExpressionCriteria(new ElementSymbol("a")), new ExpressionCriteria(new ElementSymbol("b"))))))));
- helpTest("select a or b", "SELECT (a) OR (b)", query);
- }
-
- /** SELECT a FROM g WHERE a LIKE x*/
- @Test public void testLikeWOConstant(){
- GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- ElementSymbol x = new ElementSymbol("x"); //$NON-NLS-1$
- Criteria crit = new MatchCriteria(a, x);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a FROM g WHERE a LIKE x", //$NON-NLS-1$
- "SELECT a FROM g WHERE a LIKE x", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from g ORDER BY b DSC*/
- @Test public void testFailsDSCMisspelled(){
- helpException("SELECT a from g ORDER BY b DSC"); //$NON-NLS-1$
- }
-
- /** Test reusability of parser */
- @Test public void testReusabilityOfParserObject() {
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("a", false)); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT a FROM m.g", //$NON-NLS-1$
- "SELECT a FROM m.g", //$NON-NLS-1$
- query);
-
- helpTest("SELECT a FROM m.g", //$NON-NLS-1$
- "SELECT a FROM m.g", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db.g where b LIKE ? */
- @Test public void testParameter1() {
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- select.addSymbol(a);
-
- Reference ref1 = new Reference(0);
- Criteria crit = new MatchCriteria(new ElementSymbol("b"), ref1); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT a from db.g where b LIKE ?", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b LIKE ?", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a from db.g where b LIKE ? */
- @Test public void testParameter2() {
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- Reference ref0 = new Reference(0);
- ExpressionSymbol expr = new ExpressionSymbol("expr", ref0); //$NON-NLS-1$
- select.addSymbol(expr);
-
- Reference ref1 = new Reference(1);
- Criteria crit = new MatchCriteria(new ElementSymbol("b"), ref1); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
- helpTest("SELECT ? from db.g where b LIKE ?", //$NON-NLS-1$
- "SELECT ? FROM db.g WHERE b LIKE ?", //$NON-NLS-1$
- query);
- }
-
- /** SELECT a, b FROM (SELECT c FROM m.g) AS y */
- @Test public void testSubquery1() {
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol symbol = new ElementSymbol("c"); //$NON-NLS-1$
- select.addSymbol(symbol);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- SubqueryFromClause sfc = new SubqueryFromClause("y", query); //$NON-NLS-1$
- From from2 = new From();
- from2.addClause(sfc);
-
- Select select2 = new Select();
- select2.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
- select2.addSymbol(new ElementSymbol("b")); //$NON-NLS-1$
-
- Query query2 = new Query();
- query2.setSelect(select2);
- query2.setFrom(from2);
-
- helpTest("SELECT a, b FROM (SELECT c FROM m.g) AS y", //$NON-NLS-1$
- "SELECT a, b FROM (SELECT c FROM m.g) AS y", //$NON-NLS-1$
- query2);
- }
-
- /** SELECT a, b FROM ((SELECT c FROM m.g)) AS y */
- @Test public void testSubquery1a() {
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol symbol = new ElementSymbol("c"); //$NON-NLS-1$
- select.addSymbol(symbol);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- SubqueryFromClause sfc = new SubqueryFromClause("y", query); //$NON-NLS-1$
- From from2 = new From();
- from2.addClause(sfc);
-
- Select select2 = new Select();
- select2.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
- select2.addSymbol(new ElementSymbol("b")); //$NON-NLS-1$
-
- Query query2 = new Query();
- query2.setSelect(select2);
- query2.setFrom(from2);
-
- helpTest("SELECT a, b FROM ((SELECT c FROM m.g)) AS y", //$NON-NLS-1$
- "SELECT a, b FROM (SELECT c FROM m.g) AS y", //$NON-NLS-1$
- query2);
- }
-
- /** SELECT a, b FROM m.g1 JOIN (SELECT c FROM m.g2) AS y ON m.g1.a = y.c */
- @Test public void testSubquery2() {
- GroupSymbol g = new GroupSymbol("m.g2"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol symbol = new ElementSymbol("c"); //$NON-NLS-1$
- select.addSymbol(symbol);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- UnaryFromClause ufc = new UnaryFromClause(new GroupSymbol("m.g1")); //$NON-NLS-1$
- SubqueryFromClause sfc = new SubqueryFromClause("y", query); //$NON-NLS-1$
- CompareCriteria join = new CompareCriteria(new ElementSymbol("m.g1.a"), CompareCriteria.EQ, new ElementSymbol("y.c")); //$NON-NLS-1$ //$NON-NLS-2$
- List crits = new ArrayList();
- crits.add(join);
- JoinPredicate jp = new JoinPredicate(ufc, sfc, JoinType.JOIN_INNER, crits);
- From from2 = new From();
- from2.addClause(jp);
-
- Select select2 = new Select();
- select2.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
- select2.addSymbol(new ElementSymbol("b")); //$NON-NLS-1$
-
- Query query2 = new Query();
- query2.setSelect(select2);
- query2.setFrom(from2);
-
- helpTest("SELECT a, b FROM m.g1 JOIN (SELECT c FROM m.g2) AS y ON m.g1.a = y.c", //$NON-NLS-1$
- "SELECT a, b FROM m.g1 INNER JOIN (SELECT c FROM m.g2) AS y ON m.g1.a = y.c", //$NON-NLS-1$
- query2);
- }
-
- /** SELECT a, b FROM (SELECT c FROM m.g2) */
- @Test public void testSubqueryInvalid() {
- helpException("SELECT a, b FROM (SELECT c FROM m.g2)"); //$NON-NLS-1$
- }
-
- /** INSERT INTO m.g (a) VALUES (?) */
- @Test public void testInsertWithReference() {
- Insert insert = new Insert();
- insert.setGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- List vars = new ArrayList();
- vars.add(new ElementSymbol("a")); //$NON-NLS-1$
- insert.setVariables(vars);
- List values = new ArrayList();
- values.add(new Reference(0));
- insert.setValues(values);
- helpTest("INSERT INTO m.g (a) VALUES (?)", //$NON-NLS-1$
- "INSERT INTO m.g (a) VALUES (?)", //$NON-NLS-1$
- insert);
- }
-
- @Test public void testStoredQueryWithNoParameter(){
- StoredProcedure storedQuery = new StoredProcedure();
- storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
- helpTest("exec proc1()", "EXEC proc1()", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- helpTest("execute proc1()", "EXEC proc1()", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testStoredQueryWithNoParameter2(){
- StoredProcedure storedQuery = new StoredProcedure();
- storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
-
- From from = new From();
- SubqueryFromClause sfc = new SubqueryFromClause("x", storedQuery); //$NON-NLS-1$
- from.addClause(sfc);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("x.a")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT X.A FROM (exec proc1()) AS X", "SELECT X.A FROM (EXEC proc1()) AS X", query); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testStoredQuery(){
- StoredProcedure storedQuery = new StoredProcedure();
- storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
- SPParameter parameter = new SPParameter(1, new Constant("param1")); //$NON-NLS-1$
- parameter.setParameterType(ParameterInfo.IN);
- storedQuery.setParameter(parameter);
- helpTest("Exec proc1('param1')", "EXEC proc1('param1')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- helpTest("execute proc1('param1')", "EXEC proc1('param1')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testStoredQuery2(){
- StoredProcedure storedQuery = new StoredProcedure();
- storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
- SPParameter parameter = new SPParameter(1, new Constant("param1")); //$NON-NLS-1$
- storedQuery.setParameter(parameter);
- From from = new From();
- SubqueryFromClause sfc = new SubqueryFromClause("x", storedQuery); //$NON-NLS-1$
- from.addClause(sfc);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("x.a")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT X.A FROM (exec proc1('param1')) AS X", "SELECT X.A FROM (EXEC proc1('param1')) AS X", query); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testStoredQuery2SanityCheck(){
- StoredProcedure storedQuery = new StoredProcedure();
- storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
- SPParameter parameter = new SPParameter(1, new Constant("param1")); //$NON-NLS-1$
- storedQuery.setParameter(parameter);
- From from = new From();
- SubqueryFromClause sfc = new SubqueryFromClause("x", storedQuery); //$NON-NLS-1$
- from.addClause(sfc);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("x.a")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("exec proc1('param1')", "EXEC proc1('param1')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Try nesting subquery in double parentheses - parsing fails. 'exec' is not handled as
- * robustly as other types of commands that can appear in a from clause subquery.
- */
- public void testStoredQuerySubqueryMultipleParens(){
- StoredProcedure storedQuery = new StoredProcedure();
- storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
- SPParameter parameter = new SPParameter(1, new Constant("param1")); //$NON-NLS-1$
- storedQuery.setParameter(parameter);
- From from = new From();
- SubqueryFromClause sfc = new SubqueryFromClause("x", storedQuery); //$NON-NLS-1$
- from.addClause(sfc);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("x.a")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- helpTest("SELECT X.A FROM ((exec proc1('param1'))) AS X", "SELECT X.A FROM (EXEC proc1('param1')) AS X", query); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testErrorStatement() throws Exception {
- RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("Test only")); //$NON-NLS-1$
-
- helpStmtTest("ERROR 'Test only';", "ERROR 'Test only';", //$NON-NLS-1$ //$NON-NLS-2$
- errStmt);
- }
-
- @Test public void testIfStatement() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement ifStmt = new DeclareStatement(a, shortType);
-
- ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
- 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"); //$NON-NLS-1$
- 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 BEGIN DECLARE short b; END", //$NON-NLS-1$
- "IF(c = 5)"+"\n"+ "BEGIN"+"\n"+"DECLARE short a;"+"\n"+"END"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short b;"+"\n"+"END", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- 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$
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.IS_NULL);
- critSelector.addElement(a);
-
- helpCriteriaSelectorTest("IS NULL CRITERIA ON (a)", "IS NULL CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCriteriaSelector1() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.COMPARE_EQ);
- critSelector.addElement(a);
-
- helpCriteriaSelectorTest("= CRITERIA ON (a)", "= CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCriteriaSelector2() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.COMPARE_NE);
- critSelector.addElement(a);
-
- helpCriteriaSelectorTest("<> CRITERIA ON (a)", "<> CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCriteriaSelector3() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.COMPARE_LT);
- critSelector.addElement(a);
-
- helpCriteriaSelectorTest("< CRITERIA ON (a)", "< CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCriteriaSelector4() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.COMPARE_GT);
- critSelector.addElement(a);
-
- helpCriteriaSelectorTest("> CRITERIA ON (a)", "> CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCriteriaSelector5() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.COMPARE_GE);
- critSelector.addElement(a);
-
- helpCriteriaSelectorTest(">= CRITERIA ON (a)", ">= CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCriteriaSelector6() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.COMPARE_LE);
- critSelector.addElement(a);
-
- helpCriteriaSelectorTest("<= CRITERIA ON (a)", "<= CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCriteriaSelector7() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.LIKE);
- critSelector.addElement(a);
-
- helpCriteriaSelectorTest("LIKE CRITERIA ON (a)", "LIKE CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
-
- @Test public void testCriteriaSelector8() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.IN);
- critSelector.addElement(a);
-
- helpCriteriaSelectorTest("IN CRITERIA ON (a)", "IN CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCriteriaSelector9() throws Exception {
- //ElementSymbol a = new ElementSymbol("a");
-
- CriteriaSelector critSelector = new CriteriaSelector();
- //critSelector.setSelectorType(CriteriaSelector.IS_NULL);
- //critSelector.addElement(a);
-
- helpCriteriaSelectorTest("CRITERIA", "CRITERIA", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCriteriaSelector10() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.BETWEEN);
- critSelector.addElement(a);
-
- helpCriteriaSelectorTest("BETWEEN CRITERIA ON (a)", "BETWEEN CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**HAS IS NULL CRITERIA ON (a)*/
- @Test public void testHasIsNullCriteria() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.IS_NULL);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- helpCriteriaTest("HAS IS NULL CRITERIA ON (a)", "HAS IS NULL CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
- hasSelector);
- }
-
- /**HAS LIKE CRITERIA ON (a)*/
- @Test public void testHasLikeCriteria() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.LIKE);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- helpCriteriaTest("HAS LIKE CRITERIA ON (a)", "HAS LIKE CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
- hasSelector);
- }
-
- @Test public void testHasEQCriteria() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.COMPARE_EQ);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- helpCriteriaTest("HAS = CRITERIA ON (a)", "HAS = CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
- hasSelector);
- }
-
- @Test public void testHasNECriteria() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.COMPARE_NE);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- helpCriteriaTest("HAS <> CRITERIA ON (a)", "HAS <> CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
- hasSelector);
- }
-
- /**HAS IN CRITERIA ON (a)*/
- @Test public void testHasInCriteria() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.IN);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- helpCriteriaTest("HAS IN CRITERIA ON (a)", "HAS IN CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
- hasSelector);
- }
-
- /**HAS COMPARE_LT CRITERIA ON (a)*/
- @Test public void testHasLTCriteria() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.COMPARE_LT);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- helpCriteriaTest("HAS < CRITERIA ON (a)", "HAS < CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
- hasSelector);
- }
-
- /**HAS COMPARE_LE CRITERIA ON (a)*/
- @Test public void testHasLECriteria() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.COMPARE_LE);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- helpCriteriaTest("HAS <= CRITERIA ON (a)", "HAS <= CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
- hasSelector);
- }
-
- /**HAS COMPARE_GT CRITERIA ON (a)*/
- @Test public void testHasGTCriteria() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.COMPARE_GT);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- helpCriteriaTest("HAS > CRITERIA ON (a)", "HAS > CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
- hasSelector);
- }
-
- /**HAS COMPARE_GE CRITERIA ON (a)*/
- @Test public void testHasGECriteria() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.COMPARE_GE);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- helpCriteriaTest("HAS >= CRITERIA ON (a)", "HAS >= CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
- hasSelector);
- }
-
- /**HAS BETWEEN CRITERIA ON (a)*/
- @Test public void testHasBetweenCriteria() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.BETWEEN);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- helpCriteriaTest("HAS BETWEEN CRITERIA ON (a)", "HAS BETWEEN CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
- hasSelector);
- }
-
- @Test public void testTranslateCriteria() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- Criteria crit = new CompareCriteria(a, CompareCriteria.EQ,
- new Constant(new Integer(5)));
- List critList = new ArrayList();
- critList.add(crit);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.IS_NULL);
- critSelector.setElements(elements);
-
- TranslateCriteria transCriteria = new TranslateCriteria(critSelector, critList);
-
- helpCriteriaTest("TRANSLATE IS NULL CRITERIA ON (a) WITH (a = 5)", //$NON-NLS-1$
- "TRANSLATE IS NULL CRITERIA ON (a) WITH (a = 5)", //$NON-NLS-1$
- transCriteria);
-
- //helpCriteriaTest("TRANSLATE IS NULL CRITERIA ON (a) USING transFuncEQ (a)",
- //"TRANSLATE IS NULL CRITERIA ON (a) USING transFuncEQ (a)",
- //transCriteria);
-
- }
-
- @Test public void testAssignStatement() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- Expression expr = new Constant("aString"); //$NON-NLS-1$
-
- AssignmentStatement queryStmt = new AssignmentStatement(a, query);
- AssignmentStatement exprStmt = new AssignmentStatement(a, expr);
-
- helpStmtTest("a = SELECT a1 FROM g WHERE a2 = 5;", "a = (SELECT a1 FROM g WHERE a2 = 5);", //$NON-NLS-1$ //$NON-NLS-2$
- queryStmt);
-
- helpStmtTest("a = 'aString';", "a = 'aString';", exprStmt); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testDeclareStatement() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- String type = new String("short"); //$NON-NLS-1$
- DeclareStatement stmt = new DeclareStatement(a, type);
-
- helpStmtTest("DECLARE short a;","DECLARE short a;", stmt); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testDeclareStatementWithAssignment() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- String type = new String("short"); //$NON-NLS-1$
- DeclareStatement stmt = new DeclareStatement(a, type, new Constant(null));
-
- helpStmtTest("DECLARE short a = null;","DECLARE short a = null;", stmt); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testDeclareStatementWithAssignment1() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- String type = new String("string"); //$NON-NLS-1$
- DeclareStatement stmt = new DeclareStatement(a, type, new ScalarSubquery(sampleQuery()));
-
- helpStmtTest("DECLARE string a = SELECT a1 FROM g WHERE a2 = 5;","DECLARE string a = (SELECT a1 FROM g WHERE a2 = 5);", stmt); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testStatement() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- String type = new String("short"); //$NON-NLS-1$
- DeclareStatement declStmt = new DeclareStatement(a, type);
- Statement stmt = declStmt;
-
- helpStmtTest("DECLARE short a;", "DECLARE short a;", //$NON-NLS-1$ //$NON-NLS-2$
- stmt);
- }
-
- @Test public void testBlock() throws Exception {
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- String type = new String("short"); //$NON-NLS-1$
- DeclareStatement declStmt = new DeclareStatement(a, type);
- Statement stmt = declStmt;
- Block block = new Block(stmt);
-
- helpBlockTest("BEGIN DECLARE short a; END", "BEGIN"+"\n"+"DECLARE short a;"+"\n"+"END", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- block);
- }
-
- @Test public void testCommandStatement() throws Exception {
- Query query = sampleQuery();
-
- Command sqlCmd = query;
- CommandStatement cmdStmt = new CommandStatement(sqlCmd);
-
- helpStmtTest("SELECT a1 FROM g WHERE a2 = 5;", "SELECT a1 FROM g WHERE a2 = 5;", //$NON-NLS-1$ //$NON-NLS-2$
- cmdStmt);
- }
-
- /**
- * @return
- */
- private Query sampleQuery() {
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
- return query;
- }
-
- @Test public void testDynamicCommandStatement() throws Exception {
- List symbols = new ArrayList();
-
- ElementSymbol a1 = new ElementSymbol("a1"); //$NON-NLS-1$
- a1.setType(DataTypeManager.DefaultDataClasses.STRING);
- symbols.add(a1);
-
- DynamicCommand sqlCmd = new DynamicCommand();
- Expression sql = new Constant("SELECT a1 FROM g WHERE a2 = 5"); //$NON-NLS-1$
-
- sqlCmd.setSql(sql);
- sqlCmd.setAsColumns(symbols);
- sqlCmd.setAsClauseSet(true);
-
- sqlCmd.setIntoGroup(new GroupSymbol("#g")); //$NON-NLS-1$
-
- CommandStatement cmdStmt = new CommandStatement(sqlCmd);
-
- helpStmtTest("exec string 'SELECT a1 FROM g WHERE a2 = 5' as a1 string into #g;", "EXECUTE 'SELECT a1 FROM g WHERE a2 = 5' AS a1 string INTO #g;", //$NON-NLS-1$ //$NON-NLS-2$
- cmdStmt);
- }
-
- //sql is a variable, also uses the as, into, and update clauses
- @Test public void testDynamicCommandStatement1() throws Exception {
- List symbols = new ArrayList();
-
- ElementSymbol a1 = new ElementSymbol("a1"); //$NON-NLS-1$
- a1.setType(DataTypeManager.DefaultDataClasses.STRING);
- symbols.add(a1);
-
- ElementSymbol a2 = new ElementSymbol("a2"); //$NON-NLS-1$
- a1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
- symbols.add(a2);
-
- DynamicCommand sqlCmd = new DynamicCommand();
- Expression sql = new ElementSymbol("z"); //$NON-NLS-1$
-
- sqlCmd.setSql(sql);
- sqlCmd.setAsColumns(symbols);
- sqlCmd.setAsClauseSet(true);
-
- sqlCmd.setIntoGroup(new GroupSymbol("#g")); //$NON-NLS-1$
-
- sqlCmd.setUpdatingModelCount(1);
-
- CommandStatement cmdStmt = new CommandStatement(sqlCmd);
-
- helpStmtTest("execute string z as a1 string, a2 integer into #g update 1;", "EXECUTE z AS a1 string, a2 integer INTO #g UPDATE 1;", //$NON-NLS-1$ //$NON-NLS-2$
- cmdStmt);
- }
-
- @Test public void testDynamicCommandStatementWithUsing() throws Exception {
- SetClauseList using = new SetClauseList();
-
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- using.addClause(a, new ElementSymbol("b")); //$NON-NLS-1$
-
- DynamicCommand sqlCmd = new DynamicCommand();
- Expression sql = new ElementSymbol("z"); //$NON-NLS-1$
-
- sqlCmd.setSql(sql);
- sqlCmd.setUsing(using);
-
- CommandStatement cmdStmt = new CommandStatement(sqlCmd);
-
- helpStmtTest("execute immediate z using a=b;", "EXECUTE z USING a = b;", //$NON-NLS-1$ //$NON-NLS-2$
- cmdStmt);
- }
-
- //as clause should use short names
- @Test public void testDynamicCommandStatement2(){
- helpException("create virtual procedure begin execute string z as variables.a1 string, a2 integer into #g; end"); //$NON-NLS-1$
- }
-
- //using clause should use short names
- @Test public void testDynamicCommandStatement3(){
- helpException("create virtual procedure begin execute string z as a1 string, a2 integer into #g using variables.x=variables.y; end", "Parsing error: Invalid simple identifier format: [variables.x]"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- //into clause requires as clause
- @Test public void testDynamicCommandStatement4(){
- helpException("create virtual procedure begin execute string z into #g using x=variables.y; end"); //$NON-NLS-1$
- }
-
- /** original test */
- @Test public void testCreateUpdateProcedureCommand(){
- helpTestCreateUpdateProcedureCommandCase3025("CREATE PROCEDURE\nBEGIN\nDECLARE short var1;"+ //$NON-NLS-1$
- "IF(HAS IS NULL CRITERIA ON (a))\nBEGIN\nvar1 = (SELECT a1 FROM g WHERE a2 = 5);\nEND\n"+ //$NON-NLS-1$
- "ELSE\nBEGIN\nDECLARE short var2;\nvar2 = (SELECT b1 FROM g WHERE a2 = 5);\nEND\n" + //$NON-NLS-1$
- " END"); //$NON-NLS-1$
-
- }
-
- @Test public void testCreateUpdateProcedureCommandCase3025_1(){
-
- helpTestCreateUpdateProcedureCommandCase3025("CREATE PROCEDURE\nBEGIN\nDECLARE short var1;"+ //$NON-NLS-1$
- "IF(HAS IS NULL CRITERIA ON (a))\nBEGIN\nvar1 = (SELECT a1 FROM g WHERE a2 = 5);\nEND\n"+ //$NON-NLS-1$
- "ELSE\nBEGIN\nDECLARE short var2;\nvar2 = (SELECT b1 FROM g WHERE a2 = 5);\nEND\n" + //$NON-NLS-1$
- " END"); //$NON-NLS-1$
-
- }
-
- @Test public void testCreateUpdateProcedureCommandCase3025_2(){
- helpTestCreateUpdateProcedureCommandCase3025("CREATE PROCEDURE\nBEGIN\nDECLARE short var1;"+ //$NON-NLS-1$
- "IF(HAS IS NULL CRITERIA ON (a))\nBEGIN\nvar1 = ((SELECT a1 FROM g WHERE a2 = 5) );\nEND\n"+ //$NON-NLS-1$
- "ELSE\nBEGIN\nDECLARE short var2;\nvar2 = (SELECT b1 FROM g WHERE a2 = 5);\nEND\n" + //$NON-NLS-1$
- " END"); //$NON-NLS-1$
- }
-
- private void helpTestCreateUpdateProcedureCommandCase3025(String procedureString){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
- elseQuery.setCriteria(criteria);
-
- Command elseQueryCmd = elseQuery;
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- //has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.IS_NULL);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
-
- Block block = new Block();
-
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest(procedureString, "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "IF(HAS IS NULL CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-
- }
-
- /** test an expression in parentheses in an assignment statement */
- @Test public void testCreateUpdateProcedureCommandCase3025_3(){
-
- String procedureString = "CREATE PROCEDURE\nBEGIN\nDECLARE short var1;"+ //$NON-NLS-1$
- "IF(HAS IS NULL CRITERIA ON (a))\nBEGIN\nvar1 = (concat('x', 'y') );\nEND\n"+ //$NON-NLS-1$
- "ELSE\nBEGIN\nDECLARE short var2;\nvar2 = (SELECT b1 FROM g WHERE a2 = 5);\nEND\n" + //$NON-NLS-1$
- " END"; //$NON-NLS-1$
-
- helpTestCreateUpdateProcedureCommandCase3025_Expression(procedureString);
- }
-
- /** test an expression in parentheses in an assignment statement */
- @Test public void testCreateUpdateProcedureCommandCase3025_4(){
-
- String procedureString = "CREATE PROCEDURE\nBEGIN\nDECLARE short var1;"+ //$NON-NLS-1$
- "IF(HAS IS NULL CRITERIA ON (a))\nBEGIN\nvar1 = ((concat('x', 'y') ));\nEND\n"+ //$NON-NLS-1$
- "ELSE\nBEGIN\nDECLARE short var2;\nvar2 = (SELECT b1 FROM g WHERE a2 = 5);\nEND\n" + //$NON-NLS-1$
- " END"; //$NON-NLS-1$
-
- helpTestCreateUpdateProcedureCommandCase3025_Expression(procedureString);
- }
-
- /** test an expression without parentheses in an assignment statement */
- @Test public void testCreateUpdateProcedureCommandCase3025_5(){
-
- String procedureString = "CREATE PROCEDURE\nBEGIN\nDECLARE short var1;"+ //$NON-NLS-1$
- "IF(HAS IS NULL CRITERIA ON (a))\nBEGIN\nvar1 = concat('x', 'y') ;\nEND\n"+ //$NON-NLS-1$
- "ELSE\nBEGIN\nDECLARE short var2;\nvar2 = (SELECT b1 FROM g WHERE a2 = 5);\nEND\n" + //$NON-NLS-1$
- " END"; //$NON-NLS-1$
-
- helpTestCreateUpdateProcedureCommandCase3025_Expression(procedureString);
- }
-
-
- /** test an expression in parentheses in an assignment statement */
- private void helpTestCreateUpdateProcedureCommandCase3025_Expression(String procedureString){
- String expectedString = "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "IF(HAS IS NULL CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = concat('x', 'y');"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- Expression[] args = new Expression[] {new Constant("x"), new Constant("y")}; //$NON-NLS-1$ //$NON-NLS-2$
- Function function = new Function("concat", args); //$NON-NLS-1$
- AssignmentStatement queryStmt = new AssignmentStatement(var1, function);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
- elseQuery.setCriteria(criteria);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- //has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.IS_NULL);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
-
- Block block = new Block();
-
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest(procedureString, expectedString, cmd);
- }
-
- /**IF statement with has criteria */
- @Test public void testCreateUpdateProcedureCommand1(){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
- elseQuery.setCriteria(criteria);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- //has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
-
- Block block = new Block();
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
- " IF(HAS CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
- " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE a2 = 5; END" + //$NON-NLS-1$
- " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- "IF(HAS CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- @Test public void testCreateUpdateProcedureCommand0(){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
- elseQuery.setCriteria(criteria);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- //has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- //critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
-
- Block block = new Block();
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
- " IF(HAS CRITERIA) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
- " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE a2 = 5; END" + //$NON-NLS-1$
- " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- "IF(HAS CRITERIA)"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- /**IF statement with has LIKE criteria */
- @Test public void testCreateUpdateProcedureCommand2(){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
- elseQuery.setCriteria(criteria);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- //has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.LIKE);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
-
- Block block = new Block();
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
- " IF(HAS LIKE CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
- " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE a2 = 5; END" + //$NON-NLS-1$
- " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- "IF(HAS LIKE CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- /**IF statement with has IN criteria */
- @Test public void testCreateUpdateProcedureCommand3(){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
- elseQuery.setCriteria(criteria);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- //has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.IN);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
-
- Block block = new Block();
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
- " IF(HAS IN CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
- " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE a2 = 5; END" + //$NON-NLS-1$
- " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- "IF(HAS IN CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- /**IF statement with has <> criteria */
- @Test public void testCreateUpdateProcedureCommand4(){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
- elseQuery.setCriteria(criteria);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- //has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- critSelector.setSelectorType(CriteriaSelector.COMPARE_NE);
- critSelector.setElements(elements);
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
-
- Block block = new Block();
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
- " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
- " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE a2 = 5; END" + //$NON-NLS-1$
- " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- /**Has criteria in WHERE clause*/
- @Test public void testCreateUpdateProcedureCommand5(){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- //element for has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
-
- CriteriaSelector critSelector2 = new CriteriaSelector();
- //critSelector2.setSelectorType(CriteriaSelector.COMPARE_NE);
- critSelector2.setElements(elements);
-
- HasCriteria hasSelector2 = new HasCriteria();
- hasSelector2.setSelector(critSelector2);
- //has criteria for else block
- elseQuery.setCriteria(hasSelector2);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- CriteriaSelector critSelector1 = new CriteriaSelector();
- critSelector1.setSelectorType(CriteriaSelector.COMPARE_NE);
- critSelector1.setElements(elements);
-
- HasCriteria hasSelector1 = new HasCriteria();
- hasSelector1.setSelector(critSelector1);
-
- IfStatement stmt = new IfStatement(hasSelector1, ifBlock, elseBlock);
-
- Block block = new Block();
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
- " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
- " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE HAS CRITERIA ON (a); END" + //$NON-NLS-1$
- " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE HAS CRITERIA ON (a));"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- /** Translate criteria (empty criteriaSelector in WHERE clause*/
- @Test public void testCreateUpdateProcedureCommand7(){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- //element for has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
-
- Criteria crit = new CompareCriteria(a, CompareCriteria.EQ,
- new Constant(new Integer(5)));
- List critList = new ArrayList();
- critList.add(crit);
-
- CriteriaSelector critSelector2 = new CriteriaSelector();
- //critSelector2.setSelectorType(CriteriaSelector.IS_NULL);
- critSelector2.setElements(elements);
-
- TranslateCriteria transCriteria = new TranslateCriteria(critSelector2, critList);
- elseQuery.setCriteria(transCriteria);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- CriteriaSelector critSelector1 = new CriteriaSelector();
- critSelector1.setSelectorType(CriteriaSelector.COMPARE_NE);
- critSelector1.setElements(elements);
-
- HasCriteria hasSelector1 = new HasCriteria();
- hasSelector1.setSelector(critSelector1);
-
- IfStatement stmt = new IfStatement(hasSelector1, ifBlock, elseBlock);
-
- Block block = new Block();
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
- " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
- " ELSE BEGIN DECLARE short var2; var2 = (SELECT b1 FROM g WHERE TRANSLATE CRITERIA ON (a) WITH (a = 5)); END" + //$NON-NLS-1$
- " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE TRANSLATE CRITERIA ON (a) WITH (a = 5));"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- /** Translate criteria (is null criteriaSelector in WHERE clause*/
- @Test public void testCreateUpdateProcedureCommand9(){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- //element for has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
-
- Criteria crit = new CompareCriteria(a, CompareCriteria.EQ,
- new Constant(new Integer(5)));
- List critList = new ArrayList();
- critList.add(crit);
-
- CriteriaSelector critSelector2 = new CriteriaSelector();
- critSelector2.setSelectorType(CriteriaSelector.IS_NULL);
- critSelector2.setElements(elements);
-
- TranslateCriteria transCriteria = new TranslateCriteria(critSelector2, critList);
- elseQuery.setCriteria(transCriteria);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- CriteriaSelector critSelector1 = new CriteriaSelector();
- critSelector1.setSelectorType(CriteriaSelector.COMPARE_NE);
- critSelector1.setElements(elements);
-
- HasCriteria hasSelector1 = new HasCriteria();
- hasSelector1.setSelector(critSelector1);
-
- IfStatement stmt = new IfStatement(hasSelector1, ifBlock, elseBlock);
-
- Block block = new Block();
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
- " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
- " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE TRANSLATE IS NULL CRITERIA ON (a) WITH (a = 5); END" + //$NON-NLS-1$
- " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE TRANSLATE IS NULL CRITERIA ON (a) WITH (a = 5));"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- /** Translate criteria ( only with WHERE clause) */
- @Test public void testCreateUpdateProcedureCommand10(){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- //element for has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
-
- Criteria crit = new CompareCriteria(a, CompareCriteria.EQ,
- new Constant(new Integer(5)));
- List critList = new ArrayList();
- critList.add(crit);
-
- TranslateCriteria transCriteria = new TranslateCriteria();
- CriteriaSelector critSelector2 = new CriteriaSelector();
- transCriteria.setTranslations(critList);
- transCriteria.setSelector(critSelector2);
-
- elseQuery.setCriteria(transCriteria);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- CriteriaSelector critSelector1 = new CriteriaSelector();
- critSelector1.setSelectorType(CriteriaSelector.COMPARE_NE);
- critSelector1.setElements(elements);
-
- HasCriteria hasSelector1 = new HasCriteria();
- hasSelector1.setSelector(critSelector1);
-
- IfStatement stmt = new IfStatement(hasSelector1, ifBlock, elseBlock);
-
- Block block = new Block();
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
- " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
- " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE TRANSLATE CRITERIA WITH (a = 5); END" + //$NON-NLS-1$
- " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE TRANSLATE CRITERIA WITH (a = 5));"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- /** Translate criteria ( only with WHERE clause) */
- @Test public void testCreateUpdateProcedureCommand12(){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- //element for has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
-
-
- Criteria crit1 = new CompareCriteria(a, CompareCriteria.EQ,
- new Constant(new Integer(5)));
- ElementSymbol m = new ElementSymbol("m"); //$NON-NLS-1$
- Criteria crit2= new CompareCriteria(m, CompareCriteria.EQ,
- new Constant(new Integer(6)));
- List critList = new ArrayList();
- critList.add(crit1);
- critList.add(crit2);
-
- TranslateCriteria transCriteria = new TranslateCriteria();
- CriteriaSelector critSelector2 = new CriteriaSelector();
- transCriteria.setTranslations(critList);
- transCriteria.setSelector(critSelector2);
-
- elseQuery.setCriteria(transCriteria);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- CriteriaSelector critSelector1 = new CriteriaSelector();
- critSelector1.setSelectorType(CriteriaSelector.COMPARE_NE);
- critSelector1.setElements(elements);
-
- HasCriteria hasSelector1 = new HasCriteria();
- hasSelector1.setSelector(critSelector1);
-
- IfStatement stmt = new IfStatement(hasSelector1, ifBlock, elseBlock);
-
- Block block = new Block();
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
- " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
- " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE TRANSLATE CRITERIA WITH (a = 5, m = 6); END" + //$NON-NLS-1$
- " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE TRANSLATE CRITERIA WITH (a = 5, m = 6));"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-
- }
-
- /** Translate criteria (with only Criteria in WHERE clause) */
- @Test public void testCreateUpdateProcedureCommand11(){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- //element for has criteria
- ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
- List elements = new ArrayList();
- elements.add(a);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
-
- Criteria crit = new CompareCriteria(a, CompareCriteria.EQ,
- new Constant(new Integer(5)));
- List critList = new ArrayList();
- critList.add(crit);
-
- CriteriaSelector critSelector = new CriteriaSelector();
- TranslateCriteria transCrit = new TranslateCriteria();
- transCrit.setSelector(critSelector);
-
- elseQuery.setCriteria(transCrit);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- CriteriaSelector critSelector1 = new CriteriaSelector();
- critSelector1.setSelectorType(CriteriaSelector.COMPARE_NE);
- critSelector1.setElements(elements);
-
- HasCriteria hasSelector1 = new HasCriteria();
- hasSelector1.setSelector(critSelector1);
-
- IfStatement stmt = new IfStatement(hasSelector1, ifBlock, elseBlock);
-
- Block block = new Block();
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
- " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
- " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE TRANSLATE CRITERIA; END" + //$NON-NLS-1$
- " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE TRANSLATE CRITERIA);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- /**IF statement with has criteria no on */
- @Test public void testCreateUpdateProcedureCommand8(){
- //declare var1
- ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
- String shortType = new String("short"); //$NON-NLS-1$
- Statement declStmt = new DeclareStatement(var1, shortType);
-
- //ifblock
- List symbols = new ArrayList();
- symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
- Select select = new Select(symbols);
-
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
-
- AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
-
- Block ifBlock = new Block();
- ifBlock.addStatement(queryStmt);
-
- //else block
- ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
- Statement elseDeclStmt = new DeclareStatement(var2, shortType);
-
- List elseSymbols = new ArrayList();
- elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
- Select elseSelect = new Select(elseSymbols);
-
- Query elseQuery = new Query();
- elseQuery.setSelect(elseSelect);
- elseQuery.setFrom(from);
- elseQuery.setCriteria(criteria);
-
- AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
-
- Block elseBlock = new Block();
- List elseStmts = new ArrayList();
- elseStmts.add(elseDeclStmt);
- elseStmts.add(elseQueryStmt);
-
- elseBlock.setStatements(elseStmts);
-
- CriteriaSelector critSelector = new CriteriaSelector();
-
- HasCriteria hasSelector = new HasCriteria();
- hasSelector.setSelector(critSelector);
-
- IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
-
- Block block = new Block();
- block.addStatement(declStmt);
- block.addStatement(stmt);
-
- CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
- cmd.setBlock(block);
-
- helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
- " IF(HAS CRITERIA) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
- " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE a2 = 5; END" + //$NON-NLS-1$
- " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- "IF(HAS CRITERIA)"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
- "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
- "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- @Test public void testSubquerySetCriteria0() {
- //test wrap up command with subquerySetCriteria
- Query outer = exampleIn(false);
-
- helpTest("SELECT a FROM db.g WHERE b IN (SELECT a FROM db.g WHERE a2 = 5)", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b IN (SELECT a FROM db.g WHERE a2 = 5)", //$NON-NLS-1$
- outer);
- }
-
- static Query exampleIn(boolean semiJoin) {
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
-
- Expression expr = new ElementSymbol("b"); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
- SubquerySetCriteria subCrit = new SubquerySetCriteria(expr, query);
- subCrit.getSubqueryHint().setMergeJoin(semiJoin);
- Query outer = new Query();
- outer.setSelect(select);
- outer.setFrom(from);
- outer.setCriteria(subCrit);
- return outer;
- }
-
- @Test public void testSubquerySetCriteria1() {
-
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
-
- Expression expr = new ElementSymbol("b"); //$NON-NLS-1$
-
- Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
- new Constant(new Integer(5)));
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(criteria);
- SubquerySetCriteria subCrit = new SubquerySetCriteria(expr, query);
- subCrit.setNegated(true);
- Query outer = new Query();
- outer.setSelect(select);
- outer.setFrom(from);
- outer.setCriteria(subCrit);
-
- helpTest("SELECT a FROM db.g WHERE b NOT IN (SELECT a FROM db.g WHERE a2 = 5)", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b NOT IN (SELECT a FROM db.g WHERE a2 = 5)", //$NON-NLS-1$
- outer);
- }
-
- @Test public void testSubquerySetCriteriaWithExec() {
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
-
- Expression expr = new ElementSymbol("b"); //$NON-NLS-1$
-
- 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);
- SubquerySetCriteria subCrit = new SubquerySetCriteria(expr, query);
-
- Query outer = new Query();
- outer.setSelect(select);
- outer.setFrom(from);
- outer.setCriteria(subCrit);
-
- helpTest("SELECT a FROM db.g WHERE b IN (EXEC m.sq1())", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b IN (SELECT * FROM (EXEC m.sq1()) AS x)", //$NON-NLS-1$
- outer);
- }
-
- @Test public void testSubquerySetCriteriaWithUnion() {
- GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
-
- Expression expr = new ElementSymbol("b"); //$NON-NLS-1$
-
- Query u1 = new Query();
- Select u1s = new Select();
- u1s.addSymbol(new ElementSymbol("x1")); //$NON-NLS-1$
- u1.setSelect(u1s);
- From u1f = new From();
- u1f = new From();
- u1f.addClause(new UnaryFromClause(new GroupSymbol("db.g2"))); //$NON-NLS-1$
- u1.setFrom(u1f);
-
- Query u2 = new Query();
- Select u2s = new Select();
- u2s.addSymbol(new ElementSymbol("x2")); //$NON-NLS-1$
- u2.setSelect(u2s);
- From u2f = new From();
- u2f = new From();
- u2f.addClause(new UnaryFromClause(new GroupSymbol("db.g3"))); //$NON-NLS-1$
- u2.setFrom(u2f);
-
- SetQuery union = new SetQuery(Operation.UNION, true, u1, u2);
-
- SubquerySetCriteria subCrit = new SubquerySetCriteria(expr, union);
-
- Query outer = new Query();
- outer.setSelect(select);
- outer.setFrom(from);
- outer.setCriteria(subCrit);
-
- helpTest("SELECT a FROM db.g WHERE b IN (SELECT x1 FROM db.g2 UNION ALL SELECT x2 FROM db.g3)", //$NON-NLS-1$
- "SELECT a FROM db.g WHERE b IN (SELECT x1 FROM db.g2 UNION ALL SELECT x2 FROM db.g3)", //$NON-NLS-1$
- outer);
- }
-
- @Test public void testVariablesInExec(){
- StoredProcedure storedQuery = new StoredProcedure();
- storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
- SPParameter parameter = new SPParameter(1, new ElementSymbol("param1")); //$NON-NLS-1$
- parameter.setParameterType(ParameterInfo.IN);
- storedQuery.setParameter(parameter);
- helpTest("Exec proc1(param1)", "EXEC proc1(param1)", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- helpTest("execute proc1(param1)", "EXEC proc1(param1)", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testExecSubquery(){
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- from.addClause(new UnaryFromClause(new GroupSymbol("newModel2.Table1"))); //$NON-NLS-1$
- StoredProcedure subquery = new StoredProcedure();
- subquery.setProcedureName("NewVirtual.StoredQuery");
- from.addClause(new SubqueryFromClause("a", subquery)); //$NON-NLS-1$
- query.setFrom(from);
-
- helpTest("SELECT * FROM newModel2.Table1, (EXEC NewVirtual.StoredQuery()) AS a", //$NON-NLS-1$
- "SELECT * FROM newModel2.Table1, (EXEC NewVirtual.StoredQuery()) AS a", //$NON-NLS-1$
- query);
- }
-
- @Test public void testUnicode1() {
- try {
- byte[] data = { (byte)0xd0, (byte)0x9c, (byte)0xd0, (byte)0xbe, (byte)0xd1, (byte)0x81, (byte)0xd0, (byte)0xba, (byte)0xd0, (byte)0xb2, (byte)0xd0, (byte)0xb0};
-
- String string = new String(data, "UTF-8"); //$NON-NLS-1$
- String sql = "SELECT * FROM TestDocument.TestDocument WHERE Subject='" + string + "'"; //$NON-NLS-1$ //$NON-NLS-2$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- from.addGroup(new GroupSymbol("TestDocument.TestDocument")); //$NON-NLS-1$
- query.setFrom(from);
- CompareCriteria crit = new CompareCriteria(new ElementSymbol("Subject"), CompareCriteria.EQ, new Constant(string)); //$NON-NLS-1$
- query.setCriteria(crit);
-
- helpTest(sql, query.toString(), query);
-
- } catch(UnsupportedEncodingException e) {
- fail(e.getMessage());
- }
- }
-
- @Test public void testUnicode2() {
- String sql = "SELECT * FROM TestDocument.TestDocument WHERE Subject='\u0041\u005a'"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- from.addGroup(new GroupSymbol("TestDocument.TestDocument")); //$NON-NLS-1$
- query.setFrom(from);
- CompareCriteria crit = new CompareCriteria(new ElementSymbol("Subject"), CompareCriteria.EQ, new Constant("AZ")); //$NON-NLS-1$ //$NON-NLS-2$
- query.setCriteria(crit);
-
- helpTest(sql, query.toString(), query);
- }
-
- @Test public void testUnicode3() {
- String sql = "SELECT '\u05e0'"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- Constant c = new Constant("\u05e0"); //$NON-NLS-1$
- select.addSymbol(new ExpressionSymbol("expr", c)); //$NON-NLS-1$
- query.setSelect(select);
-
- helpTest(sql, query.toString(), query);
- }
-
- @Test public void testUnicode4() {
- String sql = "SELECT \u05e0 FROM g"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- ElementSymbol e = new ElementSymbol("\u05e0"); //$NON-NLS-1$
- select.addSymbol(e);
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest(sql, query.toString(), query);
- }
-
- @Test public void testEscapedFunction1() {
- String sql = "SELECT * FROM a.thing WHERE e1 = {fn concat('a', 'b')}"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
- query.setFrom(from);
- Function function = new Function("concat", new Expression[] { new Constant("a"), new Constant("b")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- CompareCriteria crit = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, function); //$NON-NLS-1$
- query.setCriteria(crit);
-
- helpTest(sql,
- "SELECT * FROM a.thing WHERE e1 = concat('a', 'b')", //$NON-NLS-1$
- query);
- }
-
- @Test public void testEscapedFunction2() {
- String sql = "SELECT * FROM a.thing WHERE e1 = {fn convert(5, string)}"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
- query.setFrom(from);
- Function function = new Function("convert", new Expression[] { new Constant(new Integer(5)), new Constant("string")}); //$NON-NLS-1$ //$NON-NLS-2$
- CompareCriteria crit = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, function); //$NON-NLS-1$
- query.setCriteria(crit);
-
- helpTest(sql,
- "SELECT * FROM a.thing WHERE e1 = convert(5, string)", //$NON-NLS-1$
- query);
- }
-
- @Test public void testEscapedFunction3() {
- String sql = "SELECT * FROM a.thing WHERE e1 = {fn cast(5 as string)}"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
- query.setFrom(from);
- Function function = new Function("cast", new Expression[] { new Constant(new Integer(5)), new Constant("string")}); //$NON-NLS-1$ //$NON-NLS-2$
- CompareCriteria crit = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, function); //$NON-NLS-1$
- query.setCriteria(crit);
-
- helpTest(sql, "SELECT * FROM a.thing WHERE e1 = cast(5 AS string)", query); //$NON-NLS-1$
- }
-
- @Test public void testEscapedFunction4() {
- String sql = "SELECT * FROM a.thing WHERE e1 = {fn concat({fn concat('a', 'b')}, 'c')}"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
- from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
- query.setFrom(from);
- Function func1 = new Function("concat", new Expression[] { new Constant("a"), new Constant("b")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Function func2 = new Function("concat", new Expression[] { func1, new Constant("c")}); //$NON-NLS-1$ //$NON-NLS-2$
- CompareCriteria crit = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, func2); //$NON-NLS-1$
- query.setCriteria(crit);
-
- helpTest(sql, "SELECT * FROM a.thing WHERE e1 = concat(concat('a', 'b'), 'c')", query); //$NON-NLS-1$
- }
-
- @Test public void testFunctionWithUnderscore() {
- String sql = "SELECT yowza_yowza() FROM a.thing"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- Function func1 = new Function("yowza_yowza", new Expression[] { }); //$NON-NLS-1$
- ExpressionSymbol exprSymbol = new ExpressionSymbol("expr", func1); //$NON-NLS-1$
- select.addSymbol(exprSymbol);
- query.setSelect(select);
-
- From from = new From();
- from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
- query.setFrom(from);
-
- helpTest(sql, "SELECT yowza_yowza() FROM a.thing", query); //$NON-NLS-1$
- }
-
- @Test public void testManyInnerJoins1() {
- String sql = "SELECT * " + //$NON-NLS-1$
- "FROM SQL1.dbo.Customers INNER JOIN SQL1.dbo.Orders " + //$NON-NLS-1$
- "ON SQL1.dbo.Customers.CustomerID = SQL1.dbo.Orders.CustomerID " + //$NON-NLS-1$
- "INNER JOIN SQL1.dbo.order_details " + //$NON-NLS-1$
- "ON SQL1.dbo.Orders.OrderID = SQL1.dbo.order_details.OrderID"; //$NON-NLS-1$
-
- String sqlExpected = "SELECT * " + //$NON-NLS-1$
- "FROM (SQL1.dbo.Customers INNER JOIN SQL1.dbo.Orders " + //$NON-NLS-1$
- "ON SQL1.dbo.Customers.CustomerID = SQL1.dbo.Orders.CustomerID) " + //$NON-NLS-1$
- "INNER JOIN SQL1.dbo.order_details " + //$NON-NLS-1$
- "ON SQL1.dbo.Orders.OrderID = SQL1.dbo.order_details.OrderID"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
-
- GroupSymbol g1 = new GroupSymbol("SQL1.dbo.Customers"); //$NON-NLS-1$
- GroupSymbol g2 = new GroupSymbol("SQL1.dbo.Orders"); //$NON-NLS-1$
- GroupSymbol g3 = new GroupSymbol("SQL1.dbo.order_details"); //$NON-NLS-1$
-
- ElementSymbol e1 = new ElementSymbol("SQL1.dbo.Customers.CustomerID"); //$NON-NLS-1$
- ElementSymbol e2 = new ElementSymbol("SQL1.dbo.Orders.CustomerID"); //$NON-NLS-1$
- ElementSymbol e3 = new ElementSymbol("SQL1.dbo.Orders.OrderID"); //$NON-NLS-1$
- ElementSymbol e4 = new ElementSymbol("SQL1.dbo.order_details.OrderID"); //$NON-NLS-1$
-
- List jcrits1 = new ArrayList();
- jcrits1.add(new CompareCriteria(e1, CompareCriteria.EQ, e2));
- List jcrits2 = new ArrayList();
- jcrits2.add(new CompareCriteria(e3, CompareCriteria.EQ, e4));
-
- JoinPredicate jp1 = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, jcrits1);
- JoinPredicate jp2 = new JoinPredicate(jp1, new UnaryFromClause(g3), JoinType.JOIN_INNER, jcrits2);
-
- from.addClause(jp2);
- query.setFrom(from);
-
- helpTest(sql, sqlExpected, query);
- }
-
- @Test public void testManyInnerJoins2() {
- String sql = "SELECT * " + //$NON-NLS-1$
- "FROM A INNER JOIN (B RIGHT OUTER JOIN C ON b1 = c1) " + //$NON-NLS-1$
- "ON a1 = b1 " + //$NON-NLS-1$
- "INNER JOIN D " + //$NON-NLS-1$
- "ON a1 = d1"; //$NON-NLS-1$
-
- String sqlExpected = "SELECT * " + //$NON-NLS-1$
- "FROM (A INNER JOIN (B RIGHT OUTER JOIN C ON b1 = c1) " + //$NON-NLS-1$
- "ON a1 = b1) " + //$NON-NLS-1$
- "INNER JOIN D " + //$NON-NLS-1$
- "ON a1 = d1"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
-
- UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("A")); //$NON-NLS-1$
- UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("B")); //$NON-NLS-1$
- UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("C")); //$NON-NLS-1$
- UnaryFromClause g4 = new UnaryFromClause(new GroupSymbol("D")); //$NON-NLS-1$
-
- ElementSymbol e1 = new ElementSymbol("a1"); //$NON-NLS-1$
- ElementSymbol e2 = new ElementSymbol("b1"); //$NON-NLS-1$
- ElementSymbol e3 = new ElementSymbol("c1"); //$NON-NLS-1$
- ElementSymbol e4 = new ElementSymbol("d1"); //$NON-NLS-1$
-
- List jcrits1 = new ArrayList();
- jcrits1.add(new CompareCriteria(e1, CompareCriteria.EQ, e2));
- List jcrits2 = new ArrayList();
- jcrits2.add(new CompareCriteria(e2, CompareCriteria.EQ, e3));
- List jcrits3 = new ArrayList();
- jcrits3.add(new CompareCriteria(e1, CompareCriteria.EQ, e4));
-
- JoinPredicate jp1 = new JoinPredicate(g2, g3, JoinType.JOIN_RIGHT_OUTER, jcrits2);
- JoinPredicate jp2 = new JoinPredicate(g1, jp1, JoinType.JOIN_INNER, jcrits1);
- JoinPredicate jp3 = new JoinPredicate(jp2, g4, JoinType.JOIN_INNER, jcrits3);
-
- from.addClause(jp3);
- query.setFrom(from);
-
- helpTest(sql, sqlExpected, query);
- }
-
- @Test public void testManyInnerJoins3() {
- String sql = "SELECT * " + //$NON-NLS-1$
- "FROM A INNER JOIN " + //$NON-NLS-1$
- "(B RIGHT OUTER JOIN C ON b1 = c1 " + //$NON-NLS-1$
- "CROSS JOIN D) " + //$NON-NLS-1$
- "ON a1 = d1"; //$NON-NLS-1$
-
- String sqlExpected = "SELECT * " + //$NON-NLS-1$
- "FROM A INNER JOIN " + //$NON-NLS-1$
- "((B RIGHT OUTER JOIN C ON b1 = c1) " + //$NON-NLS-1$
- "CROSS JOIN D) " + //$NON-NLS-1$
- "ON a1 = d1"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- query.setSelect(select);
- From from = new From();
-
- UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("A")); //$NON-NLS-1$
- UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("B")); //$NON-NLS-1$
- UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("C")); //$NON-NLS-1$
- UnaryFromClause g4 = new UnaryFromClause(new GroupSymbol("D")); //$NON-NLS-1$
-
- ElementSymbol e1 = new ElementSymbol("a1"); //$NON-NLS-1$
- ElementSymbol e2 = new ElementSymbol("b1"); //$NON-NLS-1$
- ElementSymbol e3 = new ElementSymbol("c1"); //$NON-NLS-1$
- ElementSymbol e4 = new ElementSymbol("d1"); //$NON-NLS-1$
-
- List jcrits1 = new ArrayList();
- jcrits1.add(new CompareCriteria(e2, CompareCriteria.EQ, e3));
- List jcrits2 = new ArrayList();
- jcrits2.add(new CompareCriteria(e1, CompareCriteria.EQ, e4));
-
- JoinPredicate jp1 = new JoinPredicate(g2, g3, JoinType.JOIN_RIGHT_OUTER, jcrits1);
- JoinPredicate jp2 = new JoinPredicate(jp1, g4, JoinType.JOIN_CROSS);
- JoinPredicate jp3 = new JoinPredicate(g1, jp2, JoinType.JOIN_INNER, jcrits2);
-
- from.addClause(jp3);
- query.setFrom(from);
-
- helpTest(sql, sqlExpected, query);
- }
-
- @Test public void testLoopStatement() throws Exception {
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol c1 = new ElementSymbol("c1", false); //$NON-NLS-1$
- select.addSymbol(c1);
- select.addSymbol(new ElementSymbol("c2", false)); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- ElementSymbol x = new ElementSymbol("x"); //$NON-NLS-1$
- String intType = new String("integer"); //$NON-NLS-1$
- Statement dStmt = new DeclareStatement(x, intType);
- c1 = new ElementSymbol("mycursor.c1", true); //$NON-NLS-1$
- Statement assignmentStmt = new AssignmentStatement(x, c1);
- Block block = new Block();
- block.addStatement(dStmt);
- block.addStatement(assignmentStmt);
-
- String cursor = "mycursor"; //$NON-NLS-1$
-
- LoopStatement loopStmt = new LoopStatement(block, query, cursor);
-
- helpStmtTest("LOOP ON (SELECT c1, c2 FROM m.g) AS mycursor BEGIN DECLARE integer x; x=mycursor.c1; END", //$NON-NLS-1$
- "LOOP ON (SELECT c1, c2 FROM m.g) AS mycursor"+"\n"+ "BEGIN"+"\n"+"DECLARE integer x;"+"\n"+"x = mycursor.c1;" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- +"\n"+"END", loopStmt); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testLoopStatementWithOrderBy() throws Exception {
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol c1 = new ElementSymbol("c1", false); //$NON-NLS-1$
- select.addSymbol(c1);
- select.addSymbol(new ElementSymbol("c2", false)); //$NON-NLS-1$
-
- OrderBy orderBy = new OrderBy();
- orderBy.addVariable(c1);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setOrderBy(orderBy);
-
- ElementSymbol x = new ElementSymbol("x"); //$NON-NLS-1$
- String intType = new String("integer"); //$NON-NLS-1$
- Statement dStmt = new DeclareStatement(x, intType);
- c1 = new ElementSymbol("mycursor.c1", true); //$NON-NLS-1$
- Statement assignmentStmt = new AssignmentStatement(x, c1);
- Block block = new Block();
- block.addStatement(dStmt);
- block.addStatement(assignmentStmt);
-
- String cursor = "mycursor"; //$NON-NLS-1$
-
- LoopStatement loopStmt = new LoopStatement(block, query, cursor);
-
- helpStmtTest("LOOP ON (SELECT c1, c2 FROM m.g ORDER BY c1) AS mycursor BEGIN DECLARE integer x; x=mycursor.c1; END", //$NON-NLS-1$
- "LOOP ON (SELECT c1, c2 FROM m.g ORDER BY c1) AS mycursor"+"\n"+ "BEGIN"+"\n"+"DECLARE integer x;"+"\n"+"x = mycursor.c1;" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
- +"\n"+"END", loopStmt); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testWhileStatement() 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.addStatement(assignmentStmt);
- Criteria crit = new CompareCriteria(x, CompareCriteria.LT,
- new Constant(new Integer(100)));
- WhileStatement whileStmt = new WhileStatement(crit, block);
- helpStmtTest("WHILE (x < 100) BEGIN x=x+1; END", //$NON-NLS-1$
- "WHILE(x < 100)"+"\n"+ "BEGIN"+"\n"+"x = (x + 1);" //$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();
- helpStmtTest("break;", "BREAK;", breakStmt); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testContinueStatement() throws Exception {
- Statement contStmt = new ContinueStatement();
- helpStmtTest("continue;", "CONTINUE;", 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$
- Statement dStmt = new DeclareStatement(x, intType);
-
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol c1 = new ElementSymbol("c1", false); //$NON-NLS-1$
- select.addSymbol(c1);
- select.addSymbol(new ElementSymbol("c2", false)); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- x = new ElementSymbol("x"); //$NON-NLS-1$
- c1 = new ElementSymbol("mycursor.c1", true); //$NON-NLS-1$
- Statement assignmentStmt = new AssignmentStatement(x, c1);
- Block block = new Block();
- block.addStatement(assignmentStmt);
-
- Block ifBlock = new Block();
- Statement continueStmt = new ContinueStatement();
- ifBlock.addStatement(continueStmt);
- Criteria crit = new CompareCriteria(x, CompareCriteria.GT,
- new Constant(new Integer(5)));
- IfStatement ifStmt = new IfStatement(crit, ifBlock);
- block.addStatement(ifStmt);
-
- String cursor = "mycursor"; //$NON-NLS-1$
- LoopStatement loopStmt = new LoopStatement(block, query, cursor);
-
- block = new Block();
- block.addStatement(dStmt);
- block.addStatement(loopStmt);
- CommandStatement cmdStmt = new CommandStatement(query);
- block.addStatement(cmdStmt);
-
- CreateUpdateProcedureCommand virtualProcedureCommand = new CreateUpdateProcedureCommand();
- virtualProcedureCommand.setBlock(block);
- virtualProcedureCommand.setUpdateProcedure(false);
-
- helpTest("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT c1, c2 FROM m.g) AS mycursor BEGIN x=mycursor.c1; IF(x > 5) BEGIN CONTINUE; END END SELECT c1, c2 FROM m.g; END", //$NON-NLS-1$
- "CREATE VIRTUAL PROCEDURE\nBEGIN\nDECLARE integer x;\n" //$NON-NLS-1$
- + "LOOP ON (SELECT c1, c2 FROM m.g) AS mycursor\nBEGIN\n" //$NON-NLS-1$
- + "x = mycursor.c1;\nIF(x > 5)\nBEGIN\nCONTINUE;\nEND\nEND\n" //$NON-NLS-1$
- + "SELECT c1, c2 FROM m.g;\nEND", virtualProcedureCommand); //$NON-NLS-1$
-
- }
-
- @Test public void testScalarSubqueryExpressionInSelect(){
-
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- s2.addSymbol(new ExpressionSymbol("expr", new ScalarSubquery(q1))); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
-
- helpTest("SELECT e1, (SELECT e1 FROM m.g1) FROM m.g2", //$NON-NLS-1$
- "SELECT e1, (SELECT e1 FROM m.g1) FROM m.g2", //$NON-NLS-1$
- q2);
- }
-
- @Test public void testScalarSubqueryExpressionInSelect2(){
-
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ExpressionSymbol("expr", new ScalarSubquery(q1))); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
-
- helpTest("SELECT (SELECT e1 FROM m.g1) FROM m.g2", //$NON-NLS-1$
- "SELECT (SELECT e1 FROM m.g1) FROM m.g2", //$NON-NLS-1$
- q2);
- }
-
- @Test public void testScalarSubqueryExpressionInSelect3(){
-
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ExpressionSymbol("expr", new ScalarSubquery(q1))); //$NON-NLS-1$
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
-
- helpTest("SELECT (SELECT e1 FROM m.g1), e1 FROM m.g2", //$NON-NLS-1$
- "SELECT (SELECT e1 FROM m.g1), e1 FROM m.g2", //$NON-NLS-1$
- q2);
- }
-
- @Test public void testScalarSubqueryExpressionWithAlias(){
-
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- s2.addSymbol(new AliasSymbol("X", new ExpressionSymbol("expr", new ScalarSubquery(q1)))); //$NON-NLS-1$ //$NON-NLS-2$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
-
- helpTest("SELECT e1, (SELECT e1 FROM m.g1) as X FROM m.g2", //$NON-NLS-1$
- "SELECT e1, (SELECT e1 FROM m.g1) AS X FROM m.g2", //$NON-NLS-1$
- q2);
- }
-
- @Test public void testScalarSubqueryExpressionInComplexExpression() throws QueryParserException {
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
-
- s2.addSymbol(new AliasSymbol("X", new ExpressionSymbol("expr", QueryParser.getQueryParser().parseExpression("(SELECT e1 FROM m.g1) + 2")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
-
- helpTest("SELECT e1, ((SELECT e1 FROM m.g1) + 2) as X FROM m.g2", //$NON-NLS-1$
- "SELECT e1, ((SELECT e1 FROM m.g1) + 2) AS X FROM m.g2", //$NON-NLS-1$
- q2);
- }
-
- @Test public void testScalarSubqueryExpressionInComplexExpression2() throws QueryParserException{
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
-
- s2.addSymbol(new AliasSymbol("X", new ExpressionSymbol("expr", QueryParser.getQueryParser().parseExpression("3 + (SELECT e1 FROM m.g1)")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
-
- helpTest("SELECT e1, (3 + (SELECT e1 FROM m.g1)) as X FROM m.g2", //$NON-NLS-1$
- "SELECT e1, (3 + (SELECT e1 FROM m.g1)) AS X FROM m.g2", //$NON-NLS-1$
- q2);
- }
-
- @Test public void testScalarSubqueryExpressionInComplexExpression3() throws QueryParserException{
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
-
- s2.addSymbol(new AliasSymbol("X", new ExpressionSymbol("expr", QueryParser.getQueryParser().parseExpression("(SELECT e1 FROM m.g1) + (SELECT e3 FROM m.g3)")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
-
- helpTest("SELECT e1, ((SELECT e1 FROM m.g1) + (SELECT e3 FROM m.g3)) as X FROM m.g2", //$NON-NLS-1$
- "SELECT e1, ((SELECT e1 FROM m.g1) + (SELECT e3 FROM m.g3)) AS X FROM m.g2", //$NON-NLS-1$
- q2);
- }
-
- @Test public void testScalarSubqueryExpressionInFunction() throws QueryParserException{
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
-
- s2.addSymbol(new AliasSymbol("X", new ExpressionSymbol("expr", QueryParser.getQueryParser().getQueryParser().parseExpression("length((SELECT e1 FROM m.g1))")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
-
- helpTest("SELECT e1, length((SELECT e1 FROM m.g1)) as X FROM m.g2", //$NON-NLS-1$
- "SELECT e1, length((SELECT e1 FROM m.g1)) AS X FROM m.g2", //$NON-NLS-1$
- q2);
- }
-
- @Test public void testBadScalarSubqueryExpression() {
- helpException("SELECT e1, length(SELECT e1 FROM m.g1) as X FROM m.g2"); //$NON-NLS-1$
- }
-
- @Test public void testExistsPredicateCriteria(){
-
- Query q2 = exampleExists(false);
-
- helpTest("SELECT e1 FROM m.g2 WHERE Exists (SELECT e1 FROM m.g1)", //$NON-NLS-1$
- "SELECT e1 FROM m.g2 WHERE EXISTS (SELECT e1 FROM m.g1)", //$NON-NLS-1$
- q2);
- }
- static Query exampleExists(boolean semiJoin) {
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- ExistsCriteria existsCrit = new ExistsCriteria(q1);
- existsCrit.getSubqueryHint().setMergeJoin(semiJoin);
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
- q2.setCriteria(existsCrit);
- return q2;
- }
-
- @Test public void testAnyQuantifierSubqueryComparePredicate(){
-
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Criteria left = new SubqueryCompareCriteria(new ElementSymbol("e3"), q1, SubqueryCompareCriteria.GE, SubqueryCompareCriteria.ANY); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
- q2.setCriteria(left);
-
- helpTest("SELECT e1 FROM m.g2 WHERE e3 >= ANY (SELECT e1 FROM m.g1)", //$NON-NLS-1$
- "SELECT e1 FROM m.g2 WHERE e3 >= ANY (SELECT e1 FROM m.g1)", //$NON-NLS-1$
- q2);
-
- }
-
- @Test public void testSomeQuantifierSubqueryComparePredicate(){
-
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Criteria left = new SubqueryCompareCriteria(new ElementSymbol("e3"), q1, SubqueryCompareCriteria.GT, SubqueryCompareCriteria.SOME); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
- q2.setCriteria(left);
-
- helpTest("SELECT e1 FROM m.g2 WHERE e3 > some (SELECT e1 FROM m.g1)", //$NON-NLS-1$
- "SELECT e1 FROM m.g2 WHERE e3 > SOME (SELECT e1 FROM m.g1)", //$NON-NLS-1$
- q2);
-
- }
-
- @Test public void testAllQuantifierSubqueryComparePredicate(){
-
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Criteria left = new SubqueryCompareCriteria(new ElementSymbol("e3"), q1, SubqueryCompareCriteria.EQ, SubqueryCompareCriteria.ALL); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
- q2.setCriteria(left);
-
- helpTest("SELECT e1 FROM m.g2 WHERE e3 = all (SELECT e1 FROM m.g1)", //$NON-NLS-1$
- "SELECT e1 FROM m.g2 WHERE e3 = ALL (SELECT e1 FROM m.g1)", //$NON-NLS-1$
- q2);
-
- }
-
- @Test public void testScalarSubqueryComparePredicate(){
-
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Criteria left = new CompareCriteria(new ElementSymbol("e3"), SubqueryCompareCriteria.LT, new ScalarSubquery(q1)); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
- q2.setCriteria(left);
-
- helpTest("SELECT e1 FROM m.g2 WHERE e3 < (SELECT e1 FROM m.g1)", //$NON-NLS-1$
- "SELECT e1 FROM m.g2 WHERE e3 < (SELECT e1 FROM m.g1)", //$NON-NLS-1$
- q2);
-
- }
-
- @Test public void testSelectInto(){
- GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- ElementSymbol c1 = new ElementSymbol("c1", false); //$NON-NLS-1$
- select.addSymbol(c1);
- select.addSymbol(new ElementSymbol("c2", false)); //$NON-NLS-1$
-
- Into into = new Into(new GroupSymbol("#temp")); //$NON-NLS-1$
- Query q = new Query();
- q.setSelect(select);
- q.setFrom(from);
- q.setInto(into);
- helpTest("SELECT c1, c2 INTO #temp FROM m.g", //$NON-NLS-1$
- "SELECT c1, c2 INTO #temp FROM m.g", //$NON-NLS-1$
- q);
- }
-
- @Test public void testCaseExpression1() {
- CaseExpression expr = TestCaseExpression.example(4);
- Select select = new Select();
- select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
- select.addSymbol(new ElementSymbol("z")); //$NON-NLS-1$
- // The parser hard-codes the name "expr"
- select.addSymbol(new ExpressionSymbol("expr", expr)); //$NON-NLS-1$
- From from = new From();
- from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- Query q = new Query();
- q.setSelect(select);
- q.setFrom(from);
-
- String query = new StringBuffer("SELECT y, z, ") //$NON-NLS-1$
- .append("CASE x") //$NON-NLS-1$
- .append(" WHEN 'a' THEN 0") //$NON-NLS-1$
- .append(" WHEN 'b' THEN 1") //$NON-NLS-1$
- .append(" WHEN 'c' THEN 2") //$NON-NLS-1$
- .append(" WHEN 'd' THEN 3") //$NON-NLS-1$
- .append(" ELSE 9999") //$NON-NLS-1$
- .append(" END") //$NON-NLS-1$
- .append(" FROM m.g").toString(); //$NON-NLS-1$
-
- helpTest(query, query, q);
- }
-
- @Test public void testCaseExpression2() {
- CaseExpression expr = TestCaseExpression.example(4);
- expr.setElseExpression(null);
- Select select = new Select();
- select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
- select.addSymbol(new ElementSymbol("z")); //$NON-NLS-1$
- // The parser hard-codes the name "expr"
- select.addSymbol(new ExpressionSymbol("expr", expr)); //$NON-NLS-1$
- From from = new From();
- from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- Query q = new Query();
- q.setSelect(select);
- q.setFrom(from);
-
- String query = new StringBuffer("SELECT y, z, ") //$NON-NLS-1$
- .append("CASE x") //$NON-NLS-1$
- .append(" WHEN 'a' THEN 0") //$NON-NLS-1$
- .append(" WHEN 'b' THEN 1") //$NON-NLS-1$
- .append(" WHEN 'c' THEN 2") //$NON-NLS-1$
- .append(" WHEN 'd' THEN 3") //$NON-NLS-1$
- .append(" END") //$NON-NLS-1$
- .append(" FROM m.g").toString(); //$NON-NLS-1$
-
- helpTest(query, query, q);
- }
-
- @Test public void testCaseExpression3() {
- SearchedCaseExpression expr = TestSearchedCaseExpression.example2(4);
- Select select = new Select();
- select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
- From from = new From();
- from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- CompareCriteria where = new CompareCriteria(new ElementSymbol("z"), CompareCriteria.EQ, expr); //$NON-NLS-1$
- Query q = new Query();
- q.setSelect(select);
- q.setFrom(from);
- q.setCriteria(where);
-
- String query = new StringBuffer("SELECT y FROM m.g ") //$NON-NLS-1$
- .append("WHERE z = CASE") //$NON-NLS-1$
- .append(" WHEN x = 'a' THEN 0") //$NON-NLS-1$
- .append(" WHEN x = 'b' THEN 1") //$NON-NLS-1$
- .append(" WHEN x = 'c' THEN 2") //$NON-NLS-1$
- .append(" WHEN x = 'd' THEN 3") //$NON-NLS-1$
- .append(" ELSE 9999") //$NON-NLS-1$
- .append(" END").toString(); //$NON-NLS-1$
- helpTest(query, query, q);
- }
-
- @Test public void testSearchedCaseExpression1() {
- SearchedCaseExpression expr = TestSearchedCaseExpression.example(4);
- Select select = new Select();
- select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
- select.addSymbol(new ElementSymbol("z")); //$NON-NLS-1$
- // The parser hard-codes the name "expr"
- select.addSymbol(new ExpressionSymbol("expr", expr)); //$NON-NLS-1$
- From from = new From();
- from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- Query q = new Query();
- q.setSelect(select);
- q.setFrom(from);
-
- String query = new StringBuffer("SELECT y, z, ") //$NON-NLS-1$
- .append("CASE") //$NON-NLS-1$
- .append(" WHEN x = 0 THEN 0") //$NON-NLS-1$
- .append(" WHEN x = 1 THEN 1") //$NON-NLS-1$
- .append(" WHEN x = 2 THEN 2") //$NON-NLS-1$
- .append(" WHEN x = 3 THEN 3") //$NON-NLS-1$
- .append(" ELSE 9999") //$NON-NLS-1$
- .append(" END") //$NON-NLS-1$
- .append(" FROM m.g").toString(); //$NON-NLS-1$
- helpTest(query, query, q);
- }
-
- @Test public void testSearchedCaseExpression2() {
- SearchedCaseExpression expr = TestSearchedCaseExpression.example(4);
- expr.setElseExpression(null);
- Select select = new Select();
- select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
- select.addSymbol(new ElementSymbol("z")); //$NON-NLS-1$
- // The parser hard-codes the name "expr"
- select.addSymbol(new ExpressionSymbol("expr", expr)); //$NON-NLS-1$
- From from = new From();
- from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- Query q = new Query();
- q.setSelect(select);
- q.setFrom(from);
-
- String query = new StringBuffer("SELECT y, z, ") //$NON-NLS-1$
- .append("CASE") //$NON-NLS-1$
- .append(" WHEN x = 0 THEN 0") //$NON-NLS-1$
- .append(" WHEN x = 1 THEN 1") //$NON-NLS-1$
- .append(" WHEN x = 2 THEN 2") //$NON-NLS-1$
- .append(" WHEN x = 3 THEN 3") //$NON-NLS-1$
- .append(" END") //$NON-NLS-1$
- .append(" FROM m.g").toString(); //$NON-NLS-1$
- helpTest(query, query, q);
- }
-
- @Test public void testSearchedCaseExpression3() {
- SearchedCaseExpression expr = TestSearchedCaseExpression.example(4);
- Select select = new Select();
- select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
- From from = new From();
- from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- CompareCriteria where = new CompareCriteria(new ElementSymbol("z"), CompareCriteria.EQ, expr); //$NON-NLS-1$
- Query q = new Query();
- q.setSelect(select);
- q.setFrom(from);
- q.setCriteria(where);
-
- String query = new StringBuffer("SELECT y FROM m.g ") //$NON-NLS-1$
- .append("WHERE z = CASE") //$NON-NLS-1$
- .append(" WHEN x = 0 THEN 0") //$NON-NLS-1$
- .append(" WHEN x = 1 THEN 1") //$NON-NLS-1$
- .append(" WHEN x = 2 THEN 2") //$NON-NLS-1$
- .append(" WHEN x = 3 THEN 3") //$NON-NLS-1$
- .append(" ELSE 9999") //$NON-NLS-1$
- .append(" END").toString(); //$NON-NLS-1$
- helpTest(query, query, q);
- }
-
- @Test public void testAndOrPrecedence_1575() {
- Select s = new Select();
- s.addSymbol(new AllSymbol());
- 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$
- CompareCriteria c2 = new CompareCriteria(new ElementSymbol("e2"), CompareCriteria.EQ, new Constant(new Integer(1))); //$NON-NLS-1$
- CompareCriteria c3 = new CompareCriteria(new ElementSymbol("e3"), CompareCriteria.EQ, new Constant(new Integer(3))); //$NON-NLS-1$
- CompoundCriteria cc1 = new CompoundCriteria(CompoundCriteria.AND, c2, c3);
- CompoundCriteria cc2 = new CompoundCriteria(CompoundCriteria.OR, c1, cc1);
- Query q = new Query();
- q.setSelect(s);
- q.setFrom(f);
- q.setCriteria(cc2);
-
- helpTest("SELECT * FROM m.g1 WHERE e1=0 OR e2=1 AND e3=3", //$NON-NLS-1$
- "SELECT * FROM m.g1 WHERE (e1 = 0) OR ((e2 = 1) AND (e3 = 3))", q); //$NON-NLS-1$
- }
-
- @Test public void testAndOrPrecedence2_1575() {
- Select s = new Select();
- s.addSymbol(new AllSymbol());
- 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$
- CompareCriteria c2 = new CompareCriteria(new ElementSymbol("e2"), CompareCriteria.EQ, new Constant(new Integer(1))); //$NON-NLS-1$
- CompareCriteria c3 = new CompareCriteria(new ElementSymbol("e3"), CompareCriteria.EQ, new Constant(new Integer(3))); //$NON-NLS-1$
- CompoundCriteria cc1 = new CompoundCriteria(CompoundCriteria.AND, c1, c2);
- CompoundCriteria cc2 = new CompoundCriteria(CompoundCriteria.OR, cc1, c3);
- Query q = new Query();
- q.setSelect(s);
- q.setFrom(f);
- q.setCriteria(cc2);
-
- helpTest("SELECT * FROM m.g1 WHERE e1=0 AND e2=1 OR e3=3", //$NON-NLS-1$
- "SELECT * FROM m.g1 WHERE ((e1 = 0) AND (e2 = 1)) OR (e3 = 3)", q); //$NON-NLS-1$
- }
-
- /**
- *
- * @since 4.2
- */
- private void helpTestCompoundNonJoinCriteria(String sqlPred, PredicateCriteria predCrit) {
- Select s = new Select();
- s.addSymbol(new AllSymbol());
- From f = new From();
-
- CompareCriteria c1 = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, new Constant(new Integer(0))); //$NON-NLS-1$
- CompoundCriteria cc1 = new CompoundCriteria(CompoundCriteria.AND, c1, predCrit);
- JoinPredicate jp = new JoinPredicate(new UnaryFromClause(new GroupSymbol("m.g1")), new UnaryFromClause(new GroupSymbol("m.g2")), JoinType.JOIN_INNER, cc1); //$NON-NLS-1$ //$NON-NLS-2$
- f.addClause(jp);
-
- Query q = new Query();
- q.setSelect(s);
- q.setFrom(f);
-
- helpTest("SELECT * FROM m.g1 JOIN m.g2 ON e1=0 AND " + sqlPred, //$NON-NLS-1$
- "SELECT * FROM m.g1 INNER JOIN m.g2 ON e1 = 0 AND " + sqlPred, q); //$NON-NLS-1$
-
- }
-
-
- @Test public void testCompoundNonJoinCriteriaInFromWithComparisonCriteria() {
- CompareCriteria c2 = new CompareCriteria(new ElementSymbol("e2"), CompareCriteria.EQ, new Constant(new Integer(1))); //$NON-NLS-1$
- helpTestCompoundNonJoinCriteria("e2 = 1", c2); //$NON-NLS-1$
- }
-
- @Test public void testCompoundNonJoinCriteriaInFromWithIsNull() {
- helpTestCompoundNonJoinCriteria("e2 IS NULL", new IsNullCriteria(new ElementSymbol("e2"))); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCompoundNonJoinCriteriaInFromUWithIN() {
- Collection values = new ArrayList();
- values.add(new Constant(new Integer(0)));
- values.add(new Constant(new Integer(1)));
- PredicateCriteria crit = new SetCriteria(new ElementSymbol("e2"), values); //$NON-NLS-1$
- helpTestCompoundNonJoinCriteria("e2 IN (0, 1)", crit); //$NON-NLS-1$
- }
-
- @Test public void testCompoundNonJoinCriteriaInFromUWithLIKE() {
- PredicateCriteria crit = new MatchCriteria(new ElementSymbol("e2"), new Constant("%")); //$NON-NLS-1$ //$NON-NLS-2$
- helpTestCompoundNonJoinCriteria("e2 LIKE '%'", crit); //$NON-NLS-1$
- }
-
- @Test public void testCompoundNonJoinCriteria_defect15167_1() throws Exception {
- QueryParser.getQueryParser().parseCommand("SELECT A.alert_id, A.primary_entity_name, A.primary_entity_level_code, A.alert_description, A.create_date, A.alert_risk_score, S.scenario_name, A.alert_status_code, A.process_id, A.actual_values_text, S.SCENARIO_CATEGORY_DESC, A.primary_entity_number, A.scenario_id, A.primary_entity_key FROM (FSK_ALERT AS A LEFT OUTER JOIN FSK_SCENARIO AS S ON A.scenario_id = S.scenario_id) INNER JOIN FSC_ACCOUNT_DIM AS C ON A.primary_entity_key = C.ACCOUNT_KEY AND ((S.current_ind = 'Y') OR (S.current_ind IS NULL)) WHERE (A.primary_entity_level_code = 'ACC') AND (C.ACCOUNT_KEY = 23923) AND (A.logical_delete_ind = 'N')"); //$NON-NLS-1$
- }
-
- @Test public void testCompoundNonJoinCriteria_defect15167_2() throws Exception {
- QueryParser.getQueryParser().parseCommand("SELECT A.alert_id, A.primary_entity_name, A.primary_entity_level_code, A.alert_description, A.create_date, A.alert_risk_score, S.scenario_name, A.alert_status_code, A.process_id, A.actual_values_text, S.SCENARIO_CATEGORY_DESC, A.primary_entity_number, A.scenario_id, A.primary_entity_key FROM (FSK_ALERT AS A LEFT OUTER JOIN FSK_SCENARIO AS S ON A.scenario_id = S.scenario_id) INNER JOIN FSC_ACCOUNT_DIM AS C ON A.primary_entity_key = C.ACCOUNT_KEY AND (S.current_ind = 'Y' OR S.current_ind IS NULL) WHERE (A.primary_entity_level_code = 'ACC') AND (C.ACCOUNT_KEY = 23923) AND (A.logical_delete_ind = 'N')"); //$NON-NLS-1$
- }
-
- @Test public void testCompoundNonJoinCriteria_defect15167_3() throws Exception {
- QueryParser.getQueryParser().parseCommand("SELECT A.alert_id, A.primary_entity_name, A.primary_entity_level_code, A.alert_description, A.create_date, A.alert_risk_score, S.scenario_name, A.alert_status_code, A.process_id, A.actual_values_text, S.SCENARIO_CATEGORY_DESC, A.primary_entity_number, A.scenario_id, A.primary_entity_key FROM (FSK_ALERT AS A LEFT OUTER JOIN FSK_SCENARIO AS S ON A.scenario_id = S.scenario_id) INNER JOIN FSC_ACCOUNT_DIM AS C ON (A.primary_entity_key = C.ACCOUNT_KEY AND (S.current_ind = 'Y' OR S.current_ind IS NULL)) WHERE (A.primary_entity_level_code = 'ACC') AND (C.ACCOUNT_KEY = 23923) AND (A.logical_delete_ind = 'N')"); //$NON-NLS-1$
- }
-
- @Test public void testCompoundNonJoinCriteria_defect15167_4() throws Exception {
- QueryParser.getQueryParser().parseCommand("SELECT A.alert_id, A.primary_entity_name, A.primary_entity_level_code, A.alert_description, A.create_date, A.alert_risk_score, S.scenario_name, A.alert_status_code, A.process_id, A.actual_values_text, S.SCENARIO_CATEGORY_DESC, A.primary_entity_number, A.scenario_id, A.primary_entity_key FROM (FSK_ALERT AS A LEFT OUTER JOIN FSK_SCENARIO AS S ON A.scenario_id = S.scenario_id) INNER JOIN FSC_ACCOUNT_DIM AS C ON (A.primary_entity_key = C.ACCOUNT_KEY AND S.current_ind = 'Y' OR S.current_ind IS NULL) WHERE (A.primary_entity_level_code = 'ACC') AND (C.ACCOUNT_KEY = 23923) AND (A.logical_delete_ind = 'N')"); //$NON-NLS-1$
- }
-
- @Test public void testFunctionInGroupBy() throws Exception {
- QueryParser.getQueryParser().parseCommand("SELECT SUM(s), elem+1 FROM m.g GROUP BY elem+1"); //$NON-NLS-1$
- }
-
- @Test public void testCaseInGroupBy() throws Exception {
- QueryParser.getQueryParser().parseCommand("SELECT SUM(elem+1), CASE elem WHEN 0 THEN 1 ELSE 2 END AS c FROM m.g GROUP BY CASE elem WHEN 0 THEN 1 ELSE 2 END"); //$NON-NLS-1$
- }
-
- @Test public void testNationCharString() throws Exception {
- Query query = (Query) QueryParser.getQueryParser().parseCommand("SELECT N'blah' FROM m.g"); //$NON-NLS-1$
- Select select = query.getSelect();
- ExpressionSymbol s = (ExpressionSymbol) select.getSymbol(0);
- Constant c = (Constant) s.getExpression();
- assertEquals(c, new Constant("blah")); //$NON-NLS-1$
- }
-
- @Test public void testNationCharString2() throws Exception {
- Query query = (Query) QueryParser.getQueryParser().parseCommand("SELECT DISTINCT TABLE_QUALIFIER, NULL AS TABLE_OWNER, NULL AS TABLE_NAME, NULL AS TABLE_TYPE, NULL AS REMARKS FROM ATIODBCSYSTEM.OA_TABLES WHERE TABLE_QUALIFIER LIKE N'%' ESCAPE '\\' ORDER BY TABLE_QUALIFIER "); //$NON-NLS-1$
- MatchCriteria matchCrit = (MatchCriteria) query.getCriteria();
- Constant c = (Constant) matchCrit.getRightExpression();
- assertEquals(c, new Constant("%")); //$NON-NLS-1$
- }
-
- @Test public void testScalarSubquery() throws Exception {
- QueryParser.getQueryParser().parseCommand("SELECT (SELECT 1) FROM x"); //$NON-NLS-1$
- }
-
- @Test public void testElementInDoubleQuotes() throws Exception {
- GroupSymbol g = new GroupSymbol("x"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- ElementSymbol e = new ElementSymbol("foo"); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(e);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT \"foo\" FROM x", //$NON-NLS-1$
- "SELECT foo FROM x", //$NON-NLS-1$
- query);
- }
-
- @Test public void testElementInDoubleQuotes_Insert() throws Exception {
- GroupSymbol g = new GroupSymbol("x"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- ElementSymbol e = new ElementSymbol("foo"); //$NON-NLS-1$
-
- Insert query = new Insert(g, new ArrayList(), new ArrayList());
- query.addVariable(e);
- query.addValue(new Constant("bar", String.class)); //$NON-NLS-1$
-
- helpTest("insert into x (\"foo\") values ('bar')", //$NON-NLS-1$
- "INSERT INTO x (foo) VALUES ('bar')", //$NON-NLS-1$
- query);
- }
-
- @Test public void testElementInDoubleQuotes_Update() throws Exception {
- GroupSymbol g = new GroupSymbol("x"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- ElementSymbol e = new ElementSymbol("foo"); //$NON-NLS-1$
- Update query = new Update();
- query.setGroup(g);
- query.addChange(e, new Constant("bar", String.class)); //$NON-NLS-1$
-
- helpTest("update x set \"foo\"='bar'", //$NON-NLS-1$
- "UPDATE x SET foo = 'bar'", //$NON-NLS-1$
- query);
- }
-
- @Test public void testElementInDoubleQuotes_delete() throws Exception {
- GroupSymbol g = new GroupSymbol("x"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- ElementSymbol e = new ElementSymbol("foo"); //$NON-NLS-1$
- CompareCriteria c = new CompareCriteria(e, CompareCriteria.EQ, new Constant("bar", String.class)); //$NON-NLS-1$
- Delete query = new Delete(g,c);
-
- helpTest("delete from x where \"foo\"='bar'", //$NON-NLS-1$
- "DELETE FROM x WHERE foo = 'bar'", //$NON-NLS-1$
- query);
- }
-
- @Test public void testAliasInDoubleQuotes() throws Exception {
- GroupSymbol g = new GroupSymbol("x"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- AliasSymbol as = new AliasSymbol("fooAlias", new ElementSymbol("fooKey")); //$NON-NLS-1$ //$NON-NLS-2$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT fooKey AS \"fooAlias\" FROM x", //$NON-NLS-1$
- "SELECT fooKey AS fooAlias FROM x", //$NON-NLS-1$
- query);
- }
-
- @Test public void testAliasInDoubleQuotesWithQuotedGroup() throws Exception {
-
- GroupSymbol g = new GroupSymbol("x.y.z"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- AliasSymbol as = new AliasSymbol("fooAlias", new ElementSymbol("fooKey")); //$NON-NLS-1$ //$NON-NLS-2$
- Select select = new Select();
- select.addSymbol(as);
-
- ElementSymbol a = new ElementSymbol("x.y.z.id"); //$NON-NLS-1$
- Constant c = new Constant(new Integer(10));
- Criteria crit = new CompareCriteria(a, CompareCriteria.EQ, c);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(crit);
-
- helpTest("SELECT fooKey AS \"fooAlias\" FROM \"x.y\".z where x.\"y.z\".id = 10", //$NON-NLS-1$
- "SELECT fooKey AS fooAlias FROM x.y.z WHERE x.y.z.id = 10", //$NON-NLS-1$
- query);
- }
-
- @Test public void testSingleQuotedConstant() throws Exception {
-
- GroupSymbol g = new GroupSymbol("x.y.z"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Constant as = new Constant("fooString"); //$NON-NLS-1$
- Select select = new Select();
- select.addSymbol(new ExpressionSymbol("expr", as)); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest("SELECT 'fooString' FROM \"x.y.z\"", //$NON-NLS-1$
- "SELECT 'fooString' FROM x.y.z", //$NON-NLS-1$
- query);
- }
-
- @Test public void testAliasInSingleQuotes() throws Exception {
-
- GroupSymbol g = new GroupSymbol("x.y.z"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- AliasSymbol as = new AliasSymbol("fooAlias", new ElementSymbol("fooKey")); //$NON-NLS-1$ //$NON-NLS-2$
- Select select = new Select();
- select.addSymbol(as);
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpException("SELECT fooKey 'fooAlias' FROM x.\"y\".z"); //$NON-NLS-1$
- }
-
- /** QUERY Tool Format*/
- @Test public void testQueryWithQuotes_MSQuery() throws Exception {
- QueryParser.getQueryParser().parseCommand("SELECT \"PART_COLOR\", \"PART_ID\", \"PART_NAME\", \"PART_WEIGHT\" FROM \"VirtualParts.base\".\"Parts\""); //$NON-NLS-1$
- }
-
- /** MS Access Format**/
- @Test public void testQueryWithQuotes_MSAccess() throws Exception {
- QueryParser.getQueryParser().parseCommand("SELECT \"PART_COLOR\" ,\"PART_ID\" ,\"PART_NAME\" ,\"PART_WEIGHT\" FROM \"parts_oracle.DEV_RRAMESH\".\"PARTS\""); //$NON-NLS-1$
- }
-
- /** BO Business View Manager**/
- @Test public void testQueryWithQuotes_BODesigner() throws Exception {
- QueryParser.getQueryParser().parseCommand("SELECT DISTINCT \"PARTS\".\"PART_NAME\" FROM \"parts_oracle.DEV_RRAMESH\".\"PARTS\" \"PARTS\""); //$NON-NLS-1$
- }
-
- /** Crystal Reports **/
- @Test public void testQueryWithQuotes_CrystalReports() throws Exception {
- QueryParser.getQueryParser().parseCommand("SELECT \"Oracle_PARTS\".\"PART_COLOR\", \"Oracle_PARTS\".\"PART_ID\", \"Oracle_PARTS\".\"PART_NAME\", \"Oracle_PARTS\".\"PART_WEIGHT\", \"SQL_PARTS\".\"PART_COLOR\", \"SQL_PARTS\".\"PART_ID\", \"SQL_PARTS\".\"PART_NAME\", \"SQL_PARTS\".\"PART_WEIGHT\" FROM \"parts_oracle.DEV_RRAMESH\".\"PARTS\" \"Oracle_PARTS\", \"parts_sqlserver.dv_rreddy.dv_rreddy\".\"PARTS\" \"SQL_PARTS\" WHERE (\"Oracle_PARTS\".\"PART_ID\"=\"SQL_PARTS\".\"PART_ID\")"); //$NON-NLS-1$
- }
-
- @Test public void testOrderByWithNumbers_InQuotes() throws Exception {
- GroupSymbol g = new GroupSymbol("z"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("x")); //$NON-NLS-1$
- select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
-
- OrderBy orderby = new OrderBy();
- orderby.addVariable(new ElementSymbol("1"), true); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setOrderBy(orderby);
-
- helpTest("SELECT x, y from z order by \"1\"", "SELECT x, y FROM z ORDER BY \"1\"", query); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testOrderByWithNumbers_AsInt() throws Exception {
- GroupSymbol g = new GroupSymbol("z"); //$NON-NLS-1$
- From from = new From();
- from.addGroup(g);
-
- Select select = new Select();
- select.addSymbol(new ElementSymbol("x")); //$NON-NLS-1$
- select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
-
- OrderBy orderby = new OrderBy();
- orderby.addVariable(new ExpressionSymbol("expr", new Constant(1)), true); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setOrderBy(orderby);
-
- helpTest("SELECT x, y FROM z order by 1", "SELECT x, y FROM z ORDER BY 1", query); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test(expected=QueryParserException.class) public void testOrderByWithNumbers_AsNegitiveInt() throws Exception {
- QueryParser.getQueryParser().parseCommand("SELECT x, y FROM z order by -1"); //$NON-NLS-1$
- }
-
- @Test public void testEmptyAndNullInputsGiveSameErrorMessage() throws Exception {
- String emptyMessage = null;
- try {
- QueryParser.getQueryParser().parseCommand(""); //$NON-NLS-1$
- fail("Expected exception for parsing empty string"); //$NON-NLS-1$
- } catch(TeiidException e) {
- emptyMessage = e.getMessage();
- }
-
- String nullMessage = null;
- try {
- QueryParser.getQueryParser().parseCommand(null);
- fail("Expected exception for parsing null string"); //$NON-NLS-1$
- } catch(TeiidException e) {
- nullMessage = e.getMessage();
- }
-
- assertTrue("Expected same message for empty and null cases", emptyMessage.equals(nullMessage)); //$NON-NLS-1$
- }
-
- @Test public void testCase3281NamedVariable() {
- StoredProcedure storedQuery = new StoredProcedure();
- storedQuery.setDisplayNamedParameters(true);
- storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
- SPParameter parameter = new SPParameter(1, new Constant("paramValue1")); //$NON-NLS-1$
- parameter.setName("param1"); //$NON-NLS-1$
- parameter.setParameterType(ParameterInfo.IN);
- storedQuery.setParameter(parameter);
- helpTest("Exec proc1(param1 = 'paramValue1')", "EXEC proc1(param1 => 'paramValue1')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- helpTest("execute proc1(param1 = 'paramValue1')", "EXEC proc1(param1 => 'paramValue1')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCase3281NamedVariables() {
- StoredProcedure storedQuery = new StoredProcedure();
- storedQuery.setDisplayNamedParameters(true);
- storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
- SPParameter param1 = new SPParameter(1, new Constant("paramValue1")); //$NON-NLS-1$
- param1.setName("param1"); //$NON-NLS-1$
- param1.setParameterType(ParameterInfo.IN);
- storedQuery.setParameter(param1);
- SPParameter param2 = new SPParameter(2, new Constant("paramValue2")); //$NON-NLS-1$
- param2.setName("param2"); //$NON-NLS-1$
- param2.setParameterType(ParameterInfo.IN);
- storedQuery.setParameter(param2);
- helpTest("Exec proc1(param1 = 'paramValue1', param2 = 'paramValue2')", "EXEC proc1(param1 => 'paramValue1', param2 => 'paramValue2')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- helpTest("execute proc1(param1 = 'paramValue1', param2 = 'paramValue2')", "EXEC proc1(param1 => 'paramValue1', param2 => 'paramValue2')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCase3281QuotedNamedVariableFails2() {
- StoredProcedure storedQuery = new StoredProcedure();
- storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
- SPParameter param1 = new SPParameter(1, new CompareCriteria(new Constant("a"), CompareCriteria.EQ, new Constant("b"))); //$NON-NLS-1$
- param1.setParameterType(ParameterInfo.IN);
- storedQuery.setParameter(param1);
- helpTest("Exec proc1('a' = 'b')", "EXEC proc1(('a' = 'b'))", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** Test what happens if the name of a parameter is a reserved word. It must be quoted (double-ticks). */
- @Test public void testCase3281NamedVariablesReservedWords() {
- StoredProcedure storedQuery = new StoredProcedure();
- storedQuery.setDisplayNamedParameters(true);
- storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
- SPParameter param1 = new SPParameter(1, new Constant("paramValue1")); //$NON-NLS-1$
- param1.setName("in"); //$NON-NLS-1$ //<---RESERVED WORD
- param1.setParameterType(ParameterInfo.IN);
- storedQuery.setParameter(param1);
- SPParameter param2 = new SPParameter(2, new Constant("paramValue2")); //$NON-NLS-1$
- param2.setName("in2"); //$NON-NLS-1$
- param2.setParameterType(ParameterInfo.IN);
- storedQuery.setParameter(param2);
- helpTest("Exec proc1(\"in\" = 'paramValue1', in2 = 'paramValue2')", "EXEC proc1(\"in\" => 'paramValue1', in2 => 'paramValue2')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- helpTest("execute proc1(\"in\" = 'paramValue1', in2 = 'paramValue2')", "EXEC proc1(\"in\" => 'paramValue1', in2 => 'paramValue2')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testExceptionMessageWithLocation() {
- try {
- QueryParser.getQueryParser().parseCommand("SELECT FROM"); //$NON-NLS-1$
- } catch(QueryParserException e) {
- assertTrue(e.getMessage().startsWith("Parsing error: Encountered \"FROM\" at line 1, column 8.")); //$NON-NLS-1$
- }
- }
-
- @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$
- }
-
- @Test public void testCreateTempTable1() {
- Create create = new Create();
- create.setTable(new GroupSymbol("tempTable")); //$NON-NLS-1$
- List columns = new ArrayList();
- ElementSymbol column = new ElementSymbol("c1");//$NON-NLS-1$
- column.setType(DataTypeManager.DefaultDataClasses.BOOLEAN);
- columns.add(column);
- column = new ElementSymbol("c2");//$NON-NLS-1$
- column.setType(DataTypeManager.DefaultDataClasses.BYTE);
- columns.add(column);
- create.setElementSymbolsAsColumns(columns);
- helpTest("Create local TEMPORARY table tempTable (c1 boolean, c2 byte)", "CREATE LOCAL TEMPORARY TABLE tempTable (c1 boolean, c2 byte)", create); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCreateTempTable2() {
- Create create = new Create();
- create.setTable(new GroupSymbol("tempTable")); //$NON-NLS-1$
- List columns = new ArrayList();
- ElementSymbol column = new ElementSymbol("c1");//$NON-NLS-1$
- column.setType(DataTypeManager.DefaultDataClasses.BOOLEAN);
- columns.add(column);
- column = new ElementSymbol("c2");//$NON-NLS-1$
- column.setType(DataTypeManager.DefaultDataClasses.BYTE);
- columns.add(column);
- create.setElementSymbolsAsColumns(columns);
- helpTest("Create local TEMPORARY table tempTable(c1 boolean, c2 byte)", "CREATE LOCAL TEMPORARY TABLE tempTable (c1 boolean, c2 byte)", create); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCreateTempTable3() {
- helpException("Create TEMPORARY table tempTable (c1 boolean, c2 byte)"); //$NON-NLS-1$
- }
-
- @Test public void testCreateTempTable4() {
- helpException("Create table tempTable (c1 boolean, c2 byte)"); //$NON-NLS-1$
- }
-
- @Test public void testCreateTempTable5() {
- helpException("Create local TEMPORARY table tempTable (c1 boolean primary, c2 byte)"); //$NON-NLS-1$
- }
-
- @Test public void testCreateTempTable7() {
- helpException("Create local TEMPORARY table tempTable (c1.x boolean, c2 byte)" ,"Parsing error: Invalid simple identifier format: [c1.x]"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCreateTempTableWithPrimaryKey() {
- Create create = new Create();
- create.setTable(new GroupSymbol("tempTable")); //$NON-NLS-1$
- List columns = new ArrayList();
- ElementSymbol column = new ElementSymbol("c1");//$NON-NLS-1$
- column.setType(DataTypeManager.DefaultDataClasses.BOOLEAN);
- columns.add(column);
- column = new ElementSymbol("c2");//$NON-NLS-1$
- column.setType(DataTypeManager.DefaultDataClasses.BYTE);
- columns.add(column);
- create.setElementSymbolsAsColumns(columns);
- create.getPrimaryKey().add(column);
- helpTest("Create local TEMPORARY table tempTable(c1 boolean, c2 byte, primary key (c2))", "CREATE LOCAL TEMPORARY TABLE tempTable (c1 boolean, c2 byte, PRIMARY KEY(c2))", create); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testDropTable() {
- Drop drop = new Drop();
- drop.setTable(new GroupSymbol("tempTable")); //$NON-NLS-1$
- helpTest("DROP table tempTable", "DROP TABLE tempTable", drop); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testEscapedOuterJoin() {
- String sql = "SELECT * FROM {oj A LEFT OUTER JOIN B ON (A.x=B.x)}"; //$NON-NLS-1$
- String expected = "SELECT * FROM A LEFT OUTER JOIN B ON A.x = B.x"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- query.setSelect(select);
- select.addSymbol(new AllSymbol());
- 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$
- FromClause f1 = new UnaryFromClause(new GroupSymbol("A")); //$NON-NLS-1$
- FromClause f2 = new UnaryFromClause(new GroupSymbol("B")); //$NON-NLS-1$
- JoinPredicate jp = new JoinPredicate(f1, f2, JoinType.JOIN_LEFT_OUTER, Arrays.asList(new Object[] {compareCriteria}));
- from.addClause(jp);
-
- helpTest(sql, expected, query);
- }
-
- @Test public void testBadAlias() {
- String sql = "select a as a.x from foo"; //$NON-NLS-1$
-
- helpException(sql, "Parsing error: Invalid alias format: [a.x]"); //$NON-NLS-1$
- }
-
- @Test public void testNameSpacedFunctionName() {
- String sql = "select a.x()"; //$NON-NLS-1$
-
- Query query = new Query();
- Select select = new Select();
- Function func1 = new Function("a.x", new Expression[] { }); //$NON-NLS-1$
- ExpressionSymbol exprSymbol = new ExpressionSymbol("expr", func1); //$NON-NLS-1$
- select.addSymbol(exprSymbol);
- query.setSelect(select);
-
- helpTest(sql, "SELECT a.x()", query); //$NON-NLS-1$
- }
-
- @Test public void testUnionJoin() {
- String sql = "select * from pm1.g1 union join pm1.g2 where g1.e1 = 1"; //$NON-NLS-1$
- 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());
-
- 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$
-
- Criteria crit = new CompareCriteria(new ElementSymbol("g1.e1"), CompareCriteria.EQ, new Constant(new Integer(1))); //$NON-NLS-1$
-
- Query command = new Query(select, from, crit, null, null);
- helpTest(sql, expected, command);
- }
-
- @Test public void testUnionJoin1() {
- String sql = "select * from pm1.g1 union all join pm1.g2 where g1.e1 = 1"; //$NON-NLS-1$
-
- helpException(sql);
- }
-
- @Test public void testIfElseWithoutBeginEnd() {
- String sql = "CREATE PROCEDURE BEGIN IF (x > 1) select 1; IF (x > 1) select 1; ELSE select 1; END"; //$NON-NLS-1$
- 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$
- CommandStatement commandStmt = new CommandStatement(query);
- CompareCriteria criteria = new CompareCriteria(new ElementSymbol("x"), CompareCriteria.GT, new Constant(new Integer(1))); //$NON-NLS-1$
- Block block = new Block();
- block.addStatement(commandStmt);
- IfStatement ifStmt = new IfStatement(criteria, block);
- IfStatement ifStmt1 = (IfStatement)ifStmt.clone();
- Block block2 = new Block();
- block2.addStatement(commandStmt);
- ifStmt1.setElseBlock(block2);
- Block block3 = new Block();
- block3.addStatement(ifStmt);
- block3.addStatement(ifStmt1);
- CreateUpdateProcedureCommand command = new CreateUpdateProcedureCommand(block3);
-
- helpTest(sql, expected, command);
- }
-
- @Test public void testBadCreate() {
- helpException("create insert"); //$NON-NLS-1$
- }
-
- @Test public void testCommandWithSemicolon() throws Exception {
- helpTest("select * from pm1.g1;", "SELECT * FROM pm1.g1", QueryParser.getQueryParser().parseCommand("select * from pm1.g1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testLOBTypes() throws Exception {
- 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$
- Query query = new Query();
- query.setSelect(select);
-
- helpTest("select convert(null, blob), convert(null, clob), convert(null, xml)", "SELECT convert(null, blob), convert(null, clob), convert(null, xml)", query); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testInsertWithoutColumns() {
- Insert insert = new Insert();
- insert.setGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- insert.addValue(new Constant("a")); //$NON-NLS-1$
- insert.addValue(new Constant("b")); //$NON-NLS-1$
- helpTest("INSERT INTO m.g VALUES ('a', 'b')", //$NON-NLS-1$
- "INSERT INTO m.g VALUES ('a', 'b')", //$NON-NLS-1$
- insert);
- }
-
- @Test public void testTypeAliases() {
- Create create = new Create();
- create.setTable(new GroupSymbol("tempTable")); //$NON-NLS-1$
- List columns = new ArrayList();
- ElementSymbol column = new ElementSymbol("c1");//$NON-NLS-1$
- column.setType(DataTypeManager.DefaultDataClasses.STRING);
- columns.add(column);
- column = new ElementSymbol("c2");//$NON-NLS-1$
- column.setType(DataTypeManager.DefaultDataClasses.BYTE);
- columns.add(column);
- column = new ElementSymbol("c3");//$NON-NLS-1$
- column.setType(DataTypeManager.DefaultDataClasses.SHORT);
- columns.add(column);
- column = new ElementSymbol("c4");//$NON-NLS-1$
- column.setType(DataTypeManager.DefaultDataClasses.FLOAT);
- columns.add(column);
- column = new ElementSymbol("c5");//$NON-NLS-1$
- column.setType(DataTypeManager.DefaultDataClasses.BIG_DECIMAL);
- columns.add(column);
- create.setElementSymbolsAsColumns(columns);
- helpTest("Create local TEMPORARY table tempTable (c1 varchar, c2 tinyint, c3 smallint, c4 real, c5 decimal)", "CREATE LOCAL TEMPORARY TABLE tempTable (c1 varchar, c2 tinyint, c3 smallint, c4 real, c5 decimal)", create); //$NON-NLS-1$
- }
-
- @Test public void testXmlElement() throws Exception {
- XMLElement f = new XMLElement("table", Arrays.asList((Expression)new Constant("x")));
- helpTestExpression("xmlelement(name \"table\", 'x')", "XMLELEMENT(NAME \"table\", 'x')", f);
- }
-
- @Test public void testXmlElement1() throws Exception {
- XMLElement f = new XMLElement("table", Arrays.asList((Expression)new Constant("x")));
- helpTestExpression("xmlelement(\"table\", 'x')", "XMLELEMENT(NAME \"table\", 'x')", f);
- }
-
- @Test public void testXmlElementWithAttributes() throws Exception {
- XMLElement f = new XMLElement("y", new ArrayList<Expression>());
- f.setAttributes(new XMLAttributes(Arrays.asList(new DerivedColumn("val", new Constant("a")))));
- helpTestExpression("xmlelement(y, xmlattributes('a' as val))", "XMLELEMENT(NAME y, XMLATTRIBUTES('a' AS val))", f);
- }
-
- @Test public void testXmlForest() throws Exception {
- XMLForest f = new XMLForest(Arrays.asList(new DerivedColumn("table", new ElementSymbol("a"))));
- helpTestExpression("xmlforest(a as \"table\")", "XMLFOREST(a AS \"table\")", f);
- }
-
- @Test public void testXmlPi() throws Exception {
- Function f = new Function("xmlpi", new Expression[] {new Constant("a"), new ElementSymbol("val")});
- helpTestExpression("xmlpi(NAME a, val)", "xmlpi(NAME a, val)", f);
- }
-
- @Test public void testXmlNamespaces() throws Exception {
- XMLForest f = new XMLForest(Arrays.asList(new DerivedColumn("table", new ElementSymbol("a"))));
- f.setNamespaces(new XMLNamespaces(Arrays.asList(new XMLNamespaces.NamespaceItem(), new XMLNamespaces.NamespaceItem("http://foo", "x"))));
- helpTestExpression("xmlforest(xmlnamespaces(no default, 'http://foo' as x), a as \"table\")", "XMLFOREST(XMLNAMESPACES(NO DEFAULT, 'http://foo' AS x), a AS \"table\")", f);
- }
-
- @Test public void testXmlAggWithOrderBy() throws Exception {
- String sql = "SELECT xmlAgg(1 order by e2)"; //$NON-NLS-1$
- AggregateSymbol as = new AggregateSymbol("foo", Reserved.XMLAGG, false, new Constant(1));
- as.setOrderBy(new OrderBy(Arrays.asList(new ElementSymbol("e2"))));
- Query query = new Query();
- query.setSelect(new Select(Arrays.asList(as)));
- helpTest(sql, "SELECT XMLAGG(1 ORDER BY e2)", query);
- }
-
- @Test public void testTextAggWithOrderBy() throws Exception {
- List<DerivedColumn> expressions = new ArrayList<DerivedColumn>();
- expressions.add(new DerivedColumn("col1", new ElementSymbol("e1")));
- expressions.add(new DerivedColumn("col2", new ElementSymbol("e2")));
-
- TextLine tf = new TextLine();
- tf.setExpressions(expressions);
- tf.setDelimiter(new Character(','));
- tf.setIncludeHeader(true);
-
- AggregateSymbol as = new AggregateSymbol("foo", NonReserved.TEXTAGG, false, tf);
- as.setOrderBy(new OrderBy(Arrays.asList(new ElementSymbol("e2"))));
-
- Query query = new Query();
- query.setSelect(new Select(Arrays.asList(as)));
-
- String sql = "SELECT TextAgg(FOR e1 as col1, e2 as col2 delimiter ',' header order by e2)"; //$NON-NLS-1$
- helpTest(sql, "SELECT TEXTAGG(FOR e1 AS col1, e2 AS col2 DELIMITER ',' HEADER ORDER BY e2)", query);
- }
-
- @Test public void testArrayAggWithOrderBy() throws Exception {
- String sql = "SELECT array_agg(1 order by e2)"; //$NON-NLS-1$
- AggregateSymbol as = new AggregateSymbol("foo", Reserved.ARRAY_AGG, false, new Constant(1));
- as.setOrderBy(new OrderBy(Arrays.asList(new ElementSymbol("e2"))));
- Query query = new Query();
- query.setSelect(new Select(Arrays.asList(as)));
- helpTest(sql, "SELECT ARRAY_AGG(1 ORDER BY e2)", query);
- }
-
- @Test public void testArrayAggWithIndexing() throws Exception {
- String sql = "SELECT (array_agg(1))[1]"; //$NON-NLS-1$
- AggregateSymbol as = new AggregateSymbol("foo", Reserved.ARRAY_AGG, false, new Constant(1));
- ExpressionSymbol expr = new ExpressionSymbol("expr", new Function("array_get", new Expression[] {as, new Constant(1)}));
- Query query = new Query();
- query.setSelect(new Select(Arrays.asList(expr)));
- helpTest(sql, "SELECT array_get(ARRAY_AGG(1), 1)", query);
- }
-
- @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())));
- StoredProcedure sp = new StoredProcedure();
- sp.setProcedureName("foo");
- SubqueryFromClause sfc = new SubqueryFromClause("x", sp);
- sfc.setTable(true);
- query.setFrom(new From(Arrays.asList(sfc)));
- helpTest(sql, "SELECT * FROM TABLE(EXEC foo()) AS x", query);
- }
-
- @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())));
- 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));
- tt.setColumns(columns);
- tt.setSkip(10);
- tt.setName("x");
- query.setFrom(new From(Arrays.asList(tt)));
- helpTest(sql, "SELECT * FROM TEXTTABLE(file COLUMNS x string WIDTH 1, y date WIDTH 10 SKIP 10) AS x", query);
-
- sql = "SELECT * from texttable(file columns x string, y date delimiter ',' escape '\"' header skip 10) as x"; //$NON-NLS-1$
- tt.setDelimiter(',');
- tt.setQuote('"');
- tt.setEscape(true);
- tt.setHeader(1);
- for (TextColumn textColumn : columns) {
- textColumn.setWidth(null);
- }
- helpTest(sql, "SELECT * FROM TEXTTABLE(file COLUMNS x string, y date DELIMITER ',' ESCAPE '\"' HEADER SKIP 10) AS x", query);
- }
-
- @Test public void testTextTableColumns() throws Exception {
- helpException("SELECT * from texttable(foo x string)", "Parsing error: Expected non-reserved word [COLUMNS], but was x.");
- }
-
- @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())));
- XMLTable xt = new XMLTable();
- xt.setName("x");
- xt.setNamespaces(new XMLNamespaces(Arrays.asList(new XMLNamespaces.NamespaceItem())));
- xt.setXquery("/");
- List<XMLTable.XMLColumn> columns = new ArrayList<XMLTable.XMLColumn>();
- columns.add(new XMLTable.XMLColumn("x"));
- columns.add(new XMLTable.XMLColumn("y", "date", "@date", new Constant(Date.valueOf("2000-01-01"))));
- xt.setColumns(columns);
- query.setFrom(new From(Arrays.asList(xt)));
- helpTest(sql, "SELECT * FROM XMLTABLE(XMLNAMESPACES(NO DEFAULT), '/' COLUMNS x FOR ORDINALITY, y date DEFAULT {d'2000-01-01'} PATH '@date') AS x", query);
- }
-
- @Test public void testXmlSerialize() throws Exception {
- XMLSerialize f = new XMLSerialize();
- f.setDocument(true);
- f.setExpression(new ElementSymbol("x"));
- f.setTypeString("CLOB");
- helpTestExpression("xmlserialize(document x as CLOB)", "XMLSERIALIZE(DOCUMENT x AS CLOB)", f);
- }
-
- @Test public void testXmlQuery() throws Exception {
- XMLQuery f = new XMLQuery();
- f.setXquery("/x");
- f.setEmptyOnEmpty(false);
- f.setPassing(Arrays.asList(new DerivedColumn(null, new ElementSymbol("foo"))));
- helpTestExpression("xmlquery('/x' passing foo null on empty)", "XMLQUERY('/x' PASSING foo NULL ON EMPTY)", f);
- }
-
- @Test public void testXmlParse() throws Exception {
- XMLParse f = new XMLParse();
- f.setDocument(true);
- f.setExpression(new ElementSymbol("x"));
- f.setWellFormed(true);
- helpTestExpression("xmlparse(document x wellformed)", "XMLPARSE(DOCUMENT x WELLFORMED)", f);
- }
-
- @Test public void testXmlSerialize1() throws Exception {
- XMLSerialize f = new XMLSerialize();
- f.setExpression(new ElementSymbol("x"));
- f.setTypeString("CLOB");
- helpTestExpression("xmlserialize(x as CLOB)", "XMLSERIALIZE(x AS CLOB)", f);
- }
-
- @Test public void testExpressionCriteria() throws Exception {
- SearchedCaseExpression sce = new SearchedCaseExpression(Arrays.asList(new ExpressionCriteria(new ElementSymbol("x"))), Arrays.asList(new ElementSymbol("y")));
- helpTestExpression("case when x then y end", "CASE WHEN x THEN y END", sce);
- }
-
- @Test public void testExpressionCriteria1() throws Exception {
- SearchedCaseExpression sce = new SearchedCaseExpression(Arrays.asList(new NotCriteria(new ExpressionCriteria(new ElementSymbol("x")))), Arrays.asList(new ElementSymbol("y")));
- helpTestExpression("case when not x then y end", "CASE WHEN NOT (x) THEN y END", sce);
- }
-
- @Test public void testWithClause() throws Exception {
- Query query = getOrderByQuery(null);
- query.setWith(Arrays.asList(new WithQueryCommand(new GroupSymbol("x"), null, getOrderByQuery(null))));
- helpTest("WITH x AS (SELECT a FROM db.g WHERE b = aString) SELECT a FROM db.g WHERE b = aString", "WITH x AS (SELECT a FROM db.g WHERE b = aString) SELECT a FROM db.g WHERE b = aString", query); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testExplicitTable() throws Exception {
- Query query = new Query();
- Select select = new Select();
- query.setSelect(select);
- select.addSymbol(new AllSymbol());
- From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("X"))));
- query.setFrom(from);
- helpTest("TABLE X", "SELECT * FROM X", query);
- }
-
- @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())));
- ArrayTable tt = new ArrayTable();
- tt.setArrayValue(new Constant(null, DataTypeManager.DefaultDataClasses.OBJECT));
- List<TableFunctionReference.ProjectedColumn> columns = new ArrayList<TableFunctionReference.ProjectedColumn>();
- columns.add(new TableFunctionReference.ProjectedColumn("x", "string"));
- columns.add(new TableFunctionReference.ProjectedColumn("y", "date"));
- tt.setColumns(columns);
- tt.setName("x");
- query.setFrom(new From(Arrays.asList(tt)));
- helpTest(sql, "SELECT * FROM ARRAYTABLE(null COLUMNS x string, y date) AS x", query);
- }
-
- @Test public void testPositionalReference() throws Exception {
- String sql = "select $1";
- Query query = new Query();
- query.setSelect(new Select(Arrays.asList(new ExpressionSymbol("foo", new Reference(0)))));
- helpTest(sql, "SELECT ?", query);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestParser.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/parser/TestParser.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestParser.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/parser/TestParser.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,6907 @@
+/*
+ * 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.junit.Assert.*;
+
+import java.io.StringReader;
+import java.io.UnsupportedEncodingException;
+import java.math.BigInteger;
+import java.sql.Date;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.api.exception.query.QueryParserException;
+import org.teiid.client.metadata.ParameterInfo;
+import org.teiid.core.TeiidException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.language.SQLConstants.NonReserved;
+import org.teiid.language.SQLConstants.Reserved;
+import org.teiid.language.SortSpecification.NullOrdering;
+import org.teiid.query.sql.lang.ArrayTable;
+import org.teiid.query.sql.lang.BetweenCriteria;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Create;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.Drop;
+import org.teiid.query.sql.lang.DynamicCommand;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.ExpressionCriteria;
+import org.teiid.query.sql.lang.From;
+import org.teiid.query.sql.lang.FromClause;
+import org.teiid.query.sql.lang.GroupBy;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.Into;
+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;
+import org.teiid.query.sql.lang.OrderByItem;
+import org.teiid.query.sql.lang.PredicateCriteria;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.SetClauseList;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.SubqueryCompareCriteria;
+import org.teiid.query.sql.lang.SubqueryFromClause;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.lang.TableFunctionReference;
+import org.teiid.query.sql.lang.TextTable;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.lang.WithQueryCommand;
+import org.teiid.query.sql.lang.XMLTable;
+import org.teiid.query.sql.lang.SetQuery.Operation;
+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.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;
+import org.teiid.query.sql.proc.HasCriteria;
+import org.teiid.query.sql.proc.IfStatement;
+import org.teiid.query.sql.proc.LoopStatement;
+import org.teiid.query.sql.proc.RaiseErrorStatement;
+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.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;
+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.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.XMLAttributes;
+import org.teiid.query.sql.symbol.XMLElement;
+import org.teiid.query.sql.symbol.XMLForest;
+import org.teiid.query.sql.symbol.XMLNamespaces;
+import org.teiid.query.sql.symbol.XMLParse;
+import org.teiid.query.sql.symbol.XMLQuery;
+import org.teiid.query.sql.symbol.XMLSerialize;
+
+ at SuppressWarnings("nls")
+public class TestParser {
+
+ static void helpTest(String sql, String expectedString, Command expectedCommand) {
+ helpTest(sql, expectedString, expectedCommand, new ParseInfo());
+ }
+ static void helpTest(String sql, String expectedString, Command expectedCommand, ParseInfo info) {
+ Command actualCommand = null;
+ String actualString = null;
+ try {
+ actualCommand = QueryParser.getQueryParser().parseCommand(sql, info);
+ actualString = actualCommand.toString();
+ } catch(Throwable e) {
+ throw new RuntimeException(e);
+ }
+
+ assertEquals("Parse string does not match: ", expectedString, actualString); //$NON-NLS-1$
+ assertEquals("Command objects do not match: ", expectedCommand, actualCommand); //$NON-NLS-1$
+ assertEquals("Cloned command objects do not match: ", expectedCommand, actualCommand.clone()); //$NON-NLS-1$
+ }
+
+ static void helpTestExpression(String sql, String expectedString, Expression expected) throws QueryParserException {
+ Expression actual = QueryParser.getQueryParser().parseExpression(sql);
+ String actualString = actual.toString();
+
+ assertEquals("Parse string does not match: ", expectedString, actualString); //$NON-NLS-1$
+ assertEquals("Command objects do not match: ", expected, actual); //$NON-NLS-1$
+ assertEquals("Cloned command objects do not match: ", expected, actual.clone()); //$NON-NLS-1$
+ }
+
+ static void helpException(String sql) {
+ helpException(sql, null);
+ }
+
+ static void helpException(String sql, String expected){
+ try {
+ QueryParser.getQueryParser().parseCommand(sql);
+ fail("Expected exception for parsing " + sql); //$NON-NLS-1$
+ } catch(TeiidException e) {
+ if (expected != null) {
+ assertEquals(expected, e.getMessage());
+ }
+ }
+ }
+
+ private void helpBlockTest(String block, String expectedString, Block expectedBlock) throws ParseException {
+ Block actualBlock = new SQLParser(new StringReader(block)).block(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$
+ }
+
+ private void helpCriteriaSelectorTest(String selector, String expectedString, CriteriaSelector expectedSelector) throws ParseException {
+ CriteriaSelector actualSelector = new SQLParser(new StringReader(selector)).criteriaSelector();
+ String actualString = actualSelector.toString();
+ assertEquals("Parse string does not match: ", expectedString, actualString); //$NON-NLS-1$
+ assertEquals("CriteriaSelector does not match: ", expectedSelector, actualSelector); //$NON-NLS-1$
+ }
+
+ private void helpCriteriaTest(String crit, String expectedString, Criteria expectedCrit) throws QueryParserException {
+ Criteria actualCrit = QueryParser.getQueryParser().parseCriteria(crit);
+ String actualString = actualCrit.toString();
+ assertEquals("Parse string does not match: ", expectedString, actualString); //$NON-NLS-1$
+ assertEquals("Criteria does not match: ", expectedCrit, actualCrit); //$NON-NLS-1$
+ }
+
+ private void helpStmtTest(String stmt, String expectedString, Statement expectedStmt) throws ParseException {
+ Statement actualStmt = new SQLParser(new StringReader(stmt)).statement(new ParseInfo());
+ String actualString = actualStmt.toString();
+ assertEquals("Parse string does not match: ", expectedString, actualString); //$NON-NLS-1$
+ assertEquals("Language objects do not match: ", expectedStmt, actualStmt); //$NON-NLS-1$
+ }
+
+ // ################################## ACTUAL TESTS ################################
+
+ // ======================== Joins ===============================================
+
+ /** SELECT * FROM g1 inner join g2 on g1.a1=g2.a2 */
+ @Test public void testInnerJoin() {
+ UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
+ UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
+ CompareCriteria jcrit = new CompareCriteria(
+ new ElementSymbol("g1.a1"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new ElementSymbol("g2.a2")); //$NON-NLS-1$
+ ArrayList<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(jcrit);
+ JoinPredicate jp = new JoinPredicate(g1, g2, JoinType.JOIN_INNER, crits);
+ From from = new From();
+ from.addClause(jp);
+
+ AllSymbol all = new AllSymbol();
+ Select select = new Select();
+ select.addSymbol(all);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT * FROM g1 inner join g2 on g1.a1=g2.a2", //$NON-NLS-1$
+ "SELECT * FROM g1 INNER JOIN g2 ON g1.a1 = g2.a2", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT * FROM g1 cross join g2 */
+ @Test public void testCrossJoin() {
+ UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
+ UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
+ JoinPredicate jp = new JoinPredicate(g1, g2, JoinType.JOIN_CROSS);
+ From from = new From();
+ from.addClause(jp);
+
+ AllSymbol all = new AllSymbol();
+ Select select = new Select();
+ select.addSymbol(all);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT * FROM g1 cross join g2", //$NON-NLS-1$
+ "SELECT * FROM g1 CROSS JOIN g2", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT * FROM (g1 cross join g2), g3 */
+ @Test public void testFromClauses() {
+ UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
+ UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
+ JoinPredicate jp = new JoinPredicate(g1, g2, JoinType.JOIN_CROSS);
+ From from = new From();
+ from.addClause(jp);
+ from.addClause(new UnaryFromClause(new GroupSymbol("g3"))); //$NON-NLS-1$
+
+ AllSymbol all = new AllSymbol();
+ Select select = new Select();
+ select.addSymbol(all);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT * FROM (g1 cross join g2), g3", //$NON-NLS-1$
+ "SELECT * FROM g1 CROSS JOIN g2, g3", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT * FROM g1 inner join g2 */
+ @Test public void testInvalidInnerJoin() {
+ helpException("SELECT * FROM g1 inner join g2"); //$NON-NLS-1$
+ }
+
+ /** SELECT * FROM (g1 cross join g2) cross join g3 */
+ @Test public void testMultiCrossJoin() {
+ UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
+ UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
+ JoinPredicate jp = new JoinPredicate(g1, g2, JoinType.JOIN_CROSS);
+ JoinPredicate jp2 = new JoinPredicate(jp, new UnaryFromClause(new GroupSymbol("g3")), JoinType.JOIN_CROSS); //$NON-NLS-1$
+ From from = new From();
+ from.addClause(jp2);
+
+ AllSymbol all = new AllSymbol();
+ Select select = new Select();
+ select.addSymbol(all);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT * FROM (g1 cross join g2) cross join g3", //$NON-NLS-1$
+ "SELECT * FROM (g1 CROSS JOIN g2) CROSS JOIN g3", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT * FROM (g1 cross join g2) cross join (g3 cross join g4) */
+ @Test public void testMultiCrossJoin2() {
+ UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
+ UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
+ JoinPredicate jp = new JoinPredicate(g1, g2, JoinType.JOIN_CROSS);
+ UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("g3")); //$NON-NLS-1$
+ UnaryFromClause g4 = new UnaryFromClause(new GroupSymbol("g4")); //$NON-NLS-1$
+ JoinPredicate jp2 = new JoinPredicate(g3, g4, JoinType.JOIN_CROSS);
+ JoinPredicate jp3 = new JoinPredicate(jp, jp2, JoinType.JOIN_CROSS);
+ From from = new From();
+ from.addClause(jp3);
+
+ AllSymbol all = new AllSymbol();
+ Select select = new Select();
+ select.addSymbol(all);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT * FROM (g1 cross join g2) cross join (g3 cross join g4)", //$NON-NLS-1$
+ "SELECT * FROM (g1 CROSS JOIN g2) CROSS JOIN (g3 CROSS JOIN g4)", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT * FROM g1 cross join (g2 cross join g3) */
+ @Test public void testMultiCrossJoin3() {
+ UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
+ UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
+ UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("g3")); //$NON-NLS-1$
+ JoinPredicate jp = new JoinPredicate(g2, g3, JoinType.JOIN_CROSS);
+ JoinPredicate jp2 = new JoinPredicate(g1, jp, JoinType.JOIN_CROSS);
+ From from = new From();
+ from.addClause(jp2);
+
+ AllSymbol all = new AllSymbol();
+ Select select = new Select();
+ select.addSymbol(all);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT * FROM g1 cross join (g2 cross join g3)", //$NON-NLS-1$
+ "SELECT * FROM g1 CROSS JOIN (g2 CROSS JOIN g3)", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT * FROM g1 cross join (g2 cross join g3), g4 */
+ @Test public void testMixedJoin() {
+ UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
+ UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
+ UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("g3")); //$NON-NLS-1$
+ JoinPredicate jp = new JoinPredicate(g2, g3, JoinType.JOIN_CROSS);
+ JoinPredicate jp2 = new JoinPredicate(g1, jp, JoinType.JOIN_CROSS);
+ From from = new From();
+ from.addClause(jp2);
+ from.addClause(new UnaryFromClause(new GroupSymbol("g4"))); //$NON-NLS-1$
+
+ AllSymbol all = new AllSymbol();
+ Select select = new Select();
+ select.addSymbol(all);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT * FROM g1 cross join (g2 cross join g3), g4", //$NON-NLS-1$
+ "SELECT * FROM g1 CROSS JOIN (g2 CROSS JOIN g3), g4", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT * FROM g1 cross join (g2 cross join g3), g4, g5 cross join g6 */
+ @Test public void testMixedJoin2() {
+ UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
+ UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
+ UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("g3")); //$NON-NLS-1$
+ UnaryFromClause g4 = new UnaryFromClause(new GroupSymbol("g4")); //$NON-NLS-1$
+ UnaryFromClause g5 = new UnaryFromClause(new GroupSymbol("g5")); //$NON-NLS-1$
+ UnaryFromClause g6 = new UnaryFromClause(new GroupSymbol("g6")); //$NON-NLS-1$
+ JoinPredicate jp = new JoinPredicate(g2, g3, JoinType.JOIN_CROSS);
+ JoinPredicate jp2 = new JoinPredicate(g1, jp, JoinType.JOIN_CROSS);
+ JoinPredicate jp3 = new JoinPredicate(g5, g6, JoinType.JOIN_CROSS);
+ From from = new From();
+ from.addClause(jp2);
+ from.addClause(g4);
+ from.addClause(jp3);
+
+ AllSymbol all = new AllSymbol();
+ Select select = new Select();
+ select.addSymbol(all);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT * FROM g1 cross join (g2 cross join g3), g4, g5 cross join g6", //$NON-NLS-1$
+ "SELECT * FROM g1 CROSS JOIN (g2 CROSS JOIN g3), g4, g5 CROSS JOIN g6", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT * FROM g1, g2 inner join g3 on g2.a=g3.a */
+ @Test public void testMixedJoin3() {
+ UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("g1")); //$NON-NLS-1$
+ UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("g2")); //$NON-NLS-1$
+ UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("g3")); //$NON-NLS-1$
+ CompareCriteria jcrit = new CompareCriteria(
+ new ElementSymbol("g2.a"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new ElementSymbol("g3.a")); //$NON-NLS-1$
+ ArrayList<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(jcrit);
+ JoinPredicate jp = new JoinPredicate(g2, g3, JoinType.JOIN_INNER, crits);
+ From from = new From();
+ from.addClause(g1);
+ from.addClause(jp);
+
+ AllSymbol all = new AllSymbol();
+ Select select = new Select();
+ select.addSymbol(all);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT * FROM g1, g2 inner join g3 on g2.a=g3.a", //$NON-NLS-1$
+ "SELECT * FROM g1, g2 INNER JOIN g3 ON g2.a = g3.a", //$NON-NLS-1$
+ query);
+ }
+
+ /** Select myG.a myA, myH.b from g myG right outer join h myH on myG.x=myH.x */
+ @Test public void testRightOuterJoinWithAliases() {
+ UnaryFromClause g = new UnaryFromClause(new GroupSymbol("myG", "g")); //$NON-NLS-1$ //$NON-NLS-2$
+ UnaryFromClause h = new UnaryFromClause(new GroupSymbol("myH", "h")); //$NON-NLS-1$ //$NON-NLS-2$
+ CompareCriteria jcrit = new CompareCriteria(
+ new ElementSymbol("myG.x"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new ElementSymbol("myH.x")); //$NON-NLS-1$
+ ArrayList<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(jcrit);
+ JoinPredicate jp = new JoinPredicate(g, h, JoinType.JOIN_RIGHT_OUTER, crits);
+ From from = new From();
+ from.addClause(jp);
+
+ AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("myG.a")); //$NON-NLS-1$ //$NON-NLS-2$
+ Select select = new Select();
+ select.addSymbol(as);
+ select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("Select myG.a myA, myH.b from g myG right outer join h myH on myG.x=myH.x", //$NON-NLS-1$
+ "SELECT myG.a AS myA, myH.b FROM g AS myG RIGHT OUTER JOIN h AS myH ON myG.x = myH.x", //$NON-NLS-1$
+ query);
+ }
+
+ /** Select myG.x myX, myH.y from g myG right join h myH on myG.x=myH.x */
+ @Test public void testRightJoinWithAliases() {
+ UnaryFromClause g = new UnaryFromClause(new GroupSymbol("myG", "g")); //$NON-NLS-1$ //$NON-NLS-2$
+ UnaryFromClause h = new UnaryFromClause(new GroupSymbol("myH", "h")); //$NON-NLS-1$ //$NON-NLS-2$
+ CompareCriteria jcrit = new CompareCriteria(
+ new ElementSymbol("myG.x"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new ElementSymbol("myH.x")); //$NON-NLS-1$
+ ArrayList<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(jcrit);
+ JoinPredicate jp = new JoinPredicate(g, h, JoinType.JOIN_RIGHT_OUTER, crits);
+ From from = new From();
+ from.addClause(jp);
+
+ AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("myG.a")); //$NON-NLS-1$ //$NON-NLS-2$
+ Select select = new Select();
+ select.addSymbol(as);
+ select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("Select myG.a myA, myH.b from g myG right join h myH on myG.x=myH.x", //$NON-NLS-1$
+ "SELECT myG.a AS myA, myH.b FROM g AS myG RIGHT OUTER JOIN h AS myH ON myG.x = myH.x", //$NON-NLS-1$
+ query);
+ }
+
+ /** Select myG.a myA, myH.b from g myG left outer join h myH on myG.x=myH.x */
+ @Test public void testLeftOuterJoinWithAliases() {
+ UnaryFromClause g = new UnaryFromClause(new GroupSymbol("myG", "g")); //$NON-NLS-1$ //$NON-NLS-2$
+ UnaryFromClause h = new UnaryFromClause(new GroupSymbol("myH", "h")); //$NON-NLS-1$ //$NON-NLS-2$
+ CompareCriteria jcrit = new CompareCriteria(
+ new ElementSymbol("myG.x"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new ElementSymbol("myH.x")); //$NON-NLS-1$
+ ArrayList<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(jcrit);
+ JoinPredicate jp = new JoinPredicate(g, h, JoinType.JOIN_LEFT_OUTER, crits);
+ From from = new From();
+ from.addClause(jp);
+
+ AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("myG.a")); //$NON-NLS-1$ //$NON-NLS-2$
+ Select select = new Select();
+ select.addSymbol(as);
+ select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("Select myG.a myA, myH.b from g myG left outer join h myH on myG.x=myH.x", //$NON-NLS-1$
+ "SELECT myG.a AS myA, myH.b FROM g AS myG LEFT OUTER JOIN h AS myH ON myG.x = myH.x", //$NON-NLS-1$
+ query);
+ }
+
+ /** Select myG.a myA, myH.b from g myG left join h myH on myG.x=myH.x */
+ @Test public void testLeftJoinWithAliases() {
+ UnaryFromClause g = new UnaryFromClause(new GroupSymbol("myG", "g")); //$NON-NLS-1$ //$NON-NLS-2$
+ UnaryFromClause h = new UnaryFromClause(new GroupSymbol("myH", "h")); //$NON-NLS-1$ //$NON-NLS-2$
+ CompareCriteria jcrit = new CompareCriteria(
+ new ElementSymbol("myG.x"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new ElementSymbol("myH.x")); //$NON-NLS-1$
+ ArrayList<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(jcrit);
+ JoinPredicate jp = new JoinPredicate(g, h, JoinType.JOIN_LEFT_OUTER, crits);
+ From from = new From();
+ from.addClause(jp);
+
+ AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("myG.a")); //$NON-NLS-1$ //$NON-NLS-2$
+ Select select = new Select();
+ select.addSymbol(as);
+ select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("Select myG.a myA, myH.b from g myG left join h myH on myG.x=myH.x", //$NON-NLS-1$
+ "SELECT myG.a AS myA, myH.b FROM g AS myG LEFT OUTER JOIN h AS myH ON myG.x = myH.x", //$NON-NLS-1$
+ query);
+ }
+
+ /** Select myG.a myA, myH.b from g myG full outer join h myH on myG.x=myH.x */
+ @Test public void testFullOuterJoinWithAliases() {
+ UnaryFromClause g = new UnaryFromClause(new GroupSymbol("myG", "g")); //$NON-NLS-1$ //$NON-NLS-2$
+ UnaryFromClause h = new UnaryFromClause(new GroupSymbol("myH", "h")); //$NON-NLS-1$ //$NON-NLS-2$
+ CompareCriteria jcrit = new CompareCriteria(
+ new ElementSymbol("myG.x"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new ElementSymbol("myH.x")); //$NON-NLS-1$
+ ArrayList<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(jcrit);
+ JoinPredicate jp = new JoinPredicate(g, h, JoinType.JOIN_FULL_OUTER, crits);
+ From from = new From();
+ from.addClause(jp);
+
+ AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("myG.a")); //$NON-NLS-1$ //$NON-NLS-2$
+ Select select = new Select();
+ select.addSymbol(as);
+ select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("Select myG.a myA, myH.b from g myG full outer join h myH on myG.x=myH.x", //$NON-NLS-1$
+ "SELECT myG.a AS myA, myH.b FROM g AS myG FULL OUTER JOIN h AS myH ON myG.x = myH.x", //$NON-NLS-1$
+ query);
+ }
+
+ /** Select g.a, h.b from g full join h on g.x=h.x */
+ @Test public void testFullJoin() {
+ UnaryFromClause g = new UnaryFromClause(new GroupSymbol("g")); //$NON-NLS-1$
+ UnaryFromClause h = new UnaryFromClause(new GroupSymbol("h")); //$NON-NLS-1$
+ CompareCriteria jcrit = new CompareCriteria(
+ new ElementSymbol("g.x"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new ElementSymbol("h.x")); //$NON-NLS-1$
+ ArrayList<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(jcrit);
+ JoinPredicate jp = new JoinPredicate(g, h, JoinType.JOIN_FULL_OUTER, crits);
+ From from = new From();
+ from.addClause(jp);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("g.a")); //$NON-NLS-1$
+ select.addSymbol(new ElementSymbol("h.b")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("Select g.a, h.b from g full join h on g.x=h.x", //$NON-NLS-1$
+ "SELECT g.a, h.b FROM g FULL OUTER JOIN h ON g.x = h.x", //$NON-NLS-1$
+ query);
+ }
+
+ // ======================= Convert ==============================================
+
+ /** SELECT CONVERT(a, string) FROM g */
+ @Test public void testConversionFunction() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("CONVERT", new Expression[] {new ElementSymbol("a", false), new Constant("string")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT CONVERT(a, string) FROM g", //$NON-NLS-1$
+ "SELECT CONVERT(a, string) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT CONVERT(CONVERT(a, timestamp), string) FROM g */
+ @Test public void testConversionFunction2() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("CONVERT", new Expression[] {new ElementSymbol("a", false), new Constant("timestamp")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Function f2 = new Function("CONVERT", new Expression[] {f, new Constant("string")}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT CONVERT(CONVERT(a, timestamp), string) FROM g", //$NON-NLS-1$
+ "SELECT CONVERT(CONVERT(a, timestamp), string) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ // ======================= Functions ==============================================
+
+ /** SELECT 5 + length(concat(a, 'x')) FROM g */
+ @Test public void testMultiFunction() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("concat", new Expression[] {new ElementSymbol("a", false), new Constant("x")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Function f2 = new Function("length", new Expression[] {f}); //$NON-NLS-1$
+ Function f3 = new Function("+", new Expression[] {new Constant(new Integer(5)), f2}); //$NON-NLS-1$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f3); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT 5 + length(concat(a, 'x')) FROM g", //$NON-NLS-1$
+ "SELECT (5 + length(concat(a, 'x'))) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT REPLACE(a, 'x', 'y') AS y FROM g */
+ @Test public void testAliasedFunction() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("replace", new Expression[] {new ElementSymbol("a", false), new Constant("x"), new Constant("y")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ ExpressionSymbol es = new ExpressionSymbol("y", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("y", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT REPLACE(a, 'x', 'y') AS y FROM g", //$NON-NLS-1$
+ "SELECT REPLACE(a, 'x', 'y') AS y FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT cast(a as string) FROM g */
+ @Test public void testCastFunction() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("cast", new Expression[] {new ElementSymbol("a", false), new Constant("string")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT cast(a as string) FROM g", //$NON-NLS-1$
+ "SELECT cast(a AS string) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT cast(cast(a as timestamp) as string) FROM g */
+ @Test public void testMultiCastFunction() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("cast", new Expression[] {new ElementSymbol("a", false), new Constant("timestamp")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Function f2 = new Function("cast", new Expression[] {f, new Constant("string")}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT cast(cast(a as timestamp) as string) FROM g", //$NON-NLS-1$
+ "SELECT cast(cast(a AS timestamp) AS string) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT left(fullname, 3) as x FROM sys.groups */
+ @Test public void testLeftFunction() {
+ GroupSymbol g = new GroupSymbol("sys.groups"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("left", new Expression[] {new ElementSymbol("fullname", false), new Constant(new Integer(3))}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT left(fullname, 3) as x FROM sys.groups", //$NON-NLS-1$
+ "SELECT left(fullname, 3) AS x FROM sys.groups", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT right(fullname, 3) as x FROM sys.groups */
+ @Test public void testRightFunction() {
+ GroupSymbol g = new GroupSymbol("sys.groups"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("right", new Expression[] {new ElementSymbol("fullname", false), new Constant(new Integer(3))}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT right(fullname, 3) as x FROM sys.groups", //$NON-NLS-1$
+ "SELECT right(fullname, 3) AS x FROM sys.groups", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT char('x') AS x FROM sys.groups */
+ @Test public void testCharFunction() {
+ GroupSymbol g = new GroupSymbol("sys.groups"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("char", new Expression[] { new Constant("x")}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT char('x') AS x FROM sys.groups", //$NON-NLS-1$
+ "SELECT char('x') AS x FROM sys.groups", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT insert('x', 1, 'a') as x FROM sys.groups */
+ @Test public void testInsertFunction() {
+ GroupSymbol g = new GroupSymbol("sys.groups"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("insert", new Expression[] { new Constant("x"), new Constant(new Integer(1)), new Constant("a")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT insert('x', 1, 'a') AS x FROM sys.groups", //$NON-NLS-1$
+ "SELECT insert('x', 1, 'a') AS x FROM sys.groups", //$NON-NLS-1$
+ query);
+ }
+
+
+
+ @Test public void testInsertIntoSelect() {
+ GroupSymbol g = new GroupSymbol("sys.groups"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Insert insert = new Insert();
+ GroupSymbol groupSymbol = new GroupSymbol( "tempA" ); //$NON-NLS-1$
+ insert.setGroup(groupSymbol);
+
+ Select select = new Select();
+// select.addSymbol( new ExpressionSymbol( new Constant( new Integer(1) ) ) );
+ select.addSymbol( new ExpressionSymbol( "exp", new Constant( new Integer(1) ) ) ); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+
+ insert.setQueryExpression( query );
+
+ helpTest("insert into tempA SELECT 1", //$NON-NLS-1$
+ "INSERT INTO tempA SELECT 1", //$NON-NLS-1$
+ insert);
+ }
+
+ /** SELECT translate('x', 'x', 'y') FROM sys.groups */
+ @Test public void testTranslateFunction() {
+ GroupSymbol g = new GroupSymbol("sys.groups"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("translate", new Expression[] { new Constant("x"), new Constant("x"), new Constant("y")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT translate('x', 'x', 'y') FROM sys.groups", //$NON-NLS-1$
+ "SELECT translate('x', 'x', 'y') FROM sys.groups", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT timestampadd(SQL_TSI_FRAC_SECOND, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
+ @Test public void testTimestampaddFunctionFracSecond() {
+ GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
+ new Constant("SQL_TSI_FRAC_SECOND"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT timestampadd(SQL_TSI_FRAC_SECOND, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ "SELECT timestampadd(SQL_TSI_FRAC_SECOND, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT timestampadd(SQL_TSI_SECOND, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
+ @Test public void testTimestampaddFunctionSecond() {
+ GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
+ new Constant("SQL_TSI_SECOND"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT timestampadd(SQL_TSI_SECOND, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ "SELECT timestampadd(SQL_TSI_SECOND, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT timestampadd(SQL_TSI_MINUTE, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
+ @Test public void testTimestampaddFunctionMinute() {
+ GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
+ new Constant("SQL_TSI_MINUTE"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT timestampadd(SQL_TSI_MINUTE, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ "SELECT timestampadd(SQL_TSI_MINUTE, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT timestampadd(SQL_TSI_HOUR, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
+ @Test public void testTimestampaddFunctionHour() {
+ GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
+ new Constant("SQL_TSI_HOUR"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT timestampadd(SQL_TSI_HOUR, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ "SELECT timestampadd(SQL_TSI_HOUR, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT timestampadd(SQL_TSI_DAY, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
+ @Test public void testTimestampaddFunctionDay() {
+ GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
+ new Constant("SQL_TSI_DAY"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT timestampadd(SQL_TSI_DAY, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ "SELECT timestampadd(SQL_TSI_DAY, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT timestampadd(SQL_TSI_WEEK, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
+ @Test public void testTimestampaddFunctionWeek() {
+ GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
+ new Constant("SQL_TSI_WEEK"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT timestampadd(SQL_TSI_WEEK, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ "SELECT timestampadd(SQL_TSI_WEEK, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT timestampadd(SQL_TSI_QUARTER, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
+ @Test public void testTimestampaddFunctionQuarter() {
+ GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
+ new Constant("SQL_TSI_QUARTER"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT timestampadd(SQL_TSI_QUARTER, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ "SELECT timestampadd(SQL_TSI_QUARTER, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT timestampadd(SQL_TSI_YEAR, 10, '2003-05-01 10:20:30') as x FROM my.group1 */
+ @Test public void testTimestampaddFunctionYear() {
+ GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("timestampadd", new Expression[] { //$NON-NLS-1$
+ new Constant("SQL_TSI_YEAR"), new Constant(new Integer(10)), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT timestampadd(SQL_TSI_YEAR, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ "SELECT timestampadd(SQL_TSI_YEAR, 10, '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT timestampdiff(SQL_TSI_FRAC_SECOND, '2003-05-01 10:20:10', '2003-05-01 10:20:30') as x FROM my.group1 */
+ @Test public void testTimestampdiffFunctionFracSecond() {
+ GroupSymbol g = new GroupSymbol("my.group1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("timestampdiff", new Expression[] { //$NON-NLS-1$
+ new Constant("SQL_TSI_FRAC_SECOND"), new Constant("2003-05-01 10:20:10"), new Constant("2003-05-01 10:20:30")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol as = new AliasSymbol("x", es); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT timestampdiff(SQL_TSI_FRAC_SECOND, '2003-05-01 10:20:10', '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ "SELECT timestampdiff(SQL_TSI_FRAC_SECOND, '2003-05-01 10:20:10', '2003-05-01 10:20:30') AS x FROM my.group1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 5 + 2 + 3 FROM g */
+ @Test public void testArithmeticOperatorPrecedence1() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("+", new Expression[] {new Constant(new Integer(5)), new Constant(new Integer(2))}); //$NON-NLS-1$
+ Function f2 = new Function("+", new Expression[] {f, new Constant(new Integer(3))}); //$NON-NLS-1$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT 5 + 2 + 3 FROM g", //$NON-NLS-1$
+ "SELECT ((5 + 2) + 3) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 5 + 2 - 3 FROM g */
+ @Test public void testArithmeticOperatorPrecedence2() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("+", new Expression[] {new Constant(new Integer(5)), new Constant(new Integer(2))}); //$NON-NLS-1$
+ Function f2 = new Function("-", new Expression[] {f, new Constant(new Integer(3))}); //$NON-NLS-1$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT 5 + 2 - 3 FROM g", //$NON-NLS-1$
+ "SELECT ((5 + 2) - 3) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 5 + 2 * 3 FROM g */
+ @Test public void testArithmeticOperatorPrecedence3() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("*", new Expression[] {new Constant(new Integer(2)), new Constant(new Integer(3))}); //$NON-NLS-1$
+ Function f2 = new Function("+", new Expression[] {new Constant(new Integer(5)), f}); //$NON-NLS-1$
+
+ ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT 5 + 2 * 3 FROM g", //$NON-NLS-1$
+ "SELECT (5 + (2 * 3)) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 5 * 2 + 3 FROM g */
+ @Test public void testArithmeticOperatorPrecedence4() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("*", new Expression[] {new Constant(new Integer(5)), new Constant(new Integer(2))}); //$NON-NLS-1$
+ Function f2 = new Function("+", new Expression[] {f, new Constant(new Integer(3))}); //$NON-NLS-1$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT 5 * 2 + 3 FROM g", //$NON-NLS-1$
+ "SELECT ((5 * 2) + 3) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 5 * 2 * 3 FROM g */
+ @Test public void testArithmeticOperatorPrecedence5() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("*", new Expression[] {new Constant(new Integer(5)), new Constant(new Integer(2))}); //$NON-NLS-1$
+ Function f2 = new Function("*", new Expression[] {f, new Constant(new Integer(3))}); //$NON-NLS-1$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT 5 * 2 * 3 FROM g", //$NON-NLS-1$
+ "SELECT ((5 * 2) * 3) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 1 + 2 * 3 + 4 * 5 FROM g */
+ @Test public void testArithmeticOperatorPrecedenceMixed1() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("*", new Expression[] {new Constant(new Integer(2)), new Constant(new Integer(3))}); //$NON-NLS-1$
+ Function f2 = new Function("*", new Expression[] {new Constant(new Integer(4)), new Constant(new Integer(5))}); //$NON-NLS-1$
+ Function f3 = new Function("+", new Expression[] {new Constant(new Integer(1)), f}); //$NON-NLS-1$
+ Function f4 = new Function("+", new Expression[] {f3, f2}); //$NON-NLS-1$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f4); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT 1 + 2 * 3 + 4 * 5 FROM g", //$NON-NLS-1$
+ "SELECT ((1 + (2 * 3)) + (4 * 5)) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 1 * 2 + 3 * 4 + 5 FROM g */
+ @Test public void testArithmeticOperatorPrecedenceMixed2() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("*", new Expression[] {new Constant(new Integer(1)), new Constant(new Integer(2))}); //$NON-NLS-1$
+ Function f2 = new Function("*", new Expression[] {new Constant(new Integer(3)), new Constant(new Integer(4))}); //$NON-NLS-1$
+ Function f3 = new Function("+", new Expression[] {f, f2}); //$NON-NLS-1$
+ Function f4 = new Function("+", new Expression[] {f3, new Constant(new Integer(5))}); //$NON-NLS-1$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f4); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT 1 * 2 + 3 * 4 + 5 FROM g", //$NON-NLS-1$
+ "SELECT (((1 * 2) + (3 * 4)) + 5) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 5 - 4 - 3 - 2 FROM g --> SELECT ((5 - 4) - 3) - 2 FROM g */
+ @Test public void testLeftAssociativeExpressions1() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("-", new Expression[] {new Constant(new Integer(5)), new Constant(new Integer(4))}); //$NON-NLS-1$
+ Function f2 = new Function("-", new Expression[] {f, new Constant(new Integer(3))}); //$NON-NLS-1$
+ Function f3 = new Function("-", new Expression[] {f2, new Constant(new Integer(2))}); //$NON-NLS-1$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f3); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT 5 - 4 - 3 - 2 FROM g", //$NON-NLS-1$
+ "SELECT (((5 - 4) - 3) - 2) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 5 / 4 / 3 / 2 FROM g --> SELECT ((5 / 4) / 3) / 2 FROM g */
+ @Test public void testLeftAssociativeExpressions2() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("/", new Expression[] {new Constant(new Integer(5)), new Constant(new Integer(4))}); //$NON-NLS-1$
+ Function f2 = new Function("/", new Expression[] {f, new Constant(new Integer(3))}); //$NON-NLS-1$
+ Function f3 = new Function("/", new Expression[] {f2, new Constant(new Integer(2))}); //$NON-NLS-1$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f3); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT 5 / 4 / 3 / 2 FROM g", //$NON-NLS-1$
+ "SELECT (((5 / 4) / 3) / 2) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 'a' || 'b' || 'c' FROM g */
+ @Test public void testConcatOperator1() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("||", new Expression[] {new Constant("a"), new Constant("b")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Function f2 = new Function("||", new Expression[] {f, new Constant("c")}); //$NON-NLS-1$ //$NON-NLS-2$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f2); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT 'a' || 'b' || 'c' FROM g", //$NON-NLS-1$
+ "SELECT (('a' || 'b') || 'c') FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 2 + 3 || 5 + 1 * 2 FROM g */
+ @Test public void testMixedOperators1() {
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Function f = new Function("*", new Expression[] {new Constant(new Integer(1)), new Constant(new Integer(2))}); //$NON-NLS-1$
+ Function f2 = new Function("+", new Expression[] {new Constant(new Integer(5)), f}); //$NON-NLS-1$
+ Function f3 = new Function("+", new Expression[] {new Constant(new Integer(2)), new Constant(new Integer(3))}); //$NON-NLS-1$
+ Function f4 = new Function("||", new Expression[] {f3, f2}); //$NON-NLS-1$
+ ExpressionSymbol es = new ExpressionSymbol("expr", f4); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(es);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT 2 + 3 || 5 + 1 * 2 FROM g", //$NON-NLS-1$
+ "SELECT ((2 + 3) || (5 + (1 * 2))) FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ // ======================= Group By ==============================================
+
+ /** SELECT a FROM m.g GROUP BY b, c */
+ @Test public void testGroupBy() {
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("a", false)); //$NON-NLS-1$
+
+ GroupBy groupBy = new GroupBy();
+ groupBy.addSymbol(new ElementSymbol("b", false)); //$NON-NLS-1$
+ groupBy.addSymbol(new ElementSymbol("c", false)); //$NON-NLS-1$
+
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setGroupBy(groupBy);
+ helpTest("SELECT a FROM m.g GROUP BY b, c", //$NON-NLS-1$
+ "SELECT a FROM m.g GROUP BY b, c", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a FROM m.g GROUP BY b, c HAVING b=5*/
+ @Test public void testGroupByHaving() {
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("a", false)); //$NON-NLS-1$
+
+ GroupBy groupBy = new GroupBy();
+ groupBy.addSymbol(new ElementSymbol("b", false)); //$NON-NLS-1$
+ groupBy.addSymbol(new ElementSymbol("c", false)); //$NON-NLS-1$
+
+ CompareCriteria having = new CompareCriteria(new ElementSymbol("b", false), CompareCriteria.EQ, new Constant(new Integer(5))); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setGroupBy(groupBy);
+ query.setHaving(having);
+ helpTest("SELECT a FROM m.g GROUP BY b, c HAVING b=5", //$NON-NLS-1$
+ "SELECT a FROM m.g GROUP BY b, c HAVING b = 5", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT COUNT(a) AS c FROM m.g */
+ @Test public void testAggregateFunction() {
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new AliasSymbol("c", //$NON-NLS-1$
+ new AggregateSymbol("c", "COUNT", false, new ElementSymbol("a", false)))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT COUNT(a) AS c FROM m.g", //$NON-NLS-1$
+ "SELECT COUNT(a) AS c FROM m.g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT (COUNT(a)) AS c FROM m.g - this kind of query is generated by ODBC sometimes */
+ @Test public void testAggregateFunctionWithParens() {
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new AliasSymbol("c", //$NON-NLS-1$
+ new AggregateSymbol("c", "COUNT", false, new ElementSymbol("a", false)))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT (COUNT(a)) AS c FROM m.g", //$NON-NLS-1$
+ "SELECT COUNT(a) AS c FROM m.g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a FROM m.g GROUP BY a HAVING COUNT(b) > 0*/
+ @Test public void testHavingFunction() {
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+
+ GroupBy groupBy = new GroupBy();
+ groupBy.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+
+ Criteria having = new CompareCriteria(
+ new AggregateSymbol("count", "COUNT", false, new ElementSymbol("b", false)), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ CompareCriteria.GT,
+ new Constant(new Integer(0)) );
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setGroupBy(groupBy);
+ query.setHaving(having);
+
+ helpTest("SELECT a FROM m.g GROUP BY a HAVING COUNT(b) > 0", //$NON-NLS-1$
+ "SELECT a FROM m.g GROUP BY a HAVING COUNT(b) > 0", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a FROM m.g GROUP BY a, b HAVING COUNT(b) > 0 AND b+5 > 0 */
+ @Test public void testCompoundHaving() {
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+
+ GroupBy groupBy = new GroupBy();
+ groupBy.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+ groupBy.addSymbol(new ElementSymbol("b")); //$NON-NLS-1$
+
+ CompoundCriteria having = new CompoundCriteria();
+ having.setOperator(CompoundCriteria.AND);
+ having.addCriteria(new CompareCriteria(
+ new AggregateSymbol("count", "COUNT", false, new ElementSymbol("b", false)), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ CompareCriteria.GT,
+ new Constant(new Integer(0)) ));
+ having.addCriteria(new CompareCriteria(
+ new Function("+", new Expression[] { new ElementSymbol("b", false), new Constant(new Integer(5)) }), //$NON-NLS-1$ //$NON-NLS-2$
+ CompareCriteria.GT,
+ new Constant(new Integer(0)) ));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setGroupBy(groupBy);
+ query.setHaving(having);
+
+ helpTest("SELECT a FROM m.g GROUP BY a, b HAVING COUNT(b) > 0 AND b+5 > 0", //$NON-NLS-1$
+ "SELECT a FROM m.g GROUP BY a, b HAVING (COUNT(b) > 0) AND ((b + 5) > 0)", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a FROM m.g GROUP BY a, b HAVING COUNT(AVG(b)) */
+ @Test public void testFailNestedAggregateInHaving() {
+ helpException("SELECT a FROM m.g GROUP BY a, b HAVING COUNT(b) AS x = 5"); //$NON-NLS-1$
+ }
+
+ /** SELECT a FROM m.g GROUP BY a, b AS x */
+ @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() {
+ 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$
+ //}
+ }
+ }
+
+
+
+ @Test public void testFunctionOfAggregates() {
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ AggregateSymbol agg1 = new AggregateSymbol("count", "COUNT", false, new ElementSymbol("a", false)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ AggregateSymbol agg2 = new AggregateSymbol("sum", "SUM", false, new ElementSymbol("a", false)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Function f = new Function("*", new Expression[] { agg1, agg2 }); //$NON-NLS-1$
+ ExpressionSymbol expr = new ExpressionSymbol("expr", f); //$NON-NLS-1$
+ AliasSymbol alias = new AliasSymbol("c", expr); //$NON-NLS-1$
+ select.addSymbol(alias);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT COUNT(a) * SUM(a) AS c FROM m.g", //$NON-NLS-1$
+ "SELECT (COUNT(a) * SUM(a)) AS c FROM m.g", //$NON-NLS-1$
+ query);
+
+ }
+
+ /** SELECT 5-null, a.g1.c1 FROM a.g1 */
+ @Test public void testArithmeticNullFunction() {
+ GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol(
+ "expr", //$NON-NLS-1$
+ new Function("-", new Expression[] { new Constant(new Integer(5)), new Constant(null) }) ) ); //$NON-NLS-1$
+ select.addSymbol(new ElementSymbol("a.g1.c1")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT 5-null, a.g1.c1 FROM a.g1", //$NON-NLS-1$
+ "SELECT (5 - null), a.g1.c1 FROM a.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 'abc' FROM a.g1 */
+ @Test public void testStringLiteral() {
+ GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant("abc"))); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT 'abc' FROM a.g1", //$NON-NLS-1$
+ "SELECT 'abc' FROM a.g1", //$NON-NLS-1$
+ query);
+ }
+
+
+ /** SELECT 'O''Leary' FROM a.g1 */
+ @Test public void testStringLiteralEscapedTick() {
+ GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant("O'Leary"))); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT 'O''Leary' FROM a.g1", //$NON-NLS-1$
+ "SELECT 'O''Leary' FROM a.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT '''abc''' FROM a.g1 */
+ @Test public void testStringLiteralEscapedTick2() {
+ GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant("'abc'"))); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT '''abc''' FROM a.g1", //$NON-NLS-1$
+ "SELECT '''abc''' FROM a.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 'a''b''c' FROM a.g1 */
+ @Test public void testStringLiteralEscapedTick3() {
+ GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant("a'b'c"))); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT 'a''b''c' FROM a.g1", //$NON-NLS-1$
+ "SELECT 'a''b''c' FROM a.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT " "" " FROM a.g1 */
+ @Test public void testStringLiteralEscapedTick4() {
+ GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol(" \" ")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT \" \"\" \" FROM a.g1", //$NON-NLS-1$
+ "SELECT \" \"\" \" FROM a.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 123456789012 FROM a.g1 */
+ @Test public void testLongLiteral() {
+ GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant(new Long(123456789012L)))); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT 123456789012 FROM a.g1", //$NON-NLS-1$
+ "SELECT 123456789012 FROM a.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 1000000000000000000000000 FROM a.g1 */
+ @Test public void testBigIntegerLiteral() {
+ GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant(new BigInteger("1000000000000000000000000")))); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT 1000000000000000000000000 FROM a.g1", //$NON-NLS-1$
+ "SELECT 1000000000000000000000000 FROM a.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT 1.3e8 FROM a.g1 */
+ @Test public void testFloatWithE() {
+ GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant(new Double(1.3e8)))); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT 1.3e8 FROM a.g1", //$NON-NLS-1$
+ "SELECT 1.3E8 FROM a.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT -1.3e-6 FROM a.g1 */
+ @Test public void testFloatWithMinusE() {
+ GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant(new Double(-1.3e-6)))); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT -1.3e-6 FROM a.g1", //$NON-NLS-1$
+ "SELECT -1.3E-6 FROM a.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT -1.3e+8 FROM a.g1 */
+ @Test public void testFloatWithPlusE() {
+ GroupSymbol g = new GroupSymbol("a.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant(new Double(-1.3e+8)))); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT -1.3e+8 FROM a.g1", //$NON-NLS-1$
+ "SELECT -1.3E8 FROM a.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT {d'2002-10-02'} FROM m.g1 */
+ @Test public void testDateLiteral1() {
+ GroupSymbol g = new GroupSymbol("m.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant(java.sql.Date.valueOf("2002-10-02")))); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT {d'2002-10-02'} FROM m.g1", //$NON-NLS-1$
+ "SELECT {d'2002-10-02'} FROM m.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT {d'2002-9-1'} FROM m.g1 */
+ @Test public void testDateLiteral2() {
+ GroupSymbol g = new GroupSymbol("m.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant(java.sql.Date.valueOf("2002-09-01")))); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT {d'2002-09-01'} FROM m.g1", //$NON-NLS-1$
+ "SELECT {d'2002-09-01'} FROM m.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT {d'bad'} FROM m.g1 */
+ @Test public void testDateLiteralFail() {
+ helpException("SELECT {d'bad'} FROM m.g1"); //$NON-NLS-1$
+ }
+
+ /** SELECT {t '11:10:00' } FROM m.g1 */
+ @Test public void testTimeLiteral1() {
+ GroupSymbol g = new GroupSymbol("m.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant(java.sql.Time.valueOf("11:10:00")))); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT {t '11:10:00' } FROM m.g1", //$NON-NLS-1$
+ "SELECT {t'11:10:00'} FROM m.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT {t '5:10:00'} FROM m.g1 */
+ @Test public void testTimeLiteral2() {
+ GroupSymbol g = new GroupSymbol("m.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant(java.sql.Time.valueOf("5:10:00")))); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT {t '05:10:00'} FROM m.g1", //$NON-NLS-1$
+ "SELECT {t'05:10:00'} FROM m.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT {t 'xyz'} FROM m.g1 */
+ @Test public void testTimeLiteralFail() {
+ helpException("SELECT {t 'xyz'} FROM m.g1"); //$NON-NLS-1$
+ }
+
+ /** SELECT {ts'2002-10-02 19:00:02.50'} FROM m.g1 */
+ @Test public void testTimestampLiteral() {
+ GroupSymbol g = new GroupSymbol("m.g1"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant(java.sql.Timestamp.valueOf("2002-10-02 19:00:02.50")))); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT {ts'2002-10-02 19:00:02.50'} FROM m.g1", //$NON-NLS-1$
+ "SELECT {ts'2002-10-02 19:00:02.5'} FROM m.g1", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT {b'true'} FROM m.g1 */
+ @Test public void testBooleanLiteralTrue() {
+ Boolean expected = Boolean.TRUE;
+ Class<?> expectedType = DataTypeManager.DefaultDataClasses.BOOLEAN;
+ String sql = "SELECT {b'true'}"; //$NON-NLS-1$
+ String expectedSql = "SELECT TRUE"; //$NON-NLS-1$
+
+ helpTestLiteral(expected, expectedType, sql, expectedSql);
+ }
+
+ private void helpTestLiteral(Boolean expected, Class<?> expectedType,
+ String sql, String expectedSql) {
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant(expected, expectedType))); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+
+ helpTest(sql,
+ expectedSql,
+ query);
+ }
+ /** SELECT TRUE FROM m.g1 */
+ @Test public void testBooleanLiteralTrue2() {
+ Boolean expected = Boolean.TRUE;
+ Class<?> expectedType = DataTypeManager.DefaultDataClasses.BOOLEAN;
+ String sql = "SELECT TRUE"; //$NON-NLS-1$
+ String expectedSql = "SELECT TRUE"; //$NON-NLS-1$
+
+ helpTestLiteral(expected, expectedType, sql, expectedSql);
+ }
+
+ /** SELECT {b'false'} FROM m.g1 */
+ @Test public void testBooleanLiteralFalse() {
+ Boolean expected = Boolean.FALSE;
+ Class<?> expectedType = DataTypeManager.DefaultDataClasses.BOOLEAN;
+ String sql = "SELECT {b'false'}"; //$NON-NLS-1$
+ String expectedSql = "SELECT FALSE"; //$NON-NLS-1$
+
+ helpTestLiteral(expected, expectedType, sql, expectedSql);
+ }
+
+ /** SELECT FALSE FROM m.g1 */
+ @Test public void testBooleanLiteralFalse2() {
+ Boolean expected = Boolean.FALSE;
+ Class<?> expectedType = DataTypeManager.DefaultDataClasses.BOOLEAN;
+ String sql = "SELECT {b'false'}"; //$NON-NLS-1$
+ String expectedSql = "SELECT FALSE"; //$NON-NLS-1$
+
+ helpTestLiteral(expected, expectedType, sql, expectedSql);
+ }
+
+ @Test public void testBooleanLiteralUnknown() {
+ Boolean expected = null;
+ Class<?> expectedType = DataTypeManager.DefaultDataClasses.BOOLEAN;
+ String sql = "SELECT {b'unknown'}"; //$NON-NLS-1$
+ String expectedSql = "SELECT UNKNOWN"; //$NON-NLS-1$
+
+ helpTestLiteral(expected, expectedType, sql, expectedSql);
+ }
+
+ @Test public void testBooleanLiteralUnknown2() {
+ Boolean expected = null;
+ Class<?> expectedType = DataTypeManager.DefaultDataClasses.BOOLEAN;
+ String sql = "SELECT UNKNOWN"; //$NON-NLS-1$
+ String expectedSql = "SELECT UNKNOWN"; //$NON-NLS-1$
+
+ helpTestLiteral(expected, expectedType, sql, expectedSql);
+ }
+
+ /** SELECT DISTINCT a FROM g */
+ @Test public void testSelectDistinct(){
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+ select.setDistinct(true);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT DISTINCT a FROM g", //$NON-NLS-1$
+ "SELECT DISTINCT a FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT ALL a FROM g */
+ @Test public void testSelectAll(){
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+ select.setDistinct(false);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT ALL a FROM g", //$NON-NLS-1$
+ "SELECT a FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ //=========================Aliasing==============================================
+
+ /** SELECT a AS myA, b FROM g */
+ @Test public void testAliasInSelect(){
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("a")); //$NON-NLS-1$ //$NON-NLS-2$
+ Select select = new Select();
+ select.addSymbol(as);
+ select.addSymbol(new ElementSymbol("b")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT a AS myA, b FROM g", //$NON-NLS-1$
+ "SELECT a AS myA, b FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a myA, b FROM g, h */
+ @Test public void testAliasInSelect2(){
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ GroupSymbol h = new GroupSymbol("h"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+ from.addGroup(h);
+
+ AliasSymbol as = new AliasSymbol("myA", new ElementSymbol("a")); //$NON-NLS-1$ //$NON-NLS-2$
+ Select select = new Select();
+ select.addSymbol(as);
+ select.addSymbol(new ElementSymbol("b")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT a myA, b FROM g, h", //$NON-NLS-1$
+ "SELECT a AS myA, b FROM g, h", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT myG.a FROM g AS myG */
+ @Test public void testAliasInFrom(){
+ GroupSymbol g = new GroupSymbol("myG", "g"); //$NON-NLS-1$ //$NON-NLS-2$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("myG.a")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT myG.a FROM g AS myG", //$NON-NLS-1$
+ "SELECT myG.a FROM g AS myG", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT myG.*, myH.b FROM g AS myG, h AS myH */
+ @Test public void testAliasesInFrom(){
+ GroupSymbol g = new GroupSymbol("myG", "g"); //$NON-NLS-1$ //$NON-NLS-2$
+ GroupSymbol h = new GroupSymbol("myH", "h"); //$NON-NLS-1$ //$NON-NLS-2$
+ From from = new From();
+ from.addGroup(g);
+ from.addGroup(h);
+
+ Select select = new Select();
+ AllInGroupSymbol myG = new AllInGroupSymbol("myG.*"); //$NON-NLS-1$
+ select.addSymbol(myG);
+ select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT myG.*, myH.b FROM g AS myG, h AS myH", //$NON-NLS-1$
+ "SELECT myG.*, myH.b FROM g AS myG, h AS myH", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT myG.a, myH.b FROM g myG, h myH */
+ @Test public void testHiddenAliasesInFrom(){
+ GroupSymbol g = new GroupSymbol("myG", "g"); //$NON-NLS-1$ //$NON-NLS-2$
+ GroupSymbol h = new GroupSymbol("myH", "h"); //$NON-NLS-1$ //$NON-NLS-2$
+ From from = new From();
+ from.addGroup(g);
+ from.addGroup(h);
+
+ Select select = new Select();
+ AllInGroupSymbol myG = new AllInGroupSymbol("myG.*"); //$NON-NLS-1$
+ select.addSymbol(myG);
+ select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT myG.*, myH.b FROM g myG, h myH", //$NON-NLS-1$
+ "SELECT myG.*, myH.b FROM g AS myG, h AS myH", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a AS or FROM g */
+ @Test public void testAliasInSelectUsingKeywordFails(){
+ helpException("SELECT a AS or FROM g"); //$NON-NLS-1$
+ }
+
+ /** SELECT or.a FROM g AS or */
+ @Test public void testAliasInFromUsingKeywordFails(){
+ helpException("SELECT or.a FROM g AS or"); //$NON-NLS-1$
+ }
+
+ // ======================= Misc ==============================================
+
+ /** Select a From db.g Where a IS NULL */
+ @Test public void testIsNullCriteria1(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Criteria crit = new IsNullCriteria(a);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("Select a From db.g Where a IS NULL", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE a IS NULL", //$NON-NLS-1$
+ query);
+ }
+
+ /** Select a From db.g Where a IS NOT NULL */
+ @Test public void testIsNullCriteria2(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ IsNullCriteria crit = new IsNullCriteria(a);
+ crit.setNegated(true);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("Select a From db.g Where a IS NOT NULL", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE a IS NOT NULL", //$NON-NLS-1$
+ query);
+ }
+
+ /** Select a From db.g Where Not a IS NULL */
+ @Test public void testNotIsNullCriteria(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Criteria crit = new NotCriteria(new IsNullCriteria(a));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("Select a From db.g Where Not a IS NULL", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE NOT (a IS NULL)", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db.g where a <> "value" */
+ @Test public void testStringNotEqualDoubleTicks(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Expression ex = new ElementSymbol("value"); //$NON-NLS-1$
+ Criteria crit = new CompareCriteria(a, CompareCriteria.NE, ex);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a from db.g where a <> \"value\"", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE a <> \"value\"", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db.g where a != "value" */
+ @Test public void testNotEquals2(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Expression constant = new Constant("value"); //$NON-NLS-1$
+ Criteria crit = new CompareCriteria(a, CompareCriteria.NE, constant);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a from db.g where a != 'value'", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE a <> 'value'", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db."g" where a = 5 */
+ @Test public void testPartlyQuotedGroup(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Criteria crit = new CompareCriteria(a, CompareCriteria.EQ, new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a from db.\"g\" where a = 5", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE a = 5", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from "db"."g" where a = 5 */
+ @Test public void testFullyQuotedGroup(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Criteria crit = new CompareCriteria(a, CompareCriteria.EQ, new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a from \"db\".\"g\" where a = 5", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE a = 5", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT "db".g.a from db.g */
+ @Test public void testPartlyQuotedElement1(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("db.g.a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT \"db\".g.a from db.g", //$NON-NLS-1$
+ "SELECT db.g.a FROM db.g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT "db"."g".a from db.g */
+ @Test public void testPartlyQuotedElement2(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("db.g.a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT \"db\".\"g\".a from db.g", //$NON-NLS-1$
+ "SELECT db.g.a FROM db.g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT "db"."g"."a" from db.g */
+ @Test public void testPartlyQuotedElement3(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("db.g.a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT \"db\".\"g\".\"a\" from db.g", //$NON-NLS-1$
+ "SELECT db.g.a FROM db.g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT ""g"".""a" from db.g */
+ @Test public void testStringLiteralLikeQuotedElement(){
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("g\".\"a")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT \"g\"\".\"\"a\" from g", //$NON-NLS-1$
+ "SELECT \"g\"\"\".\"\"\"a\" FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT ""g"".""a" from db.g */
+ @Test public void testStringLiteralLikeQuotedElement1(){
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", new Constant("g\".\"a"))); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ ParseInfo info = new ParseInfo();
+ info.ansiQuotedIdentifiers = false;
+ helpTest("SELECT \"g\"\".\"\"a\" from g", //$NON-NLS-1$
+ "SELECT 'g\".\"a' FROM g", //$NON-NLS-1$
+ query, info);
+ }
+
+ /** SELECT g.x AS "select" FROM g */
+ @Test public void testQuotedAlias(){
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ AliasSymbol a = new AliasSymbol("select", new ElementSymbol("g.x")); //$NON-NLS-1$ //$NON-NLS-2$
+ select.addSymbol(a);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT g.x AS \"select\" FROM g", //$NON-NLS-1$
+ "SELECT g.x AS \"select\" FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT g.x AS year FROM g */
+ @Test public void testQuotedAlias2(){
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ AliasSymbol a = new AliasSymbol("year", new ElementSymbol("g.x")); //$NON-NLS-1$ //$NON-NLS-2$
+ select.addSymbol(a);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT g.x AS \"year\" FROM g", //$NON-NLS-1$
+ "SELECT g.x AS \"year\" FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testQuotedAlias3(){
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ AliasSymbol a = new AliasSymbol("some year", new ElementSymbol("g.x")); //$NON-NLS-1$ //$NON-NLS-2$
+ select.addSymbol(a);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT g.x AS \"some year\" FROM g", //$NON-NLS-1$
+ "SELECT g.x AS \"some year\" FROM g", //$NON-NLS-1$
+ query);
+ }
+
+
+ /** SELECT g."select" FROM g */
+ @Test public void testReservedWordElement1(){
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("g.select"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT g.\"select\" FROM g", //$NON-NLS-1$
+ "SELECT g.\"select\" FROM g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet.x FROM newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet */
+ @Test public void testReservedWordElement2() {
+ GroupSymbol g = new GroupSymbol("newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet.x"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet.x FROM newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet", //$NON-NLS-1$
+ "SELECT newModel5.ResultSetDocument.MappingClasses.\"from\".\"from\".Query1InputSet.x FROM newModel5.ResultSetDocument.MappingClasses.\"from\".\"from\".Query1InputSet", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT * FROM newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet */
+ @Test public void testReservedWordGroup1(){
+ GroupSymbol g = new GroupSymbol("newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT * FROM newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet", //$NON-NLS-1$
+ "SELECT * FROM newModel5.ResultSetDocument.MappingClasses.\"from\".\"from\".Query1InputSet", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT * FROM newModel5."ResultSetDocument.MappingClasses.from.from.Query1InputSet" */
+ @Test public void testReservedWordGroup2(){
+ GroupSymbol g = new GroupSymbol("newModel5.ResultSetDocument.MappingClasses.from.from.Query1InputSet"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT * FROM newModel5.\"ResultSetDocument.MappingClasses.from.from.Query1InputSet\"", //$NON-NLS-1$
+ "SELECT * FROM newModel5.ResultSetDocument.MappingClasses.\"from\".\"from\".Query1InputSet", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT * FROM model.doc WHERE ab.cd. at ef = 'abc' */
+ @Test public void testXMLCriteriaWithAttribute() {
+ GroupSymbol g = new GroupSymbol("model.doc"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ ElementSymbol elem = new ElementSymbol("ab.cd. at ef"); //$NON-NLS-1$
+ query.setCriteria(new CompareCriteria(elem, CompareCriteria.EQ, new Constant("abc"))); //$NON-NLS-1$
+
+ helpTest("SELECT * FROM model.doc WHERE ab.cd. at ef = 'abc'", //$NON-NLS-1$
+ "SELECT * FROM model.doc WHERE ab.cd. at ef = 'abc'", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db.g where a <> 'value' */
+ @Test public void testStringNotEqual(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Expression constant = new Constant("value"); //$NON-NLS-1$
+ Criteria crit = new CompareCriteria(a, CompareCriteria.NE, constant);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a from db.g where a <> 'value'", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE a <> 'value'", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db.g where a BETWEEN 1000 AND 2000 */
+ @Test public void testBetween1(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Expression constant1 = new Constant(new Integer(1000));
+ Expression constant2 = new Constant(new Integer(2000));
+ Criteria crit = new BetweenCriteria(a, constant1, constant2);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a from db.g where a BETWEEN 1000 AND 2000", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE a BETWEEN 1000 AND 2000", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db.g where a NOT BETWEEN 1000 AND 2000 */
+ @Test public void testBetween2(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Expression constant1 = new Constant(new Integer(1000));
+ Expression constant2 = new Constant(new Integer(2000));
+ BetweenCriteria crit = new BetweenCriteria(a, constant1, constant2);
+ crit.setNegated(true);
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a from db.g where a NOT BETWEEN 1000 AND 2000", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE a NOT BETWEEN 1000 AND 2000", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db.g where a < 1000 */
+ @Test public void testCompareLT(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Expression constant = new Constant(new Integer(1000));
+ Criteria crit = new CompareCriteria(a, CompareCriteria.LT, constant);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a from db.g where a < 1000", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE a < 1000", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db.g where a > 1000 */
+ @Test public void testCompareGT(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Expression constant = new Constant(new Integer(1000));
+ Criteria crit = new CompareCriteria(a, CompareCriteria.GT, constant);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a from db.g where a > 1000", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE a > 1000", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db.g where a <= 1000 */
+ @Test public void testCompareLE(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Expression constant = new Constant(new Integer(1000));
+ Criteria crit = new CompareCriteria(a, CompareCriteria.LE, constant);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a from db.g where a <= 1000", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE a <= 1000", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db.g where a >= 1000 */
+ @Test public void testCompareGE(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Expression constant = new Constant(new Integer(1000));
+ Criteria crit = new CompareCriteria(a, CompareCriteria.GE, constant);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a from db.g where a >= 1000", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE a >= 1000", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db.g where b = x and a = 1000 */
+ @Test public void testCompoundCompare1(){
+ helpTestCompoundCompare("SELECT a from db.g where b = x and a = 1000"); //$NON-NLS-1$
+ }
+
+ /** SELECT a from db.g where (b = x and a = 1000) */
+ @Test public void testCompoundCompare2(){
+ helpTestCompoundCompare("SELECT a from db.g where (b = x and a = 1000)"); //$NON-NLS-1$
+ }
+
+ /** SELECT a from db.g where ((b = x) and (a = 1000)) */
+ @Test public void testCompoundCompare3(){
+ helpTestCompoundCompare("SELECT a from db.g where ((b = x) and (a = 1000))"); //$NON-NLS-1$
+ }
+
+ /** SELECT a from db.g where (((b = x) and (a = 1000))) */
+ @Test public void testCompoundCompare4(){
+ helpTestCompoundCompare("SELECT a from db.g where (((b = x) and (a = 1000)))"); //$NON-NLS-1$
+ }
+
+ /** SELECT a FROM db.g WHERE (b = x) AND (a = 1000) */
+ private void helpTestCompoundCompare(String testSQL){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Criteria crit1 = new CompareCriteria(new ElementSymbol("b"), CompareCriteria.EQ, new ElementSymbol("x")); //$NON-NLS-1$ //$NON-NLS-2$
+ Expression constant = new Constant(new Integer(1000));
+ Criteria crit2 = new CompareCriteria(a, CompareCriteria.EQ, constant);
+ Criteria crit = new CompoundCriteria(CompoundCriteria.AND, crit1, crit2);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest(testSQL,
+ "SELECT a FROM db.g WHERE (b = x) AND (a = 1000)", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a FROM db.g WHERE b IN (1000,5000)*/
+ @Test public void testSetCriteria0(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+
+ Expression constant1 = new Constant(new Integer(1000));
+ Expression constant2 = new Constant(new Integer(5000));
+ Collection constants = new ArrayList(2);
+ constants.add(constant1);
+ constants.add(constant2);
+ Criteria crit = new SetCriteria(new ElementSymbol("b"), constants); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a FROM db.g WHERE b IN (1000,5000)", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b IN (1000, 5000)", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a FROM db.g WHERE b NOT IN (1000,5000)*/
+ @Test public void testSetCriteria1(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+
+ Expression constant1 = new Constant(new Integer(1000));
+ Expression constant2 = new Constant(new Integer(5000));
+ Collection constants = new ArrayList(2);
+ constants.add(constant1);
+ constants.add(constant2);
+ SetCriteria crit = new SetCriteria(new ElementSymbol("b"), constants); //$NON-NLS-1$
+ crit.setNegated(true);
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a FROM db.g WHERE b NOT IN (1000,5000)", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b NOT IN (1000, 5000)", //$NON-NLS-1$
+ query);
+ }
+
+ // ================================== order by ==================================
+
+ /** SELECT a FROM db.g WHERE b = aString order by c*/
+ @Test public void testOrderBy(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Criteria crit = new CompareCriteria(new ElementSymbol("b"), CompareCriteria.EQ, new ElementSymbol("aString")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ ArrayList elements = new ArrayList();
+ elements.add(new ElementSymbol("c")); //$NON-NLS-1$
+ OrderBy orderBy = new OrderBy(elements);
+
+ Query query = new Query(select, from, crit, orderBy, null);
+ helpTest("SELECT a FROM db.g WHERE b = aString ORDER BY c", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b = aString ORDER BY c", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a FROM db.g WHERE b = aString order by c desc*/
+ @Test public void testOrderByDesc(){
+ ArrayList elements = new ArrayList();
+ elements.add(new ElementSymbol("c")); //$NON-NLS-1$
+ ArrayList orderTypes = new ArrayList();
+ orderTypes.add(Boolean.FALSE);
+ OrderBy orderBy = new OrderBy(elements, orderTypes);
+
+ Query query = getOrderByQuery(orderBy);
+ helpTest("SELECT a FROM db.g WHERE b = aString ORDER BY c desc", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b = aString ORDER BY c DESC", //$NON-NLS-1$
+ query);
+ }
+ private Query getOrderByQuery(OrderBy orderBy) {
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Criteria crit = new CompareCriteria(new ElementSymbol("b"), CompareCriteria.EQ, new ElementSymbol("aString")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Query query = new Query(select, from, crit, orderBy, null);
+ return query;
+ }
+
+ /** SELECT a FROM db.g WHERE b = aString order by c,d*/
+ @Test public void testOrderBys(){
+ ArrayList elements = new ArrayList();
+ elements.add(new ElementSymbol("c")); //$NON-NLS-1$
+ elements.add(new ElementSymbol("d")); //$NON-NLS-1$
+ OrderBy orderBy = new OrderBy(elements);
+
+ Query query = getOrderByQuery(orderBy);
+ helpTest("SELECT a FROM db.g WHERE b = aString ORDER BY c,d", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b = aString ORDER BY c, d", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a FROM db.g WHERE b = aString order by c desc,d desc*/
+ @Test public void testOrderBysDesc(){
+ ArrayList elements = new ArrayList();
+ elements.add(new ElementSymbol("c")); //$NON-NLS-1$
+ elements.add(new ElementSymbol("d")); //$NON-NLS-1$
+ ArrayList orderTypes = new ArrayList();
+ orderTypes.add(Boolean.FALSE);
+ orderTypes.add(Boolean.FALSE);
+ OrderBy orderBy = new OrderBy(elements, orderTypes);
+
+ Query query = getOrderByQuery(orderBy);
+ helpTest("SELECT a FROM db.g WHERE b = aString ORDER BY c desc,d desc", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b = aString ORDER BY c DESC, d DESC", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a FROM db.g WHERE b = aString order by c desc,d*/
+ @Test public void testMixedOrderBys(){
+ ArrayList elements = new ArrayList();
+ elements.add(new ElementSymbol("c")); //$NON-NLS-1$
+ elements.add(new ElementSymbol("d")); //$NON-NLS-1$
+ ArrayList orderTypes = new ArrayList();
+ orderTypes.add(Boolean.FALSE);
+ orderTypes.add(Boolean.TRUE);
+ OrderBy orderBy = new OrderBy(elements, orderTypes);
+
+ Query query = getOrderByQuery(orderBy);
+ helpTest("SELECT a FROM db.g WHERE b = aString ORDER BY c desc,d", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b = aString ORDER BY c DESC, d", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testOrderByNullOrdering(){
+ OrderBy orderBy = new OrderBy();
+ OrderByItem item = new OrderByItem(new ElementSymbol("c"), true);
+ item.setNullOrdering(NullOrdering.FIRST);
+ orderBy.getOrderByItems().add(item);
+ item = new OrderByItem(new ElementSymbol("d"), false);
+ item.setNullOrdering(NullOrdering.LAST);
+ orderBy.getOrderByItems().add(item);
+
+ Query query = getOrderByQuery(orderBy);
+ helpTest("SELECT a FROM db.g WHERE b = aString ORDER BY c NULLS FIRST,d desc nulls last", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b = aString ORDER BY c NULLS FIRST, d DESC NULLS LAST", //$NON-NLS-1$
+ query);
+ }
+
+ // ================================== match ====================================
+
+ /** SELECT a FROM db.g WHERE b LIKE 'aString'*/
+ @Test public void testLike0(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Expression string1 = new Constant("aString"); //$NON-NLS-1$
+ Criteria crit = new MatchCriteria(new ElementSymbol("b"), string1); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a FROM db.g WHERE b LIKE 'aString'", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b LIKE 'aString'", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a FROM db.g WHERE b NOT LIKE 'aString'*/
+ @Test public void testLike1(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Expression string1 = new Constant("aString"); //$NON-NLS-1$
+ MatchCriteria crit = new MatchCriteria(new ElementSymbol("b"), string1); //$NON-NLS-1$
+ crit.setNegated(true);
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a FROM db.g WHERE b NOT LIKE 'aString'", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b NOT LIKE 'aString'", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db.g where b like '#String' escape '#'*/
+ @Test public void testLikeWithEscape(){
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Expression string1 = new Constant("#String"); //$NON-NLS-1$
+ Criteria crit = new MatchCriteria(new ElementSymbol("b"), string1, '#'); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a from db.g where b like '#String' escape '#'", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b LIKE '#String' ESCAPE '#'", //$NON-NLS-1$
+ query);
+ }
+
+ @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$
+ }
+
+ /** SELECT "date"."time" from db.g */
+ @Test public void testReservedWordsInElement() {
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("date.time"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT \"date\".\"time\" from db.g", //$NON-NLS-1$
+ "SELECT \"date\".\"time\" FROM db.g", //$NON-NLS-1$
+ query);
+
+ }
+
+ /** SELECT a */
+ @Test public void testNoFromClause(){
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ ExpressionSymbol b = new ExpressionSymbol("expr", new Constant(new Integer(5), Integer.class)); //$NON-NLS-1$
+ select.addSymbol(a);
+ select.addSymbol(b);
+ Query query = new Query();
+ query.setSelect(select);
+ helpTest("SELECT a, 5", "SELECT a, 5", query); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // ==================== misc queries that should fail ===========================
+
+ /** FROM g WHERE a = 'aString' */
+ @Test public void testFailsNoSelectClause(){
+ helpException("FROM g WHERE a = 'aString'"); //$NON-NLS-1$
+ }
+
+ /** SELECT a WHERE a = 'aString' */
+ @Test public void testFailsNoFromClause(){
+ helpException("SELECT a WHERE a = 'aString'"); //$NON-NLS-1$
+ }
+
+ /** SELECT xx.yy%.a from xx.yy */
+ @Test public void testFailsWildcardInSelect(){
+ helpException("SELECT xx.yy%.a from xx.yy"); //$NON-NLS-1$
+ }
+
+ /** SELECT a or b from g */
+ @Test public void testOrInSelect(){
+ Query query = new Query();
+ query.setSelect(new Select(Arrays.asList(new ExpressionSymbol("foo", new CompoundCriteria(CompoundCriteria.OR, Arrays.asList(new ExpressionCriteria(new ElementSymbol("a")), new ExpressionCriteria(new ElementSymbol("b"))))))));
+ helpTest("select a or b", "SELECT (a) OR (b)", query);
+ }
+
+ /** SELECT a FROM g WHERE a LIKE x*/
+ @Test public void testLikeWOConstant(){
+ GroupSymbol g = new GroupSymbol("g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ ElementSymbol x = new ElementSymbol("x"); //$NON-NLS-1$
+ Criteria crit = new MatchCriteria(a, x);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a FROM g WHERE a LIKE x", //$NON-NLS-1$
+ "SELECT a FROM g WHERE a LIKE x", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from g ORDER BY b DSC*/
+ @Test public void testFailsDSCMisspelled(){
+ helpException("SELECT a from g ORDER BY b DSC"); //$NON-NLS-1$
+ }
+
+ /** Test reusability of parser */
+ @Test public void testReusabilityOfParserObject() {
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("a", false)); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT a FROM m.g", //$NON-NLS-1$
+ "SELECT a FROM m.g", //$NON-NLS-1$
+ query);
+
+ helpTest("SELECT a FROM m.g", //$NON-NLS-1$
+ "SELECT a FROM m.g", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db.g where b LIKE ? */
+ @Test public void testParameter1() {
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ select.addSymbol(a);
+
+ Reference ref1 = new Reference(0);
+ Criteria crit = new MatchCriteria(new ElementSymbol("b"), ref1); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT a from db.g where b LIKE ?", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b LIKE ?", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a from db.g where b LIKE ? */
+ @Test public void testParameter2() {
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ Reference ref0 = new Reference(0);
+ ExpressionSymbol expr = new ExpressionSymbol("expr", ref0); //$NON-NLS-1$
+ select.addSymbol(expr);
+
+ Reference ref1 = new Reference(1);
+ Criteria crit = new MatchCriteria(new ElementSymbol("b"), ref1); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+ helpTest("SELECT ? from db.g where b LIKE ?", //$NON-NLS-1$
+ "SELECT ? FROM db.g WHERE b LIKE ?", //$NON-NLS-1$
+ query);
+ }
+
+ /** SELECT a, b FROM (SELECT c FROM m.g) AS y */
+ @Test public void testSubquery1() {
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol symbol = new ElementSymbol("c"); //$NON-NLS-1$
+ select.addSymbol(symbol);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ SubqueryFromClause sfc = new SubqueryFromClause("y", query); //$NON-NLS-1$
+ From from2 = new From();
+ from2.addClause(sfc);
+
+ Select select2 = new Select();
+ select2.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+ select2.addSymbol(new ElementSymbol("b")); //$NON-NLS-1$
+
+ Query query2 = new Query();
+ query2.setSelect(select2);
+ query2.setFrom(from2);
+
+ helpTest("SELECT a, b FROM (SELECT c FROM m.g) AS y", //$NON-NLS-1$
+ "SELECT a, b FROM (SELECT c FROM m.g) AS y", //$NON-NLS-1$
+ query2);
+ }
+
+ /** SELECT a, b FROM ((SELECT c FROM m.g)) AS y */
+ @Test public void testSubquery1a() {
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol symbol = new ElementSymbol("c"); //$NON-NLS-1$
+ select.addSymbol(symbol);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ SubqueryFromClause sfc = new SubqueryFromClause("y", query); //$NON-NLS-1$
+ From from2 = new From();
+ from2.addClause(sfc);
+
+ Select select2 = new Select();
+ select2.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+ select2.addSymbol(new ElementSymbol("b")); //$NON-NLS-1$
+
+ Query query2 = new Query();
+ query2.setSelect(select2);
+ query2.setFrom(from2);
+
+ helpTest("SELECT a, b FROM ((SELECT c FROM m.g)) AS y", //$NON-NLS-1$
+ "SELECT a, b FROM (SELECT c FROM m.g) AS y", //$NON-NLS-1$
+ query2);
+ }
+
+ /** SELECT a, b FROM m.g1 JOIN (SELECT c FROM m.g2) AS y ON m.g1.a = y.c */
+ @Test public void testSubquery2() {
+ GroupSymbol g = new GroupSymbol("m.g2"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol symbol = new ElementSymbol("c"); //$NON-NLS-1$
+ select.addSymbol(symbol);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ UnaryFromClause ufc = new UnaryFromClause(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ SubqueryFromClause sfc = new SubqueryFromClause("y", query); //$NON-NLS-1$
+ CompareCriteria join = new CompareCriteria(new ElementSymbol("m.g1.a"), CompareCriteria.EQ, new ElementSymbol("y.c")); //$NON-NLS-1$ //$NON-NLS-2$
+ List crits = new ArrayList();
+ crits.add(join);
+ JoinPredicate jp = new JoinPredicate(ufc, sfc, JoinType.JOIN_INNER, crits);
+ From from2 = new From();
+ from2.addClause(jp);
+
+ Select select2 = new Select();
+ select2.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+ select2.addSymbol(new ElementSymbol("b")); //$NON-NLS-1$
+
+ Query query2 = new Query();
+ query2.setSelect(select2);
+ query2.setFrom(from2);
+
+ helpTest("SELECT a, b FROM m.g1 JOIN (SELECT c FROM m.g2) AS y ON m.g1.a = y.c", //$NON-NLS-1$
+ "SELECT a, b FROM m.g1 INNER JOIN (SELECT c FROM m.g2) AS y ON m.g1.a = y.c", //$NON-NLS-1$
+ query2);
+ }
+
+ /** SELECT a, b FROM (SELECT c FROM m.g2) */
+ @Test public void testSubqueryInvalid() {
+ helpException("SELECT a, b FROM (SELECT c FROM m.g2)"); //$NON-NLS-1$
+ }
+
+ /** INSERT INTO m.g (a) VALUES (?) */
+ @Test public void testInsertWithReference() {
+ Insert insert = new Insert();
+ insert.setGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ List vars = new ArrayList();
+ vars.add(new ElementSymbol("a")); //$NON-NLS-1$
+ insert.setVariables(vars);
+ List values = new ArrayList();
+ values.add(new Reference(0));
+ insert.setValues(values);
+ helpTest("INSERT INTO m.g (a) VALUES (?)", //$NON-NLS-1$
+ "INSERT INTO m.g (a) VALUES (?)", //$NON-NLS-1$
+ insert);
+ }
+
+ @Test public void testStoredQueryWithNoParameter(){
+ StoredProcedure storedQuery = new StoredProcedure();
+ storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
+ helpTest("exec proc1()", "EXEC proc1()", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ helpTest("execute proc1()", "EXEC proc1()", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testStoredQueryWithNoParameter2(){
+ StoredProcedure storedQuery = new StoredProcedure();
+ storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
+
+ From from = new From();
+ SubqueryFromClause sfc = new SubqueryFromClause("x", storedQuery); //$NON-NLS-1$
+ from.addClause(sfc);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("x.a")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT X.A FROM (exec proc1()) AS X", "SELECT X.A FROM (EXEC proc1()) AS X", query); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testStoredQuery(){
+ StoredProcedure storedQuery = new StoredProcedure();
+ storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
+ SPParameter parameter = new SPParameter(1, new Constant("param1")); //$NON-NLS-1$
+ parameter.setParameterType(ParameterInfo.IN);
+ storedQuery.setParameter(parameter);
+ helpTest("Exec proc1('param1')", "EXEC proc1('param1')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ helpTest("execute proc1('param1')", "EXEC proc1('param1')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testStoredQuery2(){
+ StoredProcedure storedQuery = new StoredProcedure();
+ storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
+ SPParameter parameter = new SPParameter(1, new Constant("param1")); //$NON-NLS-1$
+ storedQuery.setParameter(parameter);
+ From from = new From();
+ SubqueryFromClause sfc = new SubqueryFromClause("x", storedQuery); //$NON-NLS-1$
+ from.addClause(sfc);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("x.a")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT X.A FROM (exec proc1('param1')) AS X", "SELECT X.A FROM (EXEC proc1('param1')) AS X", query); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testStoredQuery2SanityCheck(){
+ StoredProcedure storedQuery = new StoredProcedure();
+ storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
+ SPParameter parameter = new SPParameter(1, new Constant("param1")); //$NON-NLS-1$
+ storedQuery.setParameter(parameter);
+ From from = new From();
+ SubqueryFromClause sfc = new SubqueryFromClause("x", storedQuery); //$NON-NLS-1$
+ from.addClause(sfc);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("x.a")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("exec proc1('param1')", "EXEC proc1('param1')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Try nesting subquery in double parentheses - parsing fails. 'exec' is not handled as
+ * robustly as other types of commands that can appear in a from clause subquery.
+ */
+ public void testStoredQuerySubqueryMultipleParens(){
+ StoredProcedure storedQuery = new StoredProcedure();
+ storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
+ SPParameter parameter = new SPParameter(1, new Constant("param1")); //$NON-NLS-1$
+ storedQuery.setParameter(parameter);
+ From from = new From();
+ SubqueryFromClause sfc = new SubqueryFromClause("x", storedQuery); //$NON-NLS-1$
+ from.addClause(sfc);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("x.a")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ helpTest("SELECT X.A FROM ((exec proc1('param1'))) AS X", "SELECT X.A FROM (EXEC proc1('param1')) AS X", query); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testErrorStatement() throws Exception {
+ RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("Test only")); //$NON-NLS-1$
+
+ helpStmtTest("ERROR 'Test only';", "ERROR 'Test only';", //$NON-NLS-1$ //$NON-NLS-2$
+ errStmt);
+ }
+
+ @Test public void testIfStatement() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement ifStmt = new DeclareStatement(a, shortType);
+
+ ElementSymbol b = new ElementSymbol("b"); //$NON-NLS-1$
+ 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"); //$NON-NLS-1$
+ 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 BEGIN DECLARE short b; END", //$NON-NLS-1$
+ "IF(c = 5)"+"\n"+ "BEGIN"+"\n"+"DECLARE short a;"+"\n"+"END"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short b;"+"\n"+"END", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ 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$
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.IS_NULL);
+ critSelector.addElement(a);
+
+ helpCriteriaSelectorTest("IS NULL CRITERIA ON (a)", "IS NULL CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCriteriaSelector1() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.COMPARE_EQ);
+ critSelector.addElement(a);
+
+ helpCriteriaSelectorTest("= CRITERIA ON (a)", "= CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCriteriaSelector2() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.COMPARE_NE);
+ critSelector.addElement(a);
+
+ helpCriteriaSelectorTest("<> CRITERIA ON (a)", "<> CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCriteriaSelector3() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.COMPARE_LT);
+ critSelector.addElement(a);
+
+ helpCriteriaSelectorTest("< CRITERIA ON (a)", "< CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCriteriaSelector4() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.COMPARE_GT);
+ critSelector.addElement(a);
+
+ helpCriteriaSelectorTest("> CRITERIA ON (a)", "> CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCriteriaSelector5() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.COMPARE_GE);
+ critSelector.addElement(a);
+
+ helpCriteriaSelectorTest(">= CRITERIA ON (a)", ">= CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCriteriaSelector6() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.COMPARE_LE);
+ critSelector.addElement(a);
+
+ helpCriteriaSelectorTest("<= CRITERIA ON (a)", "<= CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCriteriaSelector7() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.LIKE);
+ critSelector.addElement(a);
+
+ helpCriteriaSelectorTest("LIKE CRITERIA ON (a)", "LIKE CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+
+ @Test public void testCriteriaSelector8() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.IN);
+ critSelector.addElement(a);
+
+ helpCriteriaSelectorTest("IN CRITERIA ON (a)", "IN CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCriteriaSelector9() throws Exception {
+ //ElementSymbol a = new ElementSymbol("a");
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ //critSelector.setSelectorType(CriteriaSelector.IS_NULL);
+ //critSelector.addElement(a);
+
+ helpCriteriaSelectorTest("CRITERIA", "CRITERIA", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCriteriaSelector10() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.BETWEEN);
+ critSelector.addElement(a);
+
+ helpCriteriaSelectorTest("BETWEEN CRITERIA ON (a)", "BETWEEN CRITERIA ON (a)", critSelector); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**HAS IS NULL CRITERIA ON (a)*/
+ @Test public void testHasIsNullCriteria() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.IS_NULL);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ helpCriteriaTest("HAS IS NULL CRITERIA ON (a)", "HAS IS NULL CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
+ hasSelector);
+ }
+
+ /**HAS LIKE CRITERIA ON (a)*/
+ @Test public void testHasLikeCriteria() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.LIKE);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ helpCriteriaTest("HAS LIKE CRITERIA ON (a)", "HAS LIKE CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
+ hasSelector);
+ }
+
+ @Test public void testHasEQCriteria() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.COMPARE_EQ);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ helpCriteriaTest("HAS = CRITERIA ON (a)", "HAS = CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
+ hasSelector);
+ }
+
+ @Test public void testHasNECriteria() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.COMPARE_NE);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ helpCriteriaTest("HAS <> CRITERIA ON (a)", "HAS <> CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
+ hasSelector);
+ }
+
+ /**HAS IN CRITERIA ON (a)*/
+ @Test public void testHasInCriteria() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.IN);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ helpCriteriaTest("HAS IN CRITERIA ON (a)", "HAS IN CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
+ hasSelector);
+ }
+
+ /**HAS COMPARE_LT CRITERIA ON (a)*/
+ @Test public void testHasLTCriteria() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.COMPARE_LT);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ helpCriteriaTest("HAS < CRITERIA ON (a)", "HAS < CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
+ hasSelector);
+ }
+
+ /**HAS COMPARE_LE CRITERIA ON (a)*/
+ @Test public void testHasLECriteria() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.COMPARE_LE);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ helpCriteriaTest("HAS <= CRITERIA ON (a)", "HAS <= CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
+ hasSelector);
+ }
+
+ /**HAS COMPARE_GT CRITERIA ON (a)*/
+ @Test public void testHasGTCriteria() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.COMPARE_GT);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ helpCriteriaTest("HAS > CRITERIA ON (a)", "HAS > CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
+ hasSelector);
+ }
+
+ /**HAS COMPARE_GE CRITERIA ON (a)*/
+ @Test public void testHasGECriteria() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.COMPARE_GE);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ helpCriteriaTest("HAS >= CRITERIA ON (a)", "HAS >= CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
+ hasSelector);
+ }
+
+ /**HAS BETWEEN CRITERIA ON (a)*/
+ @Test public void testHasBetweenCriteria() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.BETWEEN);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ helpCriteriaTest("HAS BETWEEN CRITERIA ON (a)", "HAS BETWEEN CRITERIA ON (a)", //$NON-NLS-1$ //$NON-NLS-2$
+ hasSelector);
+ }
+
+ @Test public void testTranslateCriteria() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ Criteria crit = new CompareCriteria(a, CompareCriteria.EQ,
+ new Constant(new Integer(5)));
+ List critList = new ArrayList();
+ critList.add(crit);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.IS_NULL);
+ critSelector.setElements(elements);
+
+ TranslateCriteria transCriteria = new TranslateCriteria(critSelector, critList);
+
+ helpCriteriaTest("TRANSLATE IS NULL CRITERIA ON (a) WITH (a = 5)", //$NON-NLS-1$
+ "TRANSLATE IS NULL CRITERIA ON (a) WITH (a = 5)", //$NON-NLS-1$
+ transCriteria);
+
+ //helpCriteriaTest("TRANSLATE IS NULL CRITERIA ON (a) USING transFuncEQ (a)",
+ //"TRANSLATE IS NULL CRITERIA ON (a) USING transFuncEQ (a)",
+ //transCriteria);
+
+ }
+
+ @Test public void testAssignStatement() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ Expression expr = new Constant("aString"); //$NON-NLS-1$
+
+ AssignmentStatement queryStmt = new AssignmentStatement(a, query);
+ AssignmentStatement exprStmt = new AssignmentStatement(a, expr);
+
+ helpStmtTest("a = SELECT a1 FROM g WHERE a2 = 5;", "a = (SELECT a1 FROM g WHERE a2 = 5);", //$NON-NLS-1$ //$NON-NLS-2$
+ queryStmt);
+
+ helpStmtTest("a = 'aString';", "a = 'aString';", exprStmt); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDeclareStatement() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ String type = new String("short"); //$NON-NLS-1$
+ DeclareStatement stmt = new DeclareStatement(a, type);
+
+ helpStmtTest("DECLARE short a;","DECLARE short a;", stmt); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDeclareStatementWithAssignment() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ String type = new String("short"); //$NON-NLS-1$
+ DeclareStatement stmt = new DeclareStatement(a, type, new Constant(null));
+
+ helpStmtTest("DECLARE short a = null;","DECLARE short a = null;", stmt); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDeclareStatementWithAssignment1() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ String type = new String("string"); //$NON-NLS-1$
+ DeclareStatement stmt = new DeclareStatement(a, type, new ScalarSubquery(sampleQuery()));
+
+ helpStmtTest("DECLARE string a = SELECT a1 FROM g WHERE a2 = 5;","DECLARE string a = (SELECT a1 FROM g WHERE a2 = 5);", stmt); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testStatement() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ String type = new String("short"); //$NON-NLS-1$
+ DeclareStatement declStmt = new DeclareStatement(a, type);
+ Statement stmt = declStmt;
+
+ helpStmtTest("DECLARE short a;", "DECLARE short a;", //$NON-NLS-1$ //$NON-NLS-2$
+ stmt);
+ }
+
+ @Test public void testBlock() throws Exception {
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ String type = new String("short"); //$NON-NLS-1$
+ DeclareStatement declStmt = new DeclareStatement(a, type);
+ Statement stmt = declStmt;
+ Block block = new Block(stmt);
+
+ helpBlockTest("BEGIN DECLARE short a; END", "BEGIN"+"\n"+"DECLARE short a;"+"\n"+"END", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ block);
+ }
+
+ @Test public void testCommandStatement() throws Exception {
+ Query query = sampleQuery();
+
+ Command sqlCmd = query;
+ CommandStatement cmdStmt = new CommandStatement(sqlCmd);
+
+ helpStmtTest("SELECT a1 FROM g WHERE a2 = 5;", "SELECT a1 FROM g WHERE a2 = 5;", //$NON-NLS-1$ //$NON-NLS-2$
+ cmdStmt);
+ }
+
+ /**
+ * @return
+ */
+ private Query sampleQuery() {
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+ return query;
+ }
+
+ @Test public void testDynamicCommandStatement() throws Exception {
+ List symbols = new ArrayList();
+
+ ElementSymbol a1 = new ElementSymbol("a1"); //$NON-NLS-1$
+ a1.setType(DataTypeManager.DefaultDataClasses.STRING);
+ symbols.add(a1);
+
+ DynamicCommand sqlCmd = new DynamicCommand();
+ Expression sql = new Constant("SELECT a1 FROM g WHERE a2 = 5"); //$NON-NLS-1$
+
+ sqlCmd.setSql(sql);
+ sqlCmd.setAsColumns(symbols);
+ sqlCmd.setAsClauseSet(true);
+
+ sqlCmd.setIntoGroup(new GroupSymbol("#g")); //$NON-NLS-1$
+
+ CommandStatement cmdStmt = new CommandStatement(sqlCmd);
+
+ helpStmtTest("exec string 'SELECT a1 FROM g WHERE a2 = 5' as a1 string into #g;", "EXECUTE 'SELECT a1 FROM g WHERE a2 = 5' AS a1 string INTO #g;", //$NON-NLS-1$ //$NON-NLS-2$
+ cmdStmt);
+ }
+
+ //sql is a variable, also uses the as, into, and update clauses
+ @Test public void testDynamicCommandStatement1() throws Exception {
+ List symbols = new ArrayList();
+
+ ElementSymbol a1 = new ElementSymbol("a1"); //$NON-NLS-1$
+ a1.setType(DataTypeManager.DefaultDataClasses.STRING);
+ symbols.add(a1);
+
+ ElementSymbol a2 = new ElementSymbol("a2"); //$NON-NLS-1$
+ a1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+ symbols.add(a2);
+
+ DynamicCommand sqlCmd = new DynamicCommand();
+ Expression sql = new ElementSymbol("z"); //$NON-NLS-1$
+
+ sqlCmd.setSql(sql);
+ sqlCmd.setAsColumns(symbols);
+ sqlCmd.setAsClauseSet(true);
+
+ sqlCmd.setIntoGroup(new GroupSymbol("#g")); //$NON-NLS-1$
+
+ sqlCmd.setUpdatingModelCount(1);
+
+ CommandStatement cmdStmt = new CommandStatement(sqlCmd);
+
+ helpStmtTest("execute string z as a1 string, a2 integer into #g update 1;", "EXECUTE z AS a1 string, a2 integer INTO #g UPDATE 1;", //$NON-NLS-1$ //$NON-NLS-2$
+ cmdStmt);
+ }
+
+ @Test public void testDynamicCommandStatementWithUsing() throws Exception {
+ SetClauseList using = new SetClauseList();
+
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ using.addClause(a, new ElementSymbol("b")); //$NON-NLS-1$
+
+ DynamicCommand sqlCmd = new DynamicCommand();
+ Expression sql = new ElementSymbol("z"); //$NON-NLS-1$
+
+ sqlCmd.setSql(sql);
+ sqlCmd.setUsing(using);
+
+ CommandStatement cmdStmt = new CommandStatement(sqlCmd);
+
+ helpStmtTest("execute immediate z using a=b;", "EXECUTE z USING a = b;", //$NON-NLS-1$ //$NON-NLS-2$
+ cmdStmt);
+ }
+
+ //as clause should use short names
+ @Test public void testDynamicCommandStatement2(){
+ helpException("create virtual procedure begin execute string z as variables.a1 string, a2 integer into #g; end"); //$NON-NLS-1$
+ }
+
+ //using clause should use short names
+ @Test public void testDynamicCommandStatement3(){
+ helpException("create virtual procedure begin execute string z as a1 string, a2 integer into #g using variables.x=variables.y; end", "Parsing error: Invalid simple identifier format: [variables.x]"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ //into clause requires as clause
+ @Test public void testDynamicCommandStatement4(){
+ helpException("create virtual procedure begin execute string z into #g using x=variables.y; end"); //$NON-NLS-1$
+ }
+
+ /** original test */
+ @Test public void testCreateUpdateProcedureCommand(){
+ helpTestCreateUpdateProcedureCommandCase3025("CREATE PROCEDURE\nBEGIN\nDECLARE short var1;"+ //$NON-NLS-1$
+ "IF(HAS IS NULL CRITERIA ON (a))\nBEGIN\nvar1 = (SELECT a1 FROM g WHERE a2 = 5);\nEND\n"+ //$NON-NLS-1$
+ "ELSE\nBEGIN\nDECLARE short var2;\nvar2 = (SELECT b1 FROM g WHERE a2 = 5);\nEND\n" + //$NON-NLS-1$
+ " END"); //$NON-NLS-1$
+
+ }
+
+ @Test public void testCreateUpdateProcedureCommandCase3025_1(){
+
+ helpTestCreateUpdateProcedureCommandCase3025("CREATE PROCEDURE\nBEGIN\nDECLARE short var1;"+ //$NON-NLS-1$
+ "IF(HAS IS NULL CRITERIA ON (a))\nBEGIN\nvar1 = (SELECT a1 FROM g WHERE a2 = 5);\nEND\n"+ //$NON-NLS-1$
+ "ELSE\nBEGIN\nDECLARE short var2;\nvar2 = (SELECT b1 FROM g WHERE a2 = 5);\nEND\n" + //$NON-NLS-1$
+ " END"); //$NON-NLS-1$
+
+ }
+
+ @Test public void testCreateUpdateProcedureCommandCase3025_2(){
+ helpTestCreateUpdateProcedureCommandCase3025("CREATE PROCEDURE\nBEGIN\nDECLARE short var1;"+ //$NON-NLS-1$
+ "IF(HAS IS NULL CRITERIA ON (a))\nBEGIN\nvar1 = ((SELECT a1 FROM g WHERE a2 = 5) );\nEND\n"+ //$NON-NLS-1$
+ "ELSE\nBEGIN\nDECLARE short var2;\nvar2 = (SELECT b1 FROM g WHERE a2 = 5);\nEND\n" + //$NON-NLS-1$
+ " END"); //$NON-NLS-1$
+ }
+
+ private void helpTestCreateUpdateProcedureCommandCase3025(String procedureString){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+ elseQuery.setCriteria(criteria);
+
+ Command elseQueryCmd = elseQuery;
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ //has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.IS_NULL);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
+
+ Block block = new Block();
+
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest(procedureString, "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "IF(HAS IS NULL CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+
+ }
+
+ /** test an expression in parentheses in an assignment statement */
+ @Test public void testCreateUpdateProcedureCommandCase3025_3(){
+
+ String procedureString = "CREATE PROCEDURE\nBEGIN\nDECLARE short var1;"+ //$NON-NLS-1$
+ "IF(HAS IS NULL CRITERIA ON (a))\nBEGIN\nvar1 = (concat('x', 'y') );\nEND\n"+ //$NON-NLS-1$
+ "ELSE\nBEGIN\nDECLARE short var2;\nvar2 = (SELECT b1 FROM g WHERE a2 = 5);\nEND\n" + //$NON-NLS-1$
+ " END"; //$NON-NLS-1$
+
+ helpTestCreateUpdateProcedureCommandCase3025_Expression(procedureString);
+ }
+
+ /** test an expression in parentheses in an assignment statement */
+ @Test public void testCreateUpdateProcedureCommandCase3025_4(){
+
+ String procedureString = "CREATE PROCEDURE\nBEGIN\nDECLARE short var1;"+ //$NON-NLS-1$
+ "IF(HAS IS NULL CRITERIA ON (a))\nBEGIN\nvar1 = ((concat('x', 'y') ));\nEND\n"+ //$NON-NLS-1$
+ "ELSE\nBEGIN\nDECLARE short var2;\nvar2 = (SELECT b1 FROM g WHERE a2 = 5);\nEND\n" + //$NON-NLS-1$
+ " END"; //$NON-NLS-1$
+
+ helpTestCreateUpdateProcedureCommandCase3025_Expression(procedureString);
+ }
+
+ /** test an expression without parentheses in an assignment statement */
+ @Test public void testCreateUpdateProcedureCommandCase3025_5(){
+
+ String procedureString = "CREATE PROCEDURE\nBEGIN\nDECLARE short var1;"+ //$NON-NLS-1$
+ "IF(HAS IS NULL CRITERIA ON (a))\nBEGIN\nvar1 = concat('x', 'y') ;\nEND\n"+ //$NON-NLS-1$
+ "ELSE\nBEGIN\nDECLARE short var2;\nvar2 = (SELECT b1 FROM g WHERE a2 = 5);\nEND\n" + //$NON-NLS-1$
+ " END"; //$NON-NLS-1$
+
+ helpTestCreateUpdateProcedureCommandCase3025_Expression(procedureString);
+ }
+
+
+ /** test an expression in parentheses in an assignment statement */
+ private void helpTestCreateUpdateProcedureCommandCase3025_Expression(String procedureString){
+ String expectedString = "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "IF(HAS IS NULL CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = concat('x', 'y');"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ Expression[] args = new Expression[] {new Constant("x"), new Constant("y")}; //$NON-NLS-1$ //$NON-NLS-2$
+ Function function = new Function("concat", args); //$NON-NLS-1$
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, function);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+ elseQuery.setCriteria(criteria);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ //has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.IS_NULL);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
+
+ Block block = new Block();
+
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest(procedureString, expectedString, cmd);
+ }
+
+ /**IF statement with has criteria */
+ @Test public void testCreateUpdateProcedureCommand1(){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+ elseQuery.setCriteria(criteria);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ //has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
+
+ Block block = new Block();
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
+ " IF(HAS CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
+ " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE a2 = 5; END" + //$NON-NLS-1$
+ " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "IF(HAS CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ @Test public void testCreateUpdateProcedureCommand0(){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+ elseQuery.setCriteria(criteria);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ //has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ //critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
+
+ Block block = new Block();
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
+ " IF(HAS CRITERIA) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
+ " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE a2 = 5; END" + //$NON-NLS-1$
+ " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "IF(HAS CRITERIA)"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ /**IF statement with has LIKE criteria */
+ @Test public void testCreateUpdateProcedureCommand2(){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+ elseQuery.setCriteria(criteria);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ //has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.LIKE);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
+
+ Block block = new Block();
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
+ " IF(HAS LIKE CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
+ " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE a2 = 5; END" + //$NON-NLS-1$
+ " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "IF(HAS LIKE CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ /**IF statement with has IN criteria */
+ @Test public void testCreateUpdateProcedureCommand3(){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+ elseQuery.setCriteria(criteria);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ //has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.IN);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
+
+ Block block = new Block();
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
+ " IF(HAS IN CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
+ " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE a2 = 5; END" + //$NON-NLS-1$
+ " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "IF(HAS IN CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ /**IF statement with has <> criteria */
+ @Test public void testCreateUpdateProcedureCommand4(){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+ elseQuery.setCriteria(criteria);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ //has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ critSelector.setSelectorType(CriteriaSelector.COMPARE_NE);
+ critSelector.setElements(elements);
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
+
+ Block block = new Block();
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
+ " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
+ " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE a2 = 5; END" + //$NON-NLS-1$
+ " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ /**Has criteria in WHERE clause*/
+ @Test public void testCreateUpdateProcedureCommand5(){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ //element for has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+
+ CriteriaSelector critSelector2 = new CriteriaSelector();
+ //critSelector2.setSelectorType(CriteriaSelector.COMPARE_NE);
+ critSelector2.setElements(elements);
+
+ HasCriteria hasSelector2 = new HasCriteria();
+ hasSelector2.setSelector(critSelector2);
+ //has criteria for else block
+ elseQuery.setCriteria(hasSelector2);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ CriteriaSelector critSelector1 = new CriteriaSelector();
+ critSelector1.setSelectorType(CriteriaSelector.COMPARE_NE);
+ critSelector1.setElements(elements);
+
+ HasCriteria hasSelector1 = new HasCriteria();
+ hasSelector1.setSelector(critSelector1);
+
+ IfStatement stmt = new IfStatement(hasSelector1, ifBlock, elseBlock);
+
+ Block block = new Block();
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
+ " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
+ " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE HAS CRITERIA ON (a); END" + //$NON-NLS-1$
+ " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE HAS CRITERIA ON (a));"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ /** Translate criteria (empty criteriaSelector in WHERE clause*/
+ @Test public void testCreateUpdateProcedureCommand7(){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ //element for has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+
+ Criteria crit = new CompareCriteria(a, CompareCriteria.EQ,
+ new Constant(new Integer(5)));
+ List critList = new ArrayList();
+ critList.add(crit);
+
+ CriteriaSelector critSelector2 = new CriteriaSelector();
+ //critSelector2.setSelectorType(CriteriaSelector.IS_NULL);
+ critSelector2.setElements(elements);
+
+ TranslateCriteria transCriteria = new TranslateCriteria(critSelector2, critList);
+ elseQuery.setCriteria(transCriteria);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ CriteriaSelector critSelector1 = new CriteriaSelector();
+ critSelector1.setSelectorType(CriteriaSelector.COMPARE_NE);
+ critSelector1.setElements(elements);
+
+ HasCriteria hasSelector1 = new HasCriteria();
+ hasSelector1.setSelector(critSelector1);
+
+ IfStatement stmt = new IfStatement(hasSelector1, ifBlock, elseBlock);
+
+ Block block = new Block();
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
+ " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
+ " ELSE BEGIN DECLARE short var2; var2 = (SELECT b1 FROM g WHERE TRANSLATE CRITERIA ON (a) WITH (a = 5)); END" + //$NON-NLS-1$
+ " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE TRANSLATE CRITERIA ON (a) WITH (a = 5));"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ /** Translate criteria (is null criteriaSelector in WHERE clause*/
+ @Test public void testCreateUpdateProcedureCommand9(){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ //element for has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+
+ Criteria crit = new CompareCriteria(a, CompareCriteria.EQ,
+ new Constant(new Integer(5)));
+ List critList = new ArrayList();
+ critList.add(crit);
+
+ CriteriaSelector critSelector2 = new CriteriaSelector();
+ critSelector2.setSelectorType(CriteriaSelector.IS_NULL);
+ critSelector2.setElements(elements);
+
+ TranslateCriteria transCriteria = new TranslateCriteria(critSelector2, critList);
+ elseQuery.setCriteria(transCriteria);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ CriteriaSelector critSelector1 = new CriteriaSelector();
+ critSelector1.setSelectorType(CriteriaSelector.COMPARE_NE);
+ critSelector1.setElements(elements);
+
+ HasCriteria hasSelector1 = new HasCriteria();
+ hasSelector1.setSelector(critSelector1);
+
+ IfStatement stmt = new IfStatement(hasSelector1, ifBlock, elseBlock);
+
+ Block block = new Block();
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
+ " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
+ " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE TRANSLATE IS NULL CRITERIA ON (a) WITH (a = 5); END" + //$NON-NLS-1$
+ " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE TRANSLATE IS NULL CRITERIA ON (a) WITH (a = 5));"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ /** Translate criteria ( only with WHERE clause) */
+ @Test public void testCreateUpdateProcedureCommand10(){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ //element for has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+
+ Criteria crit = new CompareCriteria(a, CompareCriteria.EQ,
+ new Constant(new Integer(5)));
+ List critList = new ArrayList();
+ critList.add(crit);
+
+ TranslateCriteria transCriteria = new TranslateCriteria();
+ CriteriaSelector critSelector2 = new CriteriaSelector();
+ transCriteria.setTranslations(critList);
+ transCriteria.setSelector(critSelector2);
+
+ elseQuery.setCriteria(transCriteria);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ CriteriaSelector critSelector1 = new CriteriaSelector();
+ critSelector1.setSelectorType(CriteriaSelector.COMPARE_NE);
+ critSelector1.setElements(elements);
+
+ HasCriteria hasSelector1 = new HasCriteria();
+ hasSelector1.setSelector(critSelector1);
+
+ IfStatement stmt = new IfStatement(hasSelector1, ifBlock, elseBlock);
+
+ Block block = new Block();
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
+ " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
+ " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE TRANSLATE CRITERIA WITH (a = 5); END" + //$NON-NLS-1$
+ " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE TRANSLATE CRITERIA WITH (a = 5));"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ /** Translate criteria ( only with WHERE clause) */
+ @Test public void testCreateUpdateProcedureCommand12(){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ //element for has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+
+
+ Criteria crit1 = new CompareCriteria(a, CompareCriteria.EQ,
+ new Constant(new Integer(5)));
+ ElementSymbol m = new ElementSymbol("m"); //$NON-NLS-1$
+ Criteria crit2= new CompareCriteria(m, CompareCriteria.EQ,
+ new Constant(new Integer(6)));
+ List critList = new ArrayList();
+ critList.add(crit1);
+ critList.add(crit2);
+
+ TranslateCriteria transCriteria = new TranslateCriteria();
+ CriteriaSelector critSelector2 = new CriteriaSelector();
+ transCriteria.setTranslations(critList);
+ transCriteria.setSelector(critSelector2);
+
+ elseQuery.setCriteria(transCriteria);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ CriteriaSelector critSelector1 = new CriteriaSelector();
+ critSelector1.setSelectorType(CriteriaSelector.COMPARE_NE);
+ critSelector1.setElements(elements);
+
+ HasCriteria hasSelector1 = new HasCriteria();
+ hasSelector1.setSelector(critSelector1);
+
+ IfStatement stmt = new IfStatement(hasSelector1, ifBlock, elseBlock);
+
+ Block block = new Block();
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
+ " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
+ " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE TRANSLATE CRITERIA WITH (a = 5, m = 6); END" + //$NON-NLS-1$
+ " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE TRANSLATE CRITERIA WITH (a = 5, m = 6));"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+
+ }
+
+ /** Translate criteria (with only Criteria in WHERE clause) */
+ @Test public void testCreateUpdateProcedureCommand11(){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ //element for has criteria
+ ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
+ List elements = new ArrayList();
+ elements.add(a);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+
+ Criteria crit = new CompareCriteria(a, CompareCriteria.EQ,
+ new Constant(new Integer(5)));
+ List critList = new ArrayList();
+ critList.add(crit);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+ TranslateCriteria transCrit = new TranslateCriteria();
+ transCrit.setSelector(critSelector);
+
+ elseQuery.setCriteria(transCrit);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ CriteriaSelector critSelector1 = new CriteriaSelector();
+ critSelector1.setSelectorType(CriteriaSelector.COMPARE_NE);
+ critSelector1.setElements(elements);
+
+ HasCriteria hasSelector1 = new HasCriteria();
+ hasSelector1.setSelector(critSelector1);
+
+ IfStatement stmt = new IfStatement(hasSelector1, ifBlock, elseBlock);
+
+ Block block = new Block();
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
+ " IF(HAS <> CRITERIA ON (a)) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
+ " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE TRANSLATE CRITERIA; END" + //$NON-NLS-1$
+ " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "IF(HAS <> CRITERIA ON (a))"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE TRANSLATE CRITERIA);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ /**IF statement with has criteria no on */
+ @Test public void testCreateUpdateProcedureCommand8(){
+ //declare var1
+ ElementSymbol var1 = new ElementSymbol("var1"); //$NON-NLS-1$
+ String shortType = new String("short"); //$NON-NLS-1$
+ Statement declStmt = new DeclareStatement(var1, shortType);
+
+ //ifblock
+ List symbols = new ArrayList();
+ symbols.add(new ElementSymbol("a1")); //$NON-NLS-1$
+ Select select = new Select(symbols);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+
+ AssignmentStatement queryStmt = new AssignmentStatement(var1, query);
+
+ Block ifBlock = new Block();
+ ifBlock.addStatement(queryStmt);
+
+ //else block
+ ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
+ Statement elseDeclStmt = new DeclareStatement(var2, shortType);
+
+ List elseSymbols = new ArrayList();
+ elseSymbols.add(new ElementSymbol("b1")); //$NON-NLS-1$
+ Select elseSelect = new Select(elseSymbols);
+
+ Query elseQuery = new Query();
+ elseQuery.setSelect(elseSelect);
+ elseQuery.setFrom(from);
+ elseQuery.setCriteria(criteria);
+
+ AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
+
+ Block elseBlock = new Block();
+ List elseStmts = new ArrayList();
+ elseStmts.add(elseDeclStmt);
+ elseStmts.add(elseQueryStmt);
+
+ elseBlock.setStatements(elseStmts);
+
+ CriteriaSelector critSelector = new CriteriaSelector();
+
+ HasCriteria hasSelector = new HasCriteria();
+ hasSelector.setSelector(critSelector);
+
+ IfStatement stmt = new IfStatement(hasSelector, ifBlock, elseBlock);
+
+ Block block = new Block();
+ block.addStatement(declStmt);
+ block.addStatement(stmt);
+
+ CreateUpdateProcedureCommand cmd = new CreateUpdateProcedureCommand();
+ cmd.setBlock(block);
+
+ helpTest("CREATE PROCEDURE BEGIN DECLARE short var1;"+ //$NON-NLS-1$
+ " IF(HAS CRITERIA) BEGIN var1 = SELECT a1 FROM g WHERE a2 = 5; END"+ //$NON-NLS-1$
+ " ELSE BEGIN DECLARE short var2; var2 = SELECT b1 FROM g WHERE a2 = 5; END" + //$NON-NLS-1$
+ " END", "CREATE PROCEDURE"+"\n"+"BEGIN"+"\n"+"DECLARE short var1;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "IF(HAS CRITERIA)"+"\n"+"BEGIN"+"\n"+ "var1 = (SELECT a1 FROM g WHERE a2 = 5);"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+ "END"+"\n"+"ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short var2;"+"\n"+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+ "var2 = (SELECT b1 FROM g WHERE a2 = 5);"+"\n"+"END"+"\n"+"END", cmd); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ @Test public void testSubquerySetCriteria0() {
+ //test wrap up command with subquerySetCriteria
+ Query outer = exampleIn(false);
+
+ helpTest("SELECT a FROM db.g WHERE b IN (SELECT a FROM db.g WHERE a2 = 5)", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b IN (SELECT a FROM db.g WHERE a2 = 5)", //$NON-NLS-1$
+ outer);
+ }
+
+ static Query exampleIn(boolean semiJoin) {
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+
+ Expression expr = new ElementSymbol("b"); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+ SubquerySetCriteria subCrit = new SubquerySetCriteria(expr, query);
+ subCrit.getSubqueryHint().setMergeJoin(semiJoin);
+ Query outer = new Query();
+ outer.setSelect(select);
+ outer.setFrom(from);
+ outer.setCriteria(subCrit);
+ return outer;
+ }
+
+ @Test public void testSubquerySetCriteria1() {
+
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+
+ Expression expr = new ElementSymbol("b"); //$NON-NLS-1$
+
+ Criteria criteria = new CompareCriteria(new ElementSymbol("a2"), CompareCriteria.EQ, //$NON-NLS-1$
+ new Constant(new Integer(5)));
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(criteria);
+ SubquerySetCriteria subCrit = new SubquerySetCriteria(expr, query);
+ subCrit.setNegated(true);
+ Query outer = new Query();
+ outer.setSelect(select);
+ outer.setFrom(from);
+ outer.setCriteria(subCrit);
+
+ helpTest("SELECT a FROM db.g WHERE b NOT IN (SELECT a FROM db.g WHERE a2 = 5)", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b NOT IN (SELECT a FROM db.g WHERE a2 = 5)", //$NON-NLS-1$
+ outer);
+ }
+
+ @Test public void testSubquerySetCriteriaWithExec() {
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+
+ Expression expr = new ElementSymbol("b"); //$NON-NLS-1$
+
+ 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);
+ SubquerySetCriteria subCrit = new SubquerySetCriteria(expr, query);
+
+ Query outer = new Query();
+ outer.setSelect(select);
+ outer.setFrom(from);
+ outer.setCriteria(subCrit);
+
+ helpTest("SELECT a FROM db.g WHERE b IN (EXEC m.sq1())", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b IN (SELECT * FROM (EXEC m.sq1()) AS x)", //$NON-NLS-1$
+ outer);
+ }
+
+ @Test public void testSubquerySetCriteriaWithUnion() {
+ GroupSymbol g = new GroupSymbol("db.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("a")); //$NON-NLS-1$
+
+ Expression expr = new ElementSymbol("b"); //$NON-NLS-1$
+
+ Query u1 = new Query();
+ Select u1s = new Select();
+ u1s.addSymbol(new ElementSymbol("x1")); //$NON-NLS-1$
+ u1.setSelect(u1s);
+ From u1f = new From();
+ u1f = new From();
+ u1f.addClause(new UnaryFromClause(new GroupSymbol("db.g2"))); //$NON-NLS-1$
+ u1.setFrom(u1f);
+
+ Query u2 = new Query();
+ Select u2s = new Select();
+ u2s.addSymbol(new ElementSymbol("x2")); //$NON-NLS-1$
+ u2.setSelect(u2s);
+ From u2f = new From();
+ u2f = new From();
+ u2f.addClause(new UnaryFromClause(new GroupSymbol("db.g3"))); //$NON-NLS-1$
+ u2.setFrom(u2f);
+
+ SetQuery union = new SetQuery(Operation.UNION, true, u1, u2);
+
+ SubquerySetCriteria subCrit = new SubquerySetCriteria(expr, union);
+
+ Query outer = new Query();
+ outer.setSelect(select);
+ outer.setFrom(from);
+ outer.setCriteria(subCrit);
+
+ helpTest("SELECT a FROM db.g WHERE b IN (SELECT x1 FROM db.g2 UNION ALL SELECT x2 FROM db.g3)", //$NON-NLS-1$
+ "SELECT a FROM db.g WHERE b IN (SELECT x1 FROM db.g2 UNION ALL SELECT x2 FROM db.g3)", //$NON-NLS-1$
+ outer);
+ }
+
+ @Test public void testVariablesInExec(){
+ StoredProcedure storedQuery = new StoredProcedure();
+ storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
+ SPParameter parameter = new SPParameter(1, new ElementSymbol("param1")); //$NON-NLS-1$
+ parameter.setParameterType(ParameterInfo.IN);
+ storedQuery.setParameter(parameter);
+ helpTest("Exec proc1(param1)", "EXEC proc1(param1)", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ helpTest("execute proc1(param1)", "EXEC proc1(param1)", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testExecSubquery(){
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ from.addClause(new UnaryFromClause(new GroupSymbol("newModel2.Table1"))); //$NON-NLS-1$
+ StoredProcedure subquery = new StoredProcedure();
+ subquery.setProcedureName("NewVirtual.StoredQuery");
+ from.addClause(new SubqueryFromClause("a", subquery)); //$NON-NLS-1$
+ query.setFrom(from);
+
+ helpTest("SELECT * FROM newModel2.Table1, (EXEC NewVirtual.StoredQuery()) AS a", //$NON-NLS-1$
+ "SELECT * FROM newModel2.Table1, (EXEC NewVirtual.StoredQuery()) AS a", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testUnicode1() {
+ try {
+ byte[] data = { (byte)0xd0, (byte)0x9c, (byte)0xd0, (byte)0xbe, (byte)0xd1, (byte)0x81, (byte)0xd0, (byte)0xba, (byte)0xd0, (byte)0xb2, (byte)0xd0, (byte)0xb0};
+
+ String string = new String(data, "UTF-8"); //$NON-NLS-1$
+ String sql = "SELECT * FROM TestDocument.TestDocument WHERE Subject='" + string + "'"; //$NON-NLS-1$ //$NON-NLS-2$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ from.addGroup(new GroupSymbol("TestDocument.TestDocument")); //$NON-NLS-1$
+ query.setFrom(from);
+ CompareCriteria crit = new CompareCriteria(new ElementSymbol("Subject"), CompareCriteria.EQ, new Constant(string)); //$NON-NLS-1$
+ query.setCriteria(crit);
+
+ helpTest(sql, query.toString(), query);
+
+ } catch(UnsupportedEncodingException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ @Test public void testUnicode2() {
+ String sql = "SELECT * FROM TestDocument.TestDocument WHERE Subject='\u0041\u005a'"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ from.addGroup(new GroupSymbol("TestDocument.TestDocument")); //$NON-NLS-1$
+ query.setFrom(from);
+ CompareCriteria crit = new CompareCriteria(new ElementSymbol("Subject"), CompareCriteria.EQ, new Constant("AZ")); //$NON-NLS-1$ //$NON-NLS-2$
+ query.setCriteria(crit);
+
+ helpTest(sql, query.toString(), query);
+ }
+
+ @Test public void testUnicode3() {
+ String sql = "SELECT '\u05e0'"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ Constant c = new Constant("\u05e0"); //$NON-NLS-1$
+ select.addSymbol(new ExpressionSymbol("expr", c)); //$NON-NLS-1$
+ query.setSelect(select);
+
+ helpTest(sql, query.toString(), query);
+ }
+
+ @Test public void testUnicode4() {
+ String sql = "SELECT \u05e0 FROM g"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ ElementSymbol e = new ElementSymbol("\u05e0"); //$NON-NLS-1$
+ select.addSymbol(e);
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest(sql, query.toString(), query);
+ }
+
+ @Test public void testEscapedFunction1() {
+ String sql = "SELECT * FROM a.thing WHERE e1 = {fn concat('a', 'b')}"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
+ query.setFrom(from);
+ Function function = new Function("concat", new Expression[] { new Constant("a"), new Constant("b")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ CompareCriteria crit = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, function); //$NON-NLS-1$
+ query.setCriteria(crit);
+
+ helpTest(sql,
+ "SELECT * FROM a.thing WHERE e1 = concat('a', 'b')", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testEscapedFunction2() {
+ String sql = "SELECT * FROM a.thing WHERE e1 = {fn convert(5, string)}"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
+ query.setFrom(from);
+ Function function = new Function("convert", new Expression[] { new Constant(new Integer(5)), new Constant("string")}); //$NON-NLS-1$ //$NON-NLS-2$
+ CompareCriteria crit = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, function); //$NON-NLS-1$
+ query.setCriteria(crit);
+
+ helpTest(sql,
+ "SELECT * FROM a.thing WHERE e1 = convert(5, string)", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testEscapedFunction3() {
+ String sql = "SELECT * FROM a.thing WHERE e1 = {fn cast(5 as string)}"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
+ query.setFrom(from);
+ Function function = new Function("cast", new Expression[] { new Constant(new Integer(5)), new Constant("string")}); //$NON-NLS-1$ //$NON-NLS-2$
+ CompareCriteria crit = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, function); //$NON-NLS-1$
+ query.setCriteria(crit);
+
+ helpTest(sql, "SELECT * FROM a.thing WHERE e1 = cast(5 AS string)", query); //$NON-NLS-1$
+ }
+
+ @Test public void testEscapedFunction4() {
+ String sql = "SELECT * FROM a.thing WHERE e1 = {fn concat({fn concat('a', 'b')}, 'c')}"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+ from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
+ query.setFrom(from);
+ Function func1 = new Function("concat", new Expression[] { new Constant("a"), new Constant("b")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Function func2 = new Function("concat", new Expression[] { func1, new Constant("c")}); //$NON-NLS-1$ //$NON-NLS-2$
+ CompareCriteria crit = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, func2); //$NON-NLS-1$
+ query.setCriteria(crit);
+
+ helpTest(sql, "SELECT * FROM a.thing WHERE e1 = concat(concat('a', 'b'), 'c')", query); //$NON-NLS-1$
+ }
+
+ @Test public void testFunctionWithUnderscore() {
+ String sql = "SELECT yowza_yowza() FROM a.thing"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ Function func1 = new Function("yowza_yowza", new Expression[] { }); //$NON-NLS-1$
+ ExpressionSymbol exprSymbol = new ExpressionSymbol("expr", func1); //$NON-NLS-1$
+ select.addSymbol(exprSymbol);
+ query.setSelect(select);
+
+ From from = new From();
+ from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
+ query.setFrom(from);
+
+ helpTest(sql, "SELECT yowza_yowza() FROM a.thing", query); //$NON-NLS-1$
+ }
+
+ @Test public void testManyInnerJoins1() {
+ String sql = "SELECT * " + //$NON-NLS-1$
+ "FROM SQL1.dbo.Customers INNER JOIN SQL1.dbo.Orders " + //$NON-NLS-1$
+ "ON SQL1.dbo.Customers.CustomerID = SQL1.dbo.Orders.CustomerID " + //$NON-NLS-1$
+ "INNER JOIN SQL1.dbo.order_details " + //$NON-NLS-1$
+ "ON SQL1.dbo.Orders.OrderID = SQL1.dbo.order_details.OrderID"; //$NON-NLS-1$
+
+ String sqlExpected = "SELECT * " + //$NON-NLS-1$
+ "FROM (SQL1.dbo.Customers INNER JOIN SQL1.dbo.Orders " + //$NON-NLS-1$
+ "ON SQL1.dbo.Customers.CustomerID = SQL1.dbo.Orders.CustomerID) " + //$NON-NLS-1$
+ "INNER JOIN SQL1.dbo.order_details " + //$NON-NLS-1$
+ "ON SQL1.dbo.Orders.OrderID = SQL1.dbo.order_details.OrderID"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+
+ GroupSymbol g1 = new GroupSymbol("SQL1.dbo.Customers"); //$NON-NLS-1$
+ GroupSymbol g2 = new GroupSymbol("SQL1.dbo.Orders"); //$NON-NLS-1$
+ GroupSymbol g3 = new GroupSymbol("SQL1.dbo.order_details"); //$NON-NLS-1$
+
+ ElementSymbol e1 = new ElementSymbol("SQL1.dbo.Customers.CustomerID"); //$NON-NLS-1$
+ ElementSymbol e2 = new ElementSymbol("SQL1.dbo.Orders.CustomerID"); //$NON-NLS-1$
+ ElementSymbol e3 = new ElementSymbol("SQL1.dbo.Orders.OrderID"); //$NON-NLS-1$
+ ElementSymbol e4 = new ElementSymbol("SQL1.dbo.order_details.OrderID"); //$NON-NLS-1$
+
+ List jcrits1 = new ArrayList();
+ jcrits1.add(new CompareCriteria(e1, CompareCriteria.EQ, e2));
+ List jcrits2 = new ArrayList();
+ jcrits2.add(new CompareCriteria(e3, CompareCriteria.EQ, e4));
+
+ JoinPredicate jp1 = new JoinPredicate(new UnaryFromClause(g1), new UnaryFromClause(g2), JoinType.JOIN_INNER, jcrits1);
+ JoinPredicate jp2 = new JoinPredicate(jp1, new UnaryFromClause(g3), JoinType.JOIN_INNER, jcrits2);
+
+ from.addClause(jp2);
+ query.setFrom(from);
+
+ helpTest(sql, sqlExpected, query);
+ }
+
+ @Test public void testManyInnerJoins2() {
+ String sql = "SELECT * " + //$NON-NLS-1$
+ "FROM A INNER JOIN (B RIGHT OUTER JOIN C ON b1 = c1) " + //$NON-NLS-1$
+ "ON a1 = b1 " + //$NON-NLS-1$
+ "INNER JOIN D " + //$NON-NLS-1$
+ "ON a1 = d1"; //$NON-NLS-1$
+
+ String sqlExpected = "SELECT * " + //$NON-NLS-1$
+ "FROM (A INNER JOIN (B RIGHT OUTER JOIN C ON b1 = c1) " + //$NON-NLS-1$
+ "ON a1 = b1) " + //$NON-NLS-1$
+ "INNER JOIN D " + //$NON-NLS-1$
+ "ON a1 = d1"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+
+ UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("A")); //$NON-NLS-1$
+ UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("B")); //$NON-NLS-1$
+ UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("C")); //$NON-NLS-1$
+ UnaryFromClause g4 = new UnaryFromClause(new GroupSymbol("D")); //$NON-NLS-1$
+
+ ElementSymbol e1 = new ElementSymbol("a1"); //$NON-NLS-1$
+ ElementSymbol e2 = new ElementSymbol("b1"); //$NON-NLS-1$
+ ElementSymbol e3 = new ElementSymbol("c1"); //$NON-NLS-1$
+ ElementSymbol e4 = new ElementSymbol("d1"); //$NON-NLS-1$
+
+ List jcrits1 = new ArrayList();
+ jcrits1.add(new CompareCriteria(e1, CompareCriteria.EQ, e2));
+ List jcrits2 = new ArrayList();
+ jcrits2.add(new CompareCriteria(e2, CompareCriteria.EQ, e3));
+ List jcrits3 = new ArrayList();
+ jcrits3.add(new CompareCriteria(e1, CompareCriteria.EQ, e4));
+
+ JoinPredicate jp1 = new JoinPredicate(g2, g3, JoinType.JOIN_RIGHT_OUTER, jcrits2);
+ JoinPredicate jp2 = new JoinPredicate(g1, jp1, JoinType.JOIN_INNER, jcrits1);
+ JoinPredicate jp3 = new JoinPredicate(jp2, g4, JoinType.JOIN_INNER, jcrits3);
+
+ from.addClause(jp3);
+ query.setFrom(from);
+
+ helpTest(sql, sqlExpected, query);
+ }
+
+ @Test public void testManyInnerJoins3() {
+ String sql = "SELECT * " + //$NON-NLS-1$
+ "FROM A INNER JOIN " + //$NON-NLS-1$
+ "(B RIGHT OUTER JOIN C ON b1 = c1 " + //$NON-NLS-1$
+ "CROSS JOIN D) " + //$NON-NLS-1$
+ "ON a1 = d1"; //$NON-NLS-1$
+
+ String sqlExpected = "SELECT * " + //$NON-NLS-1$
+ "FROM A INNER JOIN " + //$NON-NLS-1$
+ "((B RIGHT OUTER JOIN C ON b1 = c1) " + //$NON-NLS-1$
+ "CROSS JOIN D) " + //$NON-NLS-1$
+ "ON a1 = d1"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ query.setSelect(select);
+ From from = new From();
+
+ UnaryFromClause g1 = new UnaryFromClause(new GroupSymbol("A")); //$NON-NLS-1$
+ UnaryFromClause g2 = new UnaryFromClause(new GroupSymbol("B")); //$NON-NLS-1$
+ UnaryFromClause g3 = new UnaryFromClause(new GroupSymbol("C")); //$NON-NLS-1$
+ UnaryFromClause g4 = new UnaryFromClause(new GroupSymbol("D")); //$NON-NLS-1$
+
+ ElementSymbol e1 = new ElementSymbol("a1"); //$NON-NLS-1$
+ ElementSymbol e2 = new ElementSymbol("b1"); //$NON-NLS-1$
+ ElementSymbol e3 = new ElementSymbol("c1"); //$NON-NLS-1$
+ ElementSymbol e4 = new ElementSymbol("d1"); //$NON-NLS-1$
+
+ List jcrits1 = new ArrayList();
+ jcrits1.add(new CompareCriteria(e2, CompareCriteria.EQ, e3));
+ List jcrits2 = new ArrayList();
+ jcrits2.add(new CompareCriteria(e1, CompareCriteria.EQ, e4));
+
+ JoinPredicate jp1 = new JoinPredicate(g2, g3, JoinType.JOIN_RIGHT_OUTER, jcrits1);
+ JoinPredicate jp2 = new JoinPredicate(jp1, g4, JoinType.JOIN_CROSS);
+ JoinPredicate jp3 = new JoinPredicate(g1, jp2, JoinType.JOIN_INNER, jcrits2);
+
+ from.addClause(jp3);
+ query.setFrom(from);
+
+ helpTest(sql, sqlExpected, query);
+ }
+
+ @Test public void testLoopStatement() throws Exception {
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol c1 = new ElementSymbol("c1", false); //$NON-NLS-1$
+ select.addSymbol(c1);
+ select.addSymbol(new ElementSymbol("c2", false)); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ ElementSymbol x = new ElementSymbol("x"); //$NON-NLS-1$
+ String intType = new String("integer"); //$NON-NLS-1$
+ Statement dStmt = new DeclareStatement(x, intType);
+ c1 = new ElementSymbol("mycursor.c1", true); //$NON-NLS-1$
+ Statement assignmentStmt = new AssignmentStatement(x, c1);
+ Block block = new Block();
+ block.addStatement(dStmt);
+ block.addStatement(assignmentStmt);
+
+ String cursor = "mycursor"; //$NON-NLS-1$
+
+ LoopStatement loopStmt = new LoopStatement(block, query, cursor);
+
+ helpStmtTest("LOOP ON (SELECT c1, c2 FROM m.g) AS mycursor BEGIN DECLARE integer x; x=mycursor.c1; END", //$NON-NLS-1$
+ "LOOP ON (SELECT c1, c2 FROM m.g) AS mycursor"+"\n"+ "BEGIN"+"\n"+"DECLARE integer x;"+"\n"+"x = mycursor.c1;" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ +"\n"+"END", loopStmt); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testLoopStatementWithOrderBy() throws Exception {
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol c1 = new ElementSymbol("c1", false); //$NON-NLS-1$
+ select.addSymbol(c1);
+ select.addSymbol(new ElementSymbol("c2", false)); //$NON-NLS-1$
+
+ OrderBy orderBy = new OrderBy();
+ orderBy.addVariable(c1);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setOrderBy(orderBy);
+
+ ElementSymbol x = new ElementSymbol("x"); //$NON-NLS-1$
+ String intType = new String("integer"); //$NON-NLS-1$
+ Statement dStmt = new DeclareStatement(x, intType);
+ c1 = new ElementSymbol("mycursor.c1", true); //$NON-NLS-1$
+ Statement assignmentStmt = new AssignmentStatement(x, c1);
+ Block block = new Block();
+ block.addStatement(dStmt);
+ block.addStatement(assignmentStmt);
+
+ String cursor = "mycursor"; //$NON-NLS-1$
+
+ LoopStatement loopStmt = new LoopStatement(block, query, cursor);
+
+ helpStmtTest("LOOP ON (SELECT c1, c2 FROM m.g ORDER BY c1) AS mycursor BEGIN DECLARE integer x; x=mycursor.c1; END", //$NON-NLS-1$
+ "LOOP ON (SELECT c1, c2 FROM m.g ORDER BY c1) AS mycursor"+"\n"+ "BEGIN"+"\n"+"DECLARE integer x;"+"\n"+"x = mycursor.c1;" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ +"\n"+"END", loopStmt); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testWhileStatement() 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.addStatement(assignmentStmt);
+ Criteria crit = new CompareCriteria(x, CompareCriteria.LT,
+ new Constant(new Integer(100)));
+ WhileStatement whileStmt = new WhileStatement(crit, block);
+ helpStmtTest("WHILE (x < 100) BEGIN x=x+1; END", //$NON-NLS-1$
+ "WHILE(x < 100)"+"\n"+ "BEGIN"+"\n"+"x = (x + 1);" //$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();
+ helpStmtTest("break;", "BREAK;", breakStmt); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testContinueStatement() throws Exception {
+ Statement contStmt = new ContinueStatement();
+ helpStmtTest("continue;", "CONTINUE;", 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$
+ Statement dStmt = new DeclareStatement(x, intType);
+
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol c1 = new ElementSymbol("c1", false); //$NON-NLS-1$
+ select.addSymbol(c1);
+ select.addSymbol(new ElementSymbol("c2", false)); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ x = new ElementSymbol("x"); //$NON-NLS-1$
+ c1 = new ElementSymbol("mycursor.c1", true); //$NON-NLS-1$
+ Statement assignmentStmt = new AssignmentStatement(x, c1);
+ Block block = new Block();
+ block.addStatement(assignmentStmt);
+
+ Block ifBlock = new Block();
+ Statement continueStmt = new ContinueStatement();
+ ifBlock.addStatement(continueStmt);
+ Criteria crit = new CompareCriteria(x, CompareCriteria.GT,
+ new Constant(new Integer(5)));
+ IfStatement ifStmt = new IfStatement(crit, ifBlock);
+ block.addStatement(ifStmt);
+
+ String cursor = "mycursor"; //$NON-NLS-1$
+ LoopStatement loopStmt = new LoopStatement(block, query, cursor);
+
+ block = new Block();
+ block.addStatement(dStmt);
+ block.addStatement(loopStmt);
+ CommandStatement cmdStmt = new CommandStatement(query);
+ block.addStatement(cmdStmt);
+
+ CreateUpdateProcedureCommand virtualProcedureCommand = new CreateUpdateProcedureCommand();
+ virtualProcedureCommand.setBlock(block);
+ virtualProcedureCommand.setUpdateProcedure(false);
+
+ helpTest("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT c1, c2 FROM m.g) AS mycursor BEGIN x=mycursor.c1; IF(x > 5) BEGIN CONTINUE; END END SELECT c1, c2 FROM m.g; END", //$NON-NLS-1$
+ "CREATE VIRTUAL PROCEDURE\nBEGIN\nDECLARE integer x;\n" //$NON-NLS-1$
+ + "LOOP ON (SELECT c1, c2 FROM m.g) AS mycursor\nBEGIN\n" //$NON-NLS-1$
+ + "x = mycursor.c1;\nIF(x > 5)\nBEGIN\nCONTINUE;\nEND\nEND\n" //$NON-NLS-1$
+ + "SELECT c1, c2 FROM m.g;\nEND", virtualProcedureCommand); //$NON-NLS-1$
+
+ }
+
+ @Test public void testScalarSubqueryExpressionInSelect(){
+
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ s2.addSymbol(new ExpressionSymbol("expr", new ScalarSubquery(q1))); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+
+ helpTest("SELECT e1, (SELECT e1 FROM m.g1) FROM m.g2", //$NON-NLS-1$
+ "SELECT e1, (SELECT e1 FROM m.g1) FROM m.g2", //$NON-NLS-1$
+ q2);
+ }
+
+ @Test public void testScalarSubqueryExpressionInSelect2(){
+
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ExpressionSymbol("expr", new ScalarSubquery(q1))); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+
+ helpTest("SELECT (SELECT e1 FROM m.g1) FROM m.g2", //$NON-NLS-1$
+ "SELECT (SELECT e1 FROM m.g1) FROM m.g2", //$NON-NLS-1$
+ q2);
+ }
+
+ @Test public void testScalarSubqueryExpressionInSelect3(){
+
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ExpressionSymbol("expr", new ScalarSubquery(q1))); //$NON-NLS-1$
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+
+ helpTest("SELECT (SELECT e1 FROM m.g1), e1 FROM m.g2", //$NON-NLS-1$
+ "SELECT (SELECT e1 FROM m.g1), e1 FROM m.g2", //$NON-NLS-1$
+ q2);
+ }
+
+ @Test public void testScalarSubqueryExpressionWithAlias(){
+
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ s2.addSymbol(new AliasSymbol("X", new ExpressionSymbol("expr", new ScalarSubquery(q1)))); //$NON-NLS-1$ //$NON-NLS-2$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+
+ helpTest("SELECT e1, (SELECT e1 FROM m.g1) as X FROM m.g2", //$NON-NLS-1$
+ "SELECT e1, (SELECT e1 FROM m.g1) AS X FROM m.g2", //$NON-NLS-1$
+ q2);
+ }
+
+ @Test public void testScalarSubqueryExpressionInComplexExpression() throws QueryParserException {
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+
+ s2.addSymbol(new AliasSymbol("X", new ExpressionSymbol("expr", QueryParser.getQueryParser().parseExpression("(SELECT e1 FROM m.g1) + 2")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+
+ helpTest("SELECT e1, ((SELECT e1 FROM m.g1) + 2) as X FROM m.g2", //$NON-NLS-1$
+ "SELECT e1, ((SELECT e1 FROM m.g1) + 2) AS X FROM m.g2", //$NON-NLS-1$
+ q2);
+ }
+
+ @Test public void testScalarSubqueryExpressionInComplexExpression2() throws QueryParserException{
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+
+ s2.addSymbol(new AliasSymbol("X", new ExpressionSymbol("expr", QueryParser.getQueryParser().parseExpression("3 + (SELECT e1 FROM m.g1)")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+
+ helpTest("SELECT e1, (3 + (SELECT e1 FROM m.g1)) as X FROM m.g2", //$NON-NLS-1$
+ "SELECT e1, (3 + (SELECT e1 FROM m.g1)) AS X FROM m.g2", //$NON-NLS-1$
+ q2);
+ }
+
+ @Test public void testScalarSubqueryExpressionInComplexExpression3() throws QueryParserException{
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+
+ s2.addSymbol(new AliasSymbol("X", new ExpressionSymbol("expr", QueryParser.getQueryParser().parseExpression("(SELECT e1 FROM m.g1) + (SELECT e3 FROM m.g3)")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+
+ helpTest("SELECT e1, ((SELECT e1 FROM m.g1) + (SELECT e3 FROM m.g3)) as X FROM m.g2", //$NON-NLS-1$
+ "SELECT e1, ((SELECT e1 FROM m.g1) + (SELECT e3 FROM m.g3)) AS X FROM m.g2", //$NON-NLS-1$
+ q2);
+ }
+
+ @Test public void testScalarSubqueryExpressionInFunction() throws QueryParserException{
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+
+ s2.addSymbol(new AliasSymbol("X", new ExpressionSymbol("expr", QueryParser.getQueryParser().getQueryParser().parseExpression("length((SELECT e1 FROM m.g1))")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+
+ helpTest("SELECT e1, length((SELECT e1 FROM m.g1)) as X FROM m.g2", //$NON-NLS-1$
+ "SELECT e1, length((SELECT e1 FROM m.g1)) AS X FROM m.g2", //$NON-NLS-1$
+ q2);
+ }
+
+ @Test public void testBadScalarSubqueryExpression() {
+ helpException("SELECT e1, length(SELECT e1 FROM m.g1) as X FROM m.g2"); //$NON-NLS-1$
+ }
+
+ @Test public void testExistsPredicateCriteria(){
+
+ Query q2 = exampleExists(false);
+
+ helpTest("SELECT e1 FROM m.g2 WHERE Exists (SELECT e1 FROM m.g1)", //$NON-NLS-1$
+ "SELECT e1 FROM m.g2 WHERE EXISTS (SELECT e1 FROM m.g1)", //$NON-NLS-1$
+ q2);
+ }
+ static Query exampleExists(boolean semiJoin) {
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ ExistsCriteria existsCrit = new ExistsCriteria(q1);
+ existsCrit.getSubqueryHint().setMergeJoin(semiJoin);
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+ q2.setCriteria(existsCrit);
+ return q2;
+ }
+
+ @Test public void testAnyQuantifierSubqueryComparePredicate(){
+
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Criteria left = new SubqueryCompareCriteria(new ElementSymbol("e3"), q1, SubqueryCompareCriteria.GE, SubqueryCompareCriteria.ANY); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+ q2.setCriteria(left);
+
+ helpTest("SELECT e1 FROM m.g2 WHERE e3 >= ANY (SELECT e1 FROM m.g1)", //$NON-NLS-1$
+ "SELECT e1 FROM m.g2 WHERE e3 >= ANY (SELECT e1 FROM m.g1)", //$NON-NLS-1$
+ q2);
+
+ }
+
+ @Test public void testSomeQuantifierSubqueryComparePredicate(){
+
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Criteria left = new SubqueryCompareCriteria(new ElementSymbol("e3"), q1, SubqueryCompareCriteria.GT, SubqueryCompareCriteria.SOME); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+ q2.setCriteria(left);
+
+ helpTest("SELECT e1 FROM m.g2 WHERE e3 > some (SELECT e1 FROM m.g1)", //$NON-NLS-1$
+ "SELECT e1 FROM m.g2 WHERE e3 > SOME (SELECT e1 FROM m.g1)", //$NON-NLS-1$
+ q2);
+
+ }
+
+ @Test public void testAllQuantifierSubqueryComparePredicate(){
+
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Criteria left = new SubqueryCompareCriteria(new ElementSymbol("e3"), q1, SubqueryCompareCriteria.EQ, SubqueryCompareCriteria.ALL); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+ q2.setCriteria(left);
+
+ helpTest("SELECT e1 FROM m.g2 WHERE e3 = all (SELECT e1 FROM m.g1)", //$NON-NLS-1$
+ "SELECT e1 FROM m.g2 WHERE e3 = ALL (SELECT e1 FROM m.g1)", //$NON-NLS-1$
+ q2);
+
+ }
+
+ @Test public void testScalarSubqueryComparePredicate(){
+
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Criteria left = new CompareCriteria(new ElementSymbol("e3"), SubqueryCompareCriteria.LT, new ScalarSubquery(q1)); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+ q2.setCriteria(left);
+
+ helpTest("SELECT e1 FROM m.g2 WHERE e3 < (SELECT e1 FROM m.g1)", //$NON-NLS-1$
+ "SELECT e1 FROM m.g2 WHERE e3 < (SELECT e1 FROM m.g1)", //$NON-NLS-1$
+ q2);
+
+ }
+
+ @Test public void testSelectInto(){
+ GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ ElementSymbol c1 = new ElementSymbol("c1", false); //$NON-NLS-1$
+ select.addSymbol(c1);
+ select.addSymbol(new ElementSymbol("c2", false)); //$NON-NLS-1$
+
+ Into into = new Into(new GroupSymbol("#temp")); //$NON-NLS-1$
+ Query q = new Query();
+ q.setSelect(select);
+ q.setFrom(from);
+ q.setInto(into);
+ helpTest("SELECT c1, c2 INTO #temp FROM m.g", //$NON-NLS-1$
+ "SELECT c1, c2 INTO #temp FROM m.g", //$NON-NLS-1$
+ q);
+ }
+
+ @Test public void testCaseExpression1() {
+ CaseExpression expr = TestCaseExpression.example(4);
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
+ select.addSymbol(new ElementSymbol("z")); //$NON-NLS-1$
+ // The parser hard-codes the name "expr"
+ select.addSymbol(new ExpressionSymbol("expr", expr)); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ Query q = new Query();
+ q.setSelect(select);
+ q.setFrom(from);
+
+ String query = new StringBuffer("SELECT y, z, ") //$NON-NLS-1$
+ .append("CASE x") //$NON-NLS-1$
+ .append(" WHEN 'a' THEN 0") //$NON-NLS-1$
+ .append(" WHEN 'b' THEN 1") //$NON-NLS-1$
+ .append(" WHEN 'c' THEN 2") //$NON-NLS-1$
+ .append(" WHEN 'd' THEN 3") //$NON-NLS-1$
+ .append(" ELSE 9999") //$NON-NLS-1$
+ .append(" END") //$NON-NLS-1$
+ .append(" FROM m.g").toString(); //$NON-NLS-1$
+
+ helpTest(query, query, q);
+ }
+
+ @Test public void testCaseExpression2() {
+ CaseExpression expr = TestCaseExpression.example(4);
+ expr.setElseExpression(null);
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
+ select.addSymbol(new ElementSymbol("z")); //$NON-NLS-1$
+ // The parser hard-codes the name "expr"
+ select.addSymbol(new ExpressionSymbol("expr", expr)); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ Query q = new Query();
+ q.setSelect(select);
+ q.setFrom(from);
+
+ String query = new StringBuffer("SELECT y, z, ") //$NON-NLS-1$
+ .append("CASE x") //$NON-NLS-1$
+ .append(" WHEN 'a' THEN 0") //$NON-NLS-1$
+ .append(" WHEN 'b' THEN 1") //$NON-NLS-1$
+ .append(" WHEN 'c' THEN 2") //$NON-NLS-1$
+ .append(" WHEN 'd' THEN 3") //$NON-NLS-1$
+ .append(" END") //$NON-NLS-1$
+ .append(" FROM m.g").toString(); //$NON-NLS-1$
+
+ helpTest(query, query, q);
+ }
+
+ @Test public void testCaseExpression3() {
+ SearchedCaseExpression expr = TestSearchedCaseExpression.example2(4);
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ CompareCriteria where = new CompareCriteria(new ElementSymbol("z"), CompareCriteria.EQ, expr); //$NON-NLS-1$
+ Query q = new Query();
+ q.setSelect(select);
+ q.setFrom(from);
+ q.setCriteria(where);
+
+ String query = new StringBuffer("SELECT y FROM m.g ") //$NON-NLS-1$
+ .append("WHERE z = CASE") //$NON-NLS-1$
+ .append(" WHEN x = 'a' THEN 0") //$NON-NLS-1$
+ .append(" WHEN x = 'b' THEN 1") //$NON-NLS-1$
+ .append(" WHEN x = 'c' THEN 2") //$NON-NLS-1$
+ .append(" WHEN x = 'd' THEN 3") //$NON-NLS-1$
+ .append(" ELSE 9999") //$NON-NLS-1$
+ .append(" END").toString(); //$NON-NLS-1$
+ helpTest(query, query, q);
+ }
+
+ @Test public void testSearchedCaseExpression1() {
+ SearchedCaseExpression expr = TestSearchedCaseExpression.example(4);
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
+ select.addSymbol(new ElementSymbol("z")); //$NON-NLS-1$
+ // The parser hard-codes the name "expr"
+ select.addSymbol(new ExpressionSymbol("expr", expr)); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ Query q = new Query();
+ q.setSelect(select);
+ q.setFrom(from);
+
+ String query = new StringBuffer("SELECT y, z, ") //$NON-NLS-1$
+ .append("CASE") //$NON-NLS-1$
+ .append(" WHEN x = 0 THEN 0") //$NON-NLS-1$
+ .append(" WHEN x = 1 THEN 1") //$NON-NLS-1$
+ .append(" WHEN x = 2 THEN 2") //$NON-NLS-1$
+ .append(" WHEN x = 3 THEN 3") //$NON-NLS-1$
+ .append(" ELSE 9999") //$NON-NLS-1$
+ .append(" END") //$NON-NLS-1$
+ .append(" FROM m.g").toString(); //$NON-NLS-1$
+ helpTest(query, query, q);
+ }
+
+ @Test public void testSearchedCaseExpression2() {
+ SearchedCaseExpression expr = TestSearchedCaseExpression.example(4);
+ expr.setElseExpression(null);
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
+ select.addSymbol(new ElementSymbol("z")); //$NON-NLS-1$
+ // The parser hard-codes the name "expr"
+ select.addSymbol(new ExpressionSymbol("expr", expr)); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ Query q = new Query();
+ q.setSelect(select);
+ q.setFrom(from);
+
+ String query = new StringBuffer("SELECT y, z, ") //$NON-NLS-1$
+ .append("CASE") //$NON-NLS-1$
+ .append(" WHEN x = 0 THEN 0") //$NON-NLS-1$
+ .append(" WHEN x = 1 THEN 1") //$NON-NLS-1$
+ .append(" WHEN x = 2 THEN 2") //$NON-NLS-1$
+ .append(" WHEN x = 3 THEN 3") //$NON-NLS-1$
+ .append(" END") //$NON-NLS-1$
+ .append(" FROM m.g").toString(); //$NON-NLS-1$
+ helpTest(query, query, q);
+ }
+
+ @Test public void testSearchedCaseExpression3() {
+ SearchedCaseExpression expr = TestSearchedCaseExpression.example(4);
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ CompareCriteria where = new CompareCriteria(new ElementSymbol("z"), CompareCriteria.EQ, expr); //$NON-NLS-1$
+ Query q = new Query();
+ q.setSelect(select);
+ q.setFrom(from);
+ q.setCriteria(where);
+
+ String query = new StringBuffer("SELECT y FROM m.g ") //$NON-NLS-1$
+ .append("WHERE z = CASE") //$NON-NLS-1$
+ .append(" WHEN x = 0 THEN 0") //$NON-NLS-1$
+ .append(" WHEN x = 1 THEN 1") //$NON-NLS-1$
+ .append(" WHEN x = 2 THEN 2") //$NON-NLS-1$
+ .append(" WHEN x = 3 THEN 3") //$NON-NLS-1$
+ .append(" ELSE 9999") //$NON-NLS-1$
+ .append(" END").toString(); //$NON-NLS-1$
+ helpTest(query, query, q);
+ }
+
+ @Test public void testAndOrPrecedence_1575() {
+ Select s = new Select();
+ s.addSymbol(new AllSymbol());
+ 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$
+ CompareCriteria c2 = new CompareCriteria(new ElementSymbol("e2"), CompareCriteria.EQ, new Constant(new Integer(1))); //$NON-NLS-1$
+ CompareCriteria c3 = new CompareCriteria(new ElementSymbol("e3"), CompareCriteria.EQ, new Constant(new Integer(3))); //$NON-NLS-1$
+ CompoundCriteria cc1 = new CompoundCriteria(CompoundCriteria.AND, c2, c3);
+ CompoundCriteria cc2 = new CompoundCriteria(CompoundCriteria.OR, c1, cc1);
+ Query q = new Query();
+ q.setSelect(s);
+ q.setFrom(f);
+ q.setCriteria(cc2);
+
+ helpTest("SELECT * FROM m.g1 WHERE e1=0 OR e2=1 AND e3=3", //$NON-NLS-1$
+ "SELECT * FROM m.g1 WHERE (e1 = 0) OR ((e2 = 1) AND (e3 = 3))", q); //$NON-NLS-1$
+ }
+
+ @Test public void testAndOrPrecedence2_1575() {
+ Select s = new Select();
+ s.addSymbol(new AllSymbol());
+ 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$
+ CompareCriteria c2 = new CompareCriteria(new ElementSymbol("e2"), CompareCriteria.EQ, new Constant(new Integer(1))); //$NON-NLS-1$
+ CompareCriteria c3 = new CompareCriteria(new ElementSymbol("e3"), CompareCriteria.EQ, new Constant(new Integer(3))); //$NON-NLS-1$
+ CompoundCriteria cc1 = new CompoundCriteria(CompoundCriteria.AND, c1, c2);
+ CompoundCriteria cc2 = new CompoundCriteria(CompoundCriteria.OR, cc1, c3);
+ Query q = new Query();
+ q.setSelect(s);
+ q.setFrom(f);
+ q.setCriteria(cc2);
+
+ helpTest("SELECT * FROM m.g1 WHERE e1=0 AND e2=1 OR e3=3", //$NON-NLS-1$
+ "SELECT * FROM m.g1 WHERE ((e1 = 0) AND (e2 = 1)) OR (e3 = 3)", q); //$NON-NLS-1$
+ }
+
+ /**
+ *
+ * @since 4.2
+ */
+ private void helpTestCompoundNonJoinCriteria(String sqlPred, PredicateCriteria predCrit) {
+ Select s = new Select();
+ s.addSymbol(new AllSymbol());
+ From f = new From();
+
+ CompareCriteria c1 = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, new Constant(new Integer(0))); //$NON-NLS-1$
+ CompoundCriteria cc1 = new CompoundCriteria(CompoundCriteria.AND, c1, predCrit);
+ JoinPredicate jp = new JoinPredicate(new UnaryFromClause(new GroupSymbol("m.g1")), new UnaryFromClause(new GroupSymbol("m.g2")), JoinType.JOIN_INNER, cc1); //$NON-NLS-1$ //$NON-NLS-2$
+ f.addClause(jp);
+
+ Query q = new Query();
+ q.setSelect(s);
+ q.setFrom(f);
+
+ helpTest("SELECT * FROM m.g1 JOIN m.g2 ON e1=0 AND " + sqlPred, //$NON-NLS-1$
+ "SELECT * FROM m.g1 INNER JOIN m.g2 ON e1 = 0 AND " + sqlPred, q); //$NON-NLS-1$
+
+ }
+
+
+ @Test public void testCompoundNonJoinCriteriaInFromWithComparisonCriteria() {
+ CompareCriteria c2 = new CompareCriteria(new ElementSymbol("e2"), CompareCriteria.EQ, new Constant(new Integer(1))); //$NON-NLS-1$
+ helpTestCompoundNonJoinCriteria("e2 = 1", c2); //$NON-NLS-1$
+ }
+
+ @Test public void testCompoundNonJoinCriteriaInFromWithIsNull() {
+ helpTestCompoundNonJoinCriteria("e2 IS NULL", new IsNullCriteria(new ElementSymbol("e2"))); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCompoundNonJoinCriteriaInFromUWithIN() {
+ Collection values = new ArrayList();
+ values.add(new Constant(new Integer(0)));
+ values.add(new Constant(new Integer(1)));
+ PredicateCriteria crit = new SetCriteria(new ElementSymbol("e2"), values); //$NON-NLS-1$
+ helpTestCompoundNonJoinCriteria("e2 IN (0, 1)", crit); //$NON-NLS-1$
+ }
+
+ @Test public void testCompoundNonJoinCriteriaInFromUWithLIKE() {
+ PredicateCriteria crit = new MatchCriteria(new ElementSymbol("e2"), new Constant("%")); //$NON-NLS-1$ //$NON-NLS-2$
+ helpTestCompoundNonJoinCriteria("e2 LIKE '%'", crit); //$NON-NLS-1$
+ }
+
+ @Test public void testCompoundNonJoinCriteria_defect15167_1() throws Exception {
+ QueryParser.getQueryParser().parseCommand("SELECT A.alert_id, A.primary_entity_name, A.primary_entity_level_code, A.alert_description, A.create_date, A.alert_risk_score, S.scenario_name, A.alert_status_code, A.process_id, A.actual_values_text, S.SCENARIO_CATEGORY_DESC, A.primary_entity_number, A.scenario_id, A.primary_entity_key FROM (FSK_ALERT AS A LEFT OUTER JOIN FSK_SCENARIO AS S ON A.scenario_id = S.scenario_id) INNER JOIN FSC_ACCOUNT_DIM AS C ON A.primary_entity_key = C.ACCOUNT_KEY AND ((S.current_ind = 'Y') OR (S.current_ind IS NULL)) WHERE (A.primary_entity_level_code = 'ACC') AND (C.ACCOUNT_KEY = 23923) AND (A.logical_delete_ind = 'N')"); //$NON-NLS-1$
+ }
+
+ @Test public void testCompoundNonJoinCriteria_defect15167_2() throws Exception {
+ QueryParser.getQueryParser().parseCommand("SELECT A.alert_id, A.primary_entity_name, A.primary_entity_level_code, A.alert_description, A.create_date, A.alert_risk_score, S.scenario_name, A.alert_status_code, A.process_id, A.actual_values_text, S.SCENARIO_CATEGORY_DESC, A.primary_entity_number, A.scenario_id, A.primary_entity_key FROM (FSK_ALERT AS A LEFT OUTER JOIN FSK_SCENARIO AS S ON A.scenario_id = S.scenario_id) INNER JOIN FSC_ACCOUNT_DIM AS C ON A.primary_entity_key = C.ACCOUNT_KEY AND (S.current_ind = 'Y' OR S.current_ind IS NULL) WHERE (A.primary_entity_level_code = 'ACC') AND (C.ACCOUNT_KEY = 23923) AND (A.logical_delete_ind = 'N')"); //$NON-NLS-1$
+ }
+
+ @Test public void testCompoundNonJoinCriteria_defect15167_3() throws Exception {
+ QueryParser.getQueryParser().parseCommand("SELECT A.alert_id, A.primary_entity_name, A.primary_entity_level_code, A.alert_description, A.create_date, A.alert_risk_score, S.scenario_name, A.alert_status_code, A.process_id, A.actual_values_text, S.SCENARIO_CATEGORY_DESC, A.primary_entity_number, A.scenario_id, A.primary_entity_key FROM (FSK_ALERT AS A LEFT OUTER JOIN FSK_SCENARIO AS S ON A.scenario_id = S.scenario_id) INNER JOIN FSC_ACCOUNT_DIM AS C ON (A.primary_entity_key = C.ACCOUNT_KEY AND (S.current_ind = 'Y' OR S.current_ind IS NULL)) WHERE (A.primary_entity_level_code = 'ACC') AND (C.ACCOUNT_KEY = 23923) AND (A.logical_delete_ind = 'N')"); //$NON-NLS-1$
+ }
+
+ @Test public void testCompoundNonJoinCriteria_defect15167_4() throws Exception {
+ QueryParser.getQueryParser().parseCommand("SELECT A.alert_id, A.primary_entity_name, A.primary_entity_level_code, A.alert_description, A.create_date, A.alert_risk_score, S.scenario_name, A.alert_status_code, A.process_id, A.actual_values_text, S.SCENARIO_CATEGORY_DESC, A.primary_entity_number, A.scenario_id, A.primary_entity_key FROM (FSK_ALERT AS A LEFT OUTER JOIN FSK_SCENARIO AS S ON A.scenario_id = S.scenario_id) INNER JOIN FSC_ACCOUNT_DIM AS C ON (A.primary_entity_key = C.ACCOUNT_KEY AND S.current_ind = 'Y' OR S.current_ind IS NULL) WHERE (A.primary_entity_level_code = 'ACC') AND (C.ACCOUNT_KEY = 23923) AND (A.logical_delete_ind = 'N')"); //$NON-NLS-1$
+ }
+
+ @Test public void testFunctionInGroupBy() throws Exception {
+ QueryParser.getQueryParser().parseCommand("SELECT SUM(s), elem+1 FROM m.g GROUP BY elem+1"); //$NON-NLS-1$
+ }
+
+ @Test public void testCaseInGroupBy() throws Exception {
+ QueryParser.getQueryParser().parseCommand("SELECT SUM(elem+1), CASE elem WHEN 0 THEN 1 ELSE 2 END AS c FROM m.g GROUP BY CASE elem WHEN 0 THEN 1 ELSE 2 END"); //$NON-NLS-1$
+ }
+
+ @Test public void testNationCharString() throws Exception {
+ Query query = (Query) QueryParser.getQueryParser().parseCommand("SELECT N'blah' FROM m.g"); //$NON-NLS-1$
+ Select select = query.getSelect();
+ ExpressionSymbol s = (ExpressionSymbol) select.getSymbol(0);
+ Constant c = (Constant) s.getExpression();
+ assertEquals(c, new Constant("blah")); //$NON-NLS-1$
+ }
+
+ @Test public void testNationCharString2() throws Exception {
+ Query query = (Query) QueryParser.getQueryParser().parseCommand("SELECT DISTINCT TABLE_QUALIFIER, NULL AS TABLE_OWNER, NULL AS TABLE_NAME, NULL AS TABLE_TYPE, NULL AS REMARKS FROM ATIODBCSYSTEM.OA_TABLES WHERE TABLE_QUALIFIER LIKE N'%' ESCAPE '\\' ORDER BY TABLE_QUALIFIER "); //$NON-NLS-1$
+ MatchCriteria matchCrit = (MatchCriteria) query.getCriteria();
+ Constant c = (Constant) matchCrit.getRightExpression();
+ assertEquals(c, new Constant("%")); //$NON-NLS-1$
+ }
+
+ @Test public void testScalarSubquery() throws Exception {
+ QueryParser.getQueryParser().parseCommand("SELECT (SELECT 1) FROM x"); //$NON-NLS-1$
+ }
+
+ @Test public void testElementInDoubleQuotes() throws Exception {
+ GroupSymbol g = new GroupSymbol("x"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ ElementSymbol e = new ElementSymbol("foo"); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(e);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT \"foo\" FROM x", //$NON-NLS-1$
+ "SELECT foo FROM x", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testElementInDoubleQuotes_Insert() throws Exception {
+ GroupSymbol g = new GroupSymbol("x"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ ElementSymbol e = new ElementSymbol("foo"); //$NON-NLS-1$
+
+ Insert query = new Insert(g, new ArrayList(), new ArrayList());
+ query.addVariable(e);
+ query.addValue(new Constant("bar", String.class)); //$NON-NLS-1$
+
+ helpTest("insert into x (\"foo\") values ('bar')", //$NON-NLS-1$
+ "INSERT INTO x (foo) VALUES ('bar')", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testElementInDoubleQuotes_Update() throws Exception {
+ GroupSymbol g = new GroupSymbol("x"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ ElementSymbol e = new ElementSymbol("foo"); //$NON-NLS-1$
+ Update query = new Update();
+ query.setGroup(g);
+ query.addChange(e, new Constant("bar", String.class)); //$NON-NLS-1$
+
+ helpTest("update x set \"foo\"='bar'", //$NON-NLS-1$
+ "UPDATE x SET foo = 'bar'", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testElementInDoubleQuotes_delete() throws Exception {
+ GroupSymbol g = new GroupSymbol("x"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ ElementSymbol e = new ElementSymbol("foo"); //$NON-NLS-1$
+ CompareCriteria c = new CompareCriteria(e, CompareCriteria.EQ, new Constant("bar", String.class)); //$NON-NLS-1$
+ Delete query = new Delete(g,c);
+
+ helpTest("delete from x where \"foo\"='bar'", //$NON-NLS-1$
+ "DELETE FROM x WHERE foo = 'bar'", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testAliasInDoubleQuotes() throws Exception {
+ GroupSymbol g = new GroupSymbol("x"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ AliasSymbol as = new AliasSymbol("fooAlias", new ElementSymbol("fooKey")); //$NON-NLS-1$ //$NON-NLS-2$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT fooKey AS \"fooAlias\" FROM x", //$NON-NLS-1$
+ "SELECT fooKey AS fooAlias FROM x", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testAliasInDoubleQuotesWithQuotedGroup() throws Exception {
+
+ GroupSymbol g = new GroupSymbol("x.y.z"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ AliasSymbol as = new AliasSymbol("fooAlias", new ElementSymbol("fooKey")); //$NON-NLS-1$ //$NON-NLS-2$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ ElementSymbol a = new ElementSymbol("x.y.z.id"); //$NON-NLS-1$
+ Constant c = new Constant(new Integer(10));
+ Criteria crit = new CompareCriteria(a, CompareCriteria.EQ, c);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(crit);
+
+ helpTest("SELECT fooKey AS \"fooAlias\" FROM \"x.y\".z where x.\"y.z\".id = 10", //$NON-NLS-1$
+ "SELECT fooKey AS fooAlias FROM x.y.z WHERE x.y.z.id = 10", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testSingleQuotedConstant() throws Exception {
+
+ GroupSymbol g = new GroupSymbol("x.y.z"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Constant as = new Constant("fooString"); //$NON-NLS-1$
+ Select select = new Select();
+ select.addSymbol(new ExpressionSymbol("expr", as)); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest("SELECT 'fooString' FROM \"x.y.z\"", //$NON-NLS-1$
+ "SELECT 'fooString' FROM x.y.z", //$NON-NLS-1$
+ query);
+ }
+
+ @Test public void testAliasInSingleQuotes() throws Exception {
+
+ GroupSymbol g = new GroupSymbol("x.y.z"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ AliasSymbol as = new AliasSymbol("fooAlias", new ElementSymbol("fooKey")); //$NON-NLS-1$ //$NON-NLS-2$
+ Select select = new Select();
+ select.addSymbol(as);
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpException("SELECT fooKey 'fooAlias' FROM x.\"y\".z"); //$NON-NLS-1$
+ }
+
+ /** QUERY Tool Format*/
+ @Test public void testQueryWithQuotes_MSQuery() throws Exception {
+ QueryParser.getQueryParser().parseCommand("SELECT \"PART_COLOR\", \"PART_ID\", \"PART_NAME\", \"PART_WEIGHT\" FROM \"VirtualParts.base\".\"Parts\""); //$NON-NLS-1$
+ }
+
+ /** MS Access Format**/
+ @Test public void testQueryWithQuotes_MSAccess() throws Exception {
+ QueryParser.getQueryParser().parseCommand("SELECT \"PART_COLOR\" ,\"PART_ID\" ,\"PART_NAME\" ,\"PART_WEIGHT\" FROM \"parts_oracle.DEV_RRAMESH\".\"PARTS\""); //$NON-NLS-1$
+ }
+
+ /** BO Business View Manager**/
+ @Test public void testQueryWithQuotes_BODesigner() throws Exception {
+ QueryParser.getQueryParser().parseCommand("SELECT DISTINCT \"PARTS\".\"PART_NAME\" FROM \"parts_oracle.DEV_RRAMESH\".\"PARTS\" \"PARTS\""); //$NON-NLS-1$
+ }
+
+ /** Crystal Reports **/
+ @Test public void testQueryWithQuotes_CrystalReports() throws Exception {
+ QueryParser.getQueryParser().parseCommand("SELECT \"Oracle_PARTS\".\"PART_COLOR\", \"Oracle_PARTS\".\"PART_ID\", \"Oracle_PARTS\".\"PART_NAME\", \"Oracle_PARTS\".\"PART_WEIGHT\", \"SQL_PARTS\".\"PART_COLOR\", \"SQL_PARTS\".\"PART_ID\", \"SQL_PARTS\".\"PART_NAME\", \"SQL_PARTS\".\"PART_WEIGHT\" FROM \"parts_oracle.DEV_RRAMESH\".\"PARTS\" \"Oracle_PARTS\", \"parts_sqlserver.dv_rreddy.dv_rreddy\".\"PARTS\" \"SQL_PARTS\" WHERE (\"Oracle_PARTS\".\"PART_ID\"=\"SQL_PARTS\".\"PART_ID\")"); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderByWithNumbers_InQuotes() throws Exception {
+ GroupSymbol g = new GroupSymbol("z"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("x")); //$NON-NLS-1$
+ select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
+
+ OrderBy orderby = new OrderBy();
+ orderby.addVariable(new ElementSymbol("1"), true); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setOrderBy(orderby);
+
+ helpTest("SELECT x, y from z order by \"1\"", "SELECT x, y FROM z ORDER BY \"1\"", query); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testOrderByWithNumbers_AsInt() throws Exception {
+ GroupSymbol g = new GroupSymbol("z"); //$NON-NLS-1$
+ From from = new From();
+ from.addGroup(g);
+
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("x")); //$NON-NLS-1$
+ select.addSymbol(new ElementSymbol("y")); //$NON-NLS-1$
+
+ OrderBy orderby = new OrderBy();
+ orderby.addVariable(new ExpressionSymbol("expr", new Constant(1)), true); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setOrderBy(orderby);
+
+ helpTest("SELECT x, y FROM z order by 1", "SELECT x, y FROM z ORDER BY 1", query); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test(expected=QueryParserException.class) public void testOrderByWithNumbers_AsNegitiveInt() throws Exception {
+ QueryParser.getQueryParser().parseCommand("SELECT x, y FROM z order by -1"); //$NON-NLS-1$
+ }
+
+ @Test public void testEmptyAndNullInputsGiveSameErrorMessage() throws Exception {
+ String emptyMessage = null;
+ try {
+ QueryParser.getQueryParser().parseCommand(""); //$NON-NLS-1$
+ fail("Expected exception for parsing empty string"); //$NON-NLS-1$
+ } catch(TeiidException e) {
+ emptyMessage = e.getMessage();
+ }
+
+ String nullMessage = null;
+ try {
+ QueryParser.getQueryParser().parseCommand(null);
+ fail("Expected exception for parsing null string"); //$NON-NLS-1$
+ } catch(TeiidException e) {
+ nullMessage = e.getMessage();
+ }
+
+ assertTrue("Expected same message for empty and null cases", emptyMessage.equals(nullMessage)); //$NON-NLS-1$
+ }
+
+ @Test public void testCase3281NamedVariable() {
+ StoredProcedure storedQuery = new StoredProcedure();
+ storedQuery.setDisplayNamedParameters(true);
+ storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
+ SPParameter parameter = new SPParameter(1, new Constant("paramValue1")); //$NON-NLS-1$
+ parameter.setName("param1"); //$NON-NLS-1$
+ parameter.setParameterType(ParameterInfo.IN);
+ storedQuery.setParameter(parameter);
+ helpTest("Exec proc1(param1 = 'paramValue1')", "EXEC proc1(param1 => 'paramValue1')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ helpTest("execute proc1(param1 = 'paramValue1')", "EXEC proc1(param1 => 'paramValue1')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCase3281NamedVariables() {
+ StoredProcedure storedQuery = new StoredProcedure();
+ storedQuery.setDisplayNamedParameters(true);
+ storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
+ SPParameter param1 = new SPParameter(1, new Constant("paramValue1")); //$NON-NLS-1$
+ param1.setName("param1"); //$NON-NLS-1$
+ param1.setParameterType(ParameterInfo.IN);
+ storedQuery.setParameter(param1);
+ SPParameter param2 = new SPParameter(2, new Constant("paramValue2")); //$NON-NLS-1$
+ param2.setName("param2"); //$NON-NLS-1$
+ param2.setParameterType(ParameterInfo.IN);
+ storedQuery.setParameter(param2);
+ helpTest("Exec proc1(param1 = 'paramValue1', param2 = 'paramValue2')", "EXEC proc1(param1 => 'paramValue1', param2 => 'paramValue2')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ helpTest("execute proc1(param1 = 'paramValue1', param2 = 'paramValue2')", "EXEC proc1(param1 => 'paramValue1', param2 => 'paramValue2')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCase3281QuotedNamedVariableFails2() {
+ StoredProcedure storedQuery = new StoredProcedure();
+ storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
+ SPParameter param1 = new SPParameter(1, new CompareCriteria(new Constant("a"), CompareCriteria.EQ, new Constant("b"))); //$NON-NLS-1$
+ param1.setParameterType(ParameterInfo.IN);
+ storedQuery.setParameter(param1);
+ helpTest("Exec proc1('a' = 'b')", "EXEC proc1(('a' = 'b'))", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** Test what happens if the name of a parameter is a reserved word. It must be quoted (double-ticks). */
+ @Test public void testCase3281NamedVariablesReservedWords() {
+ StoredProcedure storedQuery = new StoredProcedure();
+ storedQuery.setDisplayNamedParameters(true);
+ storedQuery.setProcedureName("proc1"); //$NON-NLS-1$
+ SPParameter param1 = new SPParameter(1, new Constant("paramValue1")); //$NON-NLS-1$
+ param1.setName("in"); //$NON-NLS-1$ //<---RESERVED WORD
+ param1.setParameterType(ParameterInfo.IN);
+ storedQuery.setParameter(param1);
+ SPParameter param2 = new SPParameter(2, new Constant("paramValue2")); //$NON-NLS-1$
+ param2.setName("in2"); //$NON-NLS-1$
+ param2.setParameterType(ParameterInfo.IN);
+ storedQuery.setParameter(param2);
+ helpTest("Exec proc1(\"in\" = 'paramValue1', in2 = 'paramValue2')", "EXEC proc1(\"in\" => 'paramValue1', in2 => 'paramValue2')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ helpTest("execute proc1(\"in\" = 'paramValue1', in2 = 'paramValue2')", "EXEC proc1(\"in\" => 'paramValue1', in2 => 'paramValue2')", storedQuery); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testExceptionMessageWithLocation() {
+ try {
+ QueryParser.getQueryParser().parseCommand("SELECT FROM"); //$NON-NLS-1$
+ } catch(QueryParserException e) {
+ assertTrue(e.getMessage().startsWith("Parsing error: Encountered \"FROM\" at line 1, column 8.")); //$NON-NLS-1$
+ }
+ }
+
+ @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 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 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 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 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 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$
+ }
+
+ @Test public void testCreateTempTable1() {
+ Create create = new Create();
+ create.setTable(new GroupSymbol("tempTable")); //$NON-NLS-1$
+ List columns = new ArrayList();
+ ElementSymbol column = new ElementSymbol("c1");//$NON-NLS-1$
+ column.setType(DataTypeManager.DefaultDataClasses.BOOLEAN);
+ columns.add(column);
+ column = new ElementSymbol("c2");//$NON-NLS-1$
+ column.setType(DataTypeManager.DefaultDataClasses.BYTE);
+ columns.add(column);
+ create.setElementSymbolsAsColumns(columns);
+ helpTest("Create local TEMPORARY table tempTable (c1 boolean, c2 byte)", "CREATE LOCAL TEMPORARY TABLE tempTable (c1 boolean, c2 byte)", create); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCreateTempTable2() {
+ Create create = new Create();
+ create.setTable(new GroupSymbol("tempTable")); //$NON-NLS-1$
+ List columns = new ArrayList();
+ ElementSymbol column = new ElementSymbol("c1");//$NON-NLS-1$
+ column.setType(DataTypeManager.DefaultDataClasses.BOOLEAN);
+ columns.add(column);
+ column = new ElementSymbol("c2");//$NON-NLS-1$
+ column.setType(DataTypeManager.DefaultDataClasses.BYTE);
+ columns.add(column);
+ create.setElementSymbolsAsColumns(columns);
+ helpTest("Create local TEMPORARY table tempTable(c1 boolean, c2 byte)", "CREATE LOCAL TEMPORARY TABLE tempTable (c1 boolean, c2 byte)", create); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCreateTempTable3() {
+ helpException("Create TEMPORARY table tempTable (c1 boolean, c2 byte)"); //$NON-NLS-1$
+ }
+
+ @Test public void testCreateTempTable4() {
+ helpException("Create table tempTable (c1 boolean, c2 byte)"); //$NON-NLS-1$
+ }
+
+ @Test public void testCreateTempTable5() {
+ helpException("Create local TEMPORARY table tempTable (c1 boolean primary, c2 byte)"); //$NON-NLS-1$
+ }
+
+ @Test public void testCreateTempTable7() {
+ helpException("Create local TEMPORARY table tempTable (c1.x boolean, c2 byte)" ,"Parsing error: Invalid simple identifier format: [c1.x]"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCreateTempTableWithPrimaryKey() {
+ Create create = new Create();
+ create.setTable(new GroupSymbol("tempTable")); //$NON-NLS-1$
+ List columns = new ArrayList();
+ ElementSymbol column = new ElementSymbol("c1");//$NON-NLS-1$
+ column.setType(DataTypeManager.DefaultDataClasses.BOOLEAN);
+ columns.add(column);
+ column = new ElementSymbol("c2");//$NON-NLS-1$
+ column.setType(DataTypeManager.DefaultDataClasses.BYTE);
+ columns.add(column);
+ create.setElementSymbolsAsColumns(columns);
+ create.getPrimaryKey().add(column);
+ helpTest("Create local TEMPORARY table tempTable(c1 boolean, c2 byte, primary key (c2))", "CREATE LOCAL TEMPORARY TABLE tempTable (c1 boolean, c2 byte, PRIMARY KEY(c2))", create); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDropTable() {
+ Drop drop = new Drop();
+ drop.setTable(new GroupSymbol("tempTable")); //$NON-NLS-1$
+ helpTest("DROP table tempTable", "DROP TABLE tempTable", drop); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testEscapedOuterJoin() {
+ String sql = "SELECT * FROM {oj A LEFT OUTER JOIN B ON (A.x=B.x)}"; //$NON-NLS-1$
+ String expected = "SELECT * FROM A LEFT OUTER JOIN B ON A.x = B.x"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ query.setSelect(select);
+ select.addSymbol(new AllSymbol());
+ 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$
+ FromClause f1 = new UnaryFromClause(new GroupSymbol("A")); //$NON-NLS-1$
+ FromClause f2 = new UnaryFromClause(new GroupSymbol("B")); //$NON-NLS-1$
+ JoinPredicate jp = new JoinPredicate(f1, f2, JoinType.JOIN_LEFT_OUTER, Arrays.asList(new Object[] {compareCriteria}));
+ from.addClause(jp);
+
+ helpTest(sql, expected, query);
+ }
+
+ @Test public void testBadAlias() {
+ String sql = "select a as a.x from foo"; //$NON-NLS-1$
+
+ helpException(sql, "Parsing error: Invalid alias format: [a.x]"); //$NON-NLS-1$
+ }
+
+ @Test public void testNameSpacedFunctionName() {
+ String sql = "select a.x()"; //$NON-NLS-1$
+
+ Query query = new Query();
+ Select select = new Select();
+ Function func1 = new Function("a.x", new Expression[] { }); //$NON-NLS-1$
+ ExpressionSymbol exprSymbol = new ExpressionSymbol("expr", func1); //$NON-NLS-1$
+ select.addSymbol(exprSymbol);
+ query.setSelect(select);
+
+ helpTest(sql, "SELECT a.x()", query); //$NON-NLS-1$
+ }
+
+ @Test public void testUnionJoin() {
+ String sql = "select * from pm1.g1 union join pm1.g2 where g1.e1 = 1"; //$NON-NLS-1$
+ 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());
+
+ 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$
+
+ Criteria crit = new CompareCriteria(new ElementSymbol("g1.e1"), CompareCriteria.EQ, new Constant(new Integer(1))); //$NON-NLS-1$
+
+ Query command = new Query(select, from, crit, null, null);
+ helpTest(sql, expected, command);
+ }
+
+ @Test public void testUnionJoin1() {
+ String sql = "select * from pm1.g1 union all join pm1.g2 where g1.e1 = 1"; //$NON-NLS-1$
+
+ helpException(sql);
+ }
+
+ @Test public void testIfElseWithoutBeginEnd() {
+ String sql = "CREATE PROCEDURE BEGIN IF (x > 1) select 1; IF (x > 1) select 1; ELSE select 1; END"; //$NON-NLS-1$
+ 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 ExpressionSymbol("expr", new Constant(1))))); //$NON-NLS-1$
+ CommandStatement commandStmt = new CommandStatement(query);
+ 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);
+ IfStatement ifStmt1 = (IfStatement)ifStmt.clone();
+ Block block2 = new Block();
+ block2.addStatement(commandStmt);
+ ifStmt1.setElseBlock(block2);
+ Block block3 = new Block();
+ block3.addStatement(ifStmt);
+ block3.addStatement(ifStmt1);
+ CreateUpdateProcedureCommand command = new CreateUpdateProcedureCommand(block3);
+
+ helpTest(sql, expected, command);
+ }
+
+ @Test public void testBadCreate() {
+ helpException("create insert"); //$NON-NLS-1$
+ }
+
+ @Test public void testCommandWithSemicolon() throws Exception {
+ helpTest("select * from pm1.g1;", "SELECT * FROM pm1.g1", QueryParser.getQueryParser().parseCommand("select * from pm1.g1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testLOBTypes() throws Exception {
+ 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 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);
+
+ helpTest("select convert(null, blob), convert(null, clob), convert(null, xml)", "SELECT convert(null, blob), convert(null, clob), convert(null, xml)", query); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInsertWithoutColumns() {
+ Insert insert = new Insert();
+ insert.setGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ insert.addValue(new Constant("a")); //$NON-NLS-1$
+ insert.addValue(new Constant("b")); //$NON-NLS-1$
+ helpTest("INSERT INTO m.g VALUES ('a', 'b')", //$NON-NLS-1$
+ "INSERT INTO m.g VALUES ('a', 'b')", //$NON-NLS-1$
+ insert);
+ }
+
+ @Test public void testTypeAliases() {
+ Create create = new Create();
+ create.setTable(new GroupSymbol("tempTable")); //$NON-NLS-1$
+ List columns = new ArrayList();
+ ElementSymbol column = new ElementSymbol("c1");//$NON-NLS-1$
+ column.setType(DataTypeManager.DefaultDataClasses.STRING);
+ columns.add(column);
+ column = new ElementSymbol("c2");//$NON-NLS-1$
+ column.setType(DataTypeManager.DefaultDataClasses.BYTE);
+ columns.add(column);
+ column = new ElementSymbol("c3");//$NON-NLS-1$
+ column.setType(DataTypeManager.DefaultDataClasses.SHORT);
+ columns.add(column);
+ column = new ElementSymbol("c4");//$NON-NLS-1$
+ column.setType(DataTypeManager.DefaultDataClasses.FLOAT);
+ columns.add(column);
+ column = new ElementSymbol("c5");//$NON-NLS-1$
+ column.setType(DataTypeManager.DefaultDataClasses.BIG_DECIMAL);
+ columns.add(column);
+ create.setElementSymbolsAsColumns(columns);
+ helpTest("Create local TEMPORARY table tempTable (c1 varchar, c2 tinyint, c3 smallint, c4 real, c5 decimal)", "CREATE LOCAL TEMPORARY TABLE tempTable (c1 varchar, c2 tinyint, c3 smallint, c4 real, c5 decimal)", create); //$NON-NLS-1$
+ }
+
+ @Test public void testXmlElement() throws Exception {
+ XMLElement f = new XMLElement("table", Arrays.asList((Expression)new Constant("x")));
+ helpTestExpression("xmlelement(name \"table\", 'x')", "XMLELEMENT(NAME \"table\", 'x')", f);
+ }
+
+ @Test public void testXmlElement1() throws Exception {
+ XMLElement f = new XMLElement("table", Arrays.asList((Expression)new Constant("x")));
+ helpTestExpression("xmlelement(\"table\", 'x')", "XMLELEMENT(NAME \"table\", 'x')", f);
+ }
+
+ @Test public void testXmlElementWithAttributes() throws Exception {
+ XMLElement f = new XMLElement("y", new ArrayList<Expression>());
+ f.setAttributes(new XMLAttributes(Arrays.asList(new DerivedColumn("val", new Constant("a")))));
+ helpTestExpression("xmlelement(y, xmlattributes('a' as val))", "XMLELEMENT(NAME y, XMLATTRIBUTES('a' AS val))", f);
+ }
+
+ @Test public void testXmlForest() throws Exception {
+ XMLForest f = new XMLForest(Arrays.asList(new DerivedColumn("table", new ElementSymbol("a"))));
+ helpTestExpression("xmlforest(a as \"table\")", "XMLFOREST(a AS \"table\")", f);
+ }
+
+ @Test public void testXmlPi() throws Exception {
+ Function f = new Function("xmlpi", new Expression[] {new Constant("a"), new ElementSymbol("val")});
+ helpTestExpression("xmlpi(NAME a, val)", "xmlpi(NAME a, val)", f);
+ }
+
+ @Test public void testXmlNamespaces() throws Exception {
+ XMLForest f = new XMLForest(Arrays.asList(new DerivedColumn("table", new ElementSymbol("a"))));
+ f.setNamespaces(new XMLNamespaces(Arrays.asList(new XMLNamespaces.NamespaceItem(), new XMLNamespaces.NamespaceItem("http://foo", "x"))));
+ helpTestExpression("xmlforest(xmlnamespaces(no default, 'http://foo' as x), a as \"table\")", "XMLFOREST(XMLNAMESPACES(NO DEFAULT, 'http://foo' AS x), a AS \"table\")", f);
+ }
+
+ @Test public void testXmlAggWithOrderBy() throws Exception {
+ String sql = "SELECT xmlAgg(1 order by e2)"; //$NON-NLS-1$
+ AggregateSymbol as = new AggregateSymbol("foo", Reserved.XMLAGG, false, new Constant(1));
+ as.setOrderBy(new OrderBy(Arrays.asList(new ElementSymbol("e2"))));
+ Query query = new Query();
+ query.setSelect(new Select(Arrays.asList(as)));
+ helpTest(sql, "SELECT XMLAGG(1 ORDER BY e2)", query);
+ }
+
+ @Test public void testTextAggWithOrderBy() throws Exception {
+ List<DerivedColumn> expressions = new ArrayList<DerivedColumn>();
+ expressions.add(new DerivedColumn("col1", new ElementSymbol("e1")));
+ expressions.add(new DerivedColumn("col2", new ElementSymbol("e2")));
+
+ TextLine tf = new TextLine();
+ tf.setExpressions(expressions);
+ tf.setDelimiter(new Character(','));
+ tf.setIncludeHeader(true);
+
+ AggregateSymbol as = new AggregateSymbol("foo", NonReserved.TEXTAGG, false, tf);
+ as.setOrderBy(new OrderBy(Arrays.asList(new ElementSymbol("e2"))));
+
+ Query query = new Query();
+ query.setSelect(new Select(Arrays.asList(as)));
+
+ String sql = "SELECT TextAgg(FOR e1 as col1, e2 as col2 delimiter ',' header order by e2)"; //$NON-NLS-1$
+ helpTest(sql, "SELECT TEXTAGG(FOR e1 AS col1, e2 AS col2 DELIMITER ',' HEADER ORDER BY e2)", query);
+ }
+
+ @Test public void testArrayAggWithOrderBy() throws Exception {
+ String sql = "SELECT array_agg(1 order by e2)"; //$NON-NLS-1$
+ AggregateSymbol as = new AggregateSymbol("foo", Reserved.ARRAY_AGG, false, new Constant(1));
+ as.setOrderBy(new OrderBy(Arrays.asList(new ElementSymbol("e2"))));
+ Query query = new Query();
+ query.setSelect(new Select(Arrays.asList(as)));
+ helpTest(sql, "SELECT ARRAY_AGG(1 ORDER BY e2)", query);
+ }
+
+ @Test public void testArrayAggWithIndexing() throws Exception {
+ String sql = "SELECT (array_agg(1))[1]"; //$NON-NLS-1$
+ AggregateSymbol as = new AggregateSymbol("foo", Reserved.ARRAY_AGG, false, new Constant(1));
+ ExpressionSymbol expr = new ExpressionSymbol("expr", new Function("array_get", new Expression[] {as, new Constant(1)}));
+ Query query = new Query();
+ query.setSelect(new Select(Arrays.asList(expr)));
+ helpTest(sql, "SELECT array_get(ARRAY_AGG(1), 1)", query);
+ }
+
+ @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())));
+ StoredProcedure sp = new StoredProcedure();
+ sp.setProcedureName("foo");
+ SubqueryFromClause sfc = new SubqueryFromClause("x", sp);
+ sfc.setTable(true);
+ query.setFrom(new From(Arrays.asList(sfc)));
+ helpTest(sql, "SELECT * FROM TABLE(EXEC foo()) AS x", query);
+ }
+
+ @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())));
+ 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));
+ tt.setColumns(columns);
+ tt.setSkip(10);
+ tt.setName("x");
+ query.setFrom(new From(Arrays.asList(tt)));
+ helpTest(sql, "SELECT * FROM TEXTTABLE(file COLUMNS x string WIDTH 1, y date WIDTH 10 SKIP 10) AS x", query);
+
+ sql = "SELECT * from texttable(file columns x string, y date delimiter ',' escape '\"' header skip 10) as x"; //$NON-NLS-1$
+ tt.setDelimiter(',');
+ tt.setQuote('"');
+ tt.setEscape(true);
+ tt.setHeader(1);
+ for (TextColumn textColumn : columns) {
+ textColumn.setWidth(null);
+ }
+ helpTest(sql, "SELECT * FROM TEXTTABLE(file COLUMNS x string, y date DELIMITER ',' ESCAPE '\"' HEADER SKIP 10) AS x", query);
+ }
+
+ @Test public void testTextTableColumns() throws Exception {
+ helpException("SELECT * from texttable(foo x string)", "Parsing error: Expected non-reserved word [COLUMNS], but was x.");
+ }
+
+ @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())));
+ XMLTable xt = new XMLTable();
+ xt.setName("x");
+ xt.setNamespaces(new XMLNamespaces(Arrays.asList(new XMLNamespaces.NamespaceItem())));
+ xt.setXquery("/");
+ List<XMLTable.XMLColumn> columns = new ArrayList<XMLTable.XMLColumn>();
+ columns.add(new XMLTable.XMLColumn("x"));
+ columns.add(new XMLTable.XMLColumn("y", "date", "@date", new Constant(Date.valueOf("2000-01-01"))));
+ xt.setColumns(columns);
+ query.setFrom(new From(Arrays.asList(xt)));
+ helpTest(sql, "SELECT * FROM XMLTABLE(XMLNAMESPACES(NO DEFAULT), '/' COLUMNS x FOR ORDINALITY, y date DEFAULT {d'2000-01-01'} PATH '@date') AS x", query);
+ }
+
+ @Test public void testXmlSerialize() throws Exception {
+ XMLSerialize f = new XMLSerialize();
+ f.setDocument(true);
+ f.setExpression(new ElementSymbol("x"));
+ f.setTypeString("CLOB");
+ helpTestExpression("xmlserialize(document x as CLOB)", "XMLSERIALIZE(DOCUMENT x AS CLOB)", f);
+ }
+
+ @Test public void testXmlQuery() throws Exception {
+ XMLQuery f = new XMLQuery();
+ f.setXquery("/x");
+ f.setEmptyOnEmpty(false);
+ f.setPassing(Arrays.asList(new DerivedColumn(null, new ElementSymbol("foo"))));
+ helpTestExpression("xmlquery('/x' passing foo null on empty)", "XMLQUERY('/x' PASSING foo NULL ON EMPTY)", f);
+ }
+
+ @Test public void testXmlParse() throws Exception {
+ XMLParse f = new XMLParse();
+ f.setDocument(true);
+ f.setExpression(new ElementSymbol("x"));
+ f.setWellFormed(true);
+ helpTestExpression("xmlparse(document x wellformed)", "XMLPARSE(DOCUMENT x WELLFORMED)", f);
+ }
+
+ @Test public void testXmlSerialize1() throws Exception {
+ XMLSerialize f = new XMLSerialize();
+ f.setExpression(new ElementSymbol("x"));
+ f.setTypeString("CLOB");
+ helpTestExpression("xmlserialize(x as CLOB)", "XMLSERIALIZE(x AS CLOB)", f);
+ }
+
+ @Test public void testExpressionCriteria() throws Exception {
+ SearchedCaseExpression sce = new SearchedCaseExpression(Arrays.asList(new ExpressionCriteria(new ElementSymbol("x"))), Arrays.asList(new ElementSymbol("y")));
+ helpTestExpression("case when x then y end", "CASE WHEN x THEN y END", sce);
+ }
+
+ @Test public void testExpressionCriteria1() throws Exception {
+ SearchedCaseExpression sce = new SearchedCaseExpression(Arrays.asList(new NotCriteria(new ExpressionCriteria(new ElementSymbol("x")))), Arrays.asList(new ElementSymbol("y")));
+ helpTestExpression("case when not x then y end", "CASE WHEN NOT (x) THEN y END", sce);
+ }
+
+ @Test public void testWithClause() throws Exception {
+ Query query = getOrderByQuery(null);
+ query.setWith(Arrays.asList(new WithQueryCommand(new GroupSymbol("x"), null, getOrderByQuery(null))));
+ helpTest("WITH x AS (SELECT a FROM db.g WHERE b = aString) SELECT a FROM db.g WHERE b = aString", "WITH x AS (SELECT a FROM db.g WHERE b = aString) SELECT a FROM db.g WHERE b = aString", query); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testExplicitTable() throws Exception {
+ Query query = new Query();
+ Select select = new Select();
+ query.setSelect(select);
+ select.addSymbol(new AllSymbol());
+ From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("X"))));
+ query.setFrom(from);
+ helpTest("TABLE X", "SELECT * FROM X", query);
+ }
+
+ @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())));
+ ArrayTable tt = new ArrayTable();
+ tt.setArrayValue(new Constant(null, DataTypeManager.DefaultDataClasses.OBJECT));
+ List<TableFunctionReference.ProjectedColumn> columns = new ArrayList<TableFunctionReference.ProjectedColumn>();
+ columns.add(new TableFunctionReference.ProjectedColumn("x", "string"));
+ columns.add(new TableFunctionReference.ProjectedColumn("y", "date"));
+ tt.setColumns(columns);
+ tt.setName("x");
+ query.setFrom(new From(Arrays.asList(tt)));
+ helpTest(sql, "SELECT * FROM ARRAYTABLE(null COLUMNS x string, y date) AS x", query);
+ }
+
+ @Test public void testPositionalReference() throws Exception {
+ String sql = "select $1";
+ Query query = new Query();
+ query.setSelect(new Select(Arrays.asList(new ExpressionSymbol("foo", new Reference(0)))));
+ helpTest(sql, "SELECT ?", query);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,406 +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;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.TupleSource;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.events.EventDistributor;
-import org.teiid.logging.LogManager;
-import org.teiid.metadata.MetadataRepository;
-import org.teiid.query.eval.Evaluator;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataID;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.sql.lang.BatchedUpdateCommand;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.From;
-import org.teiid.query.sql.lang.Insert;
-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.TranslatableProcedureContainer;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.ElementSymbol;
-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.ReferenceCollectorVisitor;
-import org.teiid.query.util.CommandContext;
-
-
-public class FakeDataManager implements ProcessorDataManager {
- private Map tuples = new HashMap();
- private static final String LOG_CONTEXT = "FAKE_DATA_MANAGER"; //$NON-NLS-1$
-
- //used to test blocked exception. If true,
- //the first time nextTuple is called on FakeTupleSource,
- //it will throws BlockedExceptiom
- private boolean blockOnce;
-
- // ---- Cached code table stuff ----
-
- // upper table name + upper key col name + upper ret col name -> map of values
- private Map codeTableValues = new HashMap();
-
- // 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();
-
- // Track history to verify it later
- private List<String> queries = new ArrayList<String>();
- private boolean recordingCommands = true;
-
- /**
- * Return string form of all queries run against this FDM
- * @return List<String> recorded commands
- */
- public List<String> getQueries() {
- return this.queries;
- }
-
- /**
- * Clears the list of recorded commands and returns a copy
- * @return a copy of the recorded commands prior to clearing the list
- */
- public List<String> clearQueries() {
- List<String> rc = new ArrayList<String>(this.getQueries());
- this.queries.clear();
- return rc;
- }
-
- 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 {
-
- LogManager.logTrace(LOG_CONTEXT, new Object[]{"Register Request:", command, ",processorID:", context.getProcessorID(), ",model name:", modelName,",TupleSourceID nodeID:",new Integer(nodeID)}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-
- if (this.recordingCommands) {
- if (! (command instanceof BatchedUpdateCommand) ) {
- this.queries.add(command.toString());
- }
- }
-
- if (ReferenceCollectorVisitor.getReferences(command).size() > 0) {
- throw new IllegalArgumentException("Found references in the command registered with the DataManager."); //$NON-NLS-1$
- }
- // Get group ID from atomic command
- GroupSymbol group = null;
- if(command instanceof Query){
- group = getQueryGroup((Query)command);
- }else if(command instanceof SetQuery) {
- SetQuery union = (SetQuery) command;
- group = getQueryGroup(union.getProjectedQuery());
- } else if (command instanceof ProcedureContainer) {
- group = ((ProcedureContainer) command).getGroup();
- } else if ( command instanceof BatchedUpdateCommand ) {
- BatchedUpdateCommand buc = (BatchedUpdateCommand)command;
- if ( buc.getUpdateCommands().get(0) instanceof Update ) {
- group = ((Update)buc.getUpdateCommands().get(0)).getGroup();
- }
- if (this.recordingCommands) {
- for ( Iterator<Command> it = ((BatchedUpdateCommand) command).getUpdateCommands().iterator(); it.hasNext(); ) {
- this.queries.add(it.next().toString());
- }
- }
- }
-
- Object groupID = group.getMetadataID();
-
- Object[] tupleInfo = (Object[]) tuples.get(groupID);
- List elements = (List) tupleInfo[0];
- List[] tuples = (List[]) tupleInfo[1];
-
- List projectedSymbols = command.getProjectedSymbols();
- int[] columnMap = getColumnMap(elements, projectedSymbols);
-
- /*
- * updateCommands is used to hold a list of commands that
- * either came from a BatchedUpdateCommand or a signle
- * command from an Update command.
- */
- List<Command> updateCommands = new ArrayList<Command>();
-
- // Apply query criteria to tuples
- if(command instanceof Query){
- Query query = (Query)command;
- if(query.getCriteria() != null) {
- // 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);
- }
- for(int i=0; i<projectedSymbols.size(); i++) {
- Object element = projectedSymbols.get(i);
- mapElementToIndex(lookupMap, element, new Integer(columnMap[i]), group);
- }
-
- List filteredTuples = new ArrayList();
- for(int i=0; i<tuples.length; i++) {
- try {
- if(new Evaluator(lookupMap, null, null).evaluate(query.getCriteria(), tuples[i])) {
- filteredTuples.add(tuples[i]);
- }
- } catch(ExpressionEvaluationException e) {
- throw new TeiidComponentException(e, e.getMessage());
- }
- }
-
- tuples = new List[filteredTuples.size()];
- filteredTuples.toArray(tuples);
- }
- } else if ( command instanceof Insert || command instanceof Update || command instanceof Delete) {
- // add single update command to a list to be executed
- updateCommands.add(command);
- } else if ( command instanceof BatchedUpdateCommand ) {
- // add all update commands to a list to be executed
- updateCommands.addAll(((BatchedUpdateCommand) command).getUpdateCommands());
- }
-
- // if we had update commands added to the list, execute them now
- if ( updateCommands.size() > 0 ) {
- List<List<Integer>> filteredTuples = new ArrayList<List<Integer>>();
- for ( int c = 0; c < updateCommands.size(); c++ ) {
- Command cmd = updateCommands.get(c);
- if (cmd instanceof TranslatableProcedureContainer) {
- TranslatableProcedureContainer update = (TranslatableProcedureContainer)cmd;
- if ( update.getCriteria() != null ) {
- // 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);
- mapElementToIndex(lookupMap, element, new Integer(i), group);
- }
- for(int i=0; i<projectedSymbols.size(); i++) {
- Object element = projectedSymbols.get(i);
- mapElementToIndex(lookupMap, element, new Integer(columnMap[i]), group);
- }
-
- int updated = 0;
- for(int i=0; i<tuples.length; i++) {
- try {
- if(new Evaluator(lookupMap, null, null).evaluate(update.getCriteria(), tuples[i])) {
- updated++;
- }
- } catch(ExpressionEvaluationException e) {
- throw new TeiidComponentException(e, e.getMessage());
- }
- }
- List<Integer> updateTuple = new ArrayList<Integer>(1);
- updateTuple.add( new Integer(updated) );
- filteredTuples.add(updateTuple);
- }
- } else {
- filteredTuples.add(Arrays.asList(1)); //TODO: check for bulk
- }
- }
- tuples = new List[filteredTuples.size()];
- filteredTuples.toArray(tuples);
- elements = new ArrayList<Object>(projectedSymbols);
- columnMap[0] = 0;
- }
-
- FakeTupleSource ts= new FakeTupleSource(elements, tuples, projectedSymbols, columnMap);
- if(this.blockOnce){
- ts.setBlockOnce();
- }
- return ts;
- }
-
- private GroupSymbol getQueryGroup(Query query) throws TeiidComponentException {
- GroupSymbol group;
- From from = query.getFrom();
- List groups = from.getGroups();
- if(groups.size() != 1) {
- throw new TeiidComponentException("Cannot build fake tuple source for command: " + query); //$NON-NLS-1$
- }
- group = (GroupSymbol) groups.get(0);
- Iterator projSymbols = query.getSelect().getProjectedSymbols().iterator();
- while (projSymbols.hasNext()) {
- Object symbol = projSymbols.next();
- if (symbol instanceof ElementSymbol){
- ElementSymbol elementSymbol = (ElementSymbol)symbol;
- GroupSymbol g = elementSymbol.getGroupSymbol();
- if (!g.equals(group)){
- throw new TeiidComponentException("Illegal symbol " + elementSymbol + " in SELECT of command: " + query); //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (elementSymbol.getMetadataID() == null){
- throw new TeiidComponentException("Illegal null metadata ID in ElementSymbol " + elementSymbol + " in SELECT of command: " + query); //$NON-NLS-1$ //$NON-NLS-2$
- } else if (elementSymbol.getMetadataID() instanceof TempMetadataID){
- throw new TeiidComponentException("Illegal TempMetadataID in ElementSymbol " + elementSymbol + " in SELECT of command: " + query); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- }
- return group;
- }
-
- /**
- * @param lookupMap
- * @param element
- * @param integer
- * @param group
- */
- private void mapElementToIndex(Map lookupMap, Object element, Integer index, GroupSymbol group) {
- 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);
- }
- }
-
- // columnMap[expectedElementIndex] = allElementIndex
- private int[] getColumnMap(List allElements, List expectedElements) {
- int[] map = new int[expectedElements.size()];
-
- for(int i=0; i<expectedElements.size(); i++) {
- SingleElementSymbol symbol = (SingleElementSymbol) expectedElements.get(i);
-
- if (symbol instanceof AliasSymbol) {
- symbol = ((AliasSymbol)symbol).getSymbol();
- }
-
- String shortName = symbol.getShortName();
-
- // Find matching short name in all elements
- boolean foundMatch = false;
- for(int j=0; j<allElements.size(); j++) {
- SingleElementSymbol tupleSymbol = (SingleElementSymbol) allElements.get(j);
- if(tupleSymbol.getShortName().equalsIgnoreCase(shortName)) {
- map[i] = j;
- foundMatch = true;
- break;
- }
- }
-
- if(! foundMatch) {
- map[i] = -1;
- }
- }
-
- return map;
- }
-
-
- public void setThrowBlocked(boolean throwBlocked) {
- this.throwBlocked = throwBlocked;
- }
-
- public void defineCodeTable(String tableName, String keyCol, String retCol, Map values) {
- String key = tableName.toUpperCase() + keyCol.toUpperCase() + retCol.toUpperCase();
- this.codeTableValues.put(key, values);
- this.blockedState.put(key, Boolean.FALSE);
- }
-
- public Object lookupCodeValue(
- CommandContext context,
- String codeTableName,
- String returnElementName,
- String keyElementName,
- Object keyValue)
- throws BlockedException, TeiidComponentException {
-
- String tableKey = codeTableName.toUpperCase() + keyElementName.toUpperCase() + returnElementName.toUpperCase();
- if(! codeTableValues.containsKey(tableKey)) {
- throw new TeiidComponentException("Unknown code table: " + codeTableName); //$NON-NLS-1$
- }
-
- if(throwBlocked) {
- if(blockedState.get(tableKey).equals(Boolean.FALSE)) {
- blockedState.put(tableKey, Boolean.TRUE);
- throw BlockedException.INSTANCE;
- }
- }
-
- Map values = (Map) codeTableValues.get(tableKey);
- return values.get(keyValue);
- }
-
- public void setBlockOnce() {
- blockOnce = true;
- }
-
- /**
- * Are commands/queries that are registered with the data manager being
- * recorded?
- * <p>
- * Recorded commands can be retrieved by {@link #getQueries()}
- *
- * @return whether or not commands should be recorded
- */
- public boolean isRecordingCommands() {
- return recordingCommands;
- }
-
- /**
- * Indicate whether or not commands/queries registered with the data
- * manager are to be recorded in {@link #queries}.
- * <p>
- * Recorded commands can be retrieved by {@link #getQueries()}
- *
- * @param shouldRecord should commands be recorded?
- */
- public void setRecordingCommands(boolean shouldRecord) {
- this.recordingCommands = shouldRecord;
- }
-
- public void registerTuples(QueryMetadataInterface metadata, String groupName, List[] tuples) 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);
- }
-
- @Override
- public EventDistributor getEventDistributor() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public MetadataRepository getMetadataRepository() {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,416 @@
+/*
+ * 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 java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.TupleSource;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.events.EventDistributor;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.MetadataRepository;
+import org.teiid.query.eval.Evaluator;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataID;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.sql.lang.BatchedUpdateCommand;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.From;
+import org.teiid.query.sql.lang.Insert;
+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;
+import org.teiid.query.sql.symbol.ElementSymbol;
+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.ReferenceCollectorVisitor;
+import org.teiid.query.util.CommandContext;
+
+
+public class FakeDataManager implements ProcessorDataManager {
+ 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,
+ //the first time nextTuple is called on FakeTupleSource,
+ //it will throws BlockedExceptiom
+ private boolean blockOnce;
+
+ // ---- Cached code table stuff ----
+
+ // upper table name + upper key col name + upper ret col name -> map of values
+ 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<String, Boolean> blockedState = new HashMap<String, Boolean>();
+
+ // Track history to verify it later
+ private List<String> queries = new ArrayList<String>();
+ private boolean recordingCommands = true;
+
+ /**
+ * Return string form of all queries run against this FDM
+ * @return List<String> recorded commands
+ */
+ public List<String> getQueries() {
+ return this.queries;
+ }
+
+ /**
+ * Clears the list of recorded commands and returns a copy
+ * @return a copy of the recorded commands prior to clearing the list
+ */
+ public List<String> clearQueries() {
+ List<String> rc = new ArrayList<String>(this.getQueries());
+ this.queries.clear();
+ return rc;
+ }
+
+ public void registerProcTuples(String proc, List[] data) {
+ procTuples.put(proc, data);
+ }
+
+ public TupleSource registerRequest(CommandContext context, Command command, String modelName, String connectorBindingId, int nodeID, int limit)
+ throws TeiidComponentException {
+
+ LogManager.logTrace(LOG_CONTEXT, new Object[]{"Register Request:", command, ",processorID:", context.getProcessorID(), ",model name:", modelName,",TupleSourceID nodeID:",new Integer(nodeID)}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+
+ if (this.recordingCommands) {
+ if (! (command instanceof BatchedUpdateCommand) ) {
+ this.queries.add(command.toString());
+ }
+ }
+
+ if (ReferenceCollectorVisitor.getReferences(command).size() > 0) {
+ throw new IllegalArgumentException("Found references in the command registered with the DataManager."); //$NON-NLS-1$
+ }
+ // Get group ID from atomic command
+ GroupSymbol group = null;
+ if(command instanceof Query){
+ group = getQueryGroup((Query)command);
+ }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 ) {
+ BatchedUpdateCommand buc = (BatchedUpdateCommand)command;
+ if ( buc.getUpdateCommands().get(0) instanceof Update ) {
+ group = ((Update)buc.getUpdateCommands().get(0)).getGroup();
+ }
+ if (this.recordingCommands) {
+ for ( Iterator<Command> it = ((BatchedUpdateCommand) command).getUpdateCommands().iterator(); it.hasNext(); ) {
+ this.queries.add(it.next().toString());
+ }
+ }
+ }
+
+ Object[] tupleInfo = tuples.get(group.getNonCorrelationName().toUpperCase());
+ List<SingleElementSymbol> elements = (List) tupleInfo[0];
+ List[] tuples = (List[]) tupleInfo[1];
+
+ List<SingleElementSymbol> projectedSymbols = command.getProjectedSymbols();
+ int[] columnMap = getColumnMap(elements, projectedSymbols);
+
+ /*
+ * updateCommands is used to hold a list of commands that
+ * either came from a BatchedUpdateCommand or a signle
+ * command from an Update command.
+ */
+ List<Command> updateCommands = new ArrayList<Command>();
+
+ // Apply query criteria to tuples
+ if(command instanceof Query){
+ Query query = (Query)command;
+ if(query.getCriteria() != null) {
+ // 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++) {
+ SingleElementSymbol element = elements.get(i);
+ mapElementToIndex(lookupMap, element, i, group);
+ }
+ for(int i=0; i<projectedSymbols.size(); i++) {
+ SingleElementSymbol element = projectedSymbols.get(i);
+ mapElementToIndex(lookupMap, element, columnMap[i], group);
+ }
+
+ List filteredTuples = new ArrayList();
+ for(int i=0; i<tuples.length; i++) {
+ try {
+ if(new Evaluator(lookupMap, null, null).evaluate(query.getCriteria(), tuples[i])) {
+ filteredTuples.add(tuples[i]);
+ }
+ } catch(ExpressionEvaluationException e) {
+ throw new TeiidComponentException(e, e.getMessage());
+ }
+ }
+
+ tuples = new List[filteredTuples.size()];
+ filteredTuples.toArray(tuples);
+ }
+ } else if ( command instanceof Insert || command instanceof Update || command instanceof Delete) {
+ // add single update command to a list to be executed
+ updateCommands.add(command);
+ } else if ( command instanceof BatchedUpdateCommand ) {
+ // add all update commands to a list to be executed
+ updateCommands.addAll(((BatchedUpdateCommand) command).getUpdateCommands());
+ }
+
+ // if we had update commands added to the list, execute them now
+ if ( updateCommands.size() > 0 ) {
+ List<List<Integer>> filteredTuples = new ArrayList<List<Integer>>();
+ for ( int c = 0; c < updateCommands.size(); c++ ) {
+ Command cmd = updateCommands.get(c);
+ if (cmd instanceof TranslatableProcedureContainer) {
+ TranslatableProcedureContainer update = (TranslatableProcedureContainer)cmd;
+ if ( update.getCriteria() != null ) {
+ // 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++) {
+ SingleElementSymbol element = elements.get(i);
+ mapElementToIndex(lookupMap, element, new Integer(i), group);
+ }
+ for(int i=0; i<projectedSymbols.size(); i++) {
+ SingleElementSymbol element = projectedSymbols.get(i);
+ mapElementToIndex(lookupMap, element, new Integer(columnMap[i]), group);
+ }
+
+ int updated = 0;
+ for(int i=0; i<tuples.length; i++) {
+ try {
+ if(new Evaluator(lookupMap, null, null).evaluate(update.getCriteria(), tuples[i])) {
+ updated++;
+ }
+ } catch(ExpressionEvaluationException e) {
+ throw new TeiidComponentException(e, e.getMessage());
+ }
+ }
+ List<Integer> updateTuple = new ArrayList<Integer>(1);
+ updateTuple.add( new Integer(updated) );
+ filteredTuples.add(updateTuple);
+ }
+ } else {
+ filteredTuples.add(Arrays.asList(1)); //TODO: check for bulk
+ }
+ }
+ tuples = new List[filteredTuples.size()];
+ filteredTuples.toArray(tuples);
+ elements = new ArrayList<SingleElementSymbol>(projectedSymbols);
+ columnMap[0] = 0;
+ }
+
+ FakeTupleSource ts= new FakeTupleSource(elements, tuples, projectedSymbols, columnMap);
+ if(this.blockOnce){
+ ts.setBlockOnce();
+ }
+ return ts;
+ }
+
+ private GroupSymbol getQueryGroup(Query query) throws TeiidComponentException {
+ GroupSymbol group;
+ From from = query.getFrom();
+ List groups = from.getGroups();
+ if(groups.size() != 1) {
+ throw new TeiidComponentException("Cannot build fake tuple source for command: " + query); //$NON-NLS-1$
+ }
+ group = (GroupSymbol) groups.get(0);
+ Iterator projSymbols = query.getSelect().getProjectedSymbols().iterator();
+ while (projSymbols.hasNext()) {
+ Object symbol = projSymbols.next();
+ if (symbol instanceof ElementSymbol){
+ ElementSymbol elementSymbol = (ElementSymbol)symbol;
+ GroupSymbol g = elementSymbol.getGroupSymbol();
+ if (!g.equals(group)){
+ throw new TeiidComponentException("Illegal symbol " + elementSymbol + " in SELECT of command: " + query); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ if (elementSymbol.getMetadataID() == null){
+ throw new TeiidComponentException("Illegal null metadata ID in ElementSymbol " + elementSymbol + " in SELECT of command: " + query); //$NON-NLS-1$ //$NON-NLS-2$
+ } else if (elementSymbol.getMetadataID() instanceof TempMetadataID){
+ throw new TeiidComponentException("Illegal TempMetadataID in ElementSymbol " + elementSymbol + " in SELECT of command: " + query); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+ }
+ return group;
+ }
+
+ /**
+ * @param lookupMap
+ * @param element
+ * @param integer
+ * @param 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.clone();
+ elementSymbol.getGroupSymbol().setName(groupAlias);
+ }
+ lookupMap.put(elementSymbol, index);
+ }
+
+ // columnMap[expectedElementIndex] = allElementIndex
+ private int[] getColumnMap(List allElements, List expectedElements) {
+ int[] map = new int[expectedElements.size()];
+
+ for(int i=0; i<expectedElements.size(); i++) {
+ SingleElementSymbol symbol = (SingleElementSymbol) expectedElements.get(i);
+
+ if (symbol instanceof AliasSymbol) {
+ symbol = ((AliasSymbol)symbol).getSymbol();
+ }
+
+ String shortName = symbol.getShortName();
+
+ // Find matching short name in all elements
+ boolean foundMatch = false;
+ for(int j=0; j<allElements.size(); j++) {
+ SingleElementSymbol tupleSymbol = (SingleElementSymbol) allElements.get(j);
+ if(tupleSymbol.getShortName().equalsIgnoreCase(shortName)) {
+ map[i] = j;
+ foundMatch = true;
+ break;
+ }
+ }
+
+ if(! foundMatch) {
+ map[i] = -1;
+ }
+ }
+
+ return map;
+ }
+
+
+ public void setThrowBlocked(boolean throwBlocked) {
+ this.throwBlocked = throwBlocked;
+ }
+
+ public void defineCodeTable(String tableName, String keyCol, String retCol, Map values) {
+ String key = tableName.toUpperCase() + keyCol.toUpperCase() + retCol.toUpperCase();
+ this.codeTableValues.put(key, values);
+ this.blockedState.put(key, Boolean.FALSE);
+ }
+
+ public Object lookupCodeValue(
+ CommandContext context,
+ String codeTableName,
+ String returnElementName,
+ String keyElementName,
+ Object keyValue)
+ throws BlockedException, TeiidComponentException {
+
+ String tableKey = codeTableName.toUpperCase() + keyElementName.toUpperCase() + returnElementName.toUpperCase();
+ if(! codeTableValues.containsKey(tableKey)) {
+ throw new TeiidComponentException("Unknown code table: " + codeTableName); //$NON-NLS-1$
+ }
+
+ if(throwBlocked) {
+ if(blockedState.get(tableKey).equals(Boolean.FALSE)) {
+ blockedState.put(tableKey, Boolean.TRUE);
+ throw BlockedException.INSTANCE;
+ }
+ }
+
+ Map values = codeTableValues.get(tableKey);
+ return values.get(keyValue);
+ }
+
+ public void setBlockOnce() {
+ blockOnce = true;
+ }
+
+ /**
+ * Are commands/queries that are registered with the data manager being
+ * recorded?
+ * <p>
+ * Recorded commands can be retrieved by {@link #getQueries()}
+ *
+ * @return whether or not commands should be recorded
+ */
+ public boolean isRecordingCommands() {
+ return recordingCommands;
+ }
+
+ /**
+ * Indicate whether or not commands/queries registered with the data
+ * manager are to be recorded in {@link #queries}.
+ * <p>
+ * Recorded commands can be retrieved by {@link #getQueries()}
+ *
+ * @param shouldRecord should commands be recorded?
+ */
+ public void setRecordingCommands(boolean shouldRecord) {
+ this.recordingCommands = shouldRecord;
+ }
+
+ 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);
+ tuples.put(group.getName().toUpperCase(), new Object[] { elementSymbols, data });
+ }
+
+ @Override
+ public EventDistributor getEventDistributor() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public MetadataRepository getMetadataRepository() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,235 +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;
-
-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.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;
-
-
-
-/**
- * This is sample data go along with FakeMetaDataFactory and FakeDataManager
- */
- at 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 {
- 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);
-
- //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,
-
- 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$
- } );
- }
-
- 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[] {
- 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$
- } );
- }
-
- public static void sampleData2(FakeDataManager dataMgr) throws QueryMetadataException, TeiidComponentException {
- FakeMetadataFacade metadata = FakeMetadataFactory.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[] {
- 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 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[] {
- Arrays.asList(new Object[] {
- "a", new Integer(1), Boolean.TRUE, new Double(2.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] {
- "b", new Integer(0), Boolean.FALSE, new Double(0.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] {
- "b", new Integer(5), Boolean.TRUE, new Double(2.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] {
- "b", new Integer(2), Boolean.FALSE, null }), //$NON-NLS-1$
- Arrays.asList(new Object[] {
- "d", new Integer(2), Boolean.FALSE, new Double(1.0) }), //$NON-NLS-1$
- });
-
- // 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[] {
- 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 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[] {
- Arrays.asList(new Object[] {
- "a", new Integer(1), Boolean.TRUE, new Double(2.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] {
- "b", new Integer(0), Boolean.FALSE, new Double(0.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] {
- "b", new Integer(5), Boolean.TRUE, new Double(2.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] {
- "b", new Integer(2), Boolean.FALSE, null }), //$NON-NLS-1$
- Arrays.asList(new Object[] {
- "d", new Integer(2), Boolean.FALSE, new Double(1.0) }), //$NON-NLS-1$
- });
-
- // 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[] {
- 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$
- });
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,138 @@
+/*
+ * 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 java.util.Arrays;
+import java.util.List;
+
+import org.teiid.core.TeiidException;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.StoredProcedureInfo;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+/**
+ * This is sample data go along with FakeMetaDataFactory and FakeDataManager
+ */
+ at SuppressWarnings("nls")
+public class FakeDataStore {
+
+ 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);
+
+ //stored procedure pm1.sp1
+ StoredProcedureInfo procInfo = metadata.getStoredProcedureInfoForProcedure("pm1.sp1"); //$NON-NLS-1$
+ 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)}),
+ 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$
+ } );
+ }
+
+ public static void addTable(String name, FakeDataManager dataMgr,
+ 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 TeiidException {
+ TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+
+ 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[] {
+ "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 pm1.g2
+ 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[] {
+ "b", new Integer(0), Boolean.FALSE, new Double(0.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] {
+ "b", new Integer(5), Boolean.TRUE, new Double(2.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] {
+ "b", new Integer(2), Boolean.FALSE, null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] {
+ "d", new Integer(2), Boolean.FALSE, new Double(1.0) }), //$NON-NLS-1$
+ });
+
+ // Group pm2.g1
+ 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[] {
+ "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 pm2.g2
+ 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[] {
+ "b", new Integer(0), Boolean.FALSE, new Double(0.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] {
+ "b", new Integer(5), Boolean.TRUE, new Double(2.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] {
+ "b", new Integer(2), Boolean.FALSE, null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] {
+ "d", new Integer(2), Boolean.FALSE, new Double(1.0) }), //$NON-NLS-1$
+ });
+
+ // Group pm1.table1
+ 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[] {
+ "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$
+ });
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,353 +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;
-
-import static org.teiid.query.processor.TestProcessor.*;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Test;
-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.translator.SourceSystemFunctions;
-
- at SuppressWarnings("nls")
-public class TestAggregateProcessing {
-
- static void sampleDataBQT3(FakeDataManager dataMgr) throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- // Group bqt1.smalla
-
- List[] tuples = new List[20];
- for (int i = 0; i < tuples.length; i++) {
- tuples[i] = new ArrayList(17);
- tuples[i].add(new Integer(i));
- tuples[i].add("" + i); //$NON-NLS-1$
- tuples[i].add(new Integer(i + 1));
- for (int j = 0; j < 14; j++) {
- tuples[i].add(null);
- }
- }
-
- dataMgr.registerTuples(metadata, "bqt1.smalla", tuples); //$NON-NLS-1$
-
- tuples = new List[20];
- for (int i = 0; i < tuples.length; i++) {
- tuples[i] = new ArrayList(17);
- tuples[i].add(new Integer(i));
- for (int j = 0; j < 16; j++) {
- tuples[i].add(null);
- }
- }
-
- dataMgr.registerTuples(metadata, "bqt2.mediumb", tuples); //$NON-NLS-1$
- }
-
- private void sampleDataBQT_defect9842(FakeDataManager dataMgr) throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- List[] tuples = new List[5];
- for (int i = 0; i < tuples.length; i++) {
- int k = i + 10;
- tuples[i] = new ArrayList(17);
- if (i < 2) {
- tuples[i].add(new Integer(1)); // need duplicate values
- } else {
- tuples[i].add(new Integer(2)); // need duplicate values
- }
- tuples[i].add("" + k); //$NON-NLS-1$
- tuples[i].add(new Integer(k + 1));
- tuples[i].add("" + (k + 1)); //$NON-NLS-1$
- tuples[i].add(new Float(0.5));
- for (int j = 0; j < 8; j++) {
- tuples[i].add(null);
- }
- tuples[i].add(new Short((short) k));
- tuples[i].add(null);
- tuples[i].add(new BigDecimal("" + k)); //$NON-NLS-1$
- tuples[i].add(null);
- }
-
- dataMgr.registerTuples(metadata, "bqt1.smalla", tuples); //$NON-NLS-1$
- }
-
- @Test public void testAggregateOnBQT() throws Exception {
- // Create query
- String sql = "SELECT IntKey, SUM(IntNum) FROM BQT1.SmallA GROUP BY IntKey, IntNum HAVING IntNum > 10 ORDER BY IntKey"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(10), new Long(11) }),
- Arrays.asList(new Object[] { new Integer(11), new Long(12) }),
- Arrays.asList(new Object[] { new Integer(12), new Long(13) }),
- Arrays.asList(new Object[] { new Integer(13), new Long(14) }),
- Arrays.asList(new Object[] { new Integer(14), new Long(15) }),
- Arrays.asList(new Object[] { new Integer(15), new Long(16) }),
- Arrays.asList(new Object[] { new Integer(16), new Long(17) }),
- Arrays.asList(new Object[] { new Integer(17), new Long(18) }),
- Arrays.asList(new Object[] { new Integer(18), new Long(19) }),
- Arrays.asList(new Object[] { new Integer(19), new Long(20) }) };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT3(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory
- .exampleBQTCached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testAggregateOnBQT2() throws Exception {
- // Create query
- String sql = "SELECT IntNum, IsNotNull FROM (SELECT IntNum, LongNum, COUNT(IntNum) AS IsNotNull FROM BQT1.SmallA GROUP BY IntNum, LongNum HAVING LongNum IS NULL ) AS x ORDER BY IntNum, IsNotNull"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(6), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(7), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(8), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(9), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(12), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(13), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(14), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(15), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(16), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(17), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(18), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(19), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(20), new Integer(1) }) };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT3(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory
- .exampleBQTCached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testAggregateOnBQT_defect9842() throws Exception {
- // Create query
- String sql = "SELECT IntKey, SUM((BigDecimalValue)*(ShortValue)-(BigDecimalValue)*(ShortValue)*(FloatNum)) " + //$NON-NLS-1$
- "AS MySum FROM BQT1.SmallA GROUP BY IntKey ORDER BY IntKey"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1),
- new BigDecimal("110.5000000") }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(2),
- new BigDecimal("254.5000000") }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT_defect9842(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory
- .exampleBQTCached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCase186260() {
- /*
- * This case revealed that an expression like "COUNT( DISTINCT e1 )", where the type of e1 is
- * anything but integer, was not handled properly. We tried to use "integer" (the type of the
- * COUNT expression) to work with the e1 tuples.
- */
- // Create query
- String sql = "SELECT COUNT(DISTINCT pm1.g2.e1), COUNT(DISTINCT pm1.g3.e1) FROM pm1.g2, pm1.g3"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(3), new Integer(3) }),
- };
-
- // 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);
- }
-
- @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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- capFinder.addCapabilities("pm1", TestAggregatePushdown.getAggregateCapabilities()); //$NON-NLS-1$
- capFinder.addCapabilities("pm2", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
- HardcodedDataManager dataManager = new HardcodedDataManager();
-
- dataManager.addData("SELECT v_0.c_0, COUNT(v_0.c_1), 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$
- new List[] {
- Arrays.asList("a", Integer.valueOf(2), Integer.valueOf(1)), //$NON-NLS-1$
- });
- dataManager.addData("SELECT v_0.c_0, COUNT(v_0.c_1), 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", //$NON-NLS-1$
- new List[] {
- Arrays.asList("a", Integer.valueOf(3), Integer.valueOf(2)), //$NON-NLS-1$
- });
- dataManager.addData("SELECT g_0.e1, g_0.e2 FROM pm2.g1 AS g_0", //$NON-NLS-1$
- new List[] {
- Arrays.asList("a", Integer.valueOf(3)), //$NON-NLS-1$
- Arrays.asList("xyz", Integer.valueOf(4)), //$NON-NLS-1$
- Arrays.asList(null, Integer.valueOf(5)),
- });
-
- ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
-
- List[] expected = new List[] {
- Arrays.asList(null, Integer.valueOf(1), Integer.valueOf(5)),
- Arrays.asList("a", Integer.valueOf(6), Integer.valueOf(3)), //$NON-NLS-1$
- Arrays.asList("xyz", Integer.valueOf(1), Integer.valueOf(4)) //$NON-NLS-1$
- };
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testUnionAggregatePushdown() {
- Command command = helpParse("select count(*), max(e3) from (select e1, e2, e3 from pm1.g1 union all (select convert(e2, string) as a, e2, e3 from pm2.g2 order by a limit 10)) x group by e1, e2"); //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- capFinder.addCapabilities("pm1", TestAggregatePushdown.getAggregateCapabilities()); //$NON-NLS-1$
- BasicSourceCapabilities bac = TestAggregatePushdown.getAggregateCapabilities();
- bac.setFunctionSupport("convert", true); //$NON-NLS-1$
- 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$
- 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$
- new List[] {
- Arrays.asList("1", Integer.valueOf(1), Integer.valueOf(4), Boolean.FALSE), //$NON-NLS-1$
- });
-
- ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
-
- List[] expected = new List[] {
- Arrays.asList(Integer.valueOf(7), Boolean.TRUE),
- Arrays.asList(Integer.valueOf(2), Boolean.FALSE),
- };
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testPushDownOverUnionMixed1() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestAggregatePushdown.getAggregateCapabilities();
- caps.setFunctionSupport(SourceSystemFunctions.POWER, true);
- caps.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
- 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$
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData("SELECT g_0.e2 FROM pm1.g1 AS g_0", new List[] {Arrays.asList(1), Arrays.asList(2)});
- dataManager.addData("SELECT MAX(v_0.c_0), COUNT(*), COUNT(v_0.c_0), SUM(power(v_0.c_0, 2)), SUM(v_0.c_0) FROM (SELECT g_0.e2 AS c_0 FROM pm2.g2 AS g_0) AS v_0 HAVING COUNT(*) > 0", new List[] {Arrays.asList(5, 6, 4, BigInteger.valueOf(50l), 10l)});
-
- List[] expected = new List[] {
- Arrays.asList(5, 8, 2.1147629234082532, 5.366666666666666),
- };
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testBooleanAgg() {
- String sql = "select every(e3), any(e3) from pm1.g1"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(Boolean.FALSE, Boolean.TRUE),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testStatsFunctions() {
- String sql = "select stddev_pop(e2), var_samp(e2) from pm1.g1"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(1.0671873729054748, 1.3666666666666667),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testStatsFunctions1() {
- String sql = "select stddev_samp(e2), var_pop(e2) from (select 2 e2) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(null, 0.0),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,376 @@
+/*
+ * 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.processor.TestProcessor.*;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+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.RealMetadataFactory;
+import org.teiid.translator.SourceSystemFunctions;
+
+ at SuppressWarnings({"nls", "unchecked"})
+public class TestAggregateProcessing {
+
+ static void sampleDataBQT3(FakeDataManager dataMgr) throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ // Group bqt1.smalla
+
+ List[] tuples = new List[20];
+ for (int i = 0; i < tuples.length; i++) {
+ tuples[i] = new ArrayList(17);
+ tuples[i].add(new Integer(i));
+ tuples[i].add("" + i); //$NON-NLS-1$
+ tuples[i].add(new Integer(i + 1));
+ for (int j = 0; j < 14; j++) {
+ tuples[i].add(null);
+ }
+ }
+
+ dataMgr.registerTuples(metadata, "bqt1.smalla", tuples); //$NON-NLS-1$
+
+ tuples = new List[20];
+ for (int i = 0; i < tuples.length; i++) {
+ tuples[i] = new ArrayList(17);
+ tuples[i].add(new Integer(i));
+ for (int j = 0; j < 16; j++) {
+ tuples[i].add(null);
+ }
+ }
+
+ dataMgr.registerTuples(metadata, "bqt2.mediumb", tuples); //$NON-NLS-1$
+ }
+
+ private void sampleDataBQT_defect9842(FakeDataManager dataMgr) throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ List[] tuples = new List[5];
+ for (int i = 0; i < tuples.length; i++) {
+ int k = i + 10;
+ tuples[i] = new ArrayList(17);
+ if (i < 2) {
+ tuples[i].add(new Integer(1)); // need duplicate values
+ } else {
+ tuples[i].add(new Integer(2)); // need duplicate values
+ }
+ tuples[i].add("" + k); //$NON-NLS-1$
+ tuples[i].add(new Integer(k + 1));
+ tuples[i].add("" + (k + 1)); //$NON-NLS-1$
+ tuples[i].add(new Float(0.5));
+ for (int j = 0; j < 8; j++) {
+ tuples[i].add(null);
+ }
+ tuples[i].add(new Short((short) k));
+ tuples[i].add(null);
+ tuples[i].add(new BigDecimal("" + k)); //$NON-NLS-1$
+ tuples[i].add(null);
+ }
+
+ dataMgr.registerTuples(metadata, "bqt1.smalla", tuples); //$NON-NLS-1$
+ }
+
+ @Test public void testAggregateOnBQT() throws Exception {
+ // Create query
+ String sql = "SELECT IntKey, SUM(IntNum) FROM BQT1.SmallA GROUP BY IntKey, IntNum HAVING IntNum > 10 ORDER BY IntKey"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(10), new Long(11) }),
+ Arrays.asList(new Object[] { new Integer(11), new Long(12) }),
+ Arrays.asList(new Object[] { new Integer(12), new Long(13) }),
+ Arrays.asList(new Object[] { new Integer(13), new Long(14) }),
+ Arrays.asList(new Object[] { new Integer(14), new Long(15) }),
+ Arrays.asList(new Object[] { new Integer(15), new Long(16) }),
+ Arrays.asList(new Object[] { new Integer(16), new Long(17) }),
+ Arrays.asList(new Object[] { new Integer(17), new Long(18) }),
+ Arrays.asList(new Object[] { new Integer(18), new Long(19) }),
+ Arrays.asList(new Object[] { new Integer(19), new Long(20) }) };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT3(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory
+ .exampleBQTCached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testAggregateOnBQT2() throws Exception {
+ // Create query
+ String sql = "SELECT IntNum, IsNotNull FROM (SELECT IntNum, LongNum, COUNT(IntNum) AS IsNotNull FROM BQT1.SmallA GROUP BY IntNum, LongNum HAVING LongNum IS NULL ) AS x ORDER BY IntNum, IsNotNull"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(8), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(9), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(12), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(13), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(14), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(15), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(16), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(17), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(18), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(19), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(20), new Integer(1) }) };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT3(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory
+ .exampleBQTCached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testAggregateOnBQT_defect9842() throws Exception {
+ // Create query
+ String sql = "SELECT IntKey, SUM((BigDecimalValue)*(ShortValue)-(BigDecimalValue)*(ShortValue)*(FloatNum)) " + //$NON-NLS-1$
+ "AS MySum FROM BQT1.SmallA GROUP BY IntKey ORDER BY IntKey"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1),
+ new BigDecimal("110.5000000") }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(2),
+ new BigDecimal("254.5000000") }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT_defect9842(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory
+ .exampleBQTCached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCase186260() {
+ /*
+ * This case revealed that an expression like "COUNT( DISTINCT e1 )", where the type of e1 is
+ * anything but integer, was not handled properly. We tried to use "integer" (the type of the
+ * COUNT expression) to work with the e1 tuples.
+ */
+ // Create query
+ String sql = "SELECT COUNT(DISTINCT pm1.g2.e1), COUNT(DISTINCT pm1.g3.e1) FROM pm1.g2, pm1.g3"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(3), new Integer(3) }),
+ };
+
+ // 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 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$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ capFinder.addCapabilities("pm1", TestAggregatePushdown.getAggregateCapabilities()); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+
+ dataManager.addData("SELECT v_0.c_0, COUNT(v_0.c_1), 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$
+ new List[] {
+ Arrays.asList("a", Integer.valueOf(2), Integer.valueOf(1)), //$NON-NLS-1$
+ });
+ dataManager.addData("SELECT v_0.c_0, COUNT(v_0.c_1), 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", //$NON-NLS-1$
+ new List[] {
+ Arrays.asList("a", Integer.valueOf(3), Integer.valueOf(2)), //$NON-NLS-1$
+ });
+ dataManager.addData("SELECT g_0.e1, g_0.e2 FROM pm2.g1 AS g_0", //$NON-NLS-1$
+ new List[] {
+ Arrays.asList("a", Integer.valueOf(3)), //$NON-NLS-1$
+ Arrays.asList("xyz", Integer.valueOf(4)), //$NON-NLS-1$
+ Arrays.asList(null, Integer.valueOf(5)),
+ });
+
+ ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
+
+ List[] expected = new List[] {
+ Arrays.asList(null, Integer.valueOf(1), Integer.valueOf(5)),
+ Arrays.asList("a", Integer.valueOf(6), Integer.valueOf(3)), //$NON-NLS-1$
+ Arrays.asList("xyz", Integer.valueOf(1), Integer.valueOf(4)) //$NON-NLS-1$
+ };
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testUnionAggregatePushdown() {
+ Command command = helpParse("select count(*), max(e3) from (select e1, e2, e3 from pm1.g1 union all (select convert(e2, string) as a, e2, e3 from pm2.g2 order by a limit 10)) x group by e1, e2"); //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ capFinder.addCapabilities("pm1", TestAggregatePushdown.getAggregateCapabilities()); //$NON-NLS-1$
+ BasicSourceCapabilities bac = TestAggregatePushdown.getAggregateCapabilities();
+ bac.setFunctionSupport("convert", true); //$NON-NLS-1$
+ 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$
+ 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$
+ new List[] {
+ Arrays.asList("1", Integer.valueOf(1), Integer.valueOf(4), Boolean.FALSE), //$NON-NLS-1$
+ });
+
+ ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
+
+ List[] expected = new List[] {
+ Arrays.asList(Integer.valueOf(7), Boolean.TRUE),
+ Arrays.asList(Integer.valueOf(2), Boolean.FALSE),
+ };
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testPushDownOverUnionMixed1() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestAggregatePushdown.getAggregateCapabilities();
+ caps.setFunctionSupport(SourceSystemFunctions.POWER, true);
+ caps.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
+ 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"), 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)});
+ dataManager.addData("SELECT MAX(v_0.c_0), COUNT(*), COUNT(v_0.c_0), SUM(power(v_0.c_0, 2)), SUM(v_0.c_0) FROM (SELECT g_0.e2 AS c_0 FROM pm2.g2 AS g_0) AS v_0 HAVING COUNT(*) > 0", new List[] {Arrays.asList(5, 6, 4, BigInteger.valueOf(50l), 10l)});
+
+ List[] expected = new List[] {
+ Arrays.asList(5, 8, 2.1147629234082532, 5.366666666666666),
+ };
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testBooleanAgg() {
+ String sql = "select every(e3), any(e3) from pm1.g1"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(Boolean.FALSE, Boolean.TRUE),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testStatsFunctions() {
+ String sql = "select stddev_pop(e2), var_samp(e2) from pm1.g1"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(1.0671873729054748, 1.3666666666666667),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testStatsFunctions1() {
+ String sql = "select stddev_samp(e2), var_pop(e2) from (select 2 e2) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(null, 0.0),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ 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(1.0, null),
+ Arrays.asList(2.0, "aa"),
+ Arrays.asList(7.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);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,857 +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;
-
-import static org.junit.Assert.*;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-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.FakeCapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.processor.relational.JoinNode;
-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.util.CommandContext;
-
- at SuppressWarnings({"unchecked", "nls"})
-public class TestDependentJoins {
-
- /**
- * @param sql
- * @return
- */
- static ProcessorPlan helpGetPlan(String sql) {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(2));
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false); //fake data manager doesn't support order by
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
-
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(TestProcessor.helpParse(sql),
- FakeMetadataFactory.example1Cached(),
- capFinder);
- return plan;
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e1=pm2.g1.e1 AND pm1.g1.e2=pm2.g1.e2 */
- @Test public void testMultiCritDepJoin1() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e1=pm2.g1.e1 AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND pm1.g1.e2=pm2.g1.e2 */
- @Test public void testMultiCritDepJoin2() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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);
-
- ProcessorPlan plan = helpGetPlan(sql);
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND pm1.g1.e2=pm2.g1.e2 */
- @Test public void testMultiCritDepJoin3() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND pm1.g1.e2=pm2.g1.e2 */
- @Test public void testMultiCritDepJoin4() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND concat(pm1.g1.e1, 'a') = concat(pm2.g1.e1, 'a') AND pm1.g1.e2=pm2.g1.e2 */
- @Test public void testMultiCritDepJoin5() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE concat(pm1.g1.e1, 'a') = concat(pm2.g1.e1, 'a') AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testMultiCritDepJoin5a() {
- // Create query
- String sql = "SELECT X.e1 FROM pm1.g1 as X, pm2.g1 WHERE concat(X.e1, 'a') = concat(pm2.g1.e1, 'a') AND X.e2=pm2.g1.e2 order by x.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, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testMultiCritDepJoin5b() {
- //Create query
- String sql = "SELECT X.e1, X.e2 FROM pm1.g1 as X, pm2.g1 WHERE concat(X.e1, convert(X.e4, string)) = concat(pm2.g1.e1, convert(pm2.g1.e4, string)) AND X.e2=pm2.g1.e2 order by x.e1, x.e2 option makedep x"; //$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[] { "a", new Integer(0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(3) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(2) }), //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e1 = concat(pm2.g1.e1, '') AND pm1.g1.e2=pm2.g1.e2 */
- @Test public void testMultiCritDepJoin6() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e1 = concat(pm2.g1.e1, '') AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE concat(pm1.g1.e1, '') = pm2.g1.e1 AND pm1.g1.e2=pm2.g1.e2 */
- @Test public void testMultiCritDepJoin7() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE concat(pm1.g1.e1, '') = pm2.g1.e1 AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e1 = pm2.g1.e1 AND pm1.g1.e2 <> pm2.g1.e2 */
- @Test public void testMultiCritDepJoin8() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e1 = pm2.g1.e1 AND pm1.g1.e2 <> pm2.g1.e2 option makedep pm1.g1"; //$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$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql);
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e2 <> pm2.g1.e2 */
- @Test public void testMultiCritDepJoin9() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e2 <> pm2.g1.e2 option makedep pm1.g1"; //$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[] { null }),
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { null }),
- 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[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$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$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e3=pm2.g1.e3 AND pm1.g1.e2=pm2.g1.e2 AND pm2.g1.e1 = 'a' */
- @Test public void testMultiCritDepJoin10() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e3=pm2.g1.e3 AND pm1.g1.e2=pm2.g1.e2 AND pm2.g1.e1 = 'a' option makedep pm1.g1"; //$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$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testLargeSetInDepJoinWAccessPatternCausingSortNodeInsertCanHandleAlias() {
- helpTestDepAccessCausingSortNodeInsert(true);
- }
-
- @Test public void testLargeSetInDepJoinWAccessPatternCausingSortNodeInsertCannotHandleAlias() {
- helpTestDepAccessCausingSortNodeInsert(false);
- }
-
- public void helpTestDepAccessCausingSortNodeInsert(boolean accessNodeHandlesAliases) {
- String sql = "SELECT a.e1, b.e1, b.e2 FROM pm4.g1 a INNER JOIN pm1.g1 b ON a.e2=b.e2 AND a.e1 = b.e1 OPTION MAKEDEP a"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "aa ", "aa ", new Integer(0)}), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "bb ", "bb ", new Integer(1)}), //$NON-NLS-1$ //$NON-NLS-2$
- 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();
- depcaps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- depcaps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
- depcaps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- if(accessNodeHandlesAliases) {
- depcaps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- }
-
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
-
- capFinder.addCapabilities("pm4", depcaps); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // 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();
-
- Command command = TestProcessor.helpParse(sql);
- ProcessorPlan plan = TestProcessor.helpGetPlan(command, fakeMetadata, capFinder);
-
- //Verify a dependent join (not merge join) was used
- assertTrue(plan instanceof RelationalPlan);
- RelationalPlan relationalPlan = (RelationalPlan)plan;
- RelationalNode project = relationalPlan.getRootNode();
- RelationalNode join = project.getChildren()[0];
- assertTrue("Expected instance of JoinNode (for dep join) but got " + join.getClass(), join instanceof JoinNode); //$NON-NLS-1$
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCase5130() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- 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$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData("SELECT g_0.stringkey FROM bqt1.smallb AS g_0", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { "1t" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2" })}); //$NON-NLS-1$
- dataManager.addData("SELECT g_0.stringkey, g_0.intkey FROM bqt1.smalla AS g_0", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { "1", new Integer(1) })}); //$NON-NLS-1$
-
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1) }),
- };
-
- TestProcessor.helpProcess(plan, dataManager, expected);
-
- assertFalse(dataManager.getCommandHistory().contains("SELECT a.stringkey, a.intkey FROM bqt1.smalla AS a WHERE concat(a.stringkey, 't') IN ('1', '2')")); //$NON-NLS-1$
- }
-
- @Test public void testCase5130a() throws Exception {
- HardcodedDataManager dataManager = helpTestDependentJoin(false);
-
- assertFalse(dataManager.getCommandHistory().contains("SELECT a.stringkey, a.intkey FROM bqt2.smalla AS a WHERE (concat(a.stringkey, 't') IN ('1t', '2')) AND (a.intkey IN (1))")); //$NON-NLS-1$
- }
-
- @Test public void testUnlimitedIn() throws Exception {
- helpTestDependentJoin(true);
- }
-
- private HardcodedDataManager helpTestDependentJoin(boolean unlimitIn)
- throws TeiidComponentException, TeiidProcessingException {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
- if (unlimitIn) {
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, -1);
- }
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
- 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,
- 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[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 2, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData("SELECT g_0.stringkey, g_0.intkey FROM bqt2.smallb AS g_0", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { "1t", new Integer(1) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2t", new Integer(2) })}); //$NON-NLS-1$
- dataManager.addData("SELECT g_0.stringkey, g_0.intkey FROM bqt1.smalla AS g_0 WHERE g_0.intkey IN (1, 2)", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { "1", new Integer(1) })}); //$NON-NLS-1$
-
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1) }),
- };
-
- TestProcessor.helpProcess(plan, dataManager, expected);
- return dataManager;
- }
-
- static void sampleData4(FakeDataManager dataMgr) throws Exception {
- FakeMetadataFacade metadata = FakeMetadataFactory.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,
-
- 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$
- } );
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1, pm6.g1 WHERE pm1.g1.e1=pm6.g1.e1 OPTION MAKEDEP pm6.g1 */
- @Test public void testLargeSetInDepAccess() throws Exception {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm6.g1 WHERE pm1.g1.e1=pm6.g1.e1 OPTION MAKEDEP pm6.g1"; //$NON-NLS-1$
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData4(dataManager);
-
- // 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();
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities depcaps = new BasicSourceCapabilities();
- depcaps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- depcaps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
- depcaps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
-
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
-
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("pm6", depcaps); //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] {
- new String("b")})}; //$NON-NLS-1$
-
- Command command = TestProcessor.helpParse(sql);
- ProcessorPlan plan = TestProcessor.helpGetPlan(command, fakeMetadata, capFinder);
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testLargeSetInDepAccessMultiJoinCriteria() throws Exception {
- helpTestLargeSetInDepAccessMultiJoinCriteria(1, -1, 1, 2);
- }
-
- @Test public void testLargeSetInDepAccessMultiJoinCriteriaConcurrent() throws Exception {
- //allows concurrent
- helpTestLargeSetInDepAccessMultiJoinCriteria(1, -1, 4, 4);
- }
-
- @Test public void testLargeSetInDepAccessMultiJoinCriteriaCompound() throws Exception {
- //max predicates forces multiple queries
- helpTestLargeSetInDepAccessMultiJoinCriteria(1, 4, 3, 3);
- }
-
- @Test public void testLargeSetInDepAccessMultiJoinCriteriaCompoundAll() throws Exception {
- //max predicates allows a one shot
- helpTestLargeSetInDepAccessMultiJoinCriteria(1, 10, 2, 2);
- }
-
- /**
- * concurrentOpen will be minimum of 2 to gather the pm1 results.
- */
- public void helpTestLargeSetInDepAccessMultiJoinCriteria(int maxInSize, int maxPredicates, int maxConcurrency, int concurrentOpen) throws Exception {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM (pm1.g2 cross join pm1.g1) inner join pm2.g1 makedep ON pm1.g1.e1=pm2.g1.e1 AND pm1.g1.e2=pm2.g1.e2 AND pm1.g2.e4 = pm2.g1.e4 order by e1"; //$NON-NLS-1$
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // 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();
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities depcaps = new BasicSourceCapabilities();
- depcaps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- depcaps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, maxInSize);
- depcaps.setSourceProperty(Capability.MAX_DEPENDENT_PREDICATES, maxPredicates);
-
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
-
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("pm2", depcaps); //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("a"), //$NON-NLS-1$
- Arrays.asList("a"), //$NON-NLS-1$
- Arrays.asList("a"), //$NON-NLS-1$
- Arrays.asList("a"), //$NON-NLS-1$
- Arrays.asList("a"), //$NON-NLS-1$
- Arrays.asList("a"), //$NON-NLS-1$
- Arrays.asList("a"), //$NON-NLS-1$
- Arrays.asList("a"), //$NON-NLS-1$
- Arrays.asList("a"), //$NON-NLS-1$
- Arrays.asList("b"), //$NON-NLS-1$
- };
-
- Command command = TestProcessor.helpParse(sql);
- ProcessorPlan plan = TestProcessor.helpGetPlan(command, fakeMetadata, capFinder);
- TestOptimizer.checkAtomicQueries(new String[] {
- "SELECT pm1.g2.e4 FROM pm1.g2",
- "SELECT pm2.g1.e1, pm2.g1.e2, pm2.g1.e4 FROM pm2.g1 WHERE (pm2.g1.e1 IN (<dependent values>)) AND (pm2.g1.e2 IN (<dependent values>)) AND (pm2.g1.e4 IN (<dependent values>))",
- "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"
- }, plan);
- CommandContext cc = TestProcessor.createCommandContext();
- cc.setUserRequestSourceConcurrency(maxConcurrency);
- FakeTupleSource.resetStats();
- // Run query
- TestProcessor.helpProcess(plan, cc, dataManager, expected);
-
- assertEquals("Wrong number of concurrent source queries", concurrentOpen, FakeTupleSource.maxOpen);
- }
-
- @Test public void testLargeSetInDepAccessWithAccessPattern() {
- String sql = "SELECT a.e1, b.e1, b.e2 FROM pm4.g1 a INNER JOIN pm1.g1 b ON a.e1=b.e1 AND a.e2 = b.e2"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] {
- "aa ", "aa ", new Integer(0)}), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] {
- "bb ", "bb ", new Integer(1)}), //$NON-NLS-1$ //$NON-NLS-2$
- 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();
- depcaps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- depcaps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
- depcaps.setCapabilitySupport(Capability.CRITERIA_IN, true);
-
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
-
- capFinder.addCapabilities("pm4", depcaps); //$NON-NLS-1$
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade fakeMetadata = FakeMetadataFactory.example1Cached();
-
- Command command = TestProcessor.helpParse(sql);
- ProcessorPlan plan = TestProcessor.helpGetPlan(command, fakeMetadata, capFinder);
-
- //Verify a dependent join (not merge join) was used
- assertTrue(plan instanceof RelationalPlan);
- RelationalPlan relationalPlan = (RelationalPlan)plan;
- RelationalNode project = relationalPlan.getRootNode();
- RelationalNode join = project.getChildren()[0];
- assertTrue("Expected instance of JoinNode (for dep join) but got " + join.getClass(), join instanceof JoinNode); //$NON-NLS-1$
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1 AND pm1.g1.e2 = -100 OPTION MAKEDEP pm1.g2 */
- @Test public void testDependentNoRows() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1 AND pm1.g1.e2 = -100 OPTION MAKEDEP pm1.g2"; //$NON-NLS-1$
-
- // Create expected results
- 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());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT pm1.g1.e2, pm2.g1.e2 FROM pm1.g1, pm2.g1 WHERE (pm1.g1.e2+1)=pm2.g1.e2 OPTION MAKEDEP pm1.g2 */
- @Test public void testExpressionInDepJoin() {
- // Create query
- String sql = "SELECT pm1.g1.e2, pm2.g1.e2 FROM pm1.g1, pm2.g1 WHERE (pm1.g1.e2+1)=pm2.g1.e2 order by pm1.g1.e2, pm2.g1.e2 OPTION MAKEDEP pm2.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(3) })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Plan query
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
- 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);
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testDependentJoinBackoff() throws Exception {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm6.g1 WHERE pm1.g1.e1=pm6.g1.e1"; //$NON-NLS-1$
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData4(dataManager);
-
- FakeMetadataFacade fakeMetadata = FakeMetadataFactory.example1();
-
- FakeMetadataFactory.setCardinality("pm1.g1", 1, fakeMetadata);
- FakeMetadataFactory.setCardinality("pm6.g1", 1000, fakeMetadata);
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities depcaps = new BasicSourceCapabilities();
- depcaps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- depcaps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
- depcaps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
-
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
-
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("pm6", depcaps); //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] {
- new String("b")})}; //$NON-NLS-1$
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, fakeMetadata, new String[] {
- "SELECT pm6.g1.e1 FROM pm6.g1 WHERE pm6.g1.e1 IN (<dependent values>) ORDER BY pm6.g1.e1",
- "SELECT pm1.g1.e1 FROM pm1.g1"
- }, capFinder, ComparisonMode.EXACT_COMMAND_STRING);
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
-
- //note that the dependent join was not actually performed
- assertEquals(new HashSet<String>(Arrays.asList("SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm6.g1.e1 FROM pm6.g1 ORDER BY pm6.g1.e1")),
- new HashSet<String>(dataManager.getQueries()));
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,894 @@
+/*
+ * 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.junit.Assert.*;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+
+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;
+import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.processor.relational.JoinNode;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+ at SuppressWarnings({"unchecked", "nls"})
+public class TestDependentJoins {
+
+ /**
+ * @param sql
+ * @return
+ */
+ static ProcessorPlan helpGetPlan(String sql) {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(2));
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false); //fake data manager doesn't support order by
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(TestProcessor.helpParse(sql),
+ RealMetadataFactory.example1Cached(),
+ capFinder);
+ return plan;
+ }
+
+ /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e1=pm2.g1.e1 AND pm1.g1.e2=pm2.g1.e2 */
+ @Test public void testMultiCritDepJoin1() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e1=pm2.g1.e1 AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND pm1.g1.e2=pm2.g1.e2 */
+ @Test public void testMultiCritDepJoin2() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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);
+
+ ProcessorPlan plan = helpGetPlan(sql);
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND pm1.g1.e2=pm2.g1.e2 */
+ @Test public void testMultiCritDepJoin3() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND pm1.g1.e2=pm2.g1.e2 */
+ @Test public void testMultiCritDepJoin4() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm2.g1.e1=pm1.g1.e1 AND concat(pm1.g1.e1, 'a') = concat(pm2.g1.e1, 'a') AND pm1.g1.e2=pm2.g1.e2 */
+ @Test public void testMultiCritDepJoin5() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE concat(pm1.g1.e1, 'a') = concat(pm2.g1.e1, 'a') AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testMultiCritDepJoin5a() {
+ // Create query
+ String sql = "SELECT X.e1 FROM pm1.g1 as X, pm2.g1 WHERE concat(X.e1, 'a') = concat(pm2.g1.e1, 'a') AND X.e2=pm2.g1.e2 order by x.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());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testMultiCritDepJoin5b() {
+ //Create query
+ String sql = "SELECT X.e1, X.e2 FROM pm1.g1 as X, pm2.g1 WHERE concat(X.e1, convert(X.e4, string)) = concat(pm2.g1.e1, convert(pm2.g1.e4, string)) AND X.e2=pm2.g1.e2 order by x.e1, x.e2 option makedep x"; //$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[] { "a", new Integer(0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(3) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(2) }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e1 = concat(pm2.g1.e1, '') AND pm1.g1.e2=pm2.g1.e2 */
+ @Test public void testMultiCritDepJoin6() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e1 = concat(pm2.g1.e1, '') AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE concat(pm1.g1.e1, '') = pm2.g1.e1 AND pm1.g1.e2=pm2.g1.e2 */
+ @Test public void testMultiCritDepJoin7() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE concat(pm1.g1.e1, '') = pm2.g1.e1 AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1 option makedep pm1.g1"; //$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());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e1 = pm2.g1.e1 AND pm1.g1.e2 <> pm2.g1.e2 */
+ @Test public void testMultiCritDepJoin8() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e1 = pm2.g1.e1 AND pm1.g1.e2 <> pm2.g1.e2 option makedep pm1.g1"; //$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$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql);
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e2 <> pm2.g1.e2 */
+ @Test public void testMultiCritDepJoin9() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e2 <> pm2.g1.e2 option makedep pm1.g1"; //$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[] { null }),
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { null }),
+ 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[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$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$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e3=pm2.g1.e3 AND pm1.g1.e2=pm2.g1.e2 AND pm2.g1.e1 = 'a' */
+ @Test public void testMultiCritDepJoin10() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e3=pm2.g1.e3 AND pm1.g1.e2=pm2.g1.e2 AND pm2.g1.e1 = 'a' option makedep pm1.g1"; //$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$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testLargeSetInDepJoinWAccessPatternCausingSortNodeInsertCanHandleAlias() {
+ helpTestDepAccessCausingSortNodeInsert(true);
+ }
+
+ @Test public void testLargeSetInDepJoinWAccessPatternCausingSortNodeInsertCannotHandleAlias() {
+ helpTestDepAccessCausingSortNodeInsert(false);
+ }
+
+ public void helpTestDepAccessCausingSortNodeInsert(boolean accessNodeHandlesAliases) {
+ String sql = "SELECT a.e1, b.e1, b.e2 FROM pm4.g1 a INNER JOIN pm1.g1 b ON a.e2=b.e2 AND a.e1 = b.e1 OPTION MAKEDEP a"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "aa ", "aa ", new Integer(0)}), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "bb ", "bb ", new Integer(1)}), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "cc ", "cc ", new Integer(2)}) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities depcaps = new BasicSourceCapabilities();
+ depcaps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ depcaps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
+ depcaps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ if(accessNodeHandlesAliases) {
+ depcaps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ }
+
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+
+ capFinder.addCapabilities("pm4", depcaps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Slightly modify metadata to set max set size to just a few rows - this
+ // will allow us to test the dependent overflow case
+ QueryMetadataInterface fakeMetadata = RealMetadataFactory.example1Cached();
+
+ Command command = TestProcessor.helpParse(sql);
+ ProcessorPlan plan = TestProcessor.helpGetPlan(command, fakeMetadata, capFinder);
+
+ //Verify a dependent join (not merge join) was used
+ assertTrue(plan instanceof RelationalPlan);
+ RelationalPlan relationalPlan = (RelationalPlan)plan;
+ RelationalNode project = relationalPlan.getRootNode();
+ 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);
+ }
+
+ @Test public void testCase5130() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ 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, 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
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("SELECT g_0.stringkey FROM bqt1.smallb AS g_0", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { "1t" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2" })}); //$NON-NLS-1$
+ dataManager.addData("SELECT g_0.stringkey, g_0.intkey FROM bqt1.smalla AS g_0", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { "1", new Integer(1) })}); //$NON-NLS-1$
+
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1) }),
+ };
+
+ TestProcessor.helpProcess(plan, dataManager, expected);
+
+ assertFalse(dataManager.getCommandHistory().contains("SELECT a.stringkey, a.intkey FROM bqt1.smalla AS a WHERE concat(a.stringkey, 't') IN ('1', '2')")); //$NON-NLS-1$
+ }
+
+ @Test public void testCase5130a() throws Exception {
+ HardcodedDataManager dataManager = helpTestDependentJoin(false);
+
+ assertFalse(dataManager.getCommandHistory().contains("SELECT a.stringkey, a.intkey FROM bqt2.smalla AS a WHERE (concat(a.stringkey, 't') IN ('1t', '2')) AND (a.intkey IN (1))")); //$NON-NLS-1$
+ }
+
+ @Test public void testUnlimitedIn() throws Exception {
+ helpTestDependentJoin(true);
+ }
+
+ private HardcodedDataManager helpTestDependentJoin(boolean unlimitIn)
+ throws TeiidComponentException, TeiidProcessingException {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ if (unlimitIn) {
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, -1);
+ }
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ 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, 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[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 2, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("SELECT g_0.stringkey, g_0.intkey FROM bqt2.smallb AS g_0", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { "1t", new Integer(1) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2t", new Integer(2) })}); //$NON-NLS-1$
+ dataManager.addData("SELECT g_0.stringkey, g_0.intkey FROM bqt1.smalla AS g_0 WHERE g_0.intkey IN (1, 2)", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { "1", new Integer(1) })}); //$NON-NLS-1$
+
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1) }),
+ };
+
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ return dataManager;
+ }
+
+ static void sampleData4(FakeDataManager dataMgr) throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ 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[] { "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$
+ } );
+
+ dataMgr.registerTuples(
+ 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 */
+ @Test public void testLargeSetInDepAccess() throws Exception {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm6.g1 WHERE pm1.g1.e1=pm6.g1.e1 OPTION MAKEDEP pm6.g1"; //$NON-NLS-1$
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData4(dataManager);
+
+ // Slightly modify metadata to set max set size to just a few rows - this
+ // will allow us to test the dependent overflow case
+ QueryMetadataInterface fakeMetadata = RealMetadataFactory.example1Cached();
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities depcaps = new BasicSourceCapabilities();
+ depcaps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ depcaps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
+ depcaps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm6", depcaps); //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] {
+ new String("b")})}; //$NON-NLS-1$
+
+ Command command = TestProcessor.helpParse(sql);
+ ProcessorPlan plan = TestProcessor.helpGetPlan(command, fakeMetadata, capFinder);
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testLargeSetInDepAccessMultiJoinCriteria() throws Exception {
+ helpTestLargeSetInDepAccessMultiJoinCriteria(1, -1, 1, 2);
+ }
+
+ @Test public void testLargeSetInDepAccessMultiJoinCriteriaConcurrent() throws Exception {
+ //allows concurrent
+ helpTestLargeSetInDepAccessMultiJoinCriteria(1, -1, 4, 4);
+ }
+
+ @Test public void testLargeSetInDepAccessMultiJoinCriteriaCompound() throws Exception {
+ //max predicates forces multiple queries
+ helpTestLargeSetInDepAccessMultiJoinCriteria(1, 4, 3, 3);
+ }
+
+ @Test public void testLargeSetInDepAccessMultiJoinCriteriaCompoundAll() throws Exception {
+ //max predicates allows a one shot
+ helpTestLargeSetInDepAccessMultiJoinCriteria(1, 10, 2, 2);
+ }
+
+ /**
+ * concurrentOpen will be minimum of 2 to gather the pm1 results.
+ */
+ public void helpTestLargeSetInDepAccessMultiJoinCriteria(int maxInSize, int maxPredicates, int maxConcurrency, int concurrentOpen) throws Exception {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM (pm1.g2 cross join pm1.g1) inner join pm2.g1 makedep ON pm1.g1.e1=pm2.g1.e1 AND pm1.g1.e2=pm2.g1.e2 AND pm1.g2.e4 = pm2.g1.e4 order by e1"; //$NON-NLS-1$
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Slightly modify metadata to set max set size to just a few rows - this
+ // will allow us to test the dependent overflow case
+ QueryMetadataInterface fakeMetadata = RealMetadataFactory.example1Cached();
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities depcaps = new BasicSourceCapabilities();
+ depcaps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ depcaps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, maxInSize);
+ depcaps.setSourceProperty(Capability.MAX_DEPENDENT_PREDICATES, maxPredicates);
+
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", depcaps); //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("a"), //$NON-NLS-1$
+ Arrays.asList("a"), //$NON-NLS-1$
+ Arrays.asList("a"), //$NON-NLS-1$
+ Arrays.asList("a"), //$NON-NLS-1$
+ Arrays.asList("a"), //$NON-NLS-1$
+ Arrays.asList("a"), //$NON-NLS-1$
+ Arrays.asList("a"), //$NON-NLS-1$
+ Arrays.asList("a"), //$NON-NLS-1$
+ Arrays.asList("a"), //$NON-NLS-1$
+ Arrays.asList("b"), //$NON-NLS-1$
+ };
+
+ Command command = TestProcessor.helpParse(sql);
+ ProcessorPlan plan = TestProcessor.helpGetPlan(command, fakeMetadata, capFinder);
+ TestOptimizer.checkAtomicQueries(new String[] {
+ "SELECT pm1.g2.e4 FROM pm1.g2",
+ "SELECT pm2.g1.e1, pm2.g1.e2, pm2.g1.e4 FROM pm2.g1 WHERE (pm2.g1.e1 IN (<dependent values>)) AND (pm2.g1.e2 IN (<dependent values>)) AND (pm2.g1.e4 IN (<dependent values>))",
+ "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"
+ }, plan);
+ CommandContext cc = TestProcessor.createCommandContext();
+ cc.setUserRequestSourceConcurrency(maxConcurrency);
+ FakeTupleSource.resetStats();
+ // Run query
+ TestProcessor.helpProcess(plan, cc, dataManager, expected);
+
+ assertEquals("Wrong number of concurrent source queries", concurrentOpen, FakeTupleSource.maxOpen);
+ }
+
+ @Test public void testLargeSetInDepAccessWithAccessPattern() {
+ String sql = "SELECT a.e1, b.e1, b.e2 FROM pm4.g1 a INNER JOIN pm1.g1 b ON a.e1=b.e1 AND a.e2 = b.e2"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] {
+ "aa ", "aa ", new Integer(0)}), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] {
+ "bb ", "bb ", new Integer(1)}), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] {
+ "cc ", "cc ", new Integer(2)}) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities depcaps = new BasicSourceCapabilities();
+ depcaps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ depcaps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
+ depcaps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+
+ capFinder.addCapabilities("pm4", depcaps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface fakeMetadata = RealMetadataFactory.example1Cached();
+
+ Command command = TestProcessor.helpParse(sql);
+ ProcessorPlan plan = TestProcessor.helpGetPlan(command, fakeMetadata, capFinder);
+
+ //Verify a dependent join (not merge join) was used
+ assertTrue(plan instanceof RelationalPlan);
+ RelationalPlan relationalPlan = (RelationalPlan)plan;
+ RelationalNode project = relationalPlan.getRootNode();
+ 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);
+ }
+
+ /** SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1 AND pm1.g1.e2 = -100 OPTION MAKEDEP pm1.g2 */
+ @Test public void testDependentNoRows() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1 AND pm1.g1.e2 = -100 OPTION MAKEDEP pm1.g2"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT pm1.g1.e2, pm2.g1.e2 FROM pm1.g1, pm2.g1 WHERE (pm1.g1.e2+1)=pm2.g1.e2 OPTION MAKEDEP pm1.g2 */
+ @Test public void testExpressionInDepJoin() {
+ // Create query
+ String sql = "SELECT pm1.g1.e2, pm2.g1.e2 FROM pm1.g1, pm2.g1 WHERE (pm1.g1.e2+1)=pm2.g1.e2 order by pm1.g1.e2, pm2.g1.e2 OPTION MAKEDEP pm2.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(3) })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Plan query
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ Command command = TestProcessor.helpParse(sql);
+ ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testDependentJoinBackoff() throws Exception {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm6.g1 WHERE pm1.g1.e1=pm6.g1.e1"; //$NON-NLS-1$
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData4(dataManager);
+
+ QueryMetadataInterface fakeMetadata = RealMetadataFactory.example1();
+
+ RealMetadataFactory.setCardinality("pm1.g1", 1, fakeMetadata);
+ RealMetadataFactory.setCardinality("pm6.g1", 1000, fakeMetadata);
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities depcaps = new BasicSourceCapabilities();
+ depcaps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ depcaps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
+ depcaps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm6", depcaps); //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] {
+ new String("b")})}; //$NON-NLS-1$
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, fakeMetadata, new String[] {
+ "SELECT pm6.g1.e1 FROM pm6.g1 WHERE pm6.g1.e1 IN (<dependent values>) ORDER BY pm6.g1.e1",
+ "SELECT pm1.g1.e1 FROM pm1.g1"
+ }, capFinder, ComparisonMode.EXACT_COMMAND_STRING);
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+
+ //note that the dependent join was not actually performed
+ assertEquals(new HashSet<String>(Arrays.asList("SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm6.g1.e1 FROM pm6.g1 ORDER BY pm6.g1.e1")),
+ 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);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,408 +0,0 @@
-package org.teiid.query.processor;
-
-import static org.junit.Assert.*;
-import static org.teiid.query.processor.TestProcessor.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.core.types.DataTypeManager;
-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.translator.SourceSystemFunctions;
-
-
-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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.BATCHED_UPDATES, true);
- caps.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- List pm1g1e = FakeMetadataFactory.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);
-
- 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) })});
-
- String sql = "SELECT 1, convert(1, float), convert(1, float) INTO pm1.g1"; //$NON-NLS-1$
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1) }),
- };
-
- helpProcess(plan, dataManager, expected);
-
- BatchedUpdateCommand buc = (BatchedUpdateCommand)dataManager.getCommandHistory().iterator().next();
- Insert insert = (Insert)buc.getUpdateCommands().get(0);
-
- Constant value0 = (Constant)insert.getValues().get(0);
- Constant value1 = (Constant)insert.getValues().get(1);
-
- assertEquals(DataTypeManager.DefaultDataClasses.BIG_INTEGER, value0.getValue().getClass());
- assertEquals(DataTypeManager.DefaultDataClasses.FLOAT, value1.getValue().getClass());
- }
-
-
- @Test public void testSelectInto_Case5569a_BATCH_NO_BULK_NO() {
- boolean doBatching = false;
- boolean doBulkInsert = false;
- helpSelectInto_Case5569Processor( doBatching, doBulkInsert );
- }
-
- @Test public void testSelectInto_Case5569b_BATCH_YES_BULK_NO() {
- boolean doBatching = true;
- boolean doBulkInsert = false;
- helpSelectInto_Case5569Processor( doBatching, doBulkInsert );
- }
-
- @Test public void testSelectInto_Case5569c_BATCH_NO_BULK_YES() {
- boolean doBatching = false;
- boolean doBulkInsert = true;
- helpSelectInto_Case5569Processor( doBatching, doBulkInsert );
- }
-
- public void helpSelectInto_Case5569Processor( boolean doBatching, boolean doBulkInsert ) {
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
-
- caps.setCapabilitySupport(Capability.BATCHED_UPDATES, doBatching);
- caps.setCapabilitySupport(Capability.BULK_UPDATE, doBulkInsert);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
-
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
-
- dataManager.addData("SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { "1", new Integer(1), Boolean.FALSE, new Double(1)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2", new Integer(2), Boolean.TRUE, new Double(2) })}); //$NON-NLS-1$
-
- if (doBulkInsert) {
- dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES (?, ?, ?, ?)", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(2)})});
- }
- else
- if (doBatching) {
- dataManager.addData("BatchedUpdate{I,I}", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(2)})});
- } else {
- dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('1', 1, FALSE, 1.0)", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(1)})});
- dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('2', 2, TRUE, 2.0)", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(1)})});
- }
-
- String sql = "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 INTO pm1.g2 from pm1.g1"; //$NON-NLS-1$
-
- Command command = helpParse(sql);
-
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(2) }),
- };
-
- helpProcess(plan, dataManager, expected);
-
- // if not doBulkInsert and is doBatching,
- // check the command hist to ensure it contains the expected commands
- if ( !doBulkInsert && doBatching ) {
- BatchedUpdateCommand bu = (BatchedUpdateCommand)new ArrayList(dataManager.getCommandHistory()).get(1);
- assertEquals(2, bu.getUpdateCommands().size());
- assertEquals( "INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('1', 1, FALSE, 1.0)", bu.getUpdateCommands().get(0).toString() ); //$NON-NLS-1$
- assertEquals( "INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('2', 2, TRUE, 2.0)", bu.getUpdateCommands().get(1).toString() ); //$NON-NLS-1$
- }
- }
-
-
- @Test public void testSelectInto_Case5412a() {
-
- // 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$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.BULK_UPDATE, true);
- caps.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- List pm1g1e = FakeMetadataFactory.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);
-
- 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) })});
-
- String sql = "SELECT 1, convert(1, float) INTO pm1.g1"; //$NON-NLS-1$
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1) }),
- };
-
- helpProcess(plan, dataManager, expected);
- }
-
-
- @Test public void testSelectInto_Case5412b() {
-
- // 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$
-
- 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,
- 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);
-
- 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) })});
-
- String sql = "SELECT 1, convert(1, float) INTO pm1.g1"; //$NON-NLS-1$
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1) }),
- };
-
- helpProcess(plan, dataManager, expected);
-
- Insert insert = (Insert)dataManager.getCommandHistory().iterator().next();
-
- Constant value0 = (Constant)insert.getValues().get(0);
- Constant value1 = (Constant)insert.getValues().get(1);
-
- assertEquals(DataTypeManager.DefaultDataClasses.BIG_INTEGER, value0.getValue().getClass());
- assertEquals(DataTypeManager.DefaultDataClasses.FLOAT, value1.getValue().getClass());
- }
-
- @Test public void testInsertIntoWithSubquery_None() {
- helpInsertIntoWithSubquery( null );
- }
-
- @Test public void testInsertIntoWithSubquery_Batch() {
- helpInsertIntoWithSubquery( Capability.BATCHED_UPDATES );
- }
-
- @Test public void testInsertIntoWithSubquery_Bulk() {
- helpInsertIntoWithSubquery( Capability.BULK_UPDATE );
- }
-
- @Test public void testInsertIntoWithSubquery_Pushdown() {
- helpInsertIntoWithSubquery( Capability.INSERT_WITH_QUERYEXPRESSION );
- }
-
- public void helpInsertIntoWithSubquery( Capability cap ) {
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
-
- caps.setCapabilitySupport(cap, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
-
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
-
- dataManager.addData("SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { "1", new Integer(1), Boolean.FALSE, new Double(1)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2", new Integer(2), Boolean.TRUE, new Double(2) })}); //$NON-NLS-1$
-
- if (cap != null) {
- switch (cap) {
- case BULK_UPDATE:
- dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES (?, ?, ?, ?)", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(2)})});
- break;
- case BATCHED_UPDATES:
- dataManager.addData("BatchedUpdate{I,I}", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(2)})});
- break;
- case INSERT_WITH_QUERYEXPRESSION:
- dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(2)})});
- break;
- }
- } else {
- dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('1', 1, FALSE, 1.0)", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(1)})});
- dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('2', 2, TRUE, 2.0)", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(1)})});
- }
-
- String sql = "INSERT INTO pm1.g2 SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 from pm1.g1"; //$NON-NLS-1$
-
- Command command = helpParse(sql);
-
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(2) }),
- };
-
- helpProcess(plan, dataManager, expected);
-
- // if not doBulkInsert and is doBatching,
- // check the command hist to ensure it contains the expected commands
- if ( cap == Capability.BATCHED_UPDATES ) {
- BatchedUpdateCommand bu = (BatchedUpdateCommand)new ArrayList(dataManager.getCommandHistory()).get(1);
- assertEquals(2, bu.getUpdateCommands().size());
- assertEquals( "INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('1', 1, FALSE, 1.0)", bu.getUpdateCommands().get(0).toString() ); //$NON-NLS-1$
- assertEquals( "INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('2', 2, TRUE, 2.0)", bu.getUpdateCommands().get(1).toString() ); //$NON-NLS-1$
- }
- }
-
- @Test public void testInsertIntoWithSubquery2_BATCH_NO_BULK_NO() {
- boolean doBatching = false;
- boolean doBulkInsert = false;
- helpInsertIntoWithSubquery2( doBatching, doBulkInsert );
- }
-
- @Test public void testInsertIntoWithSubquery2_BATCH_YES_BULK_NO() {
- boolean doBatching = true;
- boolean doBulkInsert = false;
- helpInsertIntoWithSubquery2( doBatching, doBulkInsert );
- }
-
- @Test public void testInsertIntoWithSubquery2_BATCH_NO_BULK_YES() {
- boolean doBatching = false;
- boolean doBulkInsert = true;
- helpInsertIntoWithSubquery2( doBatching, doBulkInsert );
- }
-
- public void helpInsertIntoWithSubquery2( boolean doBatching, boolean doBulkInsert ) {
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
-
- caps.setCapabilitySupport(Capability.BATCHED_UPDATES, doBatching);
- caps.setCapabilitySupport(Capability.BULK_UPDATE, doBulkInsert);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
-
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
-
- dataManager.addData("SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { "1", new Integer(1), Boolean.FALSE, new Double(1)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2", new Integer(2), Boolean.TRUE, new Double(2) })}); //$NON-NLS-1$
-
- if (doBulkInsert) {
- dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES (?, ?, ?, ?)", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(2)})});
- }
- else
- if (doBatching) {
- dataManager.addData("BatchedUpdate{I,I}", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(2)})});
- } else {
- dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('1', 1, FALSE, 1.0)", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(1)})});
- dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('2', 2, TRUE, 2.0)", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(1)})});
- }
-
- String sql = "INSERT INTO pm1.g2 SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 from pm1.g1 UNION ALL SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 from pm1.g1"; //$NON-NLS-1$
-// String sql = "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 INTO pm1.g2 from pm1.g1"; //$NON-NLS-1$
-
- Command command = helpParse(sql);
-
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(4) }),
- };
-
- helpProcess(plan, dataManager, expected);
-
- // if not doBulkInsert and is doBatching,
- // check the command hist to ensure it contains the expected commands
- if ( !doBulkInsert && doBatching ) {
- BatchedUpdateCommand bu = (BatchedUpdateCommand)new ArrayList(dataManager.getCommandHistory()).get(2);
- assertEquals(2, bu.getUpdateCommands().size());
- assertEquals( "INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('1', 1, FALSE, 1.0)", bu.getUpdateCommands().get(0).toString() ); //$NON-NLS-1$
- assertEquals( "INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('2', 2, TRUE, 2.0)", bu.getUpdateCommands().get(1).toString() ); //$NON-NLS-1$
- }
- }
-
- @Test public void testInsertIntoVirtualWithQueryExpression() {
- String sql = "insert into vm1.g1 (e1, e2, e3, e4) select * from pm1.g1"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(6),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,394 @@
+package org.teiid.query.processor;
+
+import static org.junit.Assert.*;
+import static org.teiid.query.processor.TestProcessor.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+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.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.RealMetadataFactory;
+import org.teiid.translator.SourceSystemFunctions;
+
+ at SuppressWarnings("nls")
+public class TestInsertProcessing {
+
+ @Test public void testSelectIntoWithTypeConversion() {
+ 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();
+ caps.setCapabilitySupport(Capability.BATCHED_UPDATES, true);
+ caps.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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});
+
+ QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("BatchedUpdate{I}", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(1) })});
+
+ String sql = "SELECT 1, convert(1, float), convert(1, float) INTO pm1.g1"; //$NON-NLS-1$
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1) }),
+ };
+
+ helpProcess(plan, dataManager, expected);
+
+ BatchedUpdateCommand buc = (BatchedUpdateCommand)dataManager.getCommandHistory().iterator().next();
+ Insert insert = (Insert)buc.getUpdateCommands().get(0);
+
+ Constant value0 = (Constant)insert.getValues().get(0);
+ Constant value1 = (Constant)insert.getValues().get(1);
+
+ assertEquals(DataTypeManager.DefaultDataClasses.BIG_INTEGER, value0.getValue().getClass());
+ assertEquals(DataTypeManager.DefaultDataClasses.FLOAT, value1.getValue().getClass());
+ }
+
+
+ @Test public void testSelectInto_Case5569a_BATCH_NO_BULK_NO() {
+ boolean doBatching = false;
+ boolean doBulkInsert = false;
+ helpSelectInto_Case5569Processor( doBatching, doBulkInsert );
+ }
+
+ @Test public void testSelectInto_Case5569b_BATCH_YES_BULK_NO() {
+ boolean doBatching = true;
+ boolean doBulkInsert = false;
+ helpSelectInto_Case5569Processor( doBatching, doBulkInsert );
+ }
+
+ @Test public void testSelectInto_Case5569c_BATCH_NO_BULK_YES() {
+ boolean doBatching = false;
+ boolean doBulkInsert = true;
+ helpSelectInto_Case5569Processor( doBatching, doBulkInsert );
+ }
+
+ public void helpSelectInto_Case5569Processor( boolean doBatching, boolean doBulkInsert ) {
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+
+ caps.setCapabilitySupport(Capability.BATCHED_UPDATES, doBatching);
+ caps.setCapabilitySupport(Capability.BULK_UPDATE, doBulkInsert);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
+
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+
+ dataManager.addData("SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { "1", new Integer(1), Boolean.FALSE, new Double(1)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2", new Integer(2), Boolean.TRUE, new Double(2) })}); //$NON-NLS-1$
+
+ if (doBulkInsert) {
+ dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES (?, ?, ?, ?)", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(2)})});
+ }
+ else
+ if (doBatching) {
+ dataManager.addData("BatchedUpdate{I,I}", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(2)})});
+ } else {
+ dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('1', 1, FALSE, 1.0)", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(1)})});
+ dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('2', 2, TRUE, 2.0)", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(1)})});
+ }
+
+ String sql = "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 INTO pm1.g2 from pm1.g1"; //$NON-NLS-1$
+
+ Command command = helpParse(sql);
+
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(2) }),
+ };
+
+ helpProcess(plan, dataManager, expected);
+
+ // if not doBulkInsert and is doBatching,
+ // check the command hist to ensure it contains the expected commands
+ if ( !doBulkInsert && doBatching ) {
+ BatchedUpdateCommand bu = (BatchedUpdateCommand)new ArrayList(dataManager.getCommandHistory()).get(1);
+ assertEquals(2, bu.getUpdateCommands().size());
+ assertEquals( "INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('1', 1, FALSE, 1.0)", bu.getUpdateCommands().get(0).toString() ); //$NON-NLS-1$
+ assertEquals( "INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('2', 2, TRUE, 2.0)", bu.getUpdateCommands().get(1).toString() ); //$NON-NLS-1$
+ }
+ }
+
+
+ @Test public void testSelectInto_Case5412a() {
+ MetadataStore metadataStore = new MetadataStore();
+ // test setting BULK_INSERT capability to true
+ 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, true);
+ caps.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ RealMetadataFactory.createElements(pm1g1,
+ new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.FLOAT});
+
+ QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
+
+ 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) })});
+
+ String sql = "SELECT 1, convert(1, float) INTO pm1.g1"; //$NON-NLS-1$
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1) }),
+ };
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+
+ @Test public void testSelectInto_Case5412b() {
+ MetadataStore metadataStore = new MetadataStore();
+ // test setting BULK_INSERT capability to false
+ 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);
+ RealMetadataFactory.createElements(pm1g1,
+ new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.FLOAT});
+
+ QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
+
+ 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) })});
+
+ String sql = "SELECT 1, convert(1, float) INTO pm1.g1"; //$NON-NLS-1$
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1) }),
+ };
+
+ helpProcess(plan, dataManager, expected);
+
+ Insert insert = (Insert)dataManager.getCommandHistory().iterator().next();
+
+ Constant value0 = (Constant)insert.getValues().get(0);
+ Constant value1 = (Constant)insert.getValues().get(1);
+
+ assertEquals(DataTypeManager.DefaultDataClasses.BIG_INTEGER, value0.getValue().getClass());
+ assertEquals(DataTypeManager.DefaultDataClasses.FLOAT, value1.getValue().getClass());
+ }
+
+ @Test public void testInsertIntoWithSubquery_None() {
+ helpInsertIntoWithSubquery( null );
+ }
+
+ @Test public void testInsertIntoWithSubquery_Batch() {
+ helpInsertIntoWithSubquery( Capability.BATCHED_UPDATES );
+ }
+
+ @Test public void testInsertIntoWithSubquery_Bulk() {
+ helpInsertIntoWithSubquery( Capability.BULK_UPDATE );
+ }
+
+ @Test public void testInsertIntoWithSubquery_Pushdown() {
+ helpInsertIntoWithSubquery( Capability.INSERT_WITH_QUERYEXPRESSION );
+ }
+
+ public void helpInsertIntoWithSubquery( Capability cap ) {
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+
+ caps.setCapabilitySupport(cap, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
+
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+
+ dataManager.addData("SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { "1", new Integer(1), Boolean.FALSE, new Double(1)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2", new Integer(2), Boolean.TRUE, new Double(2) })}); //$NON-NLS-1$
+
+ if (cap != null) {
+ switch (cap) {
+ case BULK_UPDATE:
+ dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES (?, ?, ?, ?)", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(2)})});
+ break;
+ case BATCHED_UPDATES:
+ dataManager.addData("BatchedUpdate{I,I}", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(2)})});
+ break;
+ case INSERT_WITH_QUERYEXPRESSION:
+ dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(2)})});
+ break;
+ }
+ } else {
+ dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('1', 1, FALSE, 1.0)", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(1)})});
+ dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('2', 2, TRUE, 2.0)", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(1)})});
+ }
+
+ String sql = "INSERT INTO pm1.g2 SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 from pm1.g1"; //$NON-NLS-1$
+
+ Command command = helpParse(sql);
+
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(2) }),
+ };
+
+ helpProcess(plan, dataManager, expected);
+
+ // if not doBulkInsert and is doBatching,
+ // check the command hist to ensure it contains the expected commands
+ if ( cap == Capability.BATCHED_UPDATES ) {
+ BatchedUpdateCommand bu = (BatchedUpdateCommand)new ArrayList(dataManager.getCommandHistory()).get(1);
+ assertEquals(2, bu.getUpdateCommands().size());
+ assertEquals( "INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('1', 1, FALSE, 1.0)", bu.getUpdateCommands().get(0).toString() ); //$NON-NLS-1$
+ assertEquals( "INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('2', 2, TRUE, 2.0)", bu.getUpdateCommands().get(1).toString() ); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testInsertIntoWithSubquery2_BATCH_NO_BULK_NO() {
+ boolean doBatching = false;
+ boolean doBulkInsert = false;
+ helpInsertIntoWithSubquery2( doBatching, doBulkInsert );
+ }
+
+ @Test public void testInsertIntoWithSubquery2_BATCH_YES_BULK_NO() {
+ boolean doBatching = true;
+ boolean doBulkInsert = false;
+ helpInsertIntoWithSubquery2( doBatching, doBulkInsert );
+ }
+
+ @Test public void testInsertIntoWithSubquery2_BATCH_NO_BULK_YES() {
+ boolean doBatching = false;
+ boolean doBulkInsert = true;
+ helpInsertIntoWithSubquery2( doBatching, doBulkInsert );
+ }
+
+ public void helpInsertIntoWithSubquery2( boolean doBatching, boolean doBulkInsert ) {
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+
+ caps.setCapabilitySupport(Capability.BATCHED_UPDATES, doBatching);
+ caps.setCapabilitySupport(Capability.BULK_UPDATE, doBulkInsert);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
+
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+
+ dataManager.addData("SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { "1", new Integer(1), Boolean.FALSE, new Double(1)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2", new Integer(2), Boolean.TRUE, new Double(2) })}); //$NON-NLS-1$
+
+ if (doBulkInsert) {
+ dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES (?, ?, ?, ?)", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(2)})});
+ }
+ else
+ if (doBatching) {
+ dataManager.addData("BatchedUpdate{I,I}", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(2)})});
+ } else {
+ dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('1', 1, FALSE, 1.0)", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(1)})});
+ dataManager.addData("INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('2', 2, TRUE, 2.0)", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(1)})});
+ }
+
+ String sql = "INSERT INTO pm1.g2 SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 from pm1.g1 UNION ALL SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 from pm1.g1"; //$NON-NLS-1$
+// String sql = "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 INTO pm1.g2 from pm1.g1"; //$NON-NLS-1$
+
+ Command command = helpParse(sql);
+
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(4) }),
+ };
+
+ helpProcess(plan, dataManager, expected);
+
+ // if not doBulkInsert and is doBatching,
+ // check the command hist to ensure it contains the expected commands
+ if ( !doBulkInsert && doBatching ) {
+ BatchedUpdateCommand bu = (BatchedUpdateCommand)new ArrayList(dataManager.getCommandHistory()).get(2);
+ assertEquals(2, bu.getUpdateCommands().size());
+ assertEquals( "INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('1', 1, FALSE, 1.0)", bu.getUpdateCommands().get(0).toString() ); //$NON-NLS-1$
+ assertEquals( "INSERT INTO pm1.g2 (pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4) VALUES ('2', 2, TRUE, 2.0)", bu.getUpdateCommands().get(1).toString() ); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testInsertIntoVirtualWithQueryExpression() {
+ String sql = "insert into vm1.g1 (e1, e2, e3, e4) select * from pm1.g1"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(6),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,439 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright (C) 2009 Red Hat, Inc.
- * Licensed to Red Hat, Inc. under one or more contributor
- * license agreements. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * 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 java.util.Arrays;
-import java.util.List;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
-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 junit.framework.TestCase;
-
-
-/**
- * <p><code>TestCase</code> to cover processing of JOINs which use a scalar
- * function as a symbol or as part of the JOIN criteria.</p>
- *
- * <p>All tests should verify and validate that the scalar function's result
- * is being used appropriately from the pre-JOIN and post-JOIN aspect. Most
- * specifically, the results returned from the JOIN should match the expected
- * results defined in each test method.</p>
- * @since 6.0
- */
-public class TestJoinWithFunction extends TestCase {
-
- /**
- * <p>Test the use of a non-deterministic function on a user command that
- * performs a JOIN of two sources.</p>
- *
- * <p>The function should be executed on the result returned from the JOIN and
- * is expected to be executed for each row of the final result set.</p>
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- */
- public void testNonDeterministicPostJoin() throws QueryMetadataException, TeiidComponentException {
- // 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$
- // source query for other side of a JOIN
- String rightQuery = "SELECT pm2.g2.e1 as ID, pm2.g2.e2, pm2.g2.e3, pm2.g2.e4 " //$NON-NLS-1$
- + "FROM pm2.g2"; //$NON-NLS-1$
-
- // User Command
- /*
- * Return everything from the JOIN. RandomTop is the use of RAND() on
- * the user command and should result in unique random numbers for each
- * row in the JOINed output.
- */
- String sql = "SELECT l.ID, l.e2, l.e3, l.e4, r.ID, r.e2, r.e3, r.e4, RAND() AS RandomTop " + //$NON-NLS-1$
- "FROM (" + leftQuery + ") AS l, " + //$NON-NLS-1$ //$NON-NLS-2$
- "(" + rightQuery + ") AS r " + //$NON-NLS-1$ //$NON-NLS-2$
- "WHERE l.ID = r.ID"; //$NON-NLS-1$
-
- /*
- * Populate a List with our expected results. We can predict the return value
- * for RAND() because the TestProcessor.helpProcess() method seeds the random
- * number generator.
- */
- List<?>[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0), //$NON-NLS-1$
- new Boolean(false), new Double(2), "a", new Integer(1), //$NON-NLS-1$
- new Boolean(true), new Double(2.0), new Double(0.24053641567148587) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(0), //$NON-NLS-1$
- new Boolean(false), new Double(0.0), new Double(0.6374174253501083) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(5), //$NON-NLS-1$
- new Boolean(true), new Double(2.0), new Double(0.5504370051176339) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(2), //$NON-NLS-1$
- new Boolean(false), null, new Double(0.5975452777972018) }), };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- FakeDataStore.sampleData2(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- 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);
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /**
- * <p>Test the use of a non-deterministic function on a source command of a JOIN
- * defined by a user command that performs a JOIN of two sources.</p>
- *
- * <p>The function should be executed on the result that will be used for one side
- * of the JOIN. The function should only be executed for each row of the the result
- * set returned from the left-side of the JOIN which should result in the same return
- * value for multiple rows of the final result set after the JOIN is completed. For
- * example, if the left-side query is expected to return one row and the right-side
- * query will return three rows which match the JOIN criteria for the one row on the
- * left-side then the expected result should be that the function be executed once to
- * represent the one row from the left-side and the function's return value will be
- * repeated for each of the three post-JOINed results.</p>
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- */
- public void testNonDeterministicPreJoin() throws QueryMetadataException, TeiidComponentException {
- // 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$
- // source query for other side of a JOIN
- String rightQuery = "SELECT pm2.g2.e1 as ID, pm2.g2.e2, pm2.g2.e3, pm2.g2.e4 " //$NON-NLS-1$
- + "FROM pm2.g2"; //$NON-NLS-1$
-
- // User Command
- /*
- * Return everything from the JOIN. TopRandom is the use of RAND() on
- * the user command while RandomLeft is the use of RAND() within a
- * source node.
- */
- String sql = "SELECT l.ID, l.e2, l.e3, l.e4, r.ID, r.e2, r.e3, r.e4, l.RandomLeft " + //$NON-NLS-1$
- "FROM (" + leftQuery + ") AS l, " + //$NON-NLS-1$ //$NON-NLS-2$
- "(" + rightQuery + ") AS r " + //$NON-NLS-1$ //$NON-NLS-2$
- "WHERE l.ID = r.ID"; //$NON-NLS-1$
-
- /*
- * Populate a List with our expected results. We can predict the return value
- * for RAND() because the TestProcessor.helpProcess() method seeds the random
- * number generator.
- */
- List<?>[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0), //$NON-NLS-1$
- new Boolean(false), new Double(2), "a", new Integer(1), //$NON-NLS-1$
- new Boolean(true), new Double(2.0), new Double(0.24053641567148587) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(0), //$NON-NLS-1$
- new Boolean(false), new Double(0.0), new Double(0.6374174253501083) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(5), //$NON-NLS-1$
- new Boolean(true), new Double(2.0), new Double(0.6374174253501083) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(2), //$NON-NLS-1$
- new Boolean(false), null, new Double(0.6374174253501083) }),
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- FakeDataStore.sampleData2(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- 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);
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /**
- * <p>Test the use of a non-deterministic function on the sub-command of a user
- * command and the user command itself, which performs a JOIN of two sources.</p>
- *
- * <p>This test combines the PostJoin and PreJoin test cases.</p>
- * @see #testNonDeterministicPostJoin
- * @see #testNonDeterministicPreJoin
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- */
- public void testNonDeterministicPrePostJoin() throws TeiidComponentException, QueryMetadataException {
- // 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$
- // source query for other side of a JOIN
- String rightQuery = "SELECT pm2.g2.e1 as ID, pm2.g2.e2, pm2.g2.e3, pm2.g2.e4 " //$NON-NLS-1$
- + "FROM pm2.g2"; //$NON-NLS-1$
-
- // User Command
- /*
- * Return everything from the JOIN. TopRandom is the use of RAND() on
- * the user command while RandomLeft is the use of RAND() within a
- * source node.
- */
- String sql = "SELECT l.ID, l.e2, l.e3, l.e4, r.ID, r.e2, r.e3, r.e4, l.RandomLeft, RAND() AS RandomTop " + //$NON-NLS-1$
- "FROM (" + leftQuery + ") AS l, " + //$NON-NLS-1$ //$NON-NLS-2$
- "(" + rightQuery + ") AS r " + //$NON-NLS-1$ //$NON-NLS-2$
- "WHERE l.ID = r.ID"; //$NON-NLS-1$
-
- /*
- * Populate a List with our expected results. We can predict the return value
- * for RAND() because the TestProcessor.helpProcess() method seeds the random
- * number generator.
- */
- List<?>[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0), //$NON-NLS-1$
- new Boolean(false), new Double(2), "a", new Integer(1), //$NON-NLS-1$
- new Boolean(true), new Double(2.0), new Double(0.24053641567148587), new Double(0.5975452777972018) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(0), //$NON-NLS-1$
- new Boolean(false), new Double(0.0), new Double(0.6374174253501083), new Double(0.3332183994766498) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(5), //$NON-NLS-1$
- new Boolean(true), new Double(2.0), new Double(0.6374174253501083), new Double(0.3851891847407185) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(2), //$NON-NLS-1$
- new Boolean(false), null, new Double(0.6374174253501083), new Double(0.984841540199809) })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- FakeDataStore.sampleData2(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- 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);
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /**
- * <p>Test the use of a deterministic function on the user command which
- * performs a JOIN of two sources.</p>
- *
- * <p>The function should be executed prior to the JOIN being executed and should
- * result in the projected symbol becoming a constant.</p>
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- */
- public void testDeterministicPostJoin() throws TeiidComponentException, QueryMetadataException {
- // 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$
- // source query for other side of a JOIN
- String rightQuery = "SELECT pm2.g2.e1 as ID, pm2.g2.e2, pm2.g2.e3, pm2.g2.e4 " //$NON-NLS-1$
- + "FROM pm2.g2"; //$NON-NLS-1$
-
- // User Command
- /*
- * Return everything from the JOIN. SqrtTop is the use of SQRT(100) on
- * the user command and should result in 10 for each row in the JOINed
- * output.
- */
- String sql = "SELECT l.ID, l.e2, l.e3, l.e4, r.ID, r.e2, r.e3, r.e4, SQRT(100) AS SqrtTop " + //$NON-NLS-1$
- "FROM (" + leftQuery + ") AS l, " + //$NON-NLS-1$ //$NON-NLS-2$
- "(" + rightQuery + ") AS r " + //$NON-NLS-1$ //$NON-NLS-2$
- "WHERE l.ID = r.ID"; //$NON-NLS-1$
-
- /*
- * Populate a List with our expected results.
- */
- List<?>[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0), //$NON-NLS-1$
- new Boolean(false), new Double(2), "a", new Integer(1), //$NON-NLS-1$
- new Boolean(true), new Double(2.0), new Double(10) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(0), //$NON-NLS-1$
- new Boolean(false), new Double(0.0), new Double(10) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(5), //$NON-NLS-1$
- new Boolean(true), new Double(2.0), new Double(10) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(2), //$NON-NLS-1$
- new Boolean(false), null, new Double(10) }),
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- FakeDataStore.sampleData2(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- 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);
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /**
- * <p>The function should be executed prior to the JOIN being executed and should
- * result in the projected symbol becoming a constant.</p>
-
- * <p>Test the use of a deterministic function on the source command of a JOIN
- * defined by a user command which performs a JOIN of two sources.</p>
- *
- * <p>The function should be executed prior to the commands from either side of the
- * JOIN being executed and merged into user command prior to the JOIN actually being
- * executed.</p>
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- */
- public void testDeterministicPreJoin() throws QueryMetadataException, TeiidComponentException {
- // 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$
- // source query for other side of a JOIN
- String rightQuery = "SELECT pm2.g2.e1 as ID, pm2.g2.e2, pm2.g2.e3, pm2.g2.e4 " //$NON-NLS-1$
- + "FROM pm2.g2"; //$NON-NLS-1$
-
- // User Command
- /*
- * Return everything from the JOIN. SqrtLeft is the use of SQRT()
- * within a source node.
- */
- String sql = "SELECT l.ID, l.e2, l.e3, l.e4, r.ID, r.e2, r.e3, r.e4, l.SqrtLeft " + //$NON-NLS-1$
- "FROM (" + leftQuery + ") AS l, " + //$NON-NLS-1$ //$NON-NLS-2$
- "(" + rightQuery + ") AS r " + //$NON-NLS-1$ //$NON-NLS-2$
- "WHERE l.ID = r.ID"; //$NON-NLS-1$
-
- /*
- * Populate a List with our expected results.
- */
- List<?>[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0), //$NON-NLS-1$
- new Boolean(false), new Double(2), "a", new Integer(1), //$NON-NLS-1$
- new Boolean(true), new Double(2.0), new Double(10) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(0), //$NON-NLS-1$
- new Boolean(false), new Double(0.0), new Double(10) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(5), //$NON-NLS-1$
- new Boolean(true), new Double(2.0), new Double(10) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(2), //$NON-NLS-1$
- new Boolean(false), null, new Double(10) }),
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- FakeDataStore.sampleData2(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- 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);
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /**
- * <p>Test the use of a deterministic function on the sub-command of a user
- * command and the user command itself, which performs a JOIN of two sources.</p>
- *
- * <p>This test combines the PostJoin and PreJoin test cases.</p>
- * @throws TeiidComponentException
- * @throws QueryMetadataException
- * @see #testDeterministicPostJoin
- * @see #testDeterministicPreJoin
- */
- public void testDeterministicPrePostJoin() throws QueryMetadataException, TeiidComponentException {
- // 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$
- // sub-query for other side of a JOIN
- String rightQuery = "SELECT pm2.g2.e1 as ID, pm2.g2.e2, pm2.g2.e3, pm2.g2.e4 " //$NON-NLS-1$
- + "FROM pm2.g2"; //$NON-NLS-1$
-
- // User Command
- /*
- * Return everything from the JOIN. SqrtTop is the use of SQRT(100) on
- * the user command while SqrtLeft is the use of SQRT() within a
- * source node.
- */
- String sql = "SELECT l.ID, l.e2, l.e3, l.e4, r.ID, r.e2, r.e3, r.e4, l.SqrtLeft, SQRT(100) AS SqrtTop " + //$NON-NLS-1$
- "FROM (" + leftQuery + ") AS l, " + //$NON-NLS-1$ //$NON-NLS-2$
- "(" + rightQuery + ") AS r " + //$NON-NLS-1$ //$NON-NLS-2$
- "WHERE l.ID = r.ID"; //$NON-NLS-1$
-
- /*
- * Populate a List with our expected results.
- */
- List<?>[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0), //$NON-NLS-1$
- new Boolean(false), new Double(2), "a", new Integer(1), //$NON-NLS-1$
- new Boolean(true), new Double(2.0), new Double(10.0), new Double(10.0) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(0), //$NON-NLS-1$
- new Boolean(false), new Double(0.0), new Double(10.0), new Double(10.0) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(5), //$NON-NLS-1$
- new Boolean(true), new Double(2.0), new Double(10.0), new Double(10.0) }),
- Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
- new Boolean(true), null, "b", new Integer(2), //$NON-NLS-1$
- new Boolean(false), null, new Double(10.0), new Double(10.0) }),
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- FakeDataStore.sampleData2(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- 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);
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,439 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright (C) 2009 Red Hat, Inc.
+ * Licensed to Red Hat, Inc. under one or more contributor
+ * license agreements. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * 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 java.util.Arrays;
+import java.util.List;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
+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.RealMetadataFactory;
+
+import junit.framework.TestCase;
+
+
+/**
+ * <p><code>TestCase</code> to cover processing of JOINs which use a scalar
+ * function as a symbol or as part of the JOIN criteria.</p>
+ *
+ * <p>All tests should verify and validate that the scalar function's result
+ * is being used appropriately from the pre-JOIN and post-JOIN aspect. Most
+ * specifically, the results returned from the JOIN should match the expected
+ * results defined in each test method.</p>
+ * @since 6.0
+ */
+public class TestJoinWithFunction extends TestCase {
+
+ /**
+ * <p>Test the use of a non-deterministic function on a user command that
+ * performs a JOIN of two sources.</p>
+ *
+ * <p>The function should be executed on the result returned from the JOIN and
+ * is expected to be executed for each row of the final result set.</p>
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ */
+ 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$
+ // source query for other side of a JOIN
+ String rightQuery = "SELECT pm2.g2.e1 as ID, pm2.g2.e2, pm2.g2.e3, pm2.g2.e4 " //$NON-NLS-1$
+ + "FROM pm2.g2"; //$NON-NLS-1$
+
+ // User Command
+ /*
+ * Return everything from the JOIN. RandomTop is the use of RAND() on
+ * the user command and should result in unique random numbers for each
+ * row in the JOINed output.
+ */
+ String sql = "SELECT l.ID, l.e2, l.e3, l.e4, r.ID, r.e2, r.e3, r.e4, RAND() AS RandomTop " + //$NON-NLS-1$
+ "FROM (" + leftQuery + ") AS l, " + //$NON-NLS-1$ //$NON-NLS-2$
+ "(" + rightQuery + ") AS r " + //$NON-NLS-1$ //$NON-NLS-2$
+ "WHERE l.ID = r.ID"; //$NON-NLS-1$
+
+ /*
+ * Populate a List with our expected results. We can predict the return value
+ * for RAND() because the TestProcessor.helpProcess() method seeds the random
+ * number generator.
+ */
+ List<?>[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0), //$NON-NLS-1$
+ new Boolean(false), new Double(2), "a", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), new Double(2.0), new Double(0.24053641567148587) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(0), //$NON-NLS-1$
+ new Boolean(false), new Double(0.0), new Double(0.6374174253501083) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(5), //$NON-NLS-1$
+ new Boolean(true), new Double(2.0), new Double(0.5504370051176339) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(2), //$NON-NLS-1$
+ new Boolean(false), null, new Double(0.5975452777972018) }), };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ FakeDataStore.sampleData2(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+ Command command = TestProcessor.helpParse(sql);
+ ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * <p>Test the use of a non-deterministic function on a source command of a JOIN
+ * defined by a user command that performs a JOIN of two sources.</p>
+ *
+ * <p>The function should be executed on the result that will be used for one side
+ * of the JOIN. The function should only be executed for each row of the the result
+ * set returned from the left-side of the JOIN which should result in the same return
+ * value for multiple rows of the final result set after the JOIN is completed. For
+ * example, if the left-side query is expected to return one row and the right-side
+ * query will return three rows which match the JOIN criteria for the one row on the
+ * left-side then the expected result should be that the function be executed once to
+ * represent the one row from the left-side and the function's return value will be
+ * repeated for each of the three post-JOINed results.</p>
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ */
+ 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$
+ // source query for other side of a JOIN
+ String rightQuery = "SELECT pm2.g2.e1 as ID, pm2.g2.e2, pm2.g2.e3, pm2.g2.e4 " //$NON-NLS-1$
+ + "FROM pm2.g2"; //$NON-NLS-1$
+
+ // User Command
+ /*
+ * Return everything from the JOIN. TopRandom is the use of RAND() on
+ * the user command while RandomLeft is the use of RAND() within a
+ * source node.
+ */
+ String sql = "SELECT l.ID, l.e2, l.e3, l.e4, r.ID, r.e2, r.e3, r.e4, l.RandomLeft " + //$NON-NLS-1$
+ "FROM (" + leftQuery + ") AS l, " + //$NON-NLS-1$ //$NON-NLS-2$
+ "(" + rightQuery + ") AS r " + //$NON-NLS-1$ //$NON-NLS-2$
+ "WHERE l.ID = r.ID"; //$NON-NLS-1$
+
+ /*
+ * Populate a List with our expected results. We can predict the return value
+ * for RAND() because the TestProcessor.helpProcess() method seeds the random
+ * number generator.
+ */
+ List<?>[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0), //$NON-NLS-1$
+ new Boolean(false), new Double(2), "a", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), new Double(2.0), new Double(0.24053641567148587) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(0), //$NON-NLS-1$
+ new Boolean(false), new Double(0.0), new Double(0.6374174253501083) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(5), //$NON-NLS-1$
+ new Boolean(true), new Double(2.0), new Double(0.6374174253501083) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(2), //$NON-NLS-1$
+ new Boolean(false), null, new Double(0.6374174253501083) }),
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ FakeDataStore.sampleData2(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+ Command command = TestProcessor.helpParse(sql);
+ ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * <p>Test the use of a non-deterministic function on the sub-command of a user
+ * command and the user command itself, which performs a JOIN of two sources.</p>
+ *
+ * <p>This test combines the PostJoin and PreJoin test cases.</p>
+ * @see #testNonDeterministicPostJoin
+ * @see #testNonDeterministicPreJoin
+ * @throws TeiidComponentException
+ * @throws 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$
+ // source query for other side of a JOIN
+ String rightQuery = "SELECT pm2.g2.e1 as ID, pm2.g2.e2, pm2.g2.e3, pm2.g2.e4 " //$NON-NLS-1$
+ + "FROM pm2.g2"; //$NON-NLS-1$
+
+ // User Command
+ /*
+ * Return everything from the JOIN. TopRandom is the use of RAND() on
+ * the user command while RandomLeft is the use of RAND() within a
+ * source node.
+ */
+ String sql = "SELECT l.ID, l.e2, l.e3, l.e4, r.ID, r.e2, r.e3, r.e4, l.RandomLeft, RAND() AS RandomTop " + //$NON-NLS-1$
+ "FROM (" + leftQuery + ") AS l, " + //$NON-NLS-1$ //$NON-NLS-2$
+ "(" + rightQuery + ") AS r " + //$NON-NLS-1$ //$NON-NLS-2$
+ "WHERE l.ID = r.ID"; //$NON-NLS-1$
+
+ /*
+ * Populate a List with our expected results. We can predict the return value
+ * for RAND() because the TestProcessor.helpProcess() method seeds the random
+ * number generator.
+ */
+ List<?>[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0), //$NON-NLS-1$
+ new Boolean(false), new Double(2), "a", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), new Double(2.0), new Double(0.24053641567148587), new Double(0.5975452777972018) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(0), //$NON-NLS-1$
+ new Boolean(false), new Double(0.0), new Double(0.6374174253501083), new Double(0.3332183994766498) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(5), //$NON-NLS-1$
+ new Boolean(true), new Double(2.0), new Double(0.6374174253501083), new Double(0.3851891847407185) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(2), //$NON-NLS-1$
+ new Boolean(false), null, new Double(0.6374174253501083), new Double(0.984841540199809) })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ FakeDataStore.sampleData2(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+ Command command = TestProcessor.helpParse(sql);
+ ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * <p>Test the use of a deterministic function on the user command which
+ * performs a JOIN of two sources.</p>
+ *
+ * <p>The function should be executed prior to the JOIN being executed and should
+ * result in the projected symbol becoming a constant.</p>
+ * @throws TeiidComponentException
+ * @throws 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$
+ // source query for other side of a JOIN
+ String rightQuery = "SELECT pm2.g2.e1 as ID, pm2.g2.e2, pm2.g2.e3, pm2.g2.e4 " //$NON-NLS-1$
+ + "FROM pm2.g2"; //$NON-NLS-1$
+
+ // User Command
+ /*
+ * Return everything from the JOIN. SqrtTop is the use of SQRT(100) on
+ * the user command and should result in 10 for each row in the JOINed
+ * output.
+ */
+ String sql = "SELECT l.ID, l.e2, l.e3, l.e4, r.ID, r.e2, r.e3, r.e4, SQRT(100) AS SqrtTop " + //$NON-NLS-1$
+ "FROM (" + leftQuery + ") AS l, " + //$NON-NLS-1$ //$NON-NLS-2$
+ "(" + rightQuery + ") AS r " + //$NON-NLS-1$ //$NON-NLS-2$
+ "WHERE l.ID = r.ID"; //$NON-NLS-1$
+
+ /*
+ * Populate a List with our expected results.
+ */
+ List<?>[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0), //$NON-NLS-1$
+ new Boolean(false), new Double(2), "a", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), new Double(2.0), new Double(10) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(0), //$NON-NLS-1$
+ new Boolean(false), new Double(0.0), new Double(10) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(5), //$NON-NLS-1$
+ new Boolean(true), new Double(2.0), new Double(10) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(2), //$NON-NLS-1$
+ new Boolean(false), null, new Double(10) }),
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ FakeDataStore.sampleData2(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+ Command command = TestProcessor.helpParse(sql);
+ ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * <p>The function should be executed prior to the JOIN being executed and should
+ * result in the projected symbol becoming a constant.</p>
+
+ * <p>Test the use of a deterministic function on the source command of a JOIN
+ * defined by a user command which performs a JOIN of two sources.</p>
+ *
+ * <p>The function should be executed prior to the commands from either side of the
+ * JOIN being executed and merged into user command prior to the JOIN actually being
+ * executed.</p>
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ */
+ 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$
+ // source query for other side of a JOIN
+ String rightQuery = "SELECT pm2.g2.e1 as ID, pm2.g2.e2, pm2.g2.e3, pm2.g2.e4 " //$NON-NLS-1$
+ + "FROM pm2.g2"; //$NON-NLS-1$
+
+ // User Command
+ /*
+ * Return everything from the JOIN. SqrtLeft is the use of SQRT()
+ * within a source node.
+ */
+ String sql = "SELECT l.ID, l.e2, l.e3, l.e4, r.ID, r.e2, r.e3, r.e4, l.SqrtLeft " + //$NON-NLS-1$
+ "FROM (" + leftQuery + ") AS l, " + //$NON-NLS-1$ //$NON-NLS-2$
+ "(" + rightQuery + ") AS r " + //$NON-NLS-1$ //$NON-NLS-2$
+ "WHERE l.ID = r.ID"; //$NON-NLS-1$
+
+ /*
+ * Populate a List with our expected results.
+ */
+ List<?>[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0), //$NON-NLS-1$
+ new Boolean(false), new Double(2), "a", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), new Double(2.0), new Double(10) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(0), //$NON-NLS-1$
+ new Boolean(false), new Double(0.0), new Double(10) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(5), //$NON-NLS-1$
+ new Boolean(true), new Double(2.0), new Double(10) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(2), //$NON-NLS-1$
+ new Boolean(false), null, new Double(10) }),
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ FakeDataStore.sampleData2(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+ Command command = TestProcessor.helpParse(sql);
+ ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * <p>Test the use of a deterministic function on the sub-command of a user
+ * command and the user command itself, which performs a JOIN of two sources.</p>
+ *
+ * <p>This test combines the PostJoin and PreJoin test cases.</p>
+ * @throws TeiidComponentException
+ * @throws QueryMetadataException
+ * @see #testDeterministicPostJoin
+ * @see #testDeterministicPreJoin
+ */
+ 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$
+ // sub-query for other side of a JOIN
+ String rightQuery = "SELECT pm2.g2.e1 as ID, pm2.g2.e2, pm2.g2.e3, pm2.g2.e4 " //$NON-NLS-1$
+ + "FROM pm2.g2"; //$NON-NLS-1$
+
+ // User Command
+ /*
+ * Return everything from the JOIN. SqrtTop is the use of SQRT(100) on
+ * the user command while SqrtLeft is the use of SQRT() within a
+ * source node.
+ */
+ String sql = "SELECT l.ID, l.e2, l.e3, l.e4, r.ID, r.e2, r.e3, r.e4, l.SqrtLeft, SQRT(100) AS SqrtTop " + //$NON-NLS-1$
+ "FROM (" + leftQuery + ") AS l, " + //$NON-NLS-1$ //$NON-NLS-2$
+ "(" + rightQuery + ") AS r " + //$NON-NLS-1$ //$NON-NLS-2$
+ "WHERE l.ID = r.ID"; //$NON-NLS-1$
+
+ /*
+ * Populate a List with our expected results.
+ */
+ List<?>[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0), //$NON-NLS-1$
+ new Boolean(false), new Double(2), "a", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), new Double(2.0), new Double(10.0), new Double(10.0) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(0), //$NON-NLS-1$
+ new Boolean(false), new Double(0.0), new Double(10.0), new Double(10.0) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(5), //$NON-NLS-1$
+ new Boolean(true), new Double(2.0), new Double(10.0), new Double(10.0) }),
+ Arrays.asList(new Object[] { "b", new Integer(1), //$NON-NLS-1$
+ new Boolean(true), null, "b", new Integer(2), //$NON-NLS-1$
+ new Boolean(false), null, new Double(10.0), new Double(10.0) }),
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ FakeDataStore.sampleData2(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+ Command command = TestProcessor.helpParse(sql);
+ ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,492 +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;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
-
-public class TestOptionalJoins {
-
- @Test public void testOptionalJoinNode1() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, /* optional */ pm1.g2 where pm1.g1.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();
- TestProcessor.sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode2() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1, /* optional */ pm1.g2, pm1.g3 where pm1.g1.e1 = 'a' and pm1.g1.e1 = pm1.g3.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[] { "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$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode3() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- 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());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode4() {
- // Create query
- String sql = "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"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- 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());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode5() {
- // Create query
- String sql = "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"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null }),
- 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[] { "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, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode6() {
- // Create query
- String sql = "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"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null }),
- 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[] { "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, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode7() {
- // Create query
- String sql = "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"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- 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());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode8() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ (select * from pm1.g2) as X on pm1.g1.e1 = x.e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- 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());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode9() {
- // Create query
- String sql = "SELECT pm1.g2.e1 FROM pm1.g2, /* optional */ vm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- 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());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode10() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM /* optional */ vm1.g1, pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- 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());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode11() {
- // Create query
- String sql = "SELECT pm1.g1.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ vm1.g2 on pm1.g1.e1 = vm1.g2.e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- 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());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode12() {
- // Create query
- String sql = "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"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- 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());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode13() {
- // Create query
- String sql = "SELECT count(pm1.g1.e1) FROM pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(5) })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode15() {
- // Create query
- String sql = "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"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- 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());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode16() {
- // Create query
- String sql = "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 order by x.e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null }),
- 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, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode17() {
- // Create query
- String sql = "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"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(5) }),
- Arrays.asList(new Object[] { new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(5) }),
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode18() {
- // Create query
- String sql = "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"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- 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());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOptionalJoinNode19() {
- // Create query
- String sql = "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"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(5) }),
- Arrays.asList(new Object[] { new Integer(5) }),
- Arrays.asList(new Object[] { new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(6) })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,492 @@
+/*
+ * 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 java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+
+public class TestOptionalJoins {
+
+ @Test public void testOptionalJoinNode1() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, /* optional */ pm1.g2 where pm1.g1.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();
+ TestProcessor.sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode2() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1, /* optional */ pm1.g2, pm1.g3 where pm1.g1.e1 = 'a' and pm1.g1.e1 = pm1.g3.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[] { "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$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode3() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode4() {
+ // Create query
+ String sql = "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"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode5() {
+ // Create query
+ String sql = "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"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null }),
+ 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[] { "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());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode6() {
+ // Create query
+ String sql = "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"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null }),
+ 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[] { "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());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode7() {
+ // Create query
+ String sql = "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"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode8() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ (select * from pm1.g2) as X on pm1.g1.e1 = x.e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode9() {
+ // Create query
+ String sql = "SELECT pm1.g2.e1 FROM pm1.g2, /* optional */ vm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode10() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM /* optional */ vm1.g1, pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode11() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ vm1.g2 on pm1.g1.e1 = vm1.g2.e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode12() {
+ // Create query
+ String sql = "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"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode13() {
+ // Create query
+ String sql = "SELECT count(pm1.g1.e1) FROM pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(5) })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode15() {
+ // Create query
+ String sql = "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"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode16() {
+ // Create query
+ String sql = "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 order by x.e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null }),
+ 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());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode17() {
+ // Create query
+ String sql = "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"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(5) }),
+ Arrays.asList(new Object[] { new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(5) }),
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode18() {
+ // Create query
+ String sql = "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"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOptionalJoinNode19() {
+ // Create query
+ String sql = "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"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(5) }),
+ Arrays.asList(new Object[] { new Integer(5) }),
+ Arrays.asList(new Object[] { new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(6) })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,202 +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;
-
-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.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.translator.ExecutionFactory.NullOrder;
-
- at SuppressWarnings({"nls", "unchecked"})
-public class TestOrderByProcessing {
-
- @Test public void testOrderByDescAll() {
- String sql = "SELECT distinct e1 from pm1.g2 order by e1 desc limit 1"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("c"),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOrderByOutsideOfSelect() {
- // Create query
- String sql = "SELECT e1 FROM (select e1, e2 || e3 as e2 from pm1.g2) x order by e2"; //$NON-NLS-1$
-
- //a, a, null, c, b, a
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList("a"),
- Arrays.asList("a"),
- Arrays.asList((String)null),
- Arrays.asList("c"),
- Arrays.asList("b"),
- Arrays.asList("a"),
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testOrderByUnrelatedExpression() {
- String sql = "SELECT e1, e2 + 1 from pm1.g2 order by e3 || e2 limit 1"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("a", 1),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
-
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * A control test to ensure that y will still exist for sorting
- */
- @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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata);
-
- List[] expected = new List[] {
- Arrays.asList(null, null),
- Arrays.asList("a", "a"), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList("a", "a"), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList("a", "a"), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList("b", "b"), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList("c", "c"), //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- @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();
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata);
-
- List[] expected = new List[] { Arrays.asList("a", null),
- Arrays.asList("a", null), //$NON-NLS-1$
- Arrays.asList("a", 7.0), //$NON-NLS-1$
- Arrays.asList("b", 0.0), //$NON-NLS-1$
- Arrays.asList("c", null), //$NON-NLS-1$
- Arrays.asList(null, 1.0),
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- @Test public void testNullOrdering() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY_NULL_ORDERING, true);
- 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,
- 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);
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testNullOrdering1() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY_NULL_ORDERING, true);
- caps.setSourceProperty(Capability.QUERY_ORDERBY_DEFAULT_NULL_ORDER, NullOrder.LAST);
- 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,
- 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);
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- @Test public void testNullOrdering2() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY_NULL_ORDERING, true);
- 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,
- 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);
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
- /**
- * The engine will remove the null ordering if it's not needed
- * @throws Exception
- */
- @Test public void testNullOrdering3() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setSourceProperty(Capability.QUERY_ORDERBY_DEFAULT_NULL_ORDER, NullOrder.HIGH);
- 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,
- 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);
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,202 @@
+/*
+ * 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.processor.TestProcessor.*;
+
+import java.util.Arrays;
+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.RealMetadataFactory;
+import org.teiid.translator.ExecutionFactory.NullOrder;
+
+ at SuppressWarnings({"nls", "unchecked"})
+public class TestOrderByProcessing {
+
+ @Test public void testOrderByDescAll() {
+ String sql = "SELECT distinct e1 from pm1.g2 order by e1 desc limit 1"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("c"),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOrderByOutsideOfSelect() {
+ // Create query
+ String sql = "SELECT e1 FROM (select e1, e2 || e3 as e2 from pm1.g2) x order by e2"; //$NON-NLS-1$
+
+ //a, a, null, c, b, a
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList("a"),
+ Arrays.asList("a"),
+ Arrays.asList((String)null),
+ Arrays.asList("c"),
+ Arrays.asList("b"),
+ Arrays.asList("a"),
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testOrderByUnrelatedExpression() {
+ String sql = "SELECT e1, e2 + 1 from pm1.g2 order by e3 || e2 limit 1"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("a", 1),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * A control test to ensure that y will still exist for sorting
+ */
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata);
+
+ List[] expected = new List[] {
+ Arrays.asList(null, null),
+ Arrays.asList("a", "a"), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList("a", "a"), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList("a", "a"), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList("b", "b"), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList("c", "c"), //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata);
+
+ List[] expected = new List[] { Arrays.asList("a", null),
+ Arrays.asList("a", null), //$NON-NLS-1$
+ Arrays.asList("a", 7.0), //$NON-NLS-1$
+ Arrays.asList("b", 0.0), //$NON-NLS-1$
+ Arrays.asList("c", null), //$NON-NLS-1$
+ Arrays.asList(null, 1.0),
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ @Test public void testNullOrdering() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY_NULL_ORDERING, true);
+ 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$
+ 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);
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testNullOrdering1() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY_NULL_ORDERING, true);
+ caps.setSourceProperty(Capability.QUERY_ORDERBY_DEFAULT_NULL_ORDER, NullOrder.LAST);
+ 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$
+ 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);
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ @Test public void testNullOrdering2() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY_NULL_ORDERING, true);
+ 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$
+ 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);
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+ /**
+ * The engine will remove the null ordering if it's not needed
+ * @throws Exception
+ */
+ @Test public void testNullOrdering3() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setSourceProperty(Capability.QUERY_ORDERBY_DEFAULT_NULL_ORDER, NullOrder.HIGH);
+ 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$
+ 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);
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,764 +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;
-
-import static org.junit.Assert.*;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.common.buffer.TupleSource;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.optimizer.TestOptimizer;
-import org.teiid.query.processor.proc.CreateCursorResultSetInstruction;
-import org.teiid.query.processor.proc.ProcedurePlan;
-import org.teiid.query.processor.proc.TestProcedureProcessor;
-import org.teiid.query.processor.relational.DependentProcedureExecutionNode;
-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.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.util.CommandContext;
-
-
-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[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @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[] {
- Arrays.asList(new Object[] { new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(0) }),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testProcAsTable(){
- 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[] {
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- //virtual group with procedure in transformation
- @Test public void testAliasedProcAsTable(){
- 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[] {
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testAliasedJoin(){
- 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[] {
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
-
- @Test public void testAliasedJoin1(){
- 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[] {
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Will fail due to access pattern validation (missing param2 assignment)
- */
- @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);
- }
-
- /**
- * Will fail since less than does not constitue an input
- */
- @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);
- }
-
- @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[] {
- 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$
- Arrays.asList(new Object[] { new Integer(2), "b", "b", new Integer(2)}), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { new Integer(3), "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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Will fail missing param2 assignment
- */
- @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);
- }
-
- /**
- * Will fail missing param2 assignment
- */
- @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);
- }
-
- @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[] {
- 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$
- Arrays.asList(new Object[] { new Integer(0), "a", new Integer(0)}), //$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(3)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(1), "c", new Integer(1)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(2), "b", new Integer(2)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(3), "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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testProcAsTableInSubquery(){
- 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[] {
- 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$
- 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(3), new Integer(1)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(0), "a", new Integer(3), new Integer(1)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(1), "c", new Integer(1), new Integer(1)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(2), "b", new Integer(2), new Integer(1)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(3), "a", new Integer(3), new Integer(1)}), //$NON-NLS-1$
- };
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- private void helpTestProcRelational(String userQuery,
- String inputCriteria,
- String atomicQuery) {
- ProcessorPlan plan = TestOptimizer.helpPlan(userQuery, FakeMetadataFactory.example1Cached(),
- new String[] {} );
-
- RelationalPlan rplan = (RelationalPlan)plan;
-
- RelationalNode root = rplan.getRootNode();
-
- while (root.getChildren() != null) {
- root = root.getChildren()[0];
-
- if (root instanceof DependentProcedureExecutionNode) {
- break;
- }
- }
-
- DependentProcedureExecutionNode dep = (DependentProcedureExecutionNode)root;
-
- assertEquals(inputCriteria, dep.getInputCriteria().toString());
-
- ProcedurePlan pp = (ProcedurePlan)dep.getProcessorPlan();
-
- CreateCursorResultSetInstruction ccrsi = (CreateCursorResultSetInstruction)pp.getOriginalProgram().getInstructionAt(0);
-
- plan = ccrsi.getCommand();
-
- TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
-
- TestOptimizer.checkAtomicQueries(new String[] {atomicQuery}, plan);
- }
-
- //virtual group with procedure in transaformation
- @Test public void testProcInVirtualGroup1() {
-
- 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$
-
- helpTestProcRelational(userQuery, inputCriteria, atomicQuery);
- }
-
- //virtual group with procedure in transformation
- @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$
-
- helpTestProcRelational(userQuery, inputCriteria, atomicQuery);
- }
-
- @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$
-
- helpTestProcRelational(userQuery, inputCriteria, atomicQuery);
- }
-
- @Test public void testProcAsVirtualGroup2(){
- 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[] {
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testProcAsVirtualGroup3(){
- 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[] {
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testProcAsVirtualGroup4(){
- 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[] {
- 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();
- TestProcessor.sampleData1(dataManager);
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testProcAsVirtualGroup5(){
- 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[] {
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testProcAsVirtualGroup6(){
- 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[] {
- 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();
- TestProcessor.sampleData1(dataManager);
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testProcAsVirtualGroup7(){
- 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[] {
- 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();
- TestProcessor.sampleData1(dataManager);
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testProcAsVirtualGroup10_Defect20164(){
- 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];
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testProcAsVirtualGroup8(){
- 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[] {
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- //virtual group with procedure in transformation
- @Test public void testProcAsVirtualGroup9(){
- 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[] {
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Relies upon a default value of null for param1
- *
- * This is marked as defered since it is not desirable to support this behavior for a single default value
- */
- public void defer_testProcAsVirtualGroup9a(){
- 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[] {
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Relies upon a default value of null for both parameters
- *
- * This is marked as defered since it is not desirable to support this behavior for a single default value
- */
- public void defer_testProcAsVirtualGroup9b(){
- 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[] {
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /**
- * test for defect 22376
- */
- @Test public void testParameterPassing() throws Exception {
- FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$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$
-
- 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$
-
- 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$
-
- 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[] {
- Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
- };
-
- FakeMetadataFacade metadata = new FakeMetadataFacade(store);
-
- // Construct data manager with data
- // Plan query
- ProcessorPlan plan = TestProcedureProcessor.getProcedurePlan(sql, metadata);
- // Run query
- TestProcedureProcessor.helpTestProcess(plan, expected, new FakeDataManager(), metadata);
-
- }
-
- //virtual group with procedure in transformation
- @Test public void testCase6395ProcAsVirtualGroup9(){
- 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[] {
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Case 6395 - This test case will now raise a QueryPlannerException. param2 is required
- * and not nullable. This case is expected to fail because of 'param2 is null'
- */
- @Test public void testProcAsVirtualGroup2WithNull() throws Exception {
- 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[] {
- };
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
- // Plan query
- try {
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
- // Run query
- TestProcessor.doProcess(plan, dataManager, expected, TestProcessor.createCommandContext());
- fail("QueryPlannerException was expected."); //$NON-NLS-1$
- } catch (QueryValidatorException e) {
- assertEquals("The procedure parameter pm1.vsp26.param2 is not nullable, but is set to null.",e.getMessage()); //$NON-NLS-1$
- }
- }
-
- /**
- * Case 6395 - This case is expected to succeed. param1 and param2 are both required, but nulls
- * are acceptable for both.
- */
- @Test public void testProcAsVirtualGroup2WithNull2() throws Exception {
- String sql = "select * from pm1.vsp47 where param1 is null and param2 is null"; //$NON-NLS-1$
-
- // Create expected results
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Case 6395 - This will not throw an exception and the proc will not be invoked.
- */
- @Test public void testProcAsVirtualGroup2WithNull3() throws Exception {
- 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[] {
- };
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- /*
- * The following are tests that were removed from the validator. We are no longer trying to validate a priori whether
- * procedure input criteria is valid. This can be addressed later more generally when we do up front validation of
- * 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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @Test public void testProcInVirtualGroup2_Defect20164() {
- helpFailProcedure("select ve3 from vm1.vgvp2 where ve1=1 or ve2='a'", FakeMetadataFactory.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$
- }
-
- @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$
- }
-
- @Test public void testProcInVirtualGroup5_Defect20164() {
- helpFailProcedure("select ve3 from vm1.vgvp2 where ve1=1 and NOT(ve2='a')", FakeMetadataFactory.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$
- }
-
- @Test public void testProcInVirtualGroup7_Defect20164() {
- helpFailProcedure("select ve3 from vm1.vgvp2 where ve1=1 and ve2 is not null", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
- }*/
-
- /**
- * Ensures that dependent procedures are processed 1 at a time so that projected input values
- * 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$
-
- 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$
-
- 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$
-
- 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);
-
- String sql = "select * from (exec v1.vp1(1)) foo order by e4, e5"; //$NON-NLS-1$
-
- List<?>[] expected = new List[] {
- Arrays.asList(1, 1, 3, 3, 5),
- Arrays.asList(1, 1, 3, 3, 8),
- Arrays.asList(1, 1, 6, 6, 8),
- Arrays.asList(1, 1, 6, 6, 11),
- };
-
- FakeMetadataFacade metadata = new FakeMetadataFacade(store);
-
- // Construct data manager with data
- // Plan query
- ProcessorPlan plan = TestProcedureProcessor.getProcedurePlan(sql, metadata);
- // Run query
- HardcodedDataManager dataManager = new HardcodedDataManager() {
- @Override
- public TupleSource registerRequest(CommandContext context,
- Command command, String modelName,
- String connectorBindingId, int nodeID, int limit)
- throws TeiidComponentException {
- if (command instanceof StoredProcedure) {
- StoredProcedure proc = (StoredProcedure)command;
- List<SPParameter> params = proc.getInputParameters();
- assertEquals(1, params.size());
- int value = (Integer)((Constant)params.get(0).getExpression()).getValue();
- return new FakeTupleSource(command.getProjectedSymbols(), new List[] {
- Arrays.asList(value+2), Arrays.asList(value+5)
- });
- }
- return super.registerRequest(context, command, modelName,
- connectorBindingId, nodeID, limit);
- }
- };
-
- TestProcedureProcessor.helpTestProcess(plan, expected, dataManager, metadata);
-
- }
-
- @Test public void testProcRelationalWithNoInputs() {
- String sql = "select e1 from pm1.vsp2 order by e1 desc limit 1"; //$NON-NLS-1$
-
- // Create expected results
- 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());
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,756 @@
+/*
+ * 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.junit.Assert.*;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.client.metadata.ParameterInfo;
+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;
+import org.teiid.query.processor.proc.TestProcedureProcessor;
+import org.teiid.query.processor.relational.DependentProcedureExecutionNode;
+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.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.symbol.Constant;
+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[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @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[] {
+ Arrays.asList(new Object[] { new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(0) }),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testProcAsTable(){
+ 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[] {
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ //virtual group with procedure in transformation
+ @Test public void testAliasedProcAsTable(){
+ 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[] {
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testAliasedJoin(){
+ 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[] {
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+
+ @Test public void testAliasedJoin1(){
+ 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[] {
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Will fail due to access pattern validation (missing param2 assignment)
+ */
+ @Test public void testProcAsTable1(){
+ String sql = "select param1, param2, e1, e2 from pm1.vsp26 where param1=1"; //$NON-NLS-1$
+
+ TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), null, false);
+ }
+
+ /**
+ * Will fail since less than does not constitue an input
+ */
+ @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, 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[] {
+ 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$
+ Arrays.asList(new Object[] { new Integer(2), "b", "b", new Integer(2)}), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { new Integer(3), "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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Will fail missing param2 assignment
+ */
+ @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, RealMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), null, false);
+ }
+
+ /**
+ * Will fail missing param2 assignment
+ */
+ @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, 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[] {
+ 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$
+ Arrays.asList(new Object[] { new Integer(0), "a", new Integer(0)}), //$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(3)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(1), "c", new Integer(1)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(2), "b", new Integer(2)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(3), "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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testProcAsTableInSubquery(){
+ 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[] {
+ 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$
+ 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(3), new Integer(1)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(0), "a", new Integer(3), new Integer(1)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(1), "c", new Integer(1), new Integer(1)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(2), "b", new Integer(2), new Integer(1)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(3), "a", new Integer(3), new Integer(1)}), //$NON-NLS-1$
+ };
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ private void helpTestProcRelational(String userQuery,
+ String inputCriteria,
+ String atomicQuery) {
+ ProcessorPlan plan = TestOptimizer.helpPlan(userQuery, RealMetadataFactory.example1Cached(),
+ new String[] {} );
+
+ RelationalPlan rplan = (RelationalPlan)plan;
+
+ RelationalNode root = rplan.getRootNode();
+
+ while (root.getChildren() != null) {
+ root = root.getChildren()[0];
+
+ if (root instanceof DependentProcedureExecutionNode) {
+ break;
+ }
+ }
+
+ DependentProcedureExecutionNode dep = (DependentProcedureExecutionNode)root;
+
+ assertEquals(inputCriteria, dep.getInputCriteria().toString());
+
+ ProcedurePlan pp = (ProcedurePlan)dep.getProcessorPlan();
+
+ CreateCursorResultSetInstruction ccrsi = (CreateCursorResultSetInstruction)pp.getOriginalProgram().getInstructionAt(0);
+
+ plan = ccrsi.getCommand();
+
+ TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
+
+ TestOptimizer.checkAtomicQueries(new String[] {atomicQuery}, plan);
+ }
+
+ //virtual group with procedure in transaformation
+ @Test public void testProcInVirtualGroup1() {
+
+ 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$
+
+ helpTestProcRelational(userQuery, inputCriteria, atomicQuery);
+ }
+
+ //virtual group with procedure in transformation
+ @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$
+
+ helpTestProcRelational(userQuery, inputCriteria, atomicQuery);
+ }
+
+ @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$
+
+ helpTestProcRelational(userQuery, inputCriteria, atomicQuery);
+ }
+
+ @Test public void testProcAsVirtualGroup2(){
+ 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[] {
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testProcAsVirtualGroup3(){
+ 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[] {
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testProcAsVirtualGroup4(){
+ 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[] {
+ 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();
+ TestProcessor.sampleData1(dataManager);
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testProcAsVirtualGroup5(){
+ 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[] {
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testProcAsVirtualGroup6(){
+ 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[] {
+ 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();
+ TestProcessor.sampleData1(dataManager);
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testProcAsVirtualGroup7(){
+ 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[] {
+ 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();
+ TestProcessor.sampleData1(dataManager);
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testProcAsVirtualGroup10_Defect20164(){
+ 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];
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testProcAsVirtualGroup8(){
+ 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[] {
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ //virtual group with procedure in transformation
+ @Test public void testProcAsVirtualGroup9(){
+ 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[] {
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Relies upon a default value of null for param1
+ *
+ * This is marked as defered since it is not desirable to support this behavior for a single default value
+ */
+ public void defer_testProcAsVirtualGroup9a(){
+ 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[] {
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Relies upon a default value of null for both parameters
+ *
+ * This is marked as defered since it is not desirable to support this behavior for a single default value
+ */
+ public void defer_testProcAsVirtualGroup9b(){
+ 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[] {
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * test for defect 22376
+ */
+ @Test public void testParameterPassing() throws Exception {
+ MetadataStore metadataStore = new MetadataStore();
+ Schema v1 = RealMetadataFactory.createVirtualModel("v1", metadataStore); //$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$
+ Procedure vt1 = RealMetadataFactory.createVirtualProcedure("vp1", v1, null, n1); //$NON-NLS-1$
+ vt1.setResultSet(rs1);
+
+ 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 }));
+
+ String sql = "select * from (exec v1.vp1()) foo"; //$NON-NLS-1$
+
+ List<?>[] expected = new List[] {
+ Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
+ };
+
+ QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
+
+ // Construct data manager with data
+ // Plan query
+ ProcessorPlan plan = TestProcedureProcessor.getProcedurePlan(sql, metadata);
+ // Run query
+ TestProcedureProcessor.helpTestProcess(plan, expected, new FakeDataManager(), metadata);
+
+ }
+
+ //virtual group with procedure in transformation
+ @Test public void testCase6395ProcAsVirtualGroup9(){
+ 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[] {
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Case 6395 - This test case will now raise a QueryPlannerException. param2 is required
+ * and not nullable. This case is expected to fail because of 'param2 is null'
+ */
+ @Test public void testProcAsVirtualGroup2WithNull() throws Exception {
+ 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[] {
+ };
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+ // Plan query
+ try {
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.doProcess(plan, dataManager, expected, TestProcessor.createCommandContext());
+ fail("QueryPlannerException was expected."); //$NON-NLS-1$
+ } catch (QueryValidatorException e) {
+ assertEquals("The procedure parameter pm1.vsp26.param2 is not nullable, but is set to null.",e.getMessage()); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Case 6395 - This case is expected to succeed. param1 and param2 are both required, but nulls
+ * are acceptable for both.
+ */
+ @Test public void testProcAsVirtualGroup2WithNull2() throws Exception {
+ String sql = "select * from pm1.vsp47 where param1 is null and param2 is null"; //$NON-NLS-1$
+
+ // Create expected results
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Case 6395 - This will not throw an exception and the proc will not be invoked.
+ */
+ @Test public void testProcAsVirtualGroup2WithNull3() throws Exception {
+ 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[] {
+ };
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ /*
+ * The following are tests that were removed from the validator. We are no longer trying to validate a priori whether
+ * procedure input criteria is valid. This can be addressed later more generally when we do up front validation of
+ * 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"}, 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" }, 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" }, 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)" }, 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"}, 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'", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testProcInVirtualGroup2_Defect20164() {
+ 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'", 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], RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testProcInVirtualGroup5_Defect20164() {
+ 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], RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testProcInVirtualGroup7_Defect20164() {
+ helpFailProcedure("select ve3 from vm1.vgvp2 where ve1=1 and ve2 is not null", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }*/
+
+ /**
+ * Ensures that dependent procedures are processed 1 at a time so that projected input values
+ * are set correctly.
+ */
+ @Test public void testIssue119() throws Exception {
+ MetadataStore metadataStore = new MetadataStore();
+ Schema v1 = RealMetadataFactory.createVirtualModel("v1", metadataStore); //$NON-NLS-1$
+ Schema pm1 = RealMetadataFactory.createPhysicalModel("pm1", metadataStore); //$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$
+ Procedure vt1 = RealMetadataFactory.createVirtualProcedure("vp1", v1, Arrays.asList(in), n1); //$NON-NLS-1$
+ vt1.setResultSet(rs1);
+
+ 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[] {
+ Arrays.asList(1, 1, 3, 3, 5),
+ Arrays.asList(1, 1, 3, 3, 8),
+ Arrays.asList(1, 1, 6, 6, 8),
+ Arrays.asList(1, 1, 6, 6, 11),
+ };
+
+ QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
+
+ // Construct data manager with data
+ // Plan query
+ ProcessorPlan plan = TestProcedureProcessor.getProcedurePlan(sql, metadata);
+ // Run query
+ HardcodedDataManager dataManager = new HardcodedDataManager() {
+ @Override
+ public TupleSource registerRequest(CommandContext context,
+ Command command, String modelName,
+ String connectorBindingId, int nodeID, int limit)
+ throws TeiidComponentException {
+ if (command instanceof StoredProcedure) {
+ StoredProcedure proc = (StoredProcedure)command;
+ List<SPParameter> params = proc.getInputParameters();
+ assertEquals(1, params.size());
+ int value = (Integer)((Constant)params.get(0).getExpression()).getValue();
+ return new FakeTupleSource(command.getProjectedSymbols(), new List[] {
+ Arrays.asList(value+2), Arrays.asList(value+5)
+ });
+ }
+ return super.registerRequest(context, command, modelName,
+ connectorBindingId, nodeID, limit);
+ }
+ };
+
+ TestProcedureProcessor.helpTestProcess(plan, expected, dataManager, metadata);
+
+ }
+
+ @Test public void testProcRelationalWithNoInputs() {
+ String sql = "select e1 from pm1.vsp2 order by e1 desc limit 1"; //$NON-NLS-1$
+
+ // Create expected results
+ 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, RealMetadataFactory.example1Cached());
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcessor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestProcessor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcessor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,7652 +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;
-
-import static org.junit.Assert.*;
-import static org.teiid.query.optimizer.TestOptimizer.*;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.sql.SQLException;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.concurrent.Executor;
-
-import org.junit.Test;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.BufferManagerFactory;
-import org.teiid.common.buffer.TupleBuffer;
-import org.teiid.common.buffer.TupleSource;
-import org.teiid.common.buffer.impl.BufferManagerImpl;
-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.dqp.internal.process.CachedResults;
-import org.teiid.dqp.internal.process.PreparedPlan;
-import org.teiid.dqp.internal.process.QueryProcessorFactoryImpl;
-import org.teiid.dqp.internal.process.SessionAwareCache;
-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.optimizer.FakeFunctionMetadataSource;
-import org.teiid.query.optimizer.QueryOptimizer;
-import org.teiid.query.optimizer.TestOptimizer;
-import org.teiid.query.optimizer.TestRuleRaiseNull;
-import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
-import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-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.optimizer.relational.rules.RuleChooseDependent;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.relational.JoinNode;
-import org.teiid.query.processor.relational.RelationalNode;
-import org.teiid.query.processor.relational.RelationalPlan;
-import org.teiid.query.resolver.QueryResolver;
-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.TimestampUtil;
-import org.teiid.query.util.CommandContext;
-import org.teiid.query.validator.Validator;
-import org.teiid.query.validator.ValidatorReport;
-
- at SuppressWarnings({"nls", "unchecked"})
-public class TestProcessor {
-
- // ################################## TEST HELPERS ################################
-
- static Command helpParse(String sql) {
- // parse
- try {
- return QueryParser.getQueryParser().parseCommand(sql);
- } catch(TeiidException e) {
- throw new TeiidRuntimeException(e);
- }
- }
-
- public static ProcessorPlan helpGetPlan(String sql, QueryMetadataInterface metadata) {
- return helpGetPlan(sql, metadata, new DefaultCapabilitiesFinder());
- }
-
- public static ProcessorPlan helpGetPlan(String sql, QueryMetadataInterface metadata, CapabilitiesFinder finder) {
- if(DEBUG) System.out.println("\n####################################\n" + sql); //$NON-NLS-1$
-
- Command command = helpParse(sql);
-
- ProcessorPlan process = helpGetPlan(command, metadata, finder);
-
- return process;
- }
-
- static ProcessorPlan helpGetPlan(Command command, QueryMetadataInterface metadata) {
- return helpGetPlan(command, metadata, new DefaultCapabilitiesFinder());
- }
-
- static ProcessorPlan helpGetPlan(Command command, QueryMetadataInterface metadata, CapabilitiesFinder capFinder) {
- CommandContext context = createCommandContext();
- try {
- return helpGetPlan(command, metadata, capFinder, context);
- } catch (TeiidException e) {
- throw new RuntimeException(e);
- }
- }
-
- static ProcessorPlan helpGetPlan(Command command, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, CommandContext context) throws TeiidException {
- if(DEBUG) System.out.println("\n####################################\n" + command); //$NON-NLS-1$
- AnalysisRecord analysisRecord = new AnalysisRecord(false, DEBUG);
- if (!(metadata instanceof TempMetadataAdapter)) {
- metadata = new TempMetadataAdapter(metadata, new TempMetadataStore());
- }
- context.setMetadata(metadata);
- try {
- QueryResolver.resolveCommand(command, metadata);
-
- ValidatorReport repo = Validator.validate(command, metadata);
- Collection failures = new ArrayList();
- repo.collectInvalidObjects(failures);
- if (failures.size() > 0){
- fail("Exception during validation (" + repo); //$NON-NLS-1$
- }
- command = QueryRewriter.rewrite(command, metadata, context);
- ProcessorPlan process = QueryOptimizer.optimizePlan(command, metadata, null, capFinder, analysisRecord, context);
- if(DEBUG) System.out.println("\n" + process); //$NON-NLS-1$
- //per defect 10022, clone this plan before processing, just to make sure
- //a cloned plan with correlated subquery references (or any cloned plan) can be processed
- process = process.clone();
-
- assertNotNull("Output elements of process plan are null", process.getOutputElements()); //$NON-NLS-1$
-
- return process;
- } finally {
- if(DEBUG) {
- System.out.println(analysisRecord.getDebugLog());
- }
- }
- }
-
- public static void helpProcess(ProcessorPlan plan, ProcessorDataManager dataManager, List[] expectedResults) {
- CommandContext context = createCommandContext();
- try {
- helpProcess(plan, context, dataManager, expectedResults);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- public static void helpProcess(ProcessorPlan plan, CommandContext context, ProcessorDataManager dataManager, List[] expectedResults) throws Exception {
- ProcessorPlan clonePlan = plan.clone();
-
- // Process twice to test reset and clone
- doProcess(plan, dataManager, expectedResults, context);
- plan.reset();
- doProcess(plan, dataManager, expectedResults, context);
-
- // Execute cloned of original plan
- doProcess(clonePlan, dataManager, expectedResults, context);
- }
-
- private void helpProcessException(ProcessorPlan plan, ProcessorDataManager dataManager) {
- helpProcessException(plan, dataManager, null);
- }
-
- private void helpProcessException(ProcessorPlan plan, ProcessorDataManager dataManager, String expectedErrorMessage) {
- TupleBuffer tsId = null;
- BufferManager bufferMgr = null;
- try {
- bufferMgr = BufferManagerFactory.getStandaloneBufferManager();
- CommandContext context = new CommandContext("0", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
- QueryProcessor processor = new QueryProcessor(plan, context, bufferMgr, dataManager);
- processor.setNonBlocking(true);
- BatchCollector collector = processor.createBatchCollector();
- tsId = collector.collectTuples();
- fail("Expected error during processing, but got none."); //$NON-NLS-1$
- } catch(TeiidException e) {
- // ignore - this is expected
- if(expectedErrorMessage != null) {
- assertEquals(expectedErrorMessage, e.getMessage());
- }
- } finally {
- if (tsId != null) {
- tsId.remove();
- }
- }
- }
-
- public static void doProcess(ProcessorPlan plan, ProcessorDataManager dataManager, List[] expectedResults, CommandContext context) throws Exception {
- BufferManager bufferMgr = context.getBufferManager();
- if (bufferMgr == null) {
- BufferManagerImpl bm = BufferManagerFactory.createBufferManager();
- bm.setProcessorBatchSize(context.getProcessorBatchSize());
- bm.setConnectorBatchSize(context.getProcessorBatchSize());
- context.setBufferManager(bm);
- bufferMgr = bm;
- }
- context.getNextRand(0);
- if (context.getTempTableStore() == null) {
- context.setTempTableStore(new TempTableStore(context.getConnectionID()));
- }
- if (context.getGlobalTableStore() == null) {
- context.setGlobalTableStore(new TempTableStore("SYSTEM"));
- }
- if (!(dataManager instanceof TempTableDataManager)) {
- SessionAwareCache<CachedResults> cache = new SessionAwareCache<CachedResults>();
- cache.setBufferManager(bufferMgr);
- Executor executor = new Executor() {
- @Override
- public void execute(Runnable command) {
- command.run();
- }
- };
- dataManager = new TempTableDataManager(dataManager, bufferMgr, executor, cache, null, null);
- }
- if (context.getQueryProcessorFactory() == null) {
- context.setQueryProcessorFactory(new QueryProcessorFactoryImpl(bufferMgr, dataManager, new DefaultCapabilitiesFinder(), null, context.getMetadata()));
- }
- TupleBuffer id = null;
- try {
- QueryProcessor processor = new QueryProcessor(plan, context, bufferMgr, dataManager);
- //processor.setNonBlocking(true);
- BatchCollector collector = processor.createBatchCollector();
- for (int i = 0; i < 100; i++) {
- try {
- id = collector.collectTuples();
- break;
- } catch (BlockedException e) {
-
- }
- }
- if (id == null) {
- fail("did not complete processing");
- }
- if ( expectedResults != null ) {
- examineResults(expectedResults, bufferMgr, id);
- }
- } finally {
- if (id != null) {
- id.remove();
- }
- }
- }
-
- /**
- * @param expectedResults
- * @param bufferMgr
- * @param tsID
- * @throws TeiidComponentException
- * @throws TeiidProcessingException
- * @since 4.3
- */
- static void examineResults(List[] expectedResults,BufferManager bufferMgr,TupleBuffer tsID)
- throws TeiidComponentException,SQLException, TeiidProcessingException {
-
- // Create QueryResults from TupleSource
- TupleSource ts = tsID.createIndexedTupleSource();
- int count = tsID.getRowCount();
-
- if(DEBUG) {
- System.out.println("\nResults:\n" + tsID.getSchema()); //$NON-NLS-1$
- TupleSource ts2 = tsID.createIndexedTupleSource();
- for(int j=0; j<count; j++) {
- System.out.println("" + j + ": " + ts2.nextTuple()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- ts2.closeSource();
- }
-
- // Compare actual to expected row count
- assertEquals("Did not get expected row count: ", expectedResults.length, count); //$NON-NLS-1$
-
- // Walk results and compare
- for(int i=0; i<count; i++) {
- List record = ts.nextTuple();
-
- //handle xml
- if(record.size() == 1){
- Object cellValue = record.get(0);
- if(cellValue instanceof XMLType){
- XMLType id = (XMLType)cellValue;
- String actualDoc = id.getString();
- if (expectedResults[i].size() == 1) {
- compareDocuments((String)expectedResults[i].get(0), actualDoc);
- continue;
- }
- }
- }
-
- assertEquals("Row " + i + " does not match expected: ", expectedResults[i], record); //$NON-NLS-1$ //$NON-NLS-2$
- }
- ts.closeSource();
- }
-
- public static void compareDocuments(String expectedDoc, String actualDoc) {
- StringTokenizer tokens1 = new StringTokenizer(expectedDoc, "\r\n"); //$NON-NLS-1$
- StringTokenizer tokens2 = new StringTokenizer(actualDoc, "\r\n");//$NON-NLS-1$
- while(tokens1.hasMoreTokens()){
- String token1 = tokens1.nextToken().trim();
- if(!tokens2.hasMoreTokens()){
- fail("XML doc mismatch: expected=" + token1 + "\nactual=none");//$NON-NLS-1$ //$NON-NLS-2$
- }
- String token2 = tokens2.nextToken().trim();
- assertEquals("XML doc mismatch: ", token1, token2); //$NON-NLS-1$
- }
- if(tokens2.hasMoreTokens()){
- fail("XML doc mismatch: expected=none\nactual=" + tokens2.nextToken().trim());//$NON-NLS-1$
- }
- }
-
- public static CommandContext createCommandContext() {
- 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$
- context.setProcessorBatchSize(BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE);
- context.setConnectorBatchSize(BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE);
- context.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
- context.setPreparedPlanCache(new SessionAwareCache<PreparedPlan>());
- return context;
- }
-
- public static void sampleData1(FakeDataManager dataMgr) {
- try {
- FakeDataStore.sampleData1(dataMgr, FakeMetadataFactory.example1Cached());
- } catch(Throwable e) {
- throw new RuntimeException(e);
- }
- }
-
- private void sampleData2(FakeDataManager dataMgr) {
- try {
- FakeDataStore.sampleData2(dataMgr);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- private void sampleData2a(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[] { "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$
- } );
-
- // 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$
- } );
-
- } catch(TeiidException e) {
- throw new RuntimeException(e);
- }
- }
-
- public static void sampleData2b(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[] { "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$
- } );
-
- // 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$
- } );
-
-
- } 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();
-
- try {
- // Group bqt1.smalla
-
- List[] tuples = new List[20];
- for(int i=0; i<tuples.length; i++) {
- tuples[i] = new ArrayList(17);
- tuples[i].add(new Integer(i));
- for(int j=0; j<16; j++) {
- tuples[i].add(null);
- }
- }
-
- dataMgr.registerTuples(metadata, "bqt1.smalla", tuples); //$NON-NLS-1$
-
- // Group bqt2.mediumb
- tuples = new List[20];
- for(int i=0; i<tuples.length; i++) {
- tuples[i] = new ArrayList(17);
- tuples[i].add(new Integer(i));
- for(int j=0; j<16; j++) {
- tuples[i].add(null);
- }
- }
-
- dataMgr.registerTuples(metadata, "bqt2.mediumb", tuples); //$NON-NLS-1$
- } catch(TeiidException e) {
- throw new RuntimeException(e);
- }
- }
-
- private void sampleDataBQT2(FakeDataManager dataMgr) {
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- String[] groups = new String[] {"bqt1.smalla", "bqt2.smalla", "bqt3.smalla" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- try {
- for(int i=0; i<groups.length; i++) {
- String groupName = groups[i];
-
- List[] tuples = new List[30];
- for(int row=0; row<tuples.length; row++) {
- tuples[row] = new ArrayList(17);
- tuples[row].add(new Integer(row));
- for(int col=0; col<16; col++) {
- tuples[row].add(null);
- }
- }
-
- dataMgr.registerTuples(metadata, groupName, tuples);
- }
-
- } catch(TeiidException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Just want to register two rows of all the integral types to test AVG
- * @param dataMgr
- * @since 4.2
- */
- private void sampleDataBQT_defect11682(FakeDataManager dataMgr) {
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- try {
- List[] tuples = new List[2];
- for(int i=1; i<=tuples.length; i++) {
- int index=i-1;
- tuples[index] = new ArrayList(17);
- tuples[index].add(new Integer(i)); //IntKey
- tuples[index].add(null);
- tuples[index].add(new Integer(i));
- tuples[index].add(null);
- tuples[index].add(new Float(i));
- tuples[index].add(new Long(i));
- tuples[index].add(new Double(i));
- tuples[index].add(new Byte((byte)i));
- tuples[index].add(null);
- tuples[index].add(null);
- tuples[index].add(null);
- tuples[index].add(null);
- tuples[index].add(null);
- tuples[index].add(new Short((short)i));
- tuples[index].add(new BigInteger(i+"")); //$NON-NLS-1$
- tuples[index].add(new BigDecimal(i+".0")); //$NON-NLS-1$
- tuples[index].add(null);
- }
-
- dataMgr.registerTuples(metadata, "bqt1.smalla", tuples); //$NON-NLS-1$
-
- } catch(TeiidException e) {
- throw new RuntimeException(e);
- }
- }
-
- private void sampleDataBQTSmall(FakeDataManager dataMgr) {
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- try {
- List[] tuples = new List[1];
- for(int i=0; i<tuples.length; i++) {
- tuples[i] = new ArrayList(17);
- tuples[i].add(new Integer(i));
- for(int j=0; j<16; j++) {
- tuples[i].add(null);
- }
- }
-
- dataMgr.registerTuples(metadata, "bqt1.smalla", tuples); //$NON-NLS-1$
-
- } catch(TeiidException e) {
- throw new RuntimeException(e);
- }
- }
-
- private List createRowWithTimestamp(String tsStr) {
- Timestamp ts = Timestamp.valueOf(tsStr);
- return Arrays.asList(new Object[] {
- new Integer(0), "a", new Integer(1), "a", //$NON-NLS-1$ //$NON-NLS-2$
- null, null, null, null, null, null, ts, null, null, null, null, null, null
- });
- }
-
- private void sampleDataBQT_case1566(FakeDataManager dataMgr) throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- dataMgr.registerTuples(metadata, "bqt1.smalla", new List[] { //$NON-NLS-1$
- createRowWithTimestamp("2002-01-01 10:00:00"), //$NON-NLS-1$
- createRowWithTimestamp("2002-01-01 14:00:00"), //$NON-NLS-1$
- createRowWithTimestamp("2002-01-02 10:00:00"), //$NON-NLS-1$
- createRowWithTimestamp("2002-01-02 14:00:00"), //$NON-NLS-1$
- createRowWithTimestamp("2002-01-02 19:00:00.01"), //$NON-NLS-1$
- } );
- }
-
- 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;
- }
-
- @Test public void test1() {
- // Create query
- String sql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = 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$
- };
-
- // 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 test2() {
- // Create query
- String sql = "SELECT COUNT(*) FROM pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(6) })
- };
-
- // 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 test3() {
- // Create query
- String sql = "SELECT COUNT(*), COUNT(e1), COUNT(distinct e1), COUNT(distinct e2), COUNT(distinct e3), COUNT(distinct e4) FROM pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(6), new Integer(5), new Integer(3), new Integer(4), new Integer(2), new Integer(4) }),
- };
-
- // 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);
- }
-
- /** see also integer average defect 11682 */
- @Test public void test4() {
- // Create query
- String sql = "SELECT MIN(e2), MAX(e2), SUM(e2), AVG(e2), SUM(distinct e2), AVG(distinct e2) FROM pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0), new Integer(3), new Long(7), new Double(1.1666666666666667), new Long(6), new Double(1.5) }),
- };
-
- // 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 test5() {
- // Create query
- String sql = "SELECT MIN(e4), MAX(e4), SUM(e4), AVG(e4), SUM(distinct e4), AVG(distinct e4) FROM pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Double(0.0), new Double(7.0), new Double(12.0), new Double(2.4), new Double(10.0), new Double(2.5) }),
- };
-
- // 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 test7() {
- // Create query
- String sql = "SELECT * FROM vm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = 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$
- };
-
- // 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 test8() {
- // Create query
- String sql = "SELECT * FROM vm1.g2 order by 1, 2, 3"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.TRUE, new Double(7.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.TRUE, new Double(7.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(3), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(3), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null }) //$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 test9() {
- // Create query
- String sql = "SELECT * FROM vm1.g4 order by e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "3" }), //$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();
- sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void test10() {
- // Create query
- String sql = "SELECT e1 FROM vm1.g4 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 testBooleanComparisonGT() {
- // Create query
- String sql = "SELECT pm1.g1.e3 FROM pm1.g1 WHERE e3 > {b'false'}"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { Boolean.TRUE }),
- Arrays.asList(new Object[] { Boolean.TRUE })
- };
-
- // 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 testBooleanComparisonGE() {
- // Create query
- String sql = "SELECT pm1.g1.e3 FROM pm1.g1 WHERE e3 >= {b'false'}"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { Boolean.FALSE }),
- Arrays.asList(new Object[] { Boolean.FALSE }),
- Arrays.asList(new Object[] { Boolean.TRUE }),
- Arrays.asList(new Object[] { Boolean.TRUE }),
- Arrays.asList(new Object[] { Boolean.FALSE }),
- Arrays.asList(new Object[] { Boolean.FALSE })
- };
-
- // 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 testBooleanComparisonLT() {
- // Create query
- String sql = "SELECT pm1.g1.e3 FROM pm1.g1 WHERE e3 < {b'true'}"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { Boolean.FALSE }),
- Arrays.asList(new Object[] { Boolean.FALSE }),
- Arrays.asList(new Object[] { Boolean.FALSE }),
- Arrays.asList(new Object[] { Boolean.FALSE })
- };
-
- // 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 testBooleanComparisonLE() {
- // Create query
- String sql = "SELECT pm1.g1.e3 FROM pm1.g1 WHERE e3 <= {b'true'}"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { Boolean.FALSE }),
- Arrays.asList(new Object[] { Boolean.FALSE }),
- Arrays.asList(new Object[] { Boolean.TRUE }),
- Arrays.asList(new Object[] { Boolean.TRUE }),
- Arrays.asList(new Object[] { Boolean.FALSE }),
- Arrays.asList(new Object[] { Boolean.FALSE })
- };
-
- // 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 testConcatOperator() {
- // Create query
- String sql = "SELECT pm1.g1.e1 || e2 AS x FROM pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a0" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a3" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c1" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b2" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a0" }) //$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);
- }
-
- /** Duplicates defect #4841: SELECT e1 a, e1 b FROM pm1.g1 order by a */
- @Test public void testDefect4841_1() {
- // Create query
- String sql = "SELECT e1 a, e1 b FROM pm1.g1 order by a"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // 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);
- }
-
- /** Duplicates defect #4841: SELECT e1 a, e1 b FROM pm1.g1 order by a, b desc */
- @Test public void testDefect4841_2() {
- // Create query
- String sql = "SELECT e1 a, e1 b FROM pm1.g1 order by a"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // 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);
- }
-
- /** Duplicates defect #5292: SELECT DISTINCT e1, e1 a FROM pm1.g1 */
- @Test public void testDefect5292_1() {
- // Create query
- String sql = "SELECT DISTINCT e1, e1 a FROM pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // 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);
- }
-
- /** Duplicates defect #5292: SELECT DISTINCT e1, e1 a FROM pm1.g1 ORDER BY a */
- @Test public void testDefect5292_2() {
- // Create query
- String sql = "SELECT DISTINCT e1, e1 a FROM pm1.g1 ORDER BY a"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // 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);
- }
-
- /** Duplicates defect #5004: SELECT COUNT(*) FROM pm1.g1 WHERE e1='xxxx' */
- @Test public void testDefect5004() {
- // Create query
- String sql = "SELECT COUNT(*) FROM pm1.g1 WHERE e1='xxxx'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0) })
- };
-
- // 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 to ensure that multiple empty batches are handled by the grouping node as well
- */
- @Test public void testDefect5004a() throws Exception {
- // Create query
- String sql = "SELECT COUNT(*) FROM pm1.g1 WHERE e1='xxxx'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0) })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- CommandContext context = createCommandContext();
- context.setProcessorBatchSize(2);
- context.setConnectorBatchSize(2);
- context.setMetadata(FakeMetadataFactory.example1Cached());
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached(), new DefaultCapabilitiesFinder(), context);
-
- // Run query
- helpProcess(plan, context, dataManager, expected);
- }
-
- /** SELECT COUNT(e2), MIN(e2), MAX(e2), SUM(e2), AVG(e2) FROM pm1.g1 WHERE e2=-999999 */
- @Test public void test13() {
- // Create query
- String sql = "SELECT COUNT(e2), MIN(e2), MAX(e2), SUM(e2), AVG(e2) FROM pm1.g1 WHERE e2=-999999"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] {new Integer(0), null, null, null, null})
- };
-
- // 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);
- }
-
- /**
- * This test uncovered a bug in the FakeDataManager; the element
- * symbol in the atomic query criteria has a canonical name
- * of "Y.e4", but the FakeDataManager sends a Map of ElementSymbols
- * having the unaliased names. The first symbol cannot be found
- * in the Map due to the implementation of Symbol.equals() being
- * based entirely on the canonical name, which causes a NPE.
- * (Alex says this wasn't previously a problem because aliased groups
- * did not previously get pushed down to the source.)
- */
- @Test public void testCriteriaAliasedGroup() {
- String sql = "select e1, e2 FROM pm2.g1 Y WHERE 2.0 = e4"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "b", new Integer(0) }), //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT e1 FROM pm1.g1 WHERE 'abc' = 'xyz' */
- @Test public void testCriteriaComparesUnequalConstants() {
- // Create query
- String sql = "SELECT e1 FROM pm1.g1 WHERE 'abc' = 'xyz'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- };
-
- // 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);
- }
-
- /** SELECT pm1.g1.e1, pm2.g1.e1 FROM pm1.g1 RIGHT OUTER JOIN pm2.g1 ON pm1.g1.e1=pm2.g1.e1 */
- @Test public void testRightOuterJoin1() {
- // Create query
- String sql = "SELECT pm1.g1.e1, pm2.g1.e1 FROM pm1.g1 RIGHT OUTER JOIN pm2.g1 ON pm1.g1.e1=pm2.g1.e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { null, "d" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null, "e" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT pm1.g1.e1, pm2.g1.e1 FROM pm1.g1 LEFT OUTER JOIN pm2.g1 ON pm1.g1.e1=pm2.g1.e1 */
- @Test public void testLeftOuterJoin1() {
- // Create query
- String sql = "SELECT pm1.g1.e1, pm2.g1.e1 FROM pm1.g1 LEFT OUTER JOIN pm2.g1 ON pm1.g1.e1=pm2.g1.e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT pm1.g1.e1, pm2.g1.e1 FROM pm1.g1 FULL OUTER JOIN pm2.g1 ON pm1.g1.e1=pm2.g1.e1 */
- @Test public void testFullOuterJoin1() throws Exception {
- // Create query
- String sql = "SELECT pm1.g1.e1, pm2.g1.e1 FROM pm1.g1 FULL OUTER JOIN pm2.g1 ON pm1.g1.e1=pm2.g1.e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null, "d" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null, "e" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testFullOuterJoin2() throws Exception {
- // Create query
- String sql = "SELECT a.e4 c0, b.e4 c1 FROM pm1.g1 a FULL OUTER JOIN pm1.g1 b ON a.e4=b.e4 order by c0"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { new Double(0), new Double(0) }),
- Arrays.asList(new Object[] { new Double(2), new Double(2) }),
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testSortedFullOuterJoin() throws Exception {
- // Create query
- String sql = "SELECT pm1.g1.e2, pm2.g1.e2 FROM pm1.g1 FULL OUTER JOIN pm2.g1 ON pm1.g1.e2=pm2.g1.e2 and pm1.g1.e2 > 3"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, 2 }), //$NON-NLS-1$
- Arrays.asList(new Object[] { 3, null }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { null, 3 }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null, 4 }), //$NON-NLS-1$
- };
-
- HardcodedDataManager hdm = new HardcodedDataManager();
- hdm.addData("SELECT g_0.e2 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", new List[] {
- Arrays.asList(3),
- });
- hdm.addData("SELECT g_0.e2 AS c_0 FROM pm2.g1 AS g_0 ORDER BY c_0", new List[] {
- Arrays.asList(2),
- Arrays.asList(3),
- Arrays.asList(4),
-
- });
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
- CommandContext cc = createCommandContext();
- cc.setProcessorBatchSize(2);
- helpProcess(plan, cc, hdm, expected);
- }
-
- @Test public void testFullOuterJoin3() throws Exception {
- // Create query
- String sql = "SELECT a.e4 c0, b.e4 c1 FROM pm1.g1 b FULL OUTER JOIN (select e4, 1 x from pm1.g1 union all select e4, 2 from pm1.g1) a ON a.e4=b.e4 and a.x = 2 order by c0"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { new Double(0), new Double(0) }),
- Arrays.asList(new Object[] { new Double(0), null }),
- Arrays.asList(new Object[] { new Double(2), new Double(2) }),
- Arrays.asList(new Object[] { new Double(2), null }),
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT x.e1, pm2.g1.e1 FROM (SELECT e1 FROM pm1.g1) AS x LEFT OUTER JOIN pm2.g1 ON x.e1=pm2.g1.e1 */
- @Test public void testLeftOuterJoinWithInlineView() {
- // Create query
- String sql = "SELECT x.e1, pm2.g1.e1 FROM (SELECT e1 FROM pm1.g1) AS x LEFT OUTER JOIN pm2.g1 ON x.e1=pm2.g1.e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT * FROM vm1.g5 ORDER BY expr */
- @Test public void testDefect5273_1() {
- // Create query
- String sql = "SELECT expr FROM vm1.g5 ORDER BY expr"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "bval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "cval" }) //$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);
- }
-
- /** SELECT expr AS e FROM vm1.g5 ORDER BY e */
- @Test public void testDefect5273_2() {
- // Create query
- String sql = "SELECT expr AS e FROM vm1.g5 ORDER BY e"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "bval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "cval" }) //$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);
- }
-
- /** SELECT e2 AS e FROM vm1.g5 ORDER BY e */
- @Test public void testDefect5273_3() {
- // Create query
- String sql = "SELECT e2 AS e FROM vm1.g5 ORDER BY e"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(3) })
- };
-
- // 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);
- }
-
- /** SELECT e AS f FROM vm1.g6 ORDER BY f */
- @Test public void testDefect5273_4() {
- // Create query
- String sql = "SELECT e AS f FROM vm1.g6 ORDER BY f"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "bval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "cval" }) //$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);
- }
-
- /** SELECT e AS f FROM vm1.g7 ORDER BY f */
- @Test public void testDefect5273_5() {
- // Create query
- String sql = "SELECT e AS f FROM vm1.g7 ORDER BY f"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a0" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a0" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a3" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b2" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c1" }) //$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);
- }
-
- /** SELECT e AS f FROM vm1.g7 ORDER BY f */
- @Test public void testDefect5273_6() {
- // Create query
- String sql = "SELECT e AS f FROM vm1.g8 ORDER BY f"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "bval" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "cval" }) //$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 testFalseCriteria1() {
- // Create query
- String sql = "SELECT 5 FROM pm1.g1 WHERE 0=1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- };
-
- // 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 testFalseCriteria2() {
- // Create query
- String sql = "SELECT count(*) FROM pm1.g1 WHERE 0=1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0) }),
- };
-
- // 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 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$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$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 testSubquerySimple() {
- // Create query
- String sql = "SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS x"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$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 testCritInSubquery() {
- // Create query
- String sql = "SELECT e1 FROM (SELECT e1 FROM pm1.g1 WHERE e1 = 'a') AS x"; //$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 testCritAboveSubquery() {
- // Create query
- String sql = "SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS x 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 testSubqueryInJoinPredicate() {
- // Create query
- String sql = "SELECT x.e1 FROM (SELECT e1 FROM pm1.g1) AS x JOIN (SELECT e1 FROM pm1.g1) y ON x.e1=y.e1 order by x.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[] { "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();
- sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testSubqueryWithRenaming() {
- // Create query
- String sql = "SELECT x.a FROM (SELECT e1 AS a FROM pm1.g1) AS x"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$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 testNestedSubquery() {
- // Create query
- String sql = "SELECT x.a FROM (SELECT e1 AS a FROM (SELECT e1 FROM pm1.g1) AS y) AS x"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$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);
- }
-
- /**
- * Tests a single Subquery IN clause criteria
- */
- @Test public void testSubqueryINClause() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a single Subquery IN clause criteria with nulls
- * in sample data
- */
- @Test public void testSubqueryINClauseWithNulls() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e4 IN (SELECT e4 FROM pm2.g1)"; //$NON-NLS-1$
-
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a single Subquery IN clause criteria with nulls
- * in sample data
- */
- @Test public void testSubqueryINClauseWithNulls2() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e4 FROM pm2.g1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "c" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a compound criteria of two subqueries in IN clauses
- */
- @Test public void testSubqueryINClauses() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1) AND e1 IN (SELECT e1 FROM pm2.g1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "b" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a compound criteria of a subquery in IN clause and another type of
- * criteria
- */
- @Test public void testSubqueryINClauseMixedCriteria() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1) AND e1 IN ('b')"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "b" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a compound criteria of a subquery in IN clause and another type of
- * criteria
- */
- @Test public void testSubqueryINClauseMixedCriteria2() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1) AND NOT (e1 = 'a')"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "b" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests nesting of Subquery IN clause criteria
- */
- @Test public void testNestedSubqueryINClauses() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1 WHERE e1 IN (SELECT e1 FROM pm1.g1))"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testSubqueryXML() {
- // Create query
- String sql = "SELECT * FROM (SELECT * FROM xmltest.doc1) AS x"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] {
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
- "<root><node1><node2><node3/></node2></node1></root>" //$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);
- }
-
- /**
- * Tests a single Subquery EXISTS predicate criteria
- */
- @Test public void testSubqueryExistsPredicate() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE EXISTS (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- 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();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a single Subquery EXISTS predicate criteria
- * where the subquery returns no rows
- */
- @Test public void testSubqueryExistsPredicate2() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE EXISTS (SELECT e2 FROM pm2.g1 WHERE e1 = 'ZZTop')"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[0];
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a single Subquery in compare predicate criteria
- */
- @Test public void testSubqueryComparePredicate() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 = ANY (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a single Subquery in compare predicate criteria
- */
- @Test public void testSubqueryComparePredicate2() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 = SOME (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a single Subquery in compare predicate criteria
- */
- @Test public void testSubqueryComparePredicate3() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 = ALL (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[0];
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a single Subquery in compare predicate criteria
- */
- @Test public void testSubqueryComparePredicate4() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 <= ALL (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a single Subquery in compare predicate criteria
- */
- @Test public void testSubqueryComparePredicate5() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 < SOME (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- 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();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a single Subquery in compare predicate criteria
- */
- @Test public void testSubqueryComparePredicate5a() {
- String sql = "SELECT e1 FROM pm2.g1 WHERE e2 < SOME (SELECT e2 FROM pm1.g1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "e" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a single Subquery in compare predicate criteria
- * without predicate quantifier
- */
- @Test public void testSubqueryComparePredicate6() {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 < (SELECT e2 FROM pm2.g1 WHERE e1 = 'e')"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a single Subquery in compare predicate criteria
- */
- @Test public void testSubqueryComparePredicateNested() {
- 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());
-
- // Run query
- // Construct data manager with data
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData("SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1", new List[] { Arrays.asList(new Object[] { new Integer(0), "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { new Integer(1), "b" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(2), "c" }), //$NON-NLS-1$
- });
-
- dataManager.addData("SELECT pm2.g1.e2 FROM pm2.g1", new List[] { //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(1) }),
- });
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }) //$NON-NLS-1$
- };
-
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a scalar subquery in the SELECT clause
- */
- @Test public void testSubqueryScalar() {
- String sql = "SELECT e1, (SELECT e2 FROM pm2.g1 WHERE e1 = 'b') FROM pm1.g1"; //$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[] { "b", new Integer(0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", new Integer(0) }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a scalar subquery which returns no rows in the SELECT clause
- */
- @Test public void testSubqueryScalar2() {
- String sql = "SELECT e1, (SELECT e2 FROM pm2.g1 WHERE e1 = 'a') FROM pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Tests a scalar subquery which returns more than one rows
- * causes the expected Exception
- */
- @Test public void testSubqueryScalarException() throws Exception {
- String sql = "SELECT e1, (SELECT e2 FROM pm2.g1) FROM pm1.g1"; //$NON-NLS-1$
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcessException(plan, dataManager);
- }
-
- @Test public void testSubqueryScalarInTransformation() {
- String sql = "select * from vm1.g25"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), new Double(0.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0), new Double(0.0) }),
- Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), new Double(0.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, new Double(0.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), new Double(0.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), new Double(0.0) }) //$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 testSubqueryScalarInTransformation2() {
- String sql = "select * from vm1.g25 where e5 = 0.0"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), new Double(0.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0), new Double(0.0) }),
- Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), new Double(0.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, new Double(0.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), new Double(0.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), new Double(0.0) }) //$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 testCorrelatedSubquery_CASE2022() {
- String sql = "select * from BQT2_V WHERE BQT2_V.IntKey < 50"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[0];
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT1(dataManager);
- sampleDataBQT2(dataManager);
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MIN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- // Plan query
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.exampleBQTCached(), capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
- @Test public void testCorrelatedSubquery1() {
- String sql = "Select e1, e2, e4 from pm1.g1 where e2 in (select e2 FROM pm2.g1 WHERE pm1.g1.e4 = pm2.g1.e4)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0), new Double(2.0) }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- /**
- * There is a bug when the second query in a UNION ALL has a correlated subquery, and both
- * the outer and inner query are selecting from the same virtual group, and aliasing them
- * differently to distinguish between them. The generated atomic query has screwed up
- * aliasing.
- */
- @Test public void testCorrelatedSubqueryCase3667() {
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
-
- // Plan query
- 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);
-
- // Run query
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "aString", new Integer(22), new Double(22.0) }), //$NON-NLS-1$
- };
-
- dataManager.addData("SELECT g_0.e1, g_0.e2, g_0.e4 FROM pm1.g1 AS g_0 WHERE g_0.e2 IN (SELECT g_1.e2 FROM pm1.g1 AS g_1 WHERE g_1.e4 = g_0.e4)", //$NON-NLS-1$
- expected);
-
- helpProcess(plan, dataManager, expected);
- }
-
- /** control query, this test passes */
- @Test public void testCorrelatedSubqueryCase3667a() {
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // 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);
-
- // Run query
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "aString", new Integer(22), new Double(22.0) }), //$NON-NLS-1$
- };
-
- dataManager.addData("SELECT g_0.e1, g_0.e2, g_0.e4 FROM pm1.g1 AS g_0 WHERE g_0.e2 IN (SELECT g_1.e2 FROM pm1.g1 AS g_1 WHERE g_1.e4 = g_0.e4)", //$NON-NLS-1$
- expected);
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedSubquery2() {
- String sql = "Select e1, e2 from pm1.g1 where e2 in (select e2 FROM pm2.g1 WHERE pm1.g1.e4 = pm2.g1.e4)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- @Test public void testCorrelatedSubquery3() {
- String sql = "Select e1, (select e2 FROM pm2.g1 WHERE pm1.g1.e4 = pm2.g1.e4) from pm1.g1"; //$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[] { "b", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedSubquery3a() {
- String sql = "Select e1, (select e2 FROM pm2.g1 WHERE X.e4 = e4) from pm1.g1 X"; //$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[] { "b", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedSubquery3b() {
- String sql = "Select e1, (select e2 FROM pm2.g1 Y WHERE X.e4 = e4) from pm1.g1 X"; //$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[] { "b", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedSubquery3c() {
- String sql = "Select e1, (select e2 FROM pm2.g1 Y WHERE X.e4 = Y.e4) from pm1.g1 X"; //$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[] { "b", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedSubquery4() {
- String sql = "Select e1, e2 from pm1.g1 X where e2 in (select e2 FROM pm2.g1 WHERE X.e4 = pm2.g1.e4)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedSubquery4a() {
- String sql = "Select e1, e2 from pm1.g1 X where e2 = some (select e2 FROM pm2.g1 WHERE X.e4 = pm2.g1.e4)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedSubquery_defect9968() {
- String sql = "Select e1, e2 from pm1.g1 X where e2 in (select max(X.e2) FROM pm2.g1 WHERE X.e4 = pm2.g1.e4)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedSubquery_defect9968a() {
- String sql = "Select e1, e2 from pm1.g1 X where e2 in (select ((X.e2)/2) as e FROM pm2.g1 WHERE X.e4 = pm2.g1.e4)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedSubquery_defect9968b() {
- String sql = "Select e1, e2 from pm1.g1 X where e2 in (select (select e2 as e FROM pm2.g1 WHERE X.e4 = pm2.g1.e4) as e FROM pm2.g1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedSubquery_defect10021() {
- String sql = "Select e1, e2 from table1 X where e4 in (select max(Y.e4) FROM table1 Y WHERE X.e4 = Y.e4)"; //$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[] { "c", new Integer(2) }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Note the subquery has a multi-column result - conceptually this is
- * legal for the EXISTS predicate
- */
- @Test public void testCorrelatedSubquery5() {
- String sql = "Select * from pm1.g1 where exists (select * FROM pm2.g1 WHERE pm1.g1.e1 = e1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "b", new Integer(1), Boolean.TRUE, null }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Count the # of parent rows for which no child rows exist
- */
- @Test public void testCorrelatedSubquery6() {
- String sql = "Select count(*) from pm1.g1 where not (exists (select * FROM pm2.g1 WHERE pm1.g1.e1 = e1))"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { new Integer(2) })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Select e2, e4, and the avg of e4 for each group of e1
- */
- @Test public void testCorrelatedSubquery7() {
- String sql = "select e2, e4, (select avg(e4) FROM pm1.g1 Y WHERE X.e1 = e1) from pm1.g1 X"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { new Integer(0), new Double(2.0), new Double(3.6666666666666665) }),
- Arrays.asList(new Object[] { new Integer(1), new Double(1.0), null }),
- Arrays.asList(new Object[] { new Integer(3), new Double(7.0), new Double(3.6666666666666665) }),
- Arrays.asList(new Object[] { new Integer(1), null , null }),
- Arrays.asList(new Object[] { new Integer(2), new Double(0.0), new Double(0.0) }),
- Arrays.asList(new Object[] { new Integer(0), new Double(2.0), new Double(3.6666666666666665) })
- };
-
- // 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);
- }
-
- /**
- * Select e2, e4, and the avg of e4 for each group of e1
- */
- @Test public void testCorrelatedSubquery8() {
- String sql = "select X.e2, X.e4, (select avg(Y.e4) FROM pm1.g1 Y WHERE X.e1 = Y.e1) from pm1.g1 X"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { new Integer(0), new Double(2.0), new Double(3.6666666666666665) }),
- Arrays.asList(new Object[] { new Integer(1), new Double(1.0), null }),
- Arrays.asList(new Object[] { new Integer(3), new Double(7.0), new Double(3.6666666666666665) }),
- Arrays.asList(new Object[] { new Integer(1), null , null }),
- Arrays.asList(new Object[] { new Integer(2), new Double(0.0), new Double(0.0) }),
- Arrays.asList(new Object[] { new Integer(0), new Double(2.0), new Double(3.6666666666666665) })
- };
-
- // 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 testCorrelatedSubqueryVirtualLayer1() {
- String sql = "Select e1, e2 from vm1.g1 X where e2 in (select e2 FROM vm1.g1 Y WHERE X.e4 = Y.e4)"; //$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[] { "b", new Integer(2) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0) }) //$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 testCorrelatedSubqueryVirtualLayer2() {
- String sql = "Select e1, e2 from vm1.g2 where e2 in (select e2 FROM vm1.g1 WHERE vm1.g2.e4 = vm1.g1.e4) order by e1, e2"; //$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[] { "a", new Integer(0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(3) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(2) }) //$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 testCorrelatedSubqueryVirtualLayer3() {
- String sql = "Select e2 from vm1.g6 where e2 in (select e2 FROM vm1.g1 WHERE vm1.g6.e = e1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[0];
-
- // 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 testCorrelatedSubqueryVirtualLayer4() {
- String sql = "Select e2 from vm1.g7 where e2 in (select e2 FROM vm1.g1 WHERE vm1.g7.e = e1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[0];
-
- // 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 testCorrelatedSubqueryVirtualLayer5() {
- String sql = "Select e1 from vm1.g4 where not (e1 in (select e1 FROM vm1.g1 WHERE vm1.g4.e1 = e1)) order by e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "3" }) //$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 testCorrelatedSubqueryVirtualLayer6() {
- String sql = "Select e2 from vm1.g1 X where e2 in (select X.e2 FROM vm1.g1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(0) })
- };
-
- // 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 testCorrelatedSubqueryVirtualLayer6a() {
- String sql = "Select e2 from vm1.g1 where e2 in (select vm1.g1.e2 FROM vm1.g5)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(0) })
- };
-
-
- // 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 testCorrelatedSubqueryVirtualLayer6b() {
- String sql = "Select e2 from vm1.g1 where e2 in (select vm1.g1.e2 FROM vm1.g2)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(0) })
- };
-
- // 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 testCorrelatedSubqueryVirtualLayer6c() {
- String sql = "Select e2 from vm1.g7 where e2 in (select vm1.g7.e FROM vm1.g1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[0];
-
- // 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 testCorrelatedSubqueryVirtualLayer6e() {
- String sql = "Select e2 from vm1.g1 where e2 in (select vm1.g1.e2 FROM vm1.g2a)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(0) })
- };
-
-
- // 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 testCorrelatedSubqueryVirtualLayer7() {
- String sql = "Select e2 from vm1.g7 where e2 in (select vm1.g7.e FROM vm1.g1 WHERE vm1.g7.e = e1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[0];
-
- // 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 testCorrelatedSubqueryInTransformation() {
- String sql = "Select * from vm1.g21"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "b", new Integer(1), Boolean.TRUE, null }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedSubqueryInTransformation2() {
- String sql = "Select * from vm1.g20"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
- 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$
- };
-
- // 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 testCorrelatedSubqueryInTransformation3() {
- String sql = "Select * from vm1.g19 order by e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "3" }) //$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);
- }
-
- /**
- * User correlated subquery, and one of the virtual group transformations
- * also has a correlated subquery
- */
- @Test public void testCorrelatedSubqueryInTransformation4() {
- String sql = "Select * from vm1.g20 where exists (Select * from vm1.g19 where convert(vm1.g20.e2, string) = vm1.g19.e1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
- 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$
- };
-
- // 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);
- }
-
- /**
- * User correlated subquery, and one of the virtual group transformations
- * also has a correlated subquery
- */
- @Test public void testCorrelatedSubqueryInTransformation5() {
- String sql = "Select * from vm1.g19 where exists (Select e2 from vm1.g20 where convert(e2, string) = vm1.g19.e1) order by e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "3" }) //$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 testCorrelatedSubqueryInTransformation6() {
- String sql = "Select * from vm1.g21 where e2 = some (Select e2 from pm1.g1 where e1 = vm1.g21.e1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "b", new Integer(1), Boolean.TRUE, null }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedSubqueryInTransformation7() {
- String sql = "Select * from vm1.g21 where exists (Select e2 from pm1.g2 where e4 = convert(vm1.g21.e2, double))"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.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$
- };
-
- // 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 testCorrelatedSubqueryInTransformation8() {
- String sql = "Select * from vm1.g21 where exists (Select e2 from pm1.g1 where e4 = convert(vm1.g21.e2, double))"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.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$
- };
-
- // 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 testCorrelatedSubqueryInTransformation9() {
- String sql = "Select * from vm1.g22"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), new Double(7.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }) //$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 testCorrelatedSubqueryInTransformation10() {
- String sql = "Select * from vm1.g23"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), new Double(7.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }) //$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 testCorrelatedSubqueryInTransformation11() {
- String sql = "Select * from vm1.g24"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
- 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 }),
- 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$
- };
-
- // 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 testCorrelatedSubqueryInTransformation12() {
- String sql = "Select * from vm1.g24 X where exists (Select * from vm1.g24 Y where X.e2 = Y.e2)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
- 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 }),
- 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$
- };
-
- // 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 testCorrelatedSubqueryInTransformation13() {
- String sql = "Select e1, e2, e3, e4, (select e4 from vm1.g25 where pm1.g1.e4 = e5 and e4=0.0) as e5 from pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0), null }),
- Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), new Double(0.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }) //$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 testCorrelatedSubqueryInTransformation14() {
- String sql = "Select e1, e2, e3, e4, (select e4 from vm1.g26 where pm1.g1.e4 = e5 and e4=0.0) as e5 from pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0), null }),
- Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), new Double(0.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }) //$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 testCorrelatedSubqueryInTransformation15() {
- String sql = "Select e1, e2, e3, e4, (select e4 from vm1.g23 where vm1.g22.e4 = e5) as e5 from vm1.g22 where e1 = 'a'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), new Double(7.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }) //$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 selecting a virtual element (e5) which is defined by a scalar subquery in the virtual transformation */
- @Test public void testCorrelatedSubqueryInTransformation15a() {
- String sql = "Select e1, e2, e3, e4 from pm1.g1 where exists (select * from vm1.g26 where pm1.g1.e3 = e3)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = 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$
- };
-
- // 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 testCorrelatedSubqueryInTransformation15b() {
- String sql = "Select e1, e2, e3, e4, (select e4 from vm1.g23 where vm1.g22.e4 = e5) as e5 from vm1.g22 where e1 = 'a' and exists (select * from vm1.g23 where vm1.g22.e3 = e3)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), new Double(7.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }) //$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 selecting a virtual element (e5) which is defined by a scalar subquery in the virtual transformation */
- @Test public void testCorrelatedSubqueryInTransformation15c() {
- String sql = "Select e1, e2, e3, e4 from pm1.g1 where exists (select e1, e2, e3, e4, e5 as e from vm1.g26 where pm1.g1.e3 = e3)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = 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$
- };
-
- // 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 selecting a virtual element (e5) which is defined by a scalar subquery in the virtual transformation */
- @Test public void testCorrelatedSubqueryInTransformation15d() {
- String sql = "Select e1, e2, e3, e4 from pm1.g1 where exists (select e1, e2, e3, e4, ((e4 + e5)/(e4 + 1)) as e from vm1.g26 where pm1.g1.e3 = e3)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = 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$
- };
-
- // 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);
- }
-
-// Here is select * from vm1.g26
-// Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }),
-// Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0), null }),
-// Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), null }),
-// Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, null }),
-// Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), new Double(0.0) }),
-// Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null })
-
-
- @Test public void testCorrelatedSubqueryInTransformation16() {
-// String sql = "Select e1, e2, e3, e4, (select e4 from vm1.g23 where vm1.g22.e4 = e5) as e5 from vm1.g22 where e1 = 'a'"/* and exists (select * from vm1.g23 where vm1.g22.e3 = e3)"*/;
- String sql = "select * from vm1.g26 where e5 = 0.0"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[]{
-// Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }),
-// Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0), null }),
-// Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), null }),
-// Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, null }),
- Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), new Double(0.0) }), //$NON-NLS-1$
-// Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null })
- };
-
- // 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 testCorrelatedSubqueriesNested() {
- String sql =
- "Select e1, e2, e4 from pm1.g1 where e2 < all (" + //$NON-NLS-1$
- "select e2 from pm1.g2 where pm1.g1.e1 = e1 and exists("+ //$NON-NLS-1$
- "select e2 from pm2.g1 where pm1.g2.e4 = pm2.g1.e4))"; //$NON-NLS-1$
- Command query = helpParse(sql);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0), new Double(2.0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(1), null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", new Integer(2), new Double(0.0) }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(query, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /** defect 15124 */
- @Test public void testCorrelatedSubqueryAndInlineView() {
- String sql = "Select e1, (select e2 FROM pm2.g1 Y WHERE X.e4 = Y.e4) from (select * from pm1.g1) as X"; //$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[] { "b", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /** defect 15124 */
- @Test public void testCorrelatedSubqueryAndInlineView2() {
- String sql = "Select e1 from (select * from pm1.g1) as X WHERE e2 IN (select e2 FROM pm2.g1 Y WHERE X.e4 = Y.e4)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /** defect 15124 */
- @Test public void testCorrelatedSubqueryAndInlineView3() {
- String sql = "Select e1, (select e2 FROM pm2.g1 Y WHERE X.e4 = Y.e4) from (select * from pm1.g1 UNION ALL select * from pm1.g1) as X"; //$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[] { "b", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /** defect 15124 */
- @Test public void testCorrelatedSubqueryAndInlineView4() {
- String sql = "Select e1, (select e2 FROM pm2.g1 Y WHERE X.e4 = Y.e4) from (select pm1.g1.e1, (select pm1.g1.e2 from pm1.g1 Z where pm1.g1.e1 = Z.e1), pm1.g1.e3, pm1.g1.e4 from pm1.g1) as X"; //$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[] { "b", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", null }), //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testXMLUnion_defect8373() {
- // Create query
- String sql = "SELECT * FROM xmltest.doc5"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] {
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
- "<root><node1><node2>a</node2></node1><node1><node2/></node1><node1><node2>a</node2></node1><node1><node2>c</node2></node1><node1><node2>b</node2></node1><node1><node2>a</node2></node1><node1><node2>a</node2></node1><node1><node2/></node1><node1><node2>a</node2></node1><node1><node2>c</node2></node1><node1><node2>b</node2></node1><node1><node2>a</node2></node1></root>" //$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 testStoredQuery1() {
- // Create query
- 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$
- };
-
- // 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 testStoredQuery2() {
- // Create query
- String sql = "EXEC pm1.sq2(\'a\')"; //$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[] { "a", new Integer(3) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0) }) //$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 testStoredQuery3() {
- // Create query
- String sql = "select x.e1 from (EXEC pm1.sq1()) as x"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { null}),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }), //$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 testStoredQuery4() {
- // Create query
- String sql = "EXEC pm1.sq5('a')"; //$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[] { "a", new Integer(3) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0) }) //$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 testStoredQuery5() {
- // Create query
- 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$
- };
-
- // 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 testStoredQuery6() {
- // Create query
- String sql = "EXEC pm1.sqsp1()"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { null}),
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b"}), //$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 testStoredQuery7() {
- // Create query
- String sql = "EXEC pm1.sq17()"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] {
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
- "<root><node1><node2><node3/></node2></node1></root>" //$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);
- }
-
- // implict type conversion of parameter
- @Test public void testStoredQuery8() {
- // Create query
- String sql = "EXEC pm1.sq5(5)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- };
-
- // 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);
- }
-
- // function for parameter
- @Test public void testStoredQuery9() {
- // Create query
- String sql = "EXEC pm1.sq5(concat('a', ''))"; //$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[] { "a", new Integer(3) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0) }) //$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);
- }
-
- /** named parameters */
- @Test public void testStoredQuery10() {
- // Create query
- String sql = "EXEC pm1.sq3b(\"in\" = 'a', in3 = 'something')"; //$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[] { "a", new Integer(3) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(0) }) //$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 testInsert() {
- // Create query
- String sql = "Insert into pm1.g1 (pm1.g1.e1, pm1.g1.e2) values ('MyString', 1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1)})
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData3(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey FROM BQT1.SmallA FULL OUTER JOIN BQT2.MediumB ON BQT1.SmallA.IntKey = BQT2.MediumB.IntKey WHERE (BQT1.SmallA.IntKey >= 0) AND (BQT1.SmallA.IntKey <= 15) AND (BQT2.MediumB.IntKey >= 5) AND (BQT2.MediumB.IntKey <= 20) */
- @Test public void testDefect7770_FullOuter() {
- // Create query
- String sql = "SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey FROM BQT1.SmallA FULL OUTER JOIN BQT2.MediumB ON BQT1.SmallA.IntKey = BQT2.MediumB.IntKey WHERE (BQT1.SmallA.IntKey >= 0) AND (BQT1.SmallA.IntKey <= 15) AND (BQT2.MediumB.IntKey >= 5) AND (BQT2.MediumB.IntKey <= 20)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(5), new Integer(5) }),
- Arrays.asList(new Object[] { new Integer(6), new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(7), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(8), new Integer(8) }),
- Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(11) }),
- Arrays.asList(new Object[] { new Integer(12), new Integer(12) }),
- Arrays.asList(new Object[] { new Integer(13), new Integer(13) }),
- Arrays.asList(new Object[] { new Integer(14), new Integer(14) }),
- Arrays.asList(new Object[] { new Integer(15), new Integer(15) })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT1(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey FROM BQT1.SmallA RIGHT OUTER JOIN BQT2.MediumB ON BQT1.SmallA.IntKey = BQT2.MediumB.IntKey WHERE (BQT1.SmallA.IntKey >= 0) AND (BQT1.SmallA.IntKey <= 15) AND (BQT2.MediumB.IntKey >= 5) AND (BQT2.MediumB.IntKey <= 20) */
- @Test public void testDefect7770_RightOuter() {
- // Create query
- String sql = "SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey FROM BQT1.SmallA RIGHT OUTER JOIN BQT2.MediumB ON BQT1.SmallA.IntKey = BQT2.MediumB.IntKey WHERE (BQT1.SmallA.IntKey >= 0) AND (BQT1.SmallA.IntKey <= 15) AND (BQT2.MediumB.IntKey >= 5) AND (BQT2.MediumB.IntKey <= 20)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(5), new Integer(5) }),
- Arrays.asList(new Object[] { new Integer(6), new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(7), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(8), new Integer(8) }),
- Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(11) }),
- Arrays.asList(new Object[] { new Integer(12), new Integer(12) }),
- Arrays.asList(new Object[] { new Integer(13), new Integer(13) }),
- Arrays.asList(new Object[] { new Integer(14), new Integer(14) }),
- Arrays.asList(new Object[] { new Integer(15), new Integer(15) })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT1(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /** SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey FROM BQT1.SmallA LEFT OUTER JOIN BQT2.MediumB ON BQT1.SmallA.IntKey = BQT2.MediumB.IntKey WHERE (BQT1.SmallA.IntKey >= 0) AND (BQT1.SmallA.IntKey <= 15) AND (BQT2.MediumB.IntKey >= 5) AND (BQT2.MediumB.IntKey <= 20) */
- @Test public void testDefect7770_LeftOuter() {
- // Create query
- String sql = "SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey FROM BQT1.SmallA LEFT OUTER JOIN BQT2.MediumB ON BQT1.SmallA.IntKey = BQT2.MediumB.IntKey WHERE (BQT1.SmallA.IntKey >= 0) AND (BQT1.SmallA.IntKey <= 15) AND (BQT2.MediumB.IntKey >= 5) AND (BQT2.MediumB.IntKey <= 20)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(5), new Integer(5) }),
- Arrays.asList(new Object[] { new Integer(6), new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(7), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(8), new Integer(8) }),
- Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(11) }),
- Arrays.asList(new Object[] { new Integer(12), new Integer(12) }),
- Arrays.asList(new Object[] { new Integer(13), new Integer(13) }),
- Arrays.asList(new Object[] { new Integer(14), new Integer(14) }),
- Arrays.asList(new Object[] { new Integer(15), new Integer(15) })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT1(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testReorder1() {
- // Create query
- String sql = "SELECT e1 AS x, {b'false'}, e2+e4, e3 FROM pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", Boolean.FALSE, new Double(2.0), Boolean.FALSE }), //$NON-NLS-1$
- Arrays.asList(new Object[] { null, Boolean.FALSE, new Double(2.0), Boolean.FALSE }),
- Arrays.asList(new Object[] { "a", Boolean.FALSE, new Double(10.0), Boolean.TRUE }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", Boolean.FALSE, null, Boolean.TRUE }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", Boolean.FALSE, new Double(2.0), Boolean.FALSE }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", Boolean.FALSE, new Double(2.0), Boolean.FALSE }) //$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 testTwoFullOuterJoins1() {
- // Create query
- String sql = "SELECT A.IntKey AS A_IntKey, B.IntKey AS B_IntKey, C.IntKey AS C_IntKey " + //$NON-NLS-1$
- "FROM (BQT1.SmallA AS A FULL OUTER JOIN BQT2.SmallA AS B ON A.IntKey = B.IntKey) FULL OUTER JOIN BQT3.SmallA AS C ON B.IntKey = C.IntKey " + //$NON-NLS-1$
- "WHERE (A.IntKey >= 0) AND (A.IntKey <= 15) " + //$NON-NLS-1$
- "AND (B.IntKey >= 5) AND (B.IntKey <= 20) " + //$NON-NLS-1$
- "AND (C.IntKey >= 10) AND (C.IntKey <= 30)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(10), new Integer(10), new Integer(10) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(11), new Integer(11) }),
- Arrays.asList(new Object[] { new Integer(12), new Integer(12), new Integer(12) }),
- Arrays.asList(new Object[] { new Integer(13), new Integer(13), new Integer(13) }),
- Arrays.asList(new Object[] { new Integer(14), new Integer(14), new Integer(14) }),
- Arrays.asList(new Object[] { new Integer(15), new Integer(15), new Integer(15) })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testSelectDistinctOnBQT() {
- // Create query
- String sql = "SELECT DISTINCT IntKey FROM BQT1.SmallA"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(5) }),
- Arrays.asList(new Object[] { new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(8) }),
- Arrays.asList(new Object[] { new Integer(9) }),
- Arrays.asList(new Object[] { new Integer(10) }),
- Arrays.asList(new Object[] { new Integer(11) }),
- Arrays.asList(new Object[] { new Integer(12) }),
- Arrays.asList(new Object[] { new Integer(13) }),
- Arrays.asList(new Object[] { new Integer(14) }),
- Arrays.asList(new Object[] { new Integer(15) }),
- Arrays.asList(new Object[] { new Integer(16) }),
- Arrays.asList(new Object[] { new Integer(17) }),
- Arrays.asList(new Object[] { new Integer(18) }),
- Arrays.asList(new Object[] { new Integer(19) })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT1(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testSelectWithNoFrom() {
- // Create query
- String sql = "SELECT 5"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(5) })
- };
-
- // 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 testBetween() {
- // Create query
- String sql = "SELECT * FROM pm1.g1 WHERE e2 BETWEEN 1 AND 2"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0) }),
- 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$
- };
-
- // 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 <code>QueryProcessor</code>'s ability to process a query containing
- * a <code>CASE</code> expression in which a <code>BETWEEN</code>
- * comparison is used in the queries <code>SELECT</code> statement.
- * <p>
- * For example:
- * <p>
- * SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1
- */
- @Test public void testBetweenInCase() {
- // Create query
- final String sql = "SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(-1) }),
- Arrays.asList(new Object[] { new Integer(-1) }),
- Arrays.asList(new Object[] { new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(-1) }),
- Arrays.asList(new Object[] { new Integer(-1) }),
- Arrays.asList(new Object[] { new Integer(-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 <code>QueryProcessor</code>'s ability to process a query containing
- * an aggregate SUM with a <code>CASE</code> expression in which a
- * <code>BETWEEN</code> comparison is used in the queries <code>SELECT</code>
- * statement.
- * <p>
- * For example:
- * <p>
- * SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1
- */
- @Test public void testBetweenInCaseInSum() {
- // Create query
- final String sql = "SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Long(-2) })
- };
-
- // 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 <code>QueryProcessor</code>'s ability to process a query containing
- * an aggregate SUM with a <code>CASE</code> expression in which a
- * <code>BETWEEN</code> comparison is used in the queries <code>SELECT</code>
- * statement and a GROUP BY is specified.
- * <p>
- * For example:
- * <p>
- * SELECT e1, SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END)
- * FROM pm1.g1 GROUP BY e1 ORDER BY e1
- */
- @Test public void testBetweenInCaseInSumWithGroupBy() {
- // Create query
- final String sql = "SELECT e1, SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1 GROUP BY e1 ORDER BY e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, new Long(-1) }),
- Arrays.asList(new Object[] { "a", new Long(1) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Long(-1) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c", new Long(-1) }) //$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 <code>QueryProcessor</code>'s ability to process a query containing
- * an aggregate COUNT with a <code>CASE</code> expression in which a
- * <code>BETWEEN</code> comparison is used in the queries <code>SELECT</code>
- * statement.
- * <p>
- * For example:
- * <p>
- * SELECT COUNT(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 END) FROM pm1.g1
- */
- @Test public void testBetweenInCaseInCount() {
- // Create query
- final String sql = "SELECT COUNT(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 END) FROM pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(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 testCase() {
- // Create query
- String sql = "SELECT e2, CASE e2 WHEN 1 THEN 2 ELSE 3 END FROM pm1.g1 WHERE e2 BETWEEN 1 AND 2"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(3) })
- };
-
- // 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 testSelectNoFrom1() {
- // Create query
- String sql = "SELECT 1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(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 testSelectNoFrom2() {
- // Create query
- String sql = "SELECT 1, {b'true'}, 2.0 AS x, {d'2003-11-04'}"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), Boolean.TRUE, new Double(2.0), TimestampUtil.createDate(103, 10, 4) })
- };
-
- // 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 testCase1566() throws Exception {
- // Create query
- String sql = "SELECT x, COUNT(*) FROM (SELECT convert(TimestampValue, date) AS x FROM bqt1.smalla) as y GROUP BY x"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { java.sql.Date.valueOf("2002-01-01"), new Integer(2) }),
- Arrays.asList(new Object[] { java.sql.Date.valueOf("2002-01-02"), new Integer(3) }) };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT_case1566(dataManager);
-
- // Create capabilities
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- // Parse query
- Command command = QueryParser.getQueryParser().parseCommand(sql);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.exampleBQTCached(), capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testDefect10976(){
- String sql = "SELECT * FROM vm1.g28"; //$NON-NLS-1$
-
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { "A", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "B", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "C", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // 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 testDefect10976_2(){
- String sql = "SELECT * FROM vm1.g29"; //$NON-NLS-1$
-
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { "A", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "B", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "C", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // 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 testDefect10976_3(){
- String sql = "SELECT * FROM vm1.g30"; //$NON-NLS-1$
-
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // 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 testDefect10976_4(){
- String sql = "SELECT * FROM vm1.g31 order by x"; //$NON-NLS-1$
-
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // 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 testDefect10976_5(){
- String sql = "SELECT * FROM vm1.g32"; //$NON-NLS-1$
-
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // 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 testDefect11236_MergeJoinWithFunctions() {
- // Create query
- String sql = "SELECT pm1.g1.e2, pm2.g1.e2 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e2 = (pm2.g1.e2+1) order by pm1.g1.e2, pm2.g1.e2"; //$NON-NLS-1$
- boolean pushDown = false;
- boolean dependent = false;
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(2) })
- };
-
- helpTestMergeJoinWithExpression(sql, pushDown, dependent, expected);
- }
-
- @Test public void testMergeJoinWithFunctionsPushDown() {
- // Create query
- String sql = "SELECT pm1.g1.e2, pm2.g1.e2 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e2 = (pm2.g1.e2+1)"; //$NON-NLS-1$
- boolean pushDown = true;
- boolean dependent = false;
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(2) })
- };
-
- helpTestMergeJoinWithExpression(sql, pushDown, dependent, expected);
- }
-
- @Test public void testMergeJoinWithFunctionsPushDownDependent() {
- // Create query
- String sql = "SELECT pm1.g1.e2, pm2.g1.e2 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e2 = (pm2.g1.e2+1) option makedep pm1.g1"; //$NON-NLS-1$
- boolean pushDown = true;
- boolean dependent = true;
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(2) })
- };
-
- helpTestMergeJoinWithExpression(sql, pushDown, dependent, expected);
- }
-
-
- /**
- * @param sql
- * @param pushDown
- * @param expected
- */
- private void helpTestMergeJoinWithExpression(String sql,
- boolean pushDown,
- boolean dependent,
- List[] expected) {
- // Construct data manager with data
- ProcessorDataManager dataManager = null;
- if (!pushDown) {
- FakeDataManager fakeDataManager = new FakeDataManager();
- sampleData1(fakeDataManager);
- dataManager = fakeDataManager;
- } else {
- HardcodedDataManager hardCoded = new HardcodedDataManager();
- List[] results = new List[] {
- Arrays.asList(new Object[] {new Integer(0), new Integer(1)}),
- Arrays.asList(new Object[] {new Integer(0), new Integer(1)}),
- Arrays.asList(new Object[] {new Integer(1), new Integer(2)}),
- Arrays.asList(new Object[] {new Integer(1), new Integer(2)}),
- Arrays.asList(new Object[] {new Integer(2), new Integer(3)}),
- Arrays.asList(new Object[] {new Integer(3), new Integer(4)}),
- };
- hardCoded.addData("SELECT g_0.e2 AS c_0, (g_0.e2 + 1) AS c_1 FROM pm2.g1 AS g_0 ORDER BY c_1", results); //$NON-NLS-1$
- if (!dependent) {
- results = new List[] {
- Arrays.asList(new Object[] {new Integer(0),}),
- Arrays.asList(new Object[] {new Integer(0),}),
- Arrays.asList(new Object[] {new Integer(1),}),
- Arrays.asList(new Object[] {new Integer(1),}),
- Arrays.asList(new Object[] {new Integer(2),}),
- Arrays.asList(new Object[] {new Integer(3),}),
- };
- hardCoded.addData("SELECT g_0.e2 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", results); //$NON-NLS-1$
- } else {
- results = new List[] {
- Arrays.asList(new Object[] {new Integer(1),}),
- Arrays.asList(new Object[] {new Integer(2),}),
- Arrays.asList(new Object[] {new Integer(1),}),
- };
- hardCoded.addData("SELECT g_0.e2 AS c_0 FROM pm1.g1 AS g_0 WHERE g_0.e2 IN (1, 2)", results); //$NON-NLS-1$
- results = new List[] {
- Arrays.asList(new Object[] {new Integer(3),}),
- };
- hardCoded.addData("SELECT g_0.e2 AS c_0 FROM pm1.g1 AS g_0 WHERE g_0.e2 IN (3, 4)", results); //$NON-NLS-1$
- }
- dataManager = hardCoded;
- }
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, pushDown);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, pushDown);
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(2));
- caps.setFunctionSupport("+", pushDown); //$NON-NLS-1$
- finder.addCapabilities("pm1", caps); //$NON-NLS-1$
- finder.addCapabilities("pm2", caps); //$NON-NLS-1$
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, finder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCase2() {
- // Create query
- String sql = "SELECT e2, CASE e2 WHEN 1 THEN 2 END FROM pm1.g1 WHERE e2 BETWEEN 1 AND 2"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2), null })
- };
-
- // 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 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$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2), null })
- };
-
- // 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);
- }
-
- /** nested scalar subquery */
- @Test public void testCase4() {
- // Create query
- String nestedExpression = "(SELECT e1 FROM pm1.g2 WHERE e2 = 3)"; //$NON-NLS-1$
- String sql = "SELECT e2, CASE e2 WHEN 1 THEN " + nestedExpression + " ELSE null END FROM pm1.g1 WHERE e2 BETWEEN 1 AND 2"; //$NON-NLS-1$ //$NON-NLS-2$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(1), "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(2), null })
- };
-
- // 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);
- }
-
- /** nested correlated scalar subquery */
- @Test public void testCase5() {
- // Create query
- String nestedExpression = "(SELECT e2 FROM pm1.g2 WHERE pm1.g1.e2 = (e4 + 2))"; //$NON-NLS-1$
- String sql = "SELECT e2, CASE e2 WHEN " + nestedExpression + " THEN 1 ELSE null END FROM pm1.g1"; //$NON-NLS-1$ //$NON-NLS-2$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0), null }),
- Arrays.asList(new Object[] { new Integer(1), null }),
- Arrays.asList(new Object[] { new Integer(3), null }),
- Arrays.asList(new Object[] { new Integer(1), null }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(0), null })
- };
-
- // 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);
- }
-
- /**
- * NOTE: this test depends on the ProcessorPlan being executed
- * twice and reset in between, which currently is done in the
- * helpProcess method
- */
- @Test public void testDefect12135(){
- String sql = "SELECT pm1.g1.e1, pm1.g2.e1 FROM pm1.g1 LEFT OUTER JOIN pm1.g2 ON pm1.g1.e1=pm1.g2.e1"; //$NON-NLS-1$
-
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testDefect12081(){
- String sql = "SELECT DISTINCT vm1.g1.e1, upper(vm1.g1.e1) as Nuge, pm1.g1.e1, upper(pm1.g1.e1) as Nuge FROM vm1.g1, pm1.g1"; //$NON-NLS-1$
-
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", "A", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "a", "A", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "a", "A", "c", "C" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "b", "B", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "b", "B", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "b", "B", "c", "C" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "c", "C", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "c", "C", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "c", "C", "c", "C" }) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testDefect12081_2(){
- String sql = "SELECT DISTINCT vm1.g1b.e1, vm1.g1b.e1Upper, pm1.g1.e1, upper(pm1.g1.e1) as e1Upper FROM vm1.g1b, pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", "A", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "a", "A", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "a", "A", "c", "C" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "b", "B", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "b", "B", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "b", "B", "c", "C" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "c", "C", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "c", "C", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "c", "C", "c", "C" }) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testDefect12081_3(){
- String sql = "SELECT DISTINCT vm1.g1b.e1, vm1.g1b.e1Upper, pm1.g1.e1, vm1.g1b.e1Upper FROM vm1.g1b, pm1.g1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", "A", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "a", "A", "b", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "a", "A", "c", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "b", "B", "a", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "b", "B", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "b", "B", "c", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "c", "C", "a", "C" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "c", "C", "b", "C" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { "c", "C", "c", "C" }) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Basically the same as above, but with a limit node between the dup removal and the project
- */
- @Test public void testDefect12081_4(){
- String sql = "SELECT DISTINCT e1, e1 FROM pm1.g1 where e1 = 'a' LIMIT 1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", "a"}), //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testDefect12719(){
- String sql = "SELECT e1_, e2_, e2 FROM vm1.g34, pm1.g2 WHERE vm1.g34.e1_ = pm1.g2.e1 order by e1_, e2_"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0), new Integer(1) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(0), new Integer(0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(0), new Integer(5) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(0), new Integer(2) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(1), new Integer(0) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(1), new Integer(5) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(1), new Integer(2) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "d", new Integer(3), new Integer(2) }), //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testDefect13034() {
- String sql = "SELECT CONCAT('http://', CONCAT(CASE WHEN (HOST IS NULL) OR (HOST = '') THEN 'soap_host' ELSE HOST END, CASE WHEN (PORT IS NULL) OR (PORT = '') THEN '/metamatrix-soap/services/DataService' ELSE CONCAT(':', CONCAT(PORT, '/metamatrix-soap/services/DataService')) END)) AS location " + //$NON-NLS-1$
- "FROM (SELECT env('soap_host') AS HOST, env('soap_port') AS PORT) AS props"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "http://my.host.com:12345/metamatrix-soap/services/DataService" }), //$NON-NLS-1$
- };
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, new FakeDataManager(), expected);
-
- }
-
- /** see also integer average defect 11682 */
- @Test public void testIntAvgDefect11682() {
- // Create query
- String sql = "SELECT AVG(IntKey), AVG(IntNum), AVG(FloatNum), AVG(LongNum), AVG(DoubleNum), AVG(ByteNum), AVG(ShortValue), AVG(BigIntegerValue), AVG(BigDecimalValue) FROM BQT1.SmallA"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Double(1.5), new Double(1.5), new Double(1.5), new Double(1.5), new Double(1.5), new Double(1.5), new Double(1.5), new BigDecimal("1.500000000"), new BigDecimal("1.500000000") }), //$NON-NLS-1$//$NON-NLS-2$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT_defect11682(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testNonJoinCriteriaInFrom() {
- String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a LEFT OUTER JOIN pm2.g1 b ON a.e1=b.e1 AND b.e2 = 0"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", null, null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", "b", new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", null, null }), //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testNonJoinCriteriaInWhere() {
- String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a LEFT OUTER JOIN pm2.g1 b ON a.e1=b.e1 WHERE b.e2 = 0"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "b", "b", new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testNonJoinCriteriaInWhere2() {
- String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a LEFT OUTER JOIN pm1.g2 b ON a.e1=b.e1 WHERE (a.e2 + b.e2 = 1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", "a", new Integer(1) }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b", new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testNonJoinCriteriaInWhere3() {
- String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a LEFT OUTER JOIN pm1.g2 b ON a.e1=b.e1 WHERE (a.e2 = 0) OR (b.e2 = 0)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", "a", new Integer(1) }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b", new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testNonJoinCriteriaInFromNestedInVirtual() {
- String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a LEFT OUTER JOIN (SELECT c.e1, d.e2 FROM pm2.g1 c JOIN pm2.g1 d ON c.e1=d.e1 AND d.e2 >= 0) b ON a.e1=b.e1 AND b.e2 = 0"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", null, null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", "b", new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", null, null }), //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testNonJoinCriteriaInFromUsingDependentJoin() {
- String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a LEFT OUTER JOIN pm2.g1 b ON a.e1=b.e1 AND b.e2 = 0"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", null, null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", "b", new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", null, null }), //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2a(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testDefect13700() {
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(10) }),
- };
-
- // Plan query
- ProcessorPlan plan = helpGetPlan("EXEC pm1.vsp36(5)", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
-
- // Run query
- helpProcess(plan, new FakeDataManager(), expected);
-
- }
-
- @Test public void testDefect13920() throws Exception {
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, false);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, false);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- 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);
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataStringTimestamps(dataManager);
-
- Calendar cal = Calendar.getInstance();
- cal.set(2004, Calendar.DECEMBER, 31, 0, 0, 0);
- cal.set(Calendar.MILLISECOND, 0);
- Timestamp t1 = new Timestamp(cal.getTime().getTime());
- cal.clear();
- cal.set(2004, Calendar.AUGUST, 1, 0, 0, 0);
- cal.set(Calendar.MILLISECOND, 0);
- Timestamp t2 = new Timestamp(cal.getTime().getTime());
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { t1, new Integer(1), Boolean.TRUE, null }),
- Arrays.asList(new Object[] { t2, new Integer(2), Boolean.FALSE, new Double(0.0) }),
- };
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- /** RLM Case 2077
- * @throws Exception */
- @Test public void testComplexJoinExpressionsUsingDependentJoin() throws Exception {
- String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a, pm2.g1 b where rtrim(a.e1)=(b.e1 || b.e1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- 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();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
- caps.setFunctionSupport("||", true); //$NON-NLS-1$
- caps.setFunctionSupport("rtrim", true); //$NON-NLS-1$
- 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));
-
- Command command = helpParse(sql);
- CommandContext context = createCommandContext();
- context.setMetadata(metadata);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder,context);
-
- //Verify a dependent join (not merge join) was used
- assertTrue(plan instanceof RelationalPlan);
- RelationalPlan relationalPlan = (RelationalPlan)plan;
- RelationalNode project = relationalPlan.getRootNode();
- RelationalNode join = project.getChildren()[0];
- assertTrue("Expected instance of JoinNode (for dep join) but got " + join.getClass(), join instanceof JoinNode); //$NON-NLS-1$
-
- // Run query
- helpProcess(plan, context, dataManager, expected);
- }
-
- /** RLM Case 2077
- * @throws Exception */
- @Test public void testComplexJoinExpressionsUsingDependentJoinWithAccessPattern() throws Exception {
- String sql = "SELECT a.e1, b.e1, b.e2 FROM pm4.g1 a, pm2.g1 b where rtrim(a.e1)=(b.e1 || b.e1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- 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();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
- caps.setFunctionSupport("||", true); //$NON-NLS-1$
- caps.setFunctionSupport("rtrim", true); //$NON-NLS-1$
- 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));
-
- Command command = helpParse(sql);
- CommandContext context = createCommandContext();
- context.setMetadata(metadata);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder, context);
-
- //Verify a dependent join (not merge join) was used
- assertTrue(plan instanceof RelationalPlan);
- RelationalPlan relationalPlan = (RelationalPlan)plan;
- RelationalNode project = relationalPlan.getRootNode();
- RelationalNode join = project.getChildren()[0];
- assertTrue("Expected instance of JoinNode (for dep join) but got " + join.getClass(), join instanceof JoinNode); //$NON-NLS-1$
-
- // Run query
- helpProcess(plan, context, dataManager, expected);
- }
-
- @Test public void testPushingCriteriaUnderJoinButNotToSource() {
- // Create query
- String sql = "SELECT A.IntKey AS A_IntKey, B.IntKey AS B_IntKey, C.IntKey AS C_IntKey " + //$NON-NLS-1$
- "FROM (BQT1.SmallA AS A FULL OUTER JOIN BQT2.SmallA AS B ON A.IntKey = B.IntKey) LEFT OUTER JOIN BQT3.SmallA AS C ON B.IntKey = C.IntKey " + //$NON-NLS-1$
- "WHERE (sin(A.IntKey) >= 0) " + //$NON-NLS-1$
- "AND (C.IntKey >= 10)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(13), new Integer(13), new Integer(13) }),
- Arrays.asList(new Object[] { new Integer(14), new Integer(14), new Integer(14) }),
- Arrays.asList(new Object[] { new Integer(15), new Integer(15), new Integer(15) }),
- Arrays.asList(new Object[] { new Integer(19), new Integer(19), new Integer(19) }),
- Arrays.asList(new Object[] { new Integer(20), new Integer(20), new Integer(20) }),
- Arrays.asList(new Object[] { new Integer(21), new Integer(21), new Integer(21) }),
- Arrays.asList(new Object[] { new Integer(26), new Integer(26), new Integer(26) }),
- Arrays.asList(new Object[] { new Integer(27), new Integer(27), new Integer(27) }),
- Arrays.asList(new Object[] { new Integer(28), new Integer(28), new Integer(28) })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testPushdownLiteralInSelectUnderAggregate() {
- String sql = "SELECT COUNT(*) FROM (SELECT '' AS y, a.IntKey FROM BQT1.SmallA a union all select '', b.intkey from bqt1.smallb b) AS x"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(30) })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT2(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- 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();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testPushdownLiteralInSelectWithOrderBy() {
- String sql = "SELECT 1, concat('a', 'b' ) AS X FROM BQT1.SmallA where intkey = 0 " + //$NON-NLS-1$
- "UNION ALL " + //$NON-NLS-1$
- "select 2, 'Hello2' from BQT1.SmallA where intkey = 1 order by X desc"; //$NON-NLS-1$
-
-
- // Create expected results - would expect these to be:
- // 1, "ab"
- // 2, "Hello2"
- // but our fake tuple source is too dumb to return anything reasonable, so instead get:
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, null }),
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQTSmall(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /** defect 15348
- * @throws Exception */
- @Test public void testPreparedStatementDefect15348() throws Exception{
- String sql = "SELECT e1 from pm1.g1 where myrtrim(?)=e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2a(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- 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);
-
- processPreparedStatement(sql, expected, dataManager, capFinder,
- metadata, Arrays.asList("a "));
- }
-
- static void processPreparedStatement(String sql, List[] expected,
- ProcessorDataManager dataManager, CapabilitiesFinder capFinder,
- QueryMetadataInterface metadata, List<?> values) throws Exception {
- Command command = helpParse(sql);
- CommandContext context = createCommandContext();
- context.setMetadata(metadata);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder, context);
-
- // Collect reference, set value
- VariableContext vc = new VariableContext();
- Iterator<?> valIter = values.iterator();
- for (Reference ref : ReferenceCollectorVisitor.getReferences(command)) {
- vc.setGlobalValue(ref.getContextSymbol(), valIter.next()); //$NON-NLS-1$
- }
- context.setVariableContext(vc);
- // Run query
- helpProcess(plan, context, dataManager, expected);
- }
-
- /** defect 15348
- * @throws Exception */
- @Test public void testPreparedStatementDefect15348b() throws Exception{
- String sql = "SELECT e1 from pm4.g1 where myrtrim(concat(?, 'a '))=e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "aa" }) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2a(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setFunctionSupport("myrtrim", true); //$NON-NLS-1$
- 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);
-
- processPreparedStatement(sql, expected, dataManager, capFinder,
- metadata, Arrays.asList("a"));
- }
-
- @Test public void testSourceDoesntSupportGroupAlias() {
- String sql = "SELECT a.IntKey, b.IntKey FROM BQT1.SmallA a, BQT1.SmallB b WHERE a.IntKey = 5 AND A.IntKey = b.IntKey"; //$NON-NLS-1$
-
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- Set atomicQueries = TestOptimizer.getAtomicQueries(plan);
- assertEquals("Expected one query to get pushed down", 1, atomicQueries.size()); //$NON-NLS-1$
- String atomicSql = atomicQueries.iterator().next().toString();
- String expectedSql = "SELECT BQT1.SmallA.IntKey, BQT1.SmallB.IntKey FROM BQT1.SmallA, BQT1.SmallB WHERE (BQT1.SmallA.IntKey = BQT1.SmallB.IntKey) AND (BQT1.SmallA.IntKey = 5) AND (BQT1.SmallB.IntKey = 5)"; //$NON-NLS-1$
- assertEquals(expectedSql, atomicSql);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(5), new Integer(5)}),
- };
-
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData(expectedSql, expected);
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testSourceDoesntSupportGroupAliasOrCriteria() {
- String sql = "SELECT a.IntKey, b.IntKey FROM BQT1.SmallA a, BQT1.SmallB b WHERE a.StringKey = '5' AND A.IntKey = b.IntKey"; //$NON-NLS-1$
-
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- Set atomicQueries = TestOptimizer.getAtomicQueries(plan);
- assertEquals("Expected 2 queries to get pushed down", 2, atomicQueries.size()); //$NON-NLS-1$
-
- String expectedSql = "SELECT BQT1.SmallA.StringKey, BQT1.SmallA.IntKey FROM BQT1.SmallA"; //$NON-NLS-1$
- String expectedSql2 = "SELECT BQT1.SmallB.IntKey FROM BQT1.SmallB"; //$NON-NLS-1$
- Set expectedQueries = new HashSet();
- expectedQueries.add(expectedSql);
- expectedQueries.add(expectedSql2);
- assertEquals(expectedQueries, atomicQueries);
-
- List[] input1 = new List[] {
- Arrays.asList(new Object[] { "5", new Integer(5)}), //$NON-NLS-1$
- };
- List[] input2 = new List[] {Arrays.asList(new Object[] {new Integer(5)}),
- };
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData(expectedSql, input1);
- dataManager.addData(expectedSql2, input2);
-
- List[] expected = new List[] {Arrays.asList(new Object[] {new Integer(5), new Integer(5)}),
- };
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Same as testSourceDoesntSupportGroupAlias, but query is in an inline view and only
- * the first column is selected.
- *
- * @since 4.2
- */
- @Test public void testSourceDoesntSupportGroupAliasInVirtual() {
- String sql = "SELECT x FROM (SELECT a.IntKey as x, b.IntKey as y FROM BQT1.SmallA a, BQT1.SmallB b WHERE a.IntKey = 5 AND A.IntKey = b.IntKey) AS z, BQT2.SmallA WHERE y = IntKey"; //$NON-NLS-1$
-
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- Set atomicQueries = TestOptimizer.getAtomicQueries(plan);
- assertEquals("Expected 2 queries to get pushed down", 2, atomicQueries.size()); //$NON-NLS-1$
-
- String expectedSql = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA, BQT1.SmallB WHERE (BQT1.SmallA.IntKey = BQT1.SmallB.IntKey) AND (BQT1.SmallA.IntKey = 5) AND (BQT1.SmallB.IntKey = 5)"; //$NON-NLS-1$
- String expectedSql2 = "SELECT BQT2.SmallA.IntKey FROM BQT2.SmallA WHERE BQT2.SmallA.IntKey = 5"; //$NON-NLS-1$
-
- Set expectedQueries = new HashSet();
- expectedQueries.add(expectedSql);
- expectedQueries.add(expectedSql2);
- assertEquals(expectedQueries, atomicQueries);
-
- List[] input1 = new List[] {
- Arrays.asList(new Object[] { new Integer(5), new Integer(5)}),
- };
- List[] input2 = new List[] {
- Arrays.asList(new Object[] { new Integer(5)}),
- };
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData(expectedSql, input1);
- dataManager.addData(expectedSql2, input2);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(5)}),
- };
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCaseInGroupBy() {
- 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_SEARCHED_CASE, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- Set actualQueries = TestOptimizer.getAtomicQueries(plan);
- String expectedSql = "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$
- assertEquals(1, actualQueries.size());
- assertEquals(expectedSql, actualQueries.iterator().next().toString());
-
- List[] input1 = new List[] {
- Arrays.asList(new Object[] { new Integer(5), new Integer(10)}),
- };
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData(expectedSql, input1);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(5), new Integer(10)}),
- };
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCaseInGroupByAndHavingCantPush() {
- 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$
- "HAVING case when IntKey>=5000 then '5000 +' else '0-999' end = '5000 +'"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, false); // Can't push GROUP BY
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- Set actualQueries = TestOptimizer.getAtomicQueries(plan);
- String expectedSql = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA"; //$NON-NLS-1$
- assertEquals(1, actualQueries.size());
- assertEquals(expectedSql, actualQueries.iterator().next().toString());
-
- List[] input1 = new List[] {
- Arrays.asList(new Object[] { new Integer(2)}),
- Arrays.asList(new Object[] { new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(10000)}),
- Arrays.asList(new Object[] { new Integer(10002)}),
- };
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData(expectedSql, input1);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Long(20002), "5000 +"}), //$NON-NLS-1$
- };
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCaseInGroupByAndHavingCantPush2() {
- String sql = "SELECT sum (IntKey), case when IntKey>=5000 then '5000 +' else '0-999' end || 'x' " + //$NON-NLS-1$
- "FROM BQT1.SmallA GROUP BY case when IntKey>=5000 then '5000 +' else '0-999' end " + //$NON-NLS-1$
- "HAVING length(case when IntKey>=5000 then '5000 +' else '0-999' end) > 5"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, false); // Can't push GROUP BY
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- Set actualQueries = TestOptimizer.getAtomicQueries(plan);
- String expectedSql = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA"; //$NON-NLS-1$
- assertEquals(1, actualQueries.size());
- assertEquals(expectedSql, actualQueries.iterator().next().toString());
-
- List[] input1 = new List[] {
- Arrays.asList(new Object[] { new Integer(2)}),
- Arrays.asList(new Object[] { new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(10000)}),
- Arrays.asList(new Object[] { new Integer(10002)}),
- };
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData(expectedSql, input1);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Long(20002), "5000 +x"}), //$NON-NLS-1$
- };
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCaseInGroupByAndHavingCantPush3() {
- String sql = "SELECT s, c FROM (" + //$NON-NLS-1$
- "SELECT sum (IntKey) s, case when IntKey>=5000 then '5000 +' else '0-999' end || 'x' c " + //$NON-NLS-1$
- "FROM BQT1.SmallA GROUP BY case when IntKey>=5000 then '5000 +' else '0-999' end " + //$NON-NLS-1$
- ") AS x WHERE length(c) > 5 AND s = 20002"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, false); // Can't push GROUP BY
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- Set actualQueries = TestOptimizer.getAtomicQueries(plan);
- String expectedSql = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA"; //$NON-NLS-1$
- assertEquals(1, actualQueries.size());
- assertEquals(expectedSql, actualQueries.iterator().next().toString());
-
- List[] input1 = new List[] {
- Arrays.asList(new Object[] { new Integer(2)}),
- Arrays.asList(new Object[] { new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(10000)}),
- Arrays.asList(new Object[] { new Integer(10002)}),
- };
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData(expectedSql, input1);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Long(20002), "5000 +x"}), //$NON-NLS-1$
- };
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testFunctionOfAggregateCantPush() {
- String sql = "SELECT StringKey || 'x', SUM(length(StringKey || 'x')) + 1 AS x FROM BQT1.SmallA GROUP BY StringKey || 'x' HAVING space(MAX(length((StringKey || 'x') || 'y'))) = ' '"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- Set actualQueries = TestOptimizer.getAtomicQueries(plan);
- String expectedSql = "SELECT BQT1.SmallA.StringKey FROM BQT1.SmallA"; //$NON-NLS-1$
- assertEquals(1, actualQueries.size());
- assertEquals(expectedSql, actualQueries.iterator().next().toString());
-
- List[] input1 = new List[] {
- Arrays.asList(new Object[] { "0"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "1"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "10"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "11"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "100"}), //$NON-NLS-1$
- };
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData(expectedSql, input1);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "0x", new Long(3)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "1x", new Long(3)}), //$NON-NLS-1$
- };
- helpProcess(plan, dataManager, expected);
- }
-
-
- @Test public void testCase2634() {
-
- String sql = "SELECT x, IntKey FROM (SELECT IntKey, 'a' AS x FROM BQT1.SmallA UNION ALL SELECT IntKey, 'b' AS x FROM BQT1.SmallB) as Z"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- Set actualQueries = TestOptimizer.getAtomicQueries(plan);
- String expectedSql = "SELECT 'a' AS c_0, BQT1.SmallA.IntKey AS c_1 FROM BQT1.SmallA UNION ALL SELECT 'b' AS c_0, BQT1.SmallB.IntKey AS c_1 FROM BQT1.SmallB"; //$NON-NLS-1$
- assertEquals(1, actualQueries.size());
- assertEquals(expectedSql, actualQueries.iterator().next().toString());
-
- List[] input1 = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(1)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(0)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(1)}), //$NON-NLS-1$
- };
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData(expectedSql, input1);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(0)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(1)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(0)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", new Integer(1)}), //$NON-NLS-1$
- };
- helpProcess(plan, dataManager, expected);
-
- }
-
- @Test public void testQueryWithoutFromWithOrderBy() {
-
- String sql = "select 'three' as x ORDER BY x"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "three"} ), //$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 testQueryWithoutFromWithOrderBy2() {
-
- String sql = "select concat('three', ' sixteen') as x ORDER BY x"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "three sixteen"} ), //$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 testQueryWithoutFromWithOrderBy3() {
-
- String sql = "SELECT CONCAT('yy', 'z') as c1234567890123456789012345678901234567890, " + //$NON-NLS-1$
- "CONCAT('21', '12') AS EXPR ORDER BY c1234567890123456789012345678901234567890"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "yyz", "2112"} ), //$NON-NLS-1$ //$NON-NLS-2$
- };
- // 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 testCase2507_3(){
-
- String sql = "SELECT CONCAT('yy', 'z') AS c1234567890123456789012345678901234567890, " + //$NON-NLS-1$
- "CONCAT('21', '12') AS EXPR ORDER BY c1234567890123456789012345678901234567890"; //$NON-NLS-1$
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
- caps.setFunctionSupport("concat", true); //$NON-NLS-1$
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql,
- metadata,
- null, capFinder,
- new String[0] ,
- TestOptimizer.SHOULD_SUCCEED );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 0, // 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
- 0 // UnionAll
- });
-
- // TEST PROCESSING
-
- List[] expectedResults = new List[] {
- Arrays.asList(new Object[] { "yyz", "2112"}), //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT1(dataManager);
-
- // Run query
- helpProcess(plan, dataManager, expectedResults);
-
- }
-
- @Test public void testMultiGroupJoinCriteria() {
-
- String sql = "SELECT X.NEWFIELD FROM " + //$NON-NLS-1$
- "(SELECT SMALLA.STRINGNUM, " + //$NON-NLS-1$
- "CASE WHEN SMALLA.STRINGNUM LIKE '1%' THEN SMALLA.INTKEY " + //$NON-NLS-1$
- "WHEN SMALLA.STRINGNUM LIKE '2%' THEN SMALLB.INTNUM " + //$NON-NLS-1$
- "WHEN SMALLA.STRINGNUM LIKE '3%' THEN MEDIUMA.INTKEY " + //$NON-NLS-1$
- "END AS NEWFIELD " + //$NON-NLS-1$
- "FROM BQT1.SMALLA, BQT1.SMALLB, BQT1.MEDIUMA " + //$NON-NLS-1$
- "WHERE SMALLA.INTKEY = SMALLB.INTKEY AND SMALLA.INTKEY = MEDIUMA.INTKEY) AS X " + //$NON-NLS-1$
- "WHERE X.NEWFIELD = -3"; //$NON-NLS-1$
-
- String expectedAtomic1 = "SELECT BQT1.SMALLB.INTKEY, BQT1.SMALLB.INTNUM FROM BQT1.SMALLB"; //$NON-NLS-1$
- String expectedAtomic2 = "SELECT BQT1.MEDIUMA.INTKEY FROM BQT1.MEDIUMA"; //$NON-NLS-1$
- String expectedAtomic3 = "SELECT BQT1.SMALLA.INTKEY, BQT1.SMALLA.STRINGNUM FROM BQT1.SMALLA"; //$NON-NLS-1$
-
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql,
- metadata,
- null, capFinder,
- new String[] {expectedAtomic1, expectedAtomic2, expectedAtomic3} ,
- TestOptimizer.SHOULD_SUCCEED );
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 3, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 2, // MergeJoin
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- // TEST PROCESSING
-
- List[] expectedResults = new List[] {
- Arrays.asList(new Object[] { new Integer(-3) }),
- };
-
- // Construct data manager with data
- HardcodedDataManager dataManager = new HardcodedDataManager();
- List[] input1 = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(-4)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(-3)}),
- Arrays.asList(new Object[] { new Integer(3), new Integer(-2)}),
- };
- dataManager.addData(expectedAtomic1, input1);
- List[] input2 = new List[] {
- Arrays.asList(new Object[] { new Integer(1)}),
- Arrays.asList(new Object[] { new Integer(2)}),
- Arrays.asList(new Object[] { new Integer(3)}),
- };
- dataManager.addData(expectedAtomic2, input2);
- List[] input3 = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new String("1")}), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(2), new String("2")}), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(3), new String("3")}), //$NON-NLS-1$
- };
- dataManager.addData(expectedAtomic3, input3);
-
- // Run query
- helpProcess(plan, dataManager, expectedResults);
-
- }
-
- /**
- * Cross-source join with group by on top but no aggregate functions - running some special cases
- * where there are no "aggregate groups" (the groups of the aggregate expressions) because there
- * are no aggregate expressions. In this case, need to switch the aggregate groups to be all the grouping
- * columns because they are all being "grouped on".
- *
- * @since 4.3
- */
- @Test public void testDefect18360(){
-
- String sql = "SELECT a.intkey, a.intnum FROM bqt1.smalla a join bqt2.mediumb b on a.stringkey = b.stringkey " + //$NON-NLS-1$
- "group by a.intkey, a.intnum"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- capFinder.addCapabilities("BQT1", new BasicSourceCapabilities()); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", new BasicSourceCapabilities()); //$NON-NLS-1$
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.exampleBQTCached(), capFinder);
-
- // Construct data manager with data
- HardcodedDataManager dataManager = new HardcodedDataManager();
- List[] data1 = new List[] {
- Arrays.asList(new Object[] { "1", new Integer(1), new Integer(5) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2", new Integer(2), new Integer(6) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "3", new Integer(3), new Integer(7) }), //$NON-NLS-1$
- };
- dataManager.addData("SELECT bqt1.smalla.stringkey, bqt1.smalla.intkey, bqt1.smalla.intnum FROM bqt1.smalla", data1); //$NON-NLS-1$
-
- List[] data2 = new List[] {
- Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "3" }), //$NON-NLS-1$
- };
- dataManager.addData("SELECT bqt2.mediumb.stringkey FROM bqt2.mediumb", data2); //$NON-NLS-1$
-
- // Run query
- List[] expectedResults = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(5) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(7) }),
- };
- helpProcess(plan, dataManager, expectedResults);
-
- }
-
- @Test public void testDefect17407(){
- String sql = "select pm1.g1.e1 from pm1.g1, g7 MAKEDEP WHERE pm1.g1.e2=g7.e2 order by e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null}),
- Arrays.asList(new Object[] { null}),
- 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$
- Arrays.asList(new Object[] { "c"}),//$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 testDecodeAsCriteria() {
- // Create query
- String sql = "SELECT x.foo, e2 FROM (select decodestring(e1, 'a,q,b,w') as foo, e2 from vm1.g1) as x where x.foo = 'w'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "w", new Integer(2) }), //$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 testInputParamInNestedExecParam() {
- // Create query
- String sql = "EXEC pm1.vsp48('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 testVariableInExecParam() {
- // Create query
- String sql = "EXEC pm1.vsp49()"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "b", new Integer(2) }), //$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 testVariableInNestedExecParam() {
- // Create query
- String sql = "EXEC pm1.vsp50()"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "b" }), //$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 testVariableInNestedExecParamInLoop() {
- // Create query
- String sql = "EXEC pm1.vsp51()"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "bb" }), //$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 testVariableInNestedExecParamInAssignment() {
- // Create query
- String sql = "EXEC pm1.vsp52()"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "c" }), //$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 testInputParamInNestedExecParamInLoop() {
- // Create query
- String sql = "EXEC pm1.vsp53('b')"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "bb" }), //$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 testInputParamInNestedExecParamInAssignment() {
- // Create query
- String sql = "EXEC pm1.vsp54('c')"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "c" }), //$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 testBitwiseAggregateProc() {
- // Create query
- String sql = "EXEC virt.agg()"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0), "a", new Integer(19) }), //$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(3) }), //$NON-NLS-1$
- };
-
- // Plan query
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleBitwise();
- ProcessorPlan plan = helpGetPlan(sql, metadata);
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBitwise(dataManager, metadata);
-
- // Run query
- 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$
- }
- }
-
- @Test public void testFunctionGroupByInJoinCriteria() {
- // Create query
- String sql = "SELECT lower(vm1.g1.e1) from vm1.g1, vm1.g2a where vm1.g1.e1 = vm1.g2a.e1 group by lower(vm1.g1.e1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- 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();
- sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.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$
-
- FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$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$
-
- 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$
-
- 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);
- }
-
- @Test public void testProjectionErrorOverUnionWithConvert() {
- // Create query
- FakeMetadataFacade metadata = createProjectErrorMetadata();
- String sql = "SELECT COUNT(*) FROM v1.u1"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- capFinder.addCapabilities("p1", caps); //$NON-NLS-1$
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(2) }),
- };
-
- // Construct data manager with data
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData("SELECT 1 AS c_0 FROM p1.t AS g_1 UNION ALL SELECT 1 AS c_0 FROM p1.t AS g_0", //$NON-NLS-1$
- new List[] { Arrays.asList(1), Arrays.asList(1)});
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testUpdatesInLoop() {
- String sql = "update vm1.g39 set e2=3"; //$NON-NLS-1$
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
-
- // Construct data manager with data
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData("SELECT g_0.e2 FROM pm1.g1 AS g_0 WHERE g_0.e2 = 3", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(3) } )});
- dataManager.addData("UPDATE pm1.g1 SET e2 = 3 WHERE pm1.g1.e2 = 3", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(1) } )});
-
- // Create expected results
- List[] expected = new List[] { Arrays.asList(0)};
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- @Test public void testRand() {
- // Create query
- String sql = "SELECT RAND(E2) FROM pm1.g1 where pm1.g1.e2=3"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] {new Double(0.731057369148862)}),
- };
-
- // 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);
- }
-
- /*
- * Prior to case 3994 testInsertTempTableCreation1 worked, but testInsertTempTableCreation did not.
- * Now they should both pass
- *
- */
- @Test public void testInsertTempTableCreation() {
- FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$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$
-
- FakeMetadataStore store = new FakeMetadataStore();
- store.addObject(v1);
- store.addObject(vp);
-
- ProcessorPlan plan = helpGetPlan("exec v1.vp()", new FakeMetadataFacade(store)); //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1) })
- };
- helpProcess(plan, new FakeDataManager(), expected);
- }
-
- @Test public void testInsertTempTableCreation1() {
- FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$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$
-
- FakeMetadataStore store = new FakeMetadataStore();
- store.addObject(v1);
- store.addObject(vp);
-
- 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) })
- };
- helpProcess(plan, new FakeDataManager(), expected);
- }
-
- @Test public void testCase4531() {
- String sql = "select intkey, intnum from (select intnum as intkey, 1 as intnum from bqt1.smalla union all select intkey, intnum from bqt1.smalla union all select intkey, intnum from bqt2.smalla) x"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_UNION, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.exampleBQTCached(), capFinder);
-
- // Run query
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- };
-
- // Construct data manager with data
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.addData("SELECT g_0.intkey, g_0.intnum FROM bqt2.smalla AS g_0", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(1), new Integer(1) })});
- dataManager.addData("SELECT g_1.intnum AS c_0, 1 AS c_1 FROM bqt1.smalla AS g_1 UNION ALL SELECT g_0.IntKey AS c_0, g_0.IntNum AS c_1 FROM bqt1.smalla AS g_0", //$NON-NLS-1$
- new List[] { Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) })});
- helpProcess(plan, dataManager, expected);
- }
-
- private void sampleDataBQT2a(FakeDataManager dataMgr) throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- String[] groups = new String[] {"bqt1.smalla", "bqt2.smalla", "bqt3.smalla" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- for(int groupIndex=0; groupIndex<groups.length; groupIndex++) {
- String groupName = groups[groupIndex];
-
- List[] tuples = new List[3];
- for(int row=0; row<tuples.length; row++) {
- tuples[row] = new ArrayList(17);
- tuples[row].add(new Integer(row)); //IntKey
- tuples[row].add(String.valueOf(row)); //StringKey
- tuples[row].add(new Integer(row)); //IntNum
- tuples[row].add(String.valueOf(row)); //StringNum
- for(int col=0; col<10; col++) { //FloatNum, LongNum, DoubleNum, ByteNum, DateValue, TimeValue, TimestampValue, BooleanValue, CharValue, ShortValue
- tuples[row].add(null);
- }
- tuples[row].add(new BigInteger(String.valueOf(row))); //BigIntegerValue
- tuples[row].add(new BigDecimal(row)); //BigDecimalValue
- tuples[row].add(null); //ObjectValue
- }
- dataMgr.registerTuples(metadata, groupName, tuples);
- }
- }
-
- @Test public void testDefect15355() throws Exception {
-
- String sql = "SELECT e1, e1 FROM pm1.g1 " //$NON-NLS-1$
- +"UNION ALL " //$NON-NLS-1$
- +"SELECT e1, (SELECT e1 FROM pm2.g1 WHERE pm2.g1.e2 = pm1.g2.e2) FROM pm1.g2"; //$NON-NLS-1$
-
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "c", "c" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "a", "e" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b", null }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "d", null }), //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testDefect15355b() throws Exception {
-
- String sql = "SELECT StringKey, BigIntegerValue FROM BQT1.SmallA " //$NON-NLS-1$
- +"UNION ALL " //$NON-NLS-1$
- +"SELECT StringKey, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"; //$NON-NLS-1$
-
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "0", new BigInteger("0") }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "1", new BigInteger("1") }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "2", new BigInteger("2") }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "0", new BigInteger("0") }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "1", new BigInteger("1") }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "2", new BigInteger("2") }), //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT2a(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- @Test public void testDefect15355c() throws Exception {
-
- String sql = "SELECT StringKey, BigIntegerValue FROM VQT.Defect15355 WHERE StringKey = '0'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "0", new BigInteger("0") }), //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT2a(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- @Test public void testDefect15355d() throws Exception {
-
- String sql = "SELECT StringKey, BigIntegerValue FROM VQT.Defect15355a WHERE StringKey = '0'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "0", new BigInteger("0") }), //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT2a(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- @Test public void testDefect15355e() throws Exception {
-
- String sql = "SELECT BigIntegerValue, StringKey FROM VQT.Defect15355 WHERE StringKey = '0'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new BigInteger("0"), "0" }), //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT2a(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- @Test public void testDefect15355f() throws Exception {
-
- String sql = "SELECT BigIntegerValue FROM VQT.Defect15355 WHERE StringKey = '0'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new BigInteger("0") }), //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT2a(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- @Test public void testDefect15355f2() throws Exception {
-
- String sql = "SELECT BigIntegerValue FROM VQT.Defect15355 WHERE StringKey LIKE '%0' AND StringKey LIKE '0%'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new BigInteger("0") }), //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT2a(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- @Test public void testDefect15355g() throws Exception {
-
- String sql = "SELECT BigIntegerValue AS a, BigIntegerValue AS b FROM VQT.Defect15355 WHERE StringKey = '0'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new BigInteger("0"), new BigInteger("0") }), //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT2a(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- @Test public void testDefect15355h() throws Exception {
-
- String sql = "SELECT BigIntegerValue FROM VQT.Defect15355 WHERE BigIntegerValue = '0'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new BigInteger("0") }), //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT2a(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- @Test public void testDefect15355i() throws Exception {
-
- String sql = "SELECT BigIntegerValue FROM VQT.Defect15355b WHERE BigIntegerValue = '0'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new BigInteger("0") }), //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT2a(dataManager);
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
- capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- /**
- * The inner most A.e1 was mistakenly getting transformed into pm1.g3.e1
- */
- @Test public void testInnerCorrelatedReference() throws Exception {
-
- String sql = "SELECT DISTINCT A.e1 FROM pm1.g3 AS A WHERE (A.e1 IN (SELECT A.e1 FROM pm1.g3))"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- };
-
- // Construct data manager with data
- 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();
-
- // Plan query
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- Command command = helpParse(sql);
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
-
- // Run query
- helpProcess(plan, dataManager, expected);
-
- }
-
- @Test public void testCase5413() throws Exception {
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- // Plan query
- String sql = "SELECT e1 FROM pm1.g2 WHERE LOOKUP('pm1.g1','e1', 'e2', 0) = e1";//$NON-NLS-1$
- QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
- Command command = TestProcessor.helpParse(sql);
- CommandContext context = createCommandContext();
- ProcessorPlan plan = helpGetPlan(command, metadata, capFinder, context);
-
- // Run query
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- FakeDataStore.sampleData2(dataManager);
-
- helpProcess(plan, context, dataManager, expected);
- }
-
- @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());
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 0, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 1, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0)}),
- };
-
- helpProcess(plan, new FakeDataManager(), expected);
-
- }
-
- /*
- * Test for Case6219
- */
- @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());
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 0, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 3, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
-
- List[] expected = new List[] {
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
-
- }
-
- @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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null}),
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- @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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { Boolean.FALSE}),
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- //note that the e1 column is not used in the source query
- assertEquals("SELECT pm1.g1.e3, pm1.g1.e2 FROM pm1.g1", manager.getQueries().iterator().next()); //$NON-NLS-1$
- }
-
- @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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0) }),
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- /**
- * A more direct test of 1, where the nested order by is unrelated
- */
- @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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { Boolean.FALSE }),
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- @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();
-
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY_UNRELATED, false);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, new DefaultCapabilitiesFinder(caps));
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { Boolean.FALSE }),
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- 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 testCountWithHaving() {
- String sql = "select e1, count(*) from pm1.g1 group by e1 having count(*) > 1"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" , new Integer(3)}), //$NON-NLS-1$
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- @Test public void testLimitZero() {
- String sql = "select e1 from pm1.g1 limit 0"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- TestOptimizer.checkNodeTypes(plan, TestRuleRaiseNull.FULLY_NULL);
-
- List[] expected = new List[] {
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- @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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 0, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", null }), //$NON-NLS-1$
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- @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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- List[] expected = new List[] {
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- @Test public void testLimitZero3() {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- String sql = "select e1 from pm1.g2 limit 0"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, capFinder);
-
- List[] expected = new List[] {
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- @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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "2", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { "b", "2" }), //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- /**
- * Tests non-deterministic evaluation in the select clause.
- *
- * The evaluation of the rand function is delayed until processing time (which actually has predictable
- * values since the test initializes the command context with the same seed)
- *
- * If this function were deterministic, it would be evaluated during rewrite to a single value.
- */
- @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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(240) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(637) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(550) }), //$NON-NLS-1$
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- /**
- * here the rand function is deterministic and should yield a single value
- */
- @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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a", new Integer(730) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(730) }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "a", new Integer(730) }), //$NON-NLS-1$
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- @Test public void testEmptyAggregate() throws Exception {
- String sql = "select count(e1) from pm1.g1 where 1 = 0"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0) })
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- @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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(0), null })
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- /**
- * here the presence of a group by causes no rows to be returned
- */
- @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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- List[] expected = new List[] {
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- @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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- List[] expected = new List[] {};
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- /**
- * Here a merge join will be used since there is at least one equi join predicate.
- * TODO: this can be optimized further
- */
- @Test public void testCase6193_1() throws Exception {
- // Create query
- String sql = "select a.INTKEY, b.intkey from bqt1.smalla a LEFT OUTER JOIN bqt2.SMALLA b on a.intkey=b.intkey and a.intkey=5 where a.intkey <10 "; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- capFinder.addCapabilities("BQT2", caps);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0), null }),
- Arrays.asList(new Object[] { new Integer(1), null }),
- Arrays.asList(new Object[] { new Integer(2), null }),
- Arrays.asList(new Object[] { new Integer(3), null }),
- Arrays.asList(new Object[] { new Integer(4), null }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(5) }),
- Arrays.asList(new Object[] { new Integer(6), null }),
- Arrays.asList(new Object[] { new Integer(7), null }),
- Arrays.asList(new Object[] { new Integer(8), null }),
- Arrays.asList(new Object[] { new Integer(9), null })
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataBQT2(dataManager);
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 1, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Here a merge join will be used since there is at least one equi join predicate.
- */
- @Test public void testCase6193_2() throws Exception {
- // Create query
- String sql = "select a.e2, b.e2 from pm1.g1 a LEFT OUTER JOIN pm1.g2 b on a.e4=b.e4 and (a.e2+b.e2)=4 order by a.e2"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0), null }),
- Arrays.asList(new Object[] { new Integer(0), null }),
- Arrays.asList(new Object[] { new Integer(1), null }),
- Arrays.asList(new Object[] { new Integer(1), null }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(3), null }),
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 1, // Sort
- 0 // UnionAll
- });
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * Here a merge join will be used since there is at least one equi join predicate.
- * The inner merge join is also a dependent join
- */
- @Test public void testCase6193_3() throws Exception {
- // Create query
- String sql = "select a.x, b.y from (select 4 x union select 1) a LEFT OUTER JOIN (select (a.e2 + b.e2) y from pm1.g1 a LEFT OUTER JOIN pm1.g2 b on a.e4=b.e4) b on (a.x = b.y)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), null }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.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[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 4, // Project
- 0, // Select
- 0, // Sort
- 1 // UnionAll
- });
-
- TestOptimizer.checkDependentJoinCount(plan, 1);
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- /**
- * This is a control test. It should work regardless of whether the reference is aliased
- * since accessnodes are now fully positional
- */
- @Test public void testPushdownNonAliasedSelectLiteral() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- List[] expected = new List[] {
- Arrays.asList("a", "b"), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList("a", "c") //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- HardcodedDataManager manager = new HardcodedDataManager();
- manager.addData("SELECT 'a', pm1.g1.e1 FROM pm1.g1", expected); //$NON-NLS-1$
-
- processPreparedStatement("select ?, e1 from pm1.g1", expected, manager, capFinder,
- metadata, Arrays.asList("a"));
- }
-
- @Test public void testCase6486() {
- // Create query
- String sql = "select pm2.g1.e1 from pm1.g2, pm2.g1 where pm1.g2.e1=pm2.g1.e1 group by pm2.g1.e1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "b"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "d"}) //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- sampleData2(dataManager);
-
- // Plan query
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- // Run query
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testNonPushedOffset() throws Exception {
- String sql = "SELECT e1 FROM pm1.g1 LIMIT 1, 5"; //$NON-NLS-1$
-
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "b"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c"}), //$NON-NLS-1$
- };
-
- 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$
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testNonCorrelatedSubQueryExecution() throws Exception {
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
-
- // Construct data manager with data
- HardcodedDataManager dataManager = new HardcodedDataManager();
- dataManager.setBlockOnce(true);
- dataManager.addData("SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1", new List[] { //$NON-NLS-1$
- Arrays.asList(Integer.valueOf(1), "a"), //$NON-NLS-1$
- Arrays.asList(Integer.valueOf(2), "b") //$NON-NLS-1$
- });
- dataManager.addData("SELECT pm2.g1.e2 FROM pm2.g1", new List[] { //$NON-NLS-1$
- Arrays.asList(Integer.valueOf(2))
- });
-
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
- };
-
- doProcess(plan, dataManager, expected, createCommandContext());
-
- //we expect 2 queries, 1 for the outer and 1 for the subquery
- assertEquals(2, dataManager.getCommandHistory().size());
- }
-
- /**
- * Test a query that uses ambiguous alias names in the top level query and
- * its sub-query and uses columns belonging to the alias as a parameter to a
- * function.
- * <p>
- * For example, <code>SELECT CONVERT(A.e2, biginteger) AS e2 FROM (SELECT
- * CONVERT(e2, long) AS e2 FROM pm1.g1 AS A) AS A</code>
- * <p>
- * The test is to ensure that A.e2 from the top level is not confused with
- * e2 in the second level.
- * <p>
- * Related Defects: JBEDSP-1137
- */
- @Test public void testAliasReuseInFunctionInSubQuery() throws Exception {
- // Create query
- String sql = "SELECT CONVERT(A.e2, biginteger) AS e2 FROM (" + //$NON-NLS-1$
- " 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();
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new BigInteger("0") }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new BigInteger("3") }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new BigInteger("0") }), //$NON-NLS-1$
- };
-
- FakeDataManager manager = new FakeDataManager();
- sampleData1(manager);
- helpProcess(plan, manager, expected);
- }
-
- @Test public void testImplicitAggregateWithInlineView() {
- String sql = "SELECT * FROM (SELECT b.count, enterprise_id FROM (SELECT COUNT(*), 2 AS enterprise_id FROM (SELECT 'A Name' AS Name, 1 AS enterprise_id) c ) b ) a WHERE enterprise_id = 1"; //$NON-NLS-1$
-
- List[] expected = new List[] {};
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedNestedTable() {
- String sql = "select y.e2, x.e1, x.e2 from (select * from pm1.g1) y, table (select * from pm1.g3 where e2 = y.e2) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(0, "a", 0),
- Arrays.asList(0, "a", 0),
- Arrays.asList(1, null, 1),
- Arrays.asList(1, "c", 1),
- Arrays.asList(3, "a", 3),
- Arrays.asList(1, null, 1),
- Arrays.asList(1, "c", 1),
- Arrays.asList(2, "b", 2),
- Arrays.asList(0, "a", 0),
- Arrays.asList(0, "a", 0),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedNestedTable1() {
- String sql = "select y.e2, z.e2, x.e1, x.e2 from (select * from pm1.g1 order by e2 desc limit 2) y inner join pm1.g2 z on y.e1 = z.e1, table (select * from pm1.g3 where e2 = y.e2 + z.e2) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(3, 0, "a", 3),
- Arrays.asList(3, 0, "a", 3),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedNestedTable2() {
- String sql = "select y.e1, x.e1 from (select distinct e1 from pm1.g1 where e1 is not null) y, table (call pm1.sq3b(\"in\" = e1, in3 = 'something')) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("a", "a"),
- Arrays.asList("a", "a"),
- Arrays.asList("a", "a"),
- Arrays.asList("b", "b"),
- Arrays.asList("c", "c"),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedNestedTable3() {
- String sql = "select y.e1, x.e1 from (select * from pm1.g1) y left outer join table (call pm1.sq3b(\"in\" = e2, in3 = 'something')) x on (1=1)"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("a", null),
- Arrays.asList(null, null),
- Arrays.asList("a", null),
- Arrays.asList("c", null),
- Arrays.asList("b", null),
- Arrays.asList("a", null),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedNestedTable4() {
- String sql = "select y.e1, y.e2, z.e2 from (select * from pm1.g1) y inner join table (select * from pm1.g3 where e2 = y.e2) x left outer join (select null as e1, e2 from pm1.g2) z on (x.e1 = z.e1) on (x.e1 = y.e1)"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("a", 0, null),
- Arrays.asList("a", 0, null),
- Arrays.asList("a", 3, null),
- Arrays.asList("c", 1, null),
- Arrays.asList("b", 2, null),
- Arrays.asList("a", 0, null),
- Arrays.asList("a", 0, null),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testCorrelatedNestedTable5() {
- String sql = "select y.e1, y.e2, z.e2 from (exec pm1.sq1()) y, table (exec pm1.sq2(y.e1)) x, table (exec pm1.sq2(x.e1)) z where y.e2 = 2"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("b", 2, 2),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testUncorrelatedScalarSubqueryPushdown() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan("select pm1.g1.e1 from pm1.g1 where e1 < (select max(vm1.g1.e1) from vm1.g1)", metadata, //$NON-NLS-1$
- null, capFinder,
- new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 < (SELECT MAX(g_0.e1) FROM pm1.g1 AS g_0)" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
-
- HardcodedDataManager hdm = new HardcodedDataManager();
- hdm.addData("SELECT MAX(g_0.e1) FROM pm1.g1 AS g_0", new List[] {Arrays.asList("c")});
- hdm.addData("SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 < 'c'", new List[] {Arrays.asList("a")});
- hdm.setBlockOnce(true);
- List[] expected = new List[] {
- Arrays.asList("a"),
- };
-
- helpProcess(plan, hdm, expected);
- }
-
- @Test public void testNonDeterministicScalarSubquery() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan("select count(distinct x) from (select (select uuid()) as x from pm1.g1) as v", metadata, //$NON-NLS-1
- null, capFinder,
- new String[] { "SELECT 1 FROM pm1.g1 AS g_0" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
-
- HardcodedDataManager hdm = new HardcodedDataManager();
- hdm.addData("SELECT 1 FROM pm1.g1 AS g_0", new List[] {Arrays.asList(1), Arrays.asList(1)});
- hdm.setBlockOnce(true);
- List[] expected = new List[] {
- Arrays.asList(2),
- };
-
- helpProcess(plan, hdm, expected);
- }
-
- @Test public void testUncorrelatedScalarSubqueryPushdown1() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan("select pm1.g1.e1 from pm1.g1 where e1 < (select e1 from (EXEC pm1.sq1()) x order by e2 limit 1)", metadata, //$NON-NLS-1$
- null, capFinder,
- new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 < (SELECT e1 FROM (EXEC pm1.sq1()) AS x ORDER BY e2 LIMIT 1)" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
- checkNodeTypes(plan, FULL_PUSHDOWN);
-
- HardcodedDataManager hdm = new HardcodedDataManager();
- hdm.addData("SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 < 'z'", new List[] {Arrays.asList("c")});
- hdm.addData("SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0", new List[] {Arrays.asList("z", 1), Arrays.asList("b", 2)});
- hdm.setBlockOnce(true);
- List[] expected = new List[] {
- Arrays.asList("c"),
- };
-
- helpProcess(plan, hdm, expected);
- }
-
- @Test public void testStoredProcedureSubqueryInput() {
- String sql = "exec pm1.sp2((select e2 from pm1.g1 order by e1 limit 1))"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("b", 2),
- };
-
- 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());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testInlineViewWith() {
- String sql = "select * from (with x as (select e1 from pm1.g1) select x.e1 from x order by e1 nulls last limit 1) y"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("a"),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testDeleteCompensation() {
- String sql = "delete from pm1.g1 where e1 = 'a' and e2 in (select e2 from pm1.g2)"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(3),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example4(), TestOptimizer.getGenericFinder());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testUpdateCompensation() {
- String sql = "update pm1.g1 set e4 = null where e1 = 'a' and exists (select 1 from pm1.g2 where e2 = pm1.g1.e2)"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(3),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example4(), TestOptimizer.getGenericFinder());
-
- helpProcess(plan, dataManager, expected);
- }
-
- private static final boolean DEBUG = false;
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcessor.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestProcessor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcessor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestProcessor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,7538 @@
+/*
+ * 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.junit.Assert.*;
+import static org.teiid.query.optimizer.TestOptimizer.*;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.concurrent.Executor;
+
+import org.junit.Test;
+import org.teiid.client.metadata.ParameterInfo;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.BufferManagerFactory;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.common.buffer.TupleSource;
+import org.teiid.common.buffer.impl.BufferManagerImpl;
+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.dqp.internal.process.CachedResults;
+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.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;
+import org.teiid.query.optimizer.TestRuleRaiseNull;
+import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
+import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+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.optimizer.relational.rules.RuleChooseDependent;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.relational.JoinNode;
+import org.teiid.query.processor.relational.RelationalNode;
+import org.teiid.query.processor.relational.RelationalPlan;
+import org.teiid.query.resolver.QueryResolver;
+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.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.RealMetadataFactory;
+import org.teiid.query.unittest.TimestampUtil;
+import org.teiid.query.util.CommandContext;
+import org.teiid.query.validator.Validator;
+import org.teiid.query.validator.ValidatorReport;
+
+ at SuppressWarnings({"nls", "unchecked"})
+public class TestProcessor {
+
+ // ################################## TEST HELPERS ################################
+
+ 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);
+ } catch(TeiidException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+
+ public static ProcessorPlan helpGetPlan(String sql, QueryMetadataInterface metadata) {
+ return helpGetPlan(sql, metadata, new DefaultCapabilitiesFinder());
+ }
+
+ public static ProcessorPlan helpGetPlan(String sql, QueryMetadataInterface metadata, CapabilitiesFinder finder) {
+ if(DEBUG) System.out.println("\n####################################\n" + sql); //$NON-NLS-1$
+
+ Command command = helpParse(sql);
+
+ ProcessorPlan process = helpGetPlan(command, metadata, finder);
+
+ return process;
+ }
+
+ static ProcessorPlan helpGetPlan(Command command, QueryMetadataInterface metadata) {
+ return helpGetPlan(command, metadata, new DefaultCapabilitiesFinder());
+ }
+
+ static ProcessorPlan helpGetPlan(Command command, QueryMetadataInterface metadata, CapabilitiesFinder capFinder) {
+ CommandContext context = createCommandContext();
+ try {
+ return helpGetPlan(command, metadata, capFinder, context);
+ } catch (TeiidException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ static ProcessorPlan helpGetPlan(Command command, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, CommandContext context) throws TeiidException {
+ if(DEBUG) System.out.println("\n####################################\n" + command); //$NON-NLS-1$
+ AnalysisRecord analysisRecord = new AnalysisRecord(false, DEBUG);
+ if (!(metadata instanceof TempMetadataAdapter)) {
+ metadata = new TempMetadataAdapter(metadata, new TempMetadataStore());
+ }
+ context.setMetadata(metadata);
+ try {
+ QueryResolver.resolveCommand(command, metadata);
+
+ ValidatorReport repo = Validator.validate(command, metadata);
+ Collection failures = new ArrayList();
+ repo.collectInvalidObjects(failures);
+ if (failures.size() > 0){
+ fail("Exception during validation (" + repo); //$NON-NLS-1$
+ }
+ command = QueryRewriter.rewrite(command, metadata, context);
+ ProcessorPlan process = QueryOptimizer.optimizePlan(command, metadata, null, capFinder, analysisRecord, context);
+ if(DEBUG) System.out.println("\n" + process); //$NON-NLS-1$
+ //per defect 10022, clone this plan before processing, just to make sure
+ //a cloned plan with correlated subquery references (or any cloned plan) can be processed
+ process = process.clone();
+
+ assertNotNull("Output elements of process plan are null", process.getOutputElements()); //$NON-NLS-1$
+
+ return process;
+ } finally {
+ if(DEBUG) {
+ System.out.println(analysisRecord.getDebugLog());
+ }
+ }
+ }
+
+ public static void helpProcess(ProcessorPlan plan, ProcessorDataManager dataManager, List[] expectedResults) {
+ CommandContext context = createCommandContext();
+ try {
+ helpProcess(plan, context, dataManager, expectedResults);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static void helpProcess(ProcessorPlan plan, CommandContext context, ProcessorDataManager dataManager, List[] expectedResults) throws Exception {
+ ProcessorPlan clonePlan = plan.clone();
+
+ // Process twice to test reset and clone
+ doProcess(plan, dataManager, expectedResults, context);
+ plan.reset();
+ doProcess(plan, dataManager, expectedResults, context);
+
+ // Execute cloned of original plan
+ doProcess(clonePlan, dataManager, expectedResults, context);
+ }
+
+ private void helpProcessException(ProcessorPlan plan, ProcessorDataManager dataManager) {
+ helpProcessException(plan, dataManager, null);
+ }
+
+ private void helpProcessException(ProcessorPlan plan, ProcessorDataManager dataManager, String expectedErrorMessage) {
+ TupleBuffer tsId = null;
+ BufferManager bufferMgr = null;
+ try {
+ bufferMgr = BufferManagerFactory.getStandaloneBufferManager();
+ CommandContext context = new CommandContext("0", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
+ QueryProcessor processor = new QueryProcessor(plan, context, bufferMgr, dataManager);
+ processor.setNonBlocking(true);
+ BatchCollector collector = processor.createBatchCollector();
+ tsId = collector.collectTuples();
+ fail("Expected error during processing, but got none."); //$NON-NLS-1$
+ } catch(TeiidException e) {
+ // ignore - this is expected
+ if(expectedErrorMessage != null) {
+ assertEquals(expectedErrorMessage, e.getMessage());
+ }
+ } finally {
+ if (tsId != null) {
+ tsId.remove();
+ }
+ }
+ }
+
+ public static void doProcess(ProcessorPlan plan, ProcessorDataManager dataManager, List[] expectedResults, CommandContext context) throws Exception {
+ BufferManager bufferMgr = context.getBufferManager();
+ if (bufferMgr == null) {
+ BufferManagerImpl bm = BufferManagerFactory.createBufferManager();
+ bm.setProcessorBatchSize(context.getProcessorBatchSize());
+ bm.setConnectorBatchSize(context.getProcessorBatchSize());
+ context.setBufferManager(bm);
+ bufferMgr = bm;
+ }
+ context.getNextRand(0);
+ if (context.getTempTableStore() == null) {
+ context.setTempTableStore(new TempTableStore(context.getConnectionID()));
+ }
+ if (context.getGlobalTableStore() == null) {
+ context.setGlobalTableStore(new TempTableStore("SYSTEM"));
+ }
+ if (!(dataManager instanceof TempTableDataManager)) {
+ SessionAwareCache<CachedResults> cache = new SessionAwareCache<CachedResults>();
+ cache.setBufferManager(bufferMgr);
+ Executor executor = new Executor() {
+ @Override
+ public void execute(Runnable command) {
+ command.run();
+ }
+ };
+ dataManager = new TempTableDataManager(dataManager, bufferMgr, executor, cache, null, null);
+ }
+ if (context.getQueryProcessorFactory() == null) {
+ context.setQueryProcessorFactory(new QueryProcessorFactoryImpl(bufferMgr, dataManager, new DefaultCapabilitiesFinder(), null, context.getMetadata()));
+ }
+ TupleBuffer id = null;
+ try {
+ QueryProcessor processor = new QueryProcessor(plan, context, bufferMgr, dataManager);
+ //processor.setNonBlocking(true);
+ BatchCollector collector = processor.createBatchCollector();
+ for (int i = 0; i < 100; i++) {
+ try {
+ id = collector.collectTuples();
+ break;
+ } catch (BlockedException e) {
+
+ }
+ }
+ if (id == null) {
+ fail("did not complete processing");
+ }
+ if ( expectedResults != null ) {
+ examineResults(expectedResults, bufferMgr, id);
+ }
+ } finally {
+ if (id != null) {
+ id.remove();
+ }
+ }
+ }
+
+ /**
+ * @param expectedResults
+ * @param bufferMgr
+ * @param tsID
+ * @throws TeiidComponentException
+ * @throws TeiidProcessingException
+ * @since 4.3
+ */
+ static void examineResults(List[] expectedResults,BufferManager bufferMgr,TupleBuffer tsID)
+ throws TeiidComponentException,SQLException, TeiidProcessingException {
+
+ // Create QueryResults from TupleSource
+ TupleSource ts = tsID.createIndexedTupleSource();
+ int count = tsID.getRowCount();
+
+ if(DEBUG) {
+ System.out.println("\nResults:\n" + tsID.getSchema()); //$NON-NLS-1$
+ TupleSource ts2 = tsID.createIndexedTupleSource();
+ for(int j=0; j<count; j++) {
+ System.out.println("" + j + ": " + ts2.nextTuple()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ ts2.closeSource();
+ }
+
+ // Compare actual to expected row count
+ assertEquals("Did not get expected row count: ", expectedResults.length, count); //$NON-NLS-1$
+
+ // Walk results and compare
+ for(int i=0; i<count; i++) {
+ List record = ts.nextTuple();
+
+ //handle xml
+ if(record.size() == 1){
+ Object cellValue = record.get(0);
+ if(cellValue instanceof XMLType){
+ XMLType id = (XMLType)cellValue;
+ String actualDoc = id.getString();
+ if (expectedResults[i].size() == 1) {
+ compareDocuments((String)expectedResults[i].get(0), actualDoc);
+ continue;
+ }
+ }
+ }
+
+ assertEquals("Row " + i + " does not match expected: ", expectedResults[i], record); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ ts.closeSource();
+ }
+
+ public static void compareDocuments(String expectedDoc, String actualDoc) {
+ StringTokenizer tokens1 = new StringTokenizer(expectedDoc, "\r\n"); //$NON-NLS-1$
+ StringTokenizer tokens2 = new StringTokenizer(actualDoc, "\r\n");//$NON-NLS-1$
+ while(tokens1.hasMoreTokens()){
+ String token1 = tokens1.nextToken().trim();
+ if(!tokens2.hasMoreTokens()){
+ fail("XML doc mismatch: expected=" + token1 + "\nactual=none");//$NON-NLS-1$ //$NON-NLS-2$
+ }
+ String token2 = tokens2.nextToken().trim();
+ assertEquals("XML doc mismatch: ", token1, token2); //$NON-NLS-1$
+ }
+ if(tokens2.hasMoreTokens()){
+ fail("XML doc mismatch: expected=none\nactual=" + tokens2.nextToken().trim());//$NON-NLS-1$
+ }
+ }
+
+ public static CommandContext createCommandContext() {
+ 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$
+ context.setProcessorBatchSize(BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE);
+ context.setConnectorBatchSize(BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE);
+ context.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
+ context.setPreparedPlanCache(new SessionAwareCache<PreparedPlan>());
+ return context;
+ }
+
+ public static void sampleData1(FakeDataManager dataMgr) {
+ try {
+ FakeDataStore.sampleData1(dataMgr, RealMetadataFactory.example1Cached());
+ } catch(Throwable e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void sampleData2(FakeDataManager dataMgr) {
+ try {
+ FakeDataStore.sampleData2(dataMgr);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void sampleData2a(FakeDataManager dataMgr) {
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ try {
+ 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[] { "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$
+ } );
+
+ 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[] { "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$
+ } );
+
+ dataMgr.registerTuples(
+ 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, QueryMetadataInterface metadata) {
+ try {
+ dataMgr.registerTuples(
+ 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$
+ } );
+
+ 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[] { "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$
+ } );
+
+ dataMgr.registerTuples(
+ 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 sampleDataBQT1(FakeDataManager dataMgr) {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ try {
+ // Group bqt1.smalla
+
+ List[] tuples = new List[20];
+ for(int i=0; i<tuples.length; i++) {
+ tuples[i] = new ArrayList(17);
+ tuples[i].add(new Integer(i));
+ for(int j=0; j<16; j++) {
+ tuples[i].add(null);
+ }
+ }
+
+ dataMgr.registerTuples(metadata, "bqt1.smalla", tuples); //$NON-NLS-1$
+
+ // Group bqt2.mediumb
+ tuples = new List[20];
+ for(int i=0; i<tuples.length; i++) {
+ tuples[i] = new ArrayList(17);
+ tuples[i].add(new Integer(i));
+ for(int j=0; j<16; j++) {
+ tuples[i].add(null);
+ }
+ }
+
+ dataMgr.registerTuples(metadata, "bqt2.mediumb", tuples); //$NON-NLS-1$
+ } catch(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void sampleDataBQT2(FakeDataManager dataMgr) {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ String[] groups = new String[] {"bqt1.smalla", "bqt2.smalla", "bqt3.smalla" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ try {
+ for(int i=0; i<groups.length; i++) {
+ String groupName = groups[i];
+
+ List[] tuples = new List[30];
+ for(int row=0; row<tuples.length; row++) {
+ tuples[row] = new ArrayList(17);
+ tuples[row].add(new Integer(row));
+ for(int col=0; col<16; col++) {
+ tuples[row].add(null);
+ }
+ }
+
+ dataMgr.registerTuples(metadata, groupName, tuples);
+ }
+
+ } catch(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Just want to register two rows of all the integral types to test AVG
+ * @param dataMgr
+ * @since 4.2
+ */
+ private void sampleDataBQT_defect11682(FakeDataManager dataMgr) {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ try {
+ List[] tuples = new List[2];
+ for(int i=1; i<=tuples.length; i++) {
+ int index=i-1;
+ tuples[index] = new ArrayList(17);
+ tuples[index].add(new Integer(i)); //IntKey
+ tuples[index].add(null);
+ tuples[index].add(new Integer(i));
+ tuples[index].add(null);
+ tuples[index].add(new Float(i));
+ tuples[index].add(new Long(i));
+ tuples[index].add(new Double(i));
+ tuples[index].add(new Byte((byte)i));
+ tuples[index].add(null);
+ tuples[index].add(null);
+ tuples[index].add(null);
+ tuples[index].add(null);
+ tuples[index].add(null);
+ tuples[index].add(new Short((short)i));
+ tuples[index].add(new BigInteger(i+"")); //$NON-NLS-1$
+ tuples[index].add(new BigDecimal(i+".0")); //$NON-NLS-1$
+ tuples[index].add(null);
+ }
+
+ dataMgr.registerTuples(metadata, "bqt1.smalla", tuples); //$NON-NLS-1$
+
+ } catch(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void sampleDataBQTSmall(FakeDataManager dataMgr) {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ try {
+ List[] tuples = new List[1];
+ for(int i=0; i<tuples.length; i++) {
+ tuples[i] = new ArrayList(17);
+ tuples[i].add(new Integer(i));
+ for(int j=0; j<16; j++) {
+ tuples[i].add(null);
+ }
+ }
+
+ dataMgr.registerTuples(metadata, "bqt1.smalla", tuples); //$NON-NLS-1$
+
+ } catch(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private List createRowWithTimestamp(String tsStr) {
+ Timestamp ts = Timestamp.valueOf(tsStr);
+ return Arrays.asList(new Object[] {
+ new Integer(0), "a", new Integer(1), "a", //$NON-NLS-1$ //$NON-NLS-2$
+ null, null, null, null, null, null, ts, null, null, null, null, null, null
+ });
+ }
+
+ private void sampleDataBQT_case1566(FakeDataManager dataMgr) throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ dataMgr.registerTuples(metadata, "bqt1.smalla", new List[] { //$NON-NLS-1$
+ createRowWithTimestamp("2002-01-01 10:00:00"), //$NON-NLS-1$
+ createRowWithTimestamp("2002-01-01 14:00:00"), //$NON-NLS-1$
+ createRowWithTimestamp("2002-01-02 10:00:00"), //$NON-NLS-1$
+ createRowWithTimestamp("2002-01-02 14:00:00"), //$NON-NLS-1$
+ createRowWithTimestamp("2002-01-02 19:00:00.01"), //$NON-NLS-1$
+ } );
+ }
+
+ 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;
+ }
+
+ @Test public void test1() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = 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$
+ };
+
+ // 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 test2() {
+ // Create query
+ String sql = "SELECT COUNT(*) FROM pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(6) })
+ };
+
+ // 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 test3() {
+ // Create query
+ String sql = "SELECT COUNT(*), COUNT(e1), COUNT(distinct e1), COUNT(distinct e2), COUNT(distinct e3), COUNT(distinct e4) FROM pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(6), new Integer(5), new Integer(3), new Integer(4), new Integer(2), new Integer(4) }),
+ };
+
+ // 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);
+ }
+
+ /** see also integer average defect 11682 */
+ @Test public void test4() {
+ // Create query
+ String sql = "SELECT MIN(e2), MAX(e2), SUM(e2), AVG(e2), SUM(distinct e2), AVG(distinct e2) FROM pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0), new Integer(3), new Long(7), new Double(1.1666666666666667), new Long(6), new Double(1.5) }),
+ };
+
+ // 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 test5() {
+ // Create query
+ String sql = "SELECT MIN(e4), MAX(e4), SUM(e4), AVG(e4), SUM(distinct e4), AVG(distinct e4) FROM pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Double(0.0), new Double(7.0), new Double(12.0), new Double(2.4), new Double(10.0), new Double(2.5) }),
+ };
+
+ // 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 test7() {
+ // Create query
+ String sql = "SELECT * FROM vm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = 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$
+ };
+
+ // 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 test8() {
+ // Create query
+ String sql = "SELECT * FROM vm1.g2 order by 1, 2, 3"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.TRUE, new Double(7.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.TRUE, new Double(7.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(3), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(3), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null }) //$NON-NLS-1$
+ };
+
+ // 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 test9() {
+ // Create query
+ String sql = "SELECT * FROM vm1.g4 order by e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "3" }), //$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();
+ sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void test10() {
+ // Create query
+ String sql = "SELECT e1 FROM vm1.g4 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testBooleanComparisonGT() {
+ // Create query
+ String sql = "SELECT pm1.g1.e3 FROM pm1.g1 WHERE e3 > {b'false'}"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { Boolean.TRUE }),
+ Arrays.asList(new Object[] { Boolean.TRUE })
+ };
+
+ // 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 testBooleanComparisonGE() {
+ // Create query
+ String sql = "SELECT pm1.g1.e3 FROM pm1.g1 WHERE e3 >= {b'false'}"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { Boolean.FALSE }),
+ Arrays.asList(new Object[] { Boolean.FALSE }),
+ Arrays.asList(new Object[] { Boolean.TRUE }),
+ Arrays.asList(new Object[] { Boolean.TRUE }),
+ Arrays.asList(new Object[] { Boolean.FALSE }),
+ Arrays.asList(new Object[] { Boolean.FALSE })
+ };
+
+ // 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 testBooleanComparisonLT() {
+ // Create query
+ String sql = "SELECT pm1.g1.e3 FROM pm1.g1 WHERE e3 < {b'true'}"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { Boolean.FALSE }),
+ Arrays.asList(new Object[] { Boolean.FALSE }),
+ Arrays.asList(new Object[] { Boolean.FALSE }),
+ Arrays.asList(new Object[] { Boolean.FALSE })
+ };
+
+ // 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 testBooleanComparisonLE() {
+ // Create query
+ String sql = "SELECT pm1.g1.e3 FROM pm1.g1 WHERE e3 <= {b'true'}"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { Boolean.FALSE }),
+ Arrays.asList(new Object[] { Boolean.FALSE }),
+ Arrays.asList(new Object[] { Boolean.TRUE }),
+ Arrays.asList(new Object[] { Boolean.TRUE }),
+ Arrays.asList(new Object[] { Boolean.FALSE }),
+ Arrays.asList(new Object[] { Boolean.FALSE })
+ };
+
+ // 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 testConcatOperator() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1 || e2 AS x FROM pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a0" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a3" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c1" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b2" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a0" }) //$NON-NLS-1$
+ };
+
+ // 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);
+ }
+
+ /** Duplicates defect #4841: SELECT e1 a, e1 b FROM pm1.g1 order by a */
+ @Test public void testDefect4841_1() {
+ // Create query
+ String sql = "SELECT e1 a, e1 b FROM pm1.g1 order by a"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // 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);
+ }
+
+ /** Duplicates defect #4841: SELECT e1 a, e1 b FROM pm1.g1 order by a, b desc */
+ @Test public void testDefect4841_2() {
+ // Create query
+ String sql = "SELECT e1 a, e1 b FROM pm1.g1 order by a"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // 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);
+ }
+
+ /** Duplicates defect #5292: SELECT DISTINCT e1, e1 a FROM pm1.g1 */
+ @Test public void testDefect5292_1() {
+ // Create query
+ String sql = "SELECT DISTINCT e1, e1 a FROM pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // 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);
+ }
+
+ /** Duplicates defect #5292: SELECT DISTINCT e1, e1 a FROM pm1.g1 ORDER BY a */
+ @Test public void testDefect5292_2() {
+ // Create query
+ String sql = "SELECT DISTINCT e1, e1 a FROM pm1.g1 ORDER BY a"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // 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);
+ }
+
+ /** Duplicates defect #5004: SELECT COUNT(*) FROM pm1.g1 WHERE e1='xxxx' */
+ @Test public void testDefect5004() {
+ // Create query
+ String sql = "SELECT COUNT(*) FROM pm1.g1 WHERE e1='xxxx'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0) })
+ };
+
+ // 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 to ensure that multiple empty batches are handled by the grouping node as well
+ */
+ @Test public void testDefect5004a() throws Exception {
+ // Create query
+ String sql = "SELECT COUNT(*) FROM pm1.g1 WHERE e1='xxxx'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0) })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ CommandContext context = createCommandContext();
+ context.setProcessorBatchSize(2);
+ context.setConnectorBatchSize(2);
+ context.setMetadata(RealMetadataFactory.example1Cached());
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached(), new DefaultCapabilitiesFinder(), context);
+
+ // Run query
+ helpProcess(plan, context, dataManager, expected);
+ }
+
+ /** SELECT COUNT(e2), MIN(e2), MAX(e2), SUM(e2), AVG(e2) FROM pm1.g1 WHERE e2=-999999 */
+ @Test public void test13() {
+ // Create query
+ String sql = "SELECT COUNT(e2), MIN(e2), MAX(e2), SUM(e2), AVG(e2) FROM pm1.g1 WHERE e2=-999999"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] {new Integer(0), null, null, null, null})
+ };
+
+ // 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);
+ }
+
+ /**
+ * This test uncovered a bug in the FakeDataManager; the element
+ * symbol in the atomic query criteria has a canonical name
+ * of "Y.e4", but the FakeDataManager sends a Map of ElementSymbols
+ * having the unaliased names. The first symbol cannot be found
+ * in the Map due to the implementation of Symbol.equals() being
+ * based entirely on the canonical name, which causes a NPE.
+ * (Alex says this wasn't previously a problem because aliased groups
+ * did not previously get pushed down to the source.)
+ */
+ @Test public void testCriteriaAliasedGroup() {
+ String sql = "select e1, e2 FROM pm2.g1 Y WHERE 2.0 = e4"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "b", new Integer(0) }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT e1 FROM pm1.g1 WHERE 'abc' = 'xyz' */
+ @Test public void testCriteriaComparesUnequalConstants() {
+ // Create query
+ String sql = "SELECT e1 FROM pm1.g1 WHERE 'abc' = 'xyz'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ };
+
+ // 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);
+ }
+
+ /** SELECT pm1.g1.e1, pm2.g1.e1 FROM pm1.g1 RIGHT OUTER JOIN pm2.g1 ON pm1.g1.e1=pm2.g1.e1 */
+ @Test public void testRightOuterJoin1() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1, pm2.g1.e1 FROM pm1.g1 RIGHT OUTER JOIN pm2.g1 ON pm1.g1.e1=pm2.g1.e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { null, "d" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null, "e" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT pm1.g1.e1, pm2.g1.e1 FROM pm1.g1 LEFT OUTER JOIN pm2.g1 ON pm1.g1.e1=pm2.g1.e1 */
+ @Test public void testLeftOuterJoin1() {
+ // Create query
+ String sql = "SELECT pm1.g1.e1, pm2.g1.e1 FROM pm1.g1 LEFT OUTER JOIN pm2.g1 ON pm1.g1.e1=pm2.g1.e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT pm1.g1.e1, pm2.g1.e1 FROM pm1.g1 FULL OUTER JOIN pm2.g1 ON pm1.g1.e1=pm2.g1.e1 */
+ @Test public void testFullOuterJoin1() throws Exception {
+ // Create query
+ String sql = "SELECT pm1.g1.e1, pm2.g1.e1 FROM pm1.g1 FULL OUTER JOIN pm2.g1 ON pm1.g1.e1=pm2.g1.e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null, "d" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null, "e" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testFullOuterJoin2() throws Exception {
+ // Create query
+ String sql = "SELECT a.e4 c0, b.e4 c1 FROM pm1.g1 a FULL OUTER JOIN pm1.g1 b ON a.e4=b.e4 order by c0"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { new Double(0), new Double(0) }),
+ Arrays.asList(new Object[] { new Double(2), new Double(2) }),
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testSortedFullOuterJoin() throws Exception {
+ // Create query
+ String sql = "SELECT pm1.g1.e2, pm2.g1.e2 FROM pm1.g1 FULL OUTER JOIN pm2.g1 ON pm1.g1.e2=pm2.g1.e2 and pm1.g1.e2 > 3"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, 2 }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { 3, null }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { null, 3 }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null, 4 }), //$NON-NLS-1$
+ };
+
+ HardcodedDataManager hdm = new HardcodedDataManager();
+ hdm.addData("SELECT g_0.e2 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", new List[] {
+ Arrays.asList(3),
+ });
+ hdm.addData("SELECT g_0.e2 AS c_0 FROM pm2.g1 AS g_0 ORDER BY c_0", new List[] {
+ Arrays.asList(2),
+ Arrays.asList(3),
+ Arrays.asList(4),
+
+ });
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+ CommandContext cc = createCommandContext();
+ cc.setProcessorBatchSize(2);
+ helpProcess(plan, cc, hdm, expected);
+ }
+
+ @Test public void testFullOuterJoin3() throws Exception {
+ // Create query
+ String sql = "SELECT a.e4 c0, b.e4 c1 FROM pm1.g1 b FULL OUTER JOIN (select e4, 1 x from pm1.g1 union all select e4, 2 from pm1.g1) a ON a.e4=b.e4 and a.x = 2 order by c0"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { new Double(0), new Double(0) }),
+ Arrays.asList(new Object[] { new Double(0), null }),
+ Arrays.asList(new Object[] { new Double(2), new Double(2) }),
+ Arrays.asList(new Object[] { new Double(2), null }),
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT x.e1, pm2.g1.e1 FROM (SELECT e1 FROM pm1.g1) AS x LEFT OUTER JOIN pm2.g1 ON x.e1=pm2.g1.e1 */
+ @Test public void testLeftOuterJoinWithInlineView() {
+ // Create query
+ String sql = "SELECT x.e1, pm2.g1.e1 FROM (SELECT e1 FROM pm1.g1) AS x LEFT OUTER JOIN pm2.g1 ON x.e1=pm2.g1.e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT * FROM vm1.g5 ORDER BY expr */
+ @Test public void testDefect5273_1() {
+ // Create query
+ String sql = "SELECT expr FROM vm1.g5 ORDER BY expr"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "bval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "cval" }) //$NON-NLS-1$
+ };
+
+ // 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);
+ }
+
+ /** SELECT expr AS e FROM vm1.g5 ORDER BY e */
+ @Test public void testDefect5273_2() {
+ // Create query
+ String sql = "SELECT expr AS e FROM vm1.g5 ORDER BY e"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "bval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "cval" }) //$NON-NLS-1$
+ };
+
+ // 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);
+ }
+
+ /** SELECT e2 AS e FROM vm1.g5 ORDER BY e */
+ @Test public void testDefect5273_3() {
+ // Create query
+ String sql = "SELECT e2 AS e FROM vm1.g5 ORDER BY e"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(3) })
+ };
+
+ // 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);
+ }
+
+ /** SELECT e AS f FROM vm1.g6 ORDER BY f */
+ @Test public void testDefect5273_4() {
+ // Create query
+ String sql = "SELECT e AS f FROM vm1.g6 ORDER BY f"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "bval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "cval" }) //$NON-NLS-1$
+ };
+
+ // 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);
+ }
+
+ /** SELECT e AS f FROM vm1.g7 ORDER BY f */
+ @Test public void testDefect5273_5() {
+ // Create query
+ String sql = "SELECT e AS f FROM vm1.g7 ORDER BY f"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a0" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a0" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a3" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b2" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c1" }) //$NON-NLS-1$
+ };
+
+ // 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);
+ }
+
+ /** SELECT e AS f FROM vm1.g7 ORDER BY f */
+ @Test public void testDefect5273_6() {
+ // Create query
+ String sql = "SELECT e AS f FROM vm1.g8 ORDER BY f"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "aval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "bval" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "cval" }) //$NON-NLS-1$
+ };
+
+ // 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 testFalseCriteria1() {
+ // Create query
+ String sql = "SELECT 5 FROM pm1.g1 WHERE 0=1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ };
+
+ // 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 testFalseCriteria2() {
+ // Create query
+ String sql = "SELECT count(*) FROM pm1.g1 WHERE 0=1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0) }),
+ };
+
+ // 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 testSubquery1() {
+ // Create query
+ String sql = "SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS x"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testSubquerySimple() {
+ // Create query
+ String sql = "SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS x"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCritInSubquery() {
+ // Create query
+ String sql = "SELECT e1 FROM (SELECT e1 FROM pm1.g1 WHERE e1 = 'a') AS x"; //$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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCritAboveSubquery() {
+ // Create query
+ String sql = "SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS x 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testSubqueryInJoinPredicate() {
+ // Create query
+ String sql = "SELECT x.e1 FROM (SELECT e1 FROM pm1.g1) AS x JOIN (SELECT e1 FROM pm1.g1) y ON x.e1=y.e1 order by x.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[] { "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();
+ sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testSubqueryWithRenaming() {
+ // Create query
+ String sql = "SELECT x.a FROM (SELECT e1 AS a FROM pm1.g1) AS x"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testNestedSubquery() {
+ // Create query
+ String sql = "SELECT x.a FROM (SELECT e1 AS a FROM (SELECT e1 FROM pm1.g1) AS y) AS x"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a single Subquery IN clause criteria
+ */
+ @Test public void testSubqueryINClause() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a single Subquery IN clause criteria with nulls
+ * in sample data
+ */
+ @Test public void testSubqueryINClauseWithNulls() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e4 IN (SELECT e4 FROM pm2.g1)"; //$NON-NLS-1$
+
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a single Subquery IN clause criteria with nulls
+ * in sample data
+ */
+ @Test public void testSubqueryINClauseWithNulls2() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e4 FROM pm2.g1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "c" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a compound criteria of two subqueries in IN clauses
+ */
+ @Test public void testSubqueryINClauses() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1) AND e1 IN (SELECT e1 FROM pm2.g1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "b" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a compound criteria of a subquery in IN clause and another type of
+ * criteria
+ */
+ @Test public void testSubqueryINClauseMixedCriteria() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1) AND e1 IN ('b')"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "b" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a compound criteria of a subquery in IN clause and another type of
+ * criteria
+ */
+ @Test public void testSubqueryINClauseMixedCriteria2() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1) AND NOT (e1 = 'a')"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "b" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests nesting of Subquery IN clause criteria
+ */
+ @Test public void testNestedSubqueryINClauses() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1 WHERE e1 IN (SELECT e1 FROM pm1.g1))"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testSubqueryXML() {
+ // Create query
+ String sql = "SELECT * FROM (SELECT * FROM xmltest.doc1) AS x"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] {
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
+ "<root><node1><node2><node3/></node2></node1></root>" //$NON-NLS-1$
+ })
+ };
+
+ // 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);
+ }
+
+ /**
+ * Tests a single Subquery EXISTS predicate criteria
+ */
+ @Test public void testSubqueryExistsPredicate() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE EXISTS (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ 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();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a single Subquery EXISTS predicate criteria
+ * where the subquery returns no rows
+ */
+ @Test public void testSubqueryExistsPredicate2() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE EXISTS (SELECT e2 FROM pm2.g1 WHERE e1 = 'ZZTop')"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[0];
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a single Subquery in compare predicate criteria
+ */
+ @Test public void testSubqueryComparePredicate() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 = ANY (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a single Subquery in compare predicate criteria
+ */
+ @Test public void testSubqueryComparePredicate2() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 = SOME (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a single Subquery in compare predicate criteria
+ */
+ @Test public void testSubqueryComparePredicate3() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 = ALL (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[0];
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a single Subquery in compare predicate criteria
+ */
+ @Test public void testSubqueryComparePredicate4() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 <= ALL (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a single Subquery in compare predicate criteria
+ */
+ @Test public void testSubqueryComparePredicate5() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 < SOME (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ 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();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a single Subquery in compare predicate criteria
+ */
+ @Test public void testSubqueryComparePredicate5a() {
+ String sql = "SELECT e1 FROM pm2.g1 WHERE e2 < SOME (SELECT e2 FROM pm1.g1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "e" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a single Subquery in compare predicate criteria
+ * without predicate quantifier
+ */
+ @Test public void testSubqueryComparePredicate6() {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 < (SELECT e2 FROM pm2.g1 WHERE e1 = 'e')"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a single Subquery in compare predicate criteria
+ */
+ @Test public void testSubqueryComparePredicateNested() {
+ 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ // Construct data manager with data
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1", new List[] { Arrays.asList(new Object[] { new Integer(0), "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { new Integer(1), "b" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(2), "c" }), //$NON-NLS-1$
+ });
+
+ dataManager.addData("SELECT pm2.g1.e2 FROM pm2.g1", new List[] { //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ });
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }) //$NON-NLS-1$
+ };
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a scalar subquery in the SELECT clause
+ */
+ @Test public void testSubqueryScalar() {
+ String sql = "SELECT e1, (SELECT e2 FROM pm2.g1 WHERE e1 = 'b') FROM pm1.g1"; //$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[] { "b", new Integer(0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", new Integer(0) }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a scalar subquery which returns no rows in the SELECT clause
+ */
+ @Test public void testSubqueryScalar2() {
+ String sql = "SELECT e1, (SELECT e2 FROM pm2.g1 WHERE e1 = 'a') FROM pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Tests a scalar subquery which returns more than one rows
+ * causes the expected Exception
+ */
+ @Test public void testSubqueryScalarException() throws Exception {
+ String sql = "SELECT e1, (SELECT e2 FROM pm2.g1) FROM pm1.g1"; //$NON-NLS-1$
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcessException(plan, dataManager);
+ }
+
+ @Test public void testSubqueryScalarInTransformation() {
+ String sql = "select * from vm1.g25"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), new Double(0.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0), new Double(0.0) }),
+ Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), new Double(0.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, new Double(0.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), new Double(0.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), new Double(0.0) }) //$NON-NLS-1$
+ };
+
+ // 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 testSubqueryScalarInTransformation2() {
+ String sql = "select * from vm1.g25 where e5 = 0.0"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), new Double(0.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0), new Double(0.0) }),
+ Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), new Double(0.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, new Double(0.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), new Double(0.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), new Double(0.0) }) //$NON-NLS-1$
+ };
+
+ // 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 testCorrelatedSubquery_CASE2022() {
+ String sql = "select * from BQT2_V WHERE BQT2_V.IntKey < 50"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[0];
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT1(dataManager);
+ sampleDataBQT2(dataManager);
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_ALL, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MIN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.exampleBQTCached(), capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+ @Test public void testCorrelatedSubquery1() {
+ String sql = "Select e1, e2, e4 from pm1.g1 where e2 in (select e2 FROM pm2.g1 WHERE pm1.g1.e4 = pm2.g1.e4)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0), new Double(2.0) }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ /**
+ * There is a bug when the second query in a UNION ALL has a correlated subquery, and both
+ * the outer and inner query are selecting from the same virtual group, and aliasing them
+ * differently to distinguish between them. The generated atomic query has screwed up
+ * aliasing.
+ */
+ @Test public void testCorrelatedSubqueryCase3667() {
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ // Plan query
+ 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, RealMetadataFactory.example1Cached(), capFinder);
+
+ // Run query
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "aString", new Integer(22), new Double(22.0) }), //$NON-NLS-1$
+ };
+
+ dataManager.addData("SELECT g_0.e1, g_0.e2, g_0.e4 FROM pm1.g1 AS g_0 WHERE g_0.e2 IN (SELECT g_1.e2 FROM pm1.g1 AS g_1 WHERE g_1.e4 = g_0.e4)", //$NON-NLS-1$
+ expected);
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** control query, this test passes */
+ @Test public void testCorrelatedSubqueryCase3667a() {
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // 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, RealMetadataFactory.example1Cached(), capFinder);
+
+ // Run query
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "aString", new Integer(22), new Double(22.0) }), //$NON-NLS-1$
+ };
+
+ dataManager.addData("SELECT g_0.e1, g_0.e2, g_0.e4 FROM pm1.g1 AS g_0 WHERE g_0.e2 IN (SELECT g_1.e2 FROM pm1.g1 AS g_1 WHERE g_1.e4 = g_0.e4)", //$NON-NLS-1$
+ expected);
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedSubquery2() {
+ String sql = "Select e1, e2 from pm1.g1 where e2 in (select e2 FROM pm2.g1 WHERE pm1.g1.e4 = pm2.g1.e4)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ @Test public void testCorrelatedSubquery3() {
+ String sql = "Select e1, (select e2 FROM pm2.g1 WHERE pm1.g1.e4 = pm2.g1.e4) from pm1.g1"; //$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[] { "b", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedSubquery3a() {
+ String sql = "Select e1, (select e2 FROM pm2.g1 WHERE X.e4 = e4) from pm1.g1 X"; //$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[] { "b", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedSubquery3b() {
+ String sql = "Select e1, (select e2 FROM pm2.g1 Y WHERE X.e4 = e4) from pm1.g1 X"; //$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[] { "b", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedSubquery3c() {
+ String sql = "Select e1, (select e2 FROM pm2.g1 Y WHERE X.e4 = Y.e4) from pm1.g1 X"; //$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[] { "b", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedSubquery4() {
+ String sql = "Select e1, e2 from pm1.g1 X where e2 in (select e2 FROM pm2.g1 WHERE X.e4 = pm2.g1.e4)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedSubquery4a() {
+ String sql = "Select e1, e2 from pm1.g1 X where e2 = some (select e2 FROM pm2.g1 WHERE X.e4 = pm2.g1.e4)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedSubquery_defect9968() {
+ String sql = "Select e1, e2 from pm1.g1 X where e2 in (select max(X.e2) FROM pm2.g1 WHERE X.e4 = pm2.g1.e4)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedSubquery_defect9968a() {
+ String sql = "Select e1, e2 from pm1.g1 X where e2 in (select ((X.e2)/2) as e FROM pm2.g1 WHERE X.e4 = pm2.g1.e4)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedSubquery_defect9968b() {
+ String sql = "Select e1, e2 from pm1.g1 X where e2 in (select (select e2 as e FROM pm2.g1 WHERE X.e4 = pm2.g1.e4) as e FROM pm2.g1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedSubquery_defect10021() {
+ String sql = "Select e1, e2 from table1 X where e4 in (select max(Y.e4) FROM table1 Y WHERE X.e4 = Y.e4)"; //$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[] { "c", new Integer(2) }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Note the subquery has a multi-column result - conceptually this is
+ * legal for the EXISTS predicate
+ */
+ @Test public void testCorrelatedSubquery5() {
+ String sql = "Select * from pm1.g1 where exists (select * FROM pm2.g1 WHERE pm1.g1.e1 = e1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "b", new Integer(1), Boolean.TRUE, null }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Count the # of parent rows for which no child rows exist
+ */
+ @Test public void testCorrelatedSubquery6() {
+ String sql = "Select count(*) from pm1.g1 where not (exists (select * FROM pm2.g1 WHERE pm1.g1.e1 = e1))"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { new Integer(2) })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Select e2, e4, and the avg of e4 for each group of e1
+ */
+ @Test public void testCorrelatedSubquery7() {
+ String sql = "select e2, e4, (select avg(e4) FROM pm1.g1 Y WHERE X.e1 = e1) from pm1.g1 X"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { new Integer(0), new Double(2.0), new Double(3.6666666666666665) }),
+ Arrays.asList(new Object[] { new Integer(1), new Double(1.0), null }),
+ Arrays.asList(new Object[] { new Integer(3), new Double(7.0), new Double(3.6666666666666665) }),
+ Arrays.asList(new Object[] { new Integer(1), null , null }),
+ Arrays.asList(new Object[] { new Integer(2), new Double(0.0), new Double(0.0) }),
+ Arrays.asList(new Object[] { new Integer(0), new Double(2.0), new Double(3.6666666666666665) })
+ };
+
+ // 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);
+ }
+
+ /**
+ * Select e2, e4, and the avg of e4 for each group of e1
+ */
+ @Test public void testCorrelatedSubquery8() {
+ String sql = "select X.e2, X.e4, (select avg(Y.e4) FROM pm1.g1 Y WHERE X.e1 = Y.e1) from pm1.g1 X"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { new Integer(0), new Double(2.0), new Double(3.6666666666666665) }),
+ Arrays.asList(new Object[] { new Integer(1), new Double(1.0), null }),
+ Arrays.asList(new Object[] { new Integer(3), new Double(7.0), new Double(3.6666666666666665) }),
+ Arrays.asList(new Object[] { new Integer(1), null , null }),
+ Arrays.asList(new Object[] { new Integer(2), new Double(0.0), new Double(0.0) }),
+ Arrays.asList(new Object[] { new Integer(0), new Double(2.0), new Double(3.6666666666666665) })
+ };
+
+ // 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 testCorrelatedSubqueryVirtualLayer1() {
+ String sql = "Select e1, e2 from vm1.g1 X where e2 in (select e2 FROM vm1.g1 Y WHERE X.e4 = Y.e4)"; //$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[] { "b", new Integer(2) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
+ };
+
+ // 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 testCorrelatedSubqueryVirtualLayer2() {
+ String sql = "Select e1, e2 from vm1.g2 where e2 in (select e2 FROM vm1.g1 WHERE vm1.g2.e4 = vm1.g1.e4) order by e1, e2"; //$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[] { "a", new Integer(0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(3) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(2) }) //$NON-NLS-1$
+ };
+
+ // 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 testCorrelatedSubqueryVirtualLayer3() {
+ String sql = "Select e2 from vm1.g6 where e2 in (select e2 FROM vm1.g1 WHERE vm1.g6.e = e1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[0];
+
+ // 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 testCorrelatedSubqueryVirtualLayer4() {
+ String sql = "Select e2 from vm1.g7 where e2 in (select e2 FROM vm1.g1 WHERE vm1.g7.e = e1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[0];
+
+ // 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 testCorrelatedSubqueryVirtualLayer5() {
+ String sql = "Select e1 from vm1.g4 where not (e1 in (select e1 FROM vm1.g1 WHERE vm1.g4.e1 = e1)) order by e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "3" }) //$NON-NLS-1$
+ };
+
+ // 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 testCorrelatedSubqueryVirtualLayer6() {
+ String sql = "Select e2 from vm1.g1 X where e2 in (select X.e2 FROM vm1.g1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(0) })
+ };
+
+ // 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 testCorrelatedSubqueryVirtualLayer6a() {
+ String sql = "Select e2 from vm1.g1 where e2 in (select vm1.g1.e2 FROM vm1.g5)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(0) })
+ };
+
+
+ // 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 testCorrelatedSubqueryVirtualLayer6b() {
+ String sql = "Select e2 from vm1.g1 where e2 in (select vm1.g1.e2 FROM vm1.g2)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(0) })
+ };
+
+ // 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 testCorrelatedSubqueryVirtualLayer6c() {
+ String sql = "Select e2 from vm1.g7 where e2 in (select vm1.g7.e FROM vm1.g1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[0];
+
+ // 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 testCorrelatedSubqueryVirtualLayer6e() {
+ String sql = "Select e2 from vm1.g1 where e2 in (select vm1.g1.e2 FROM vm1.g2a)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(0) })
+ };
+
+
+ // 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 testCorrelatedSubqueryVirtualLayer7() {
+ String sql = "Select e2 from vm1.g7 where e2 in (select vm1.g7.e FROM vm1.g1 WHERE vm1.g7.e = e1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[0];
+
+ // 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 testCorrelatedSubqueryInTransformation() {
+ String sql = "Select * from vm1.g21"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "b", new Integer(1), Boolean.TRUE, null }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedSubqueryInTransformation2() {
+ String sql = "Select * from vm1.g20"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
+ 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$
+ };
+
+ // 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 testCorrelatedSubqueryInTransformation3() {
+ String sql = "Select * from vm1.g19 order by e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "3" }) //$NON-NLS-1$
+ };
+
+ // 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);
+ }
+
+ /**
+ * User correlated subquery, and one of the virtual group transformations
+ * also has a correlated subquery
+ */
+ @Test public void testCorrelatedSubqueryInTransformation4() {
+ String sql = "Select * from vm1.g20 where exists (Select * from vm1.g19 where convert(vm1.g20.e2, string) = vm1.g19.e1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
+ 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$
+ };
+
+ // 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);
+ }
+
+ /**
+ * User correlated subquery, and one of the virtual group transformations
+ * also has a correlated subquery
+ */
+ @Test public void testCorrelatedSubqueryInTransformation5() {
+ String sql = "Select * from vm1.g19 where exists (Select e2 from vm1.g20 where convert(e2, string) = vm1.g19.e1) order by e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "0" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "3" }) //$NON-NLS-1$
+ };
+
+ // 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 testCorrelatedSubqueryInTransformation6() {
+ String sql = "Select * from vm1.g21 where e2 = some (Select e2 from pm1.g1 where e1 = vm1.g21.e1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "b", new Integer(1), Boolean.TRUE, null }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedSubqueryInTransformation7() {
+ String sql = "Select * from vm1.g21 where exists (Select e2 from pm1.g2 where e4 = convert(vm1.g21.e2, double))"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.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$
+ };
+
+ // 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 testCorrelatedSubqueryInTransformation8() {
+ String sql = "Select * from vm1.g21 where exists (Select e2 from pm1.g1 where e4 = convert(vm1.g21.e2, double))"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.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$
+ };
+
+ // 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 testCorrelatedSubqueryInTransformation9() {
+ String sql = "Select * from vm1.g22"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), new Double(7.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }) //$NON-NLS-1$
+
+ };
+
+ // 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 testCorrelatedSubqueryInTransformation10() {
+ String sql = "Select * from vm1.g23"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), new Double(7.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }) //$NON-NLS-1$
+ };
+
+ // 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 testCorrelatedSubqueryInTransformation11() {
+ String sql = "Select * from vm1.g24"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
+ 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 }),
+ 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$
+ };
+
+ // 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 testCorrelatedSubqueryInTransformation12() {
+ String sql = "Select * from vm1.g24 X where exists (Select * from vm1.g24 Y where X.e2 = Y.e2)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
+ 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 }),
+ 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$
+ };
+
+ // 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 testCorrelatedSubqueryInTransformation13() {
+ String sql = "Select e1, e2, e3, e4, (select e4 from vm1.g25 where pm1.g1.e4 = e5 and e4=0.0) as e5 from pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0), null }),
+ Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), new Double(0.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }) //$NON-NLS-1$
+ };
+
+ // 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 testCorrelatedSubqueryInTransformation14() {
+ String sql = "Select e1, e2, e3, e4, (select e4 from vm1.g26 where pm1.g1.e4 = e5 and e4=0.0) as e5 from pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0), null }),
+ Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), new Double(0.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }) //$NON-NLS-1$
+ };
+
+ // 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 testCorrelatedSubqueryInTransformation15() {
+ String sql = "Select e1, e2, e3, e4, (select e4 from vm1.g23 where vm1.g22.e4 = e5) as e5 from vm1.g22 where e1 = 'a'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), new Double(7.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }) //$NON-NLS-1$
+ };
+
+ // 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 selecting a virtual element (e5) which is defined by a scalar subquery in the virtual transformation */
+ @Test public void testCorrelatedSubqueryInTransformation15a() {
+ String sql = "Select e1, e2, e3, e4 from pm1.g1 where exists (select * from vm1.g26 where pm1.g1.e3 = e3)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = 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$
+ };
+
+ // 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 testCorrelatedSubqueryInTransformation15b() {
+ String sql = "Select e1, e2, e3, e4, (select e4 from vm1.g23 where vm1.g22.e4 = e5) as e5 from vm1.g22 where e1 = 'a' and exists (select * from vm1.g23 where vm1.g22.e3 = e3)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), new Double(7.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }) //$NON-NLS-1$
+ };
+
+ // 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 selecting a virtual element (e5) which is defined by a scalar subquery in the virtual transformation */
+ @Test public void testCorrelatedSubqueryInTransformation15c() {
+ String sql = "Select e1, e2, e3, e4 from pm1.g1 where exists (select e1, e2, e3, e4, e5 as e from vm1.g26 where pm1.g1.e3 = e3)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = 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$
+ };
+
+ // 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 selecting a virtual element (e5) which is defined by a scalar subquery in the virtual transformation */
+ @Test public void testCorrelatedSubqueryInTransformation15d() {
+ String sql = "Select e1, e2, e3, e4 from pm1.g1 where exists (select e1, e2, e3, e4, ((e4 + e5)/(e4 + 1)) as e from vm1.g26 where pm1.g1.e3 = e3)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = 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$
+ };
+
+ // 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);
+ }
+
+// Here is select * from vm1.g26
+// Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }),
+// Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0), null }),
+// Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), null }),
+// Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, null }),
+// Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), new Double(0.0) }),
+// Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null })
+
+
+ @Test public void testCorrelatedSubqueryInTransformation16() {
+// String sql = "Select e1, e2, e3, e4, (select e4 from vm1.g23 where vm1.g22.e4 = e5) as e5 from vm1.g22 where e1 = 'a'"/* and exists (select * from vm1.g23 where vm1.g22.e3 = e3)"*/;
+ String sql = "select * from vm1.g26 where e5 = 0.0"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[]{
+// Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null }),
+// Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0), null }),
+// Arrays.asList(new Object[] { "a", new Integer(3), Boolean.TRUE, new Double(7.0), null }),
+// Arrays.asList(new Object[] { "c", new Integer(1), Boolean.TRUE, null, null }),
+ Arrays.asList(new Object[] { "b", new Integer(2), Boolean.FALSE, new Double(0.0), new Double(0.0) }), //$NON-NLS-1$
+// Arrays.asList(new Object[] { "a", new Integer(0), Boolean.FALSE, new Double(2.0), null })
+ };
+
+ // 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 testCorrelatedSubqueriesNested() {
+ String sql =
+ "Select e1, e2, e4 from pm1.g1 where e2 < all (" + //$NON-NLS-1$
+ "select e2 from pm1.g2 where pm1.g1.e1 = e1 and exists("+ //$NON-NLS-1$
+ "select e2 from pm2.g1 where pm1.g2.e4 = pm2.g1.e4))"; //$NON-NLS-1$
+ Command query = helpParse(sql);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0), new Double(2.0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(1), null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", new Integer(2), new Double(0.0) }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(query, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** defect 15124 */
+ @Test public void testCorrelatedSubqueryAndInlineView() {
+ String sql = "Select e1, (select e2 FROM pm2.g1 Y WHERE X.e4 = Y.e4) from (select * from pm1.g1) as X"; //$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[] { "b", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** defect 15124 */
+ @Test public void testCorrelatedSubqueryAndInlineView2() {
+ String sql = "Select e1 from (select * from pm1.g1) as X WHERE e2 IN (select e2 FROM pm2.g1 Y WHERE X.e4 = Y.e4)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** defect 15124 */
+ @Test public void testCorrelatedSubqueryAndInlineView3() {
+ String sql = "Select e1, (select e2 FROM pm2.g1 Y WHERE X.e4 = Y.e4) from (select * from pm1.g1 UNION ALL select * from pm1.g1) as X"; //$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[] { "b", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** defect 15124 */
+ @Test public void testCorrelatedSubqueryAndInlineView4() {
+ String sql = "Select e1, (select e2 FROM pm2.g1 Y WHERE X.e4 = Y.e4) from (select pm1.g1.e1, (select pm1.g1.e2 from pm1.g1 Z where pm1.g1.e1 = Z.e1), pm1.g1.e3, pm1.g1.e4 from pm1.g1) as X"; //$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[] { "b", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", null }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testXMLUnion_defect8373() {
+ // Create query
+ String sql = "SELECT * FROM xmltest.doc5"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] {
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
+ "<root><node1><node2>a</node2></node1><node1><node2/></node1><node1><node2>a</node2></node1><node1><node2>c</node2></node1><node1><node2>b</node2></node1><node1><node2>a</node2></node1><node1><node2>a</node2></node1><node1><node2/></node1><node1><node2>a</node2></node1><node1><node2>c</node2></node1><node1><node2>b</node2></node1><node1><node2>a</node2></node1></root>" //$NON-NLS-1$
+ })
+ };
+
+ // 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 testStoredQuery1() {
+ // Create query
+ String sql = "EXEC pm1.sq1()"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = SP1RS;
+
+ // 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 testStoredQuery2() {
+ // Create query
+ String sql = "EXEC pm1.sq2(\'a\')"; //$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[] { "a", new Integer(3) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
+ };
+
+ // 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 testStoredQuery3() {
+ // Create query
+ String sql = "select x.e1 from (EXEC pm1.sq1()) as x"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null}),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }), //$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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testStoredQuery4() {
+ // Create query
+ String sql = "EXEC pm1.sq5('a')"; //$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[] { "a", new Integer(3) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
+ };
+
+ // 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 testStoredQuery5() {
+ // Create query
+ String sql = "EXEC pm1.sp1()"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = SP1RS;
+
+ // Construct data manager with data
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("EXEC pm1.sp1()", expected);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testStoredQuery6() {
+ // Create query
+ String sql = "EXEC pm1.sqsp1()"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null}),
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("EXEC pm1.sp1()", SP1RS);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testStoredQuery7() {
+ // Create query
+ String sql = "EXEC pm1.sq17()"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] {
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
+ "<root><node1><node2><node3/></node2></node1></root>" //$NON-NLS-1$
+ })
+ };
+
+ // 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);
+ }
+
+ // implict type conversion of parameter
+ @Test public void testStoredQuery8() {
+ // Create query
+ String sql = "EXEC pm1.sq5(5)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ };
+
+ // 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);
+ }
+
+ // function for parameter
+ @Test public void testStoredQuery9() {
+ // Create query
+ String sql = "EXEC pm1.sq5(concat('a', ''))"; //$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[] { "a", new Integer(3) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
+ };
+
+ // 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);
+ }
+
+ /** named parameters */
+ @Test public void testStoredQuery10() {
+ // Create query
+ String sql = "EXEC pm1.sq3b(\"in\" = 'a', in3 = 'something')"; //$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[] { "a", new Integer(3) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(0) }) //$NON-NLS-1$
+ };
+
+ // 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 testInsert() {
+ // Create query
+ String sql = "Insert into pm1.g1 (pm1.g1.e1, pm1.g1.e2) values ('MyString', 1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1)})
+ };
+
+ // Construct data manager with data
+ 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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey FROM BQT1.SmallA FULL OUTER JOIN BQT2.MediumB ON BQT1.SmallA.IntKey = BQT2.MediumB.IntKey WHERE (BQT1.SmallA.IntKey >= 0) AND (BQT1.SmallA.IntKey <= 15) AND (BQT2.MediumB.IntKey >= 5) AND (BQT2.MediumB.IntKey <= 20) */
+ @Test public void testDefect7770_FullOuter() {
+ // Create query
+ String sql = "SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey FROM BQT1.SmallA FULL OUTER JOIN BQT2.MediumB ON BQT1.SmallA.IntKey = BQT2.MediumB.IntKey WHERE (BQT1.SmallA.IntKey >= 0) AND (BQT1.SmallA.IntKey <= 15) AND (BQT2.MediumB.IntKey >= 5) AND (BQT2.MediumB.IntKey <= 20)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(5), new Integer(5) }),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(8), new Integer(8) }),
+ Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(11) }),
+ Arrays.asList(new Object[] { new Integer(12), new Integer(12) }),
+ Arrays.asList(new Object[] { new Integer(13), new Integer(13) }),
+ Arrays.asList(new Object[] { new Integer(14), new Integer(14) }),
+ Arrays.asList(new Object[] { new Integer(15), new Integer(15) })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey FROM BQT1.SmallA RIGHT OUTER JOIN BQT2.MediumB ON BQT1.SmallA.IntKey = BQT2.MediumB.IntKey WHERE (BQT1.SmallA.IntKey >= 0) AND (BQT1.SmallA.IntKey <= 15) AND (BQT2.MediumB.IntKey >= 5) AND (BQT2.MediumB.IntKey <= 20) */
+ @Test public void testDefect7770_RightOuter() {
+ // Create query
+ String sql = "SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey FROM BQT1.SmallA RIGHT OUTER JOIN BQT2.MediumB ON BQT1.SmallA.IntKey = BQT2.MediumB.IntKey WHERE (BQT1.SmallA.IntKey >= 0) AND (BQT1.SmallA.IntKey <= 15) AND (BQT2.MediumB.IntKey >= 5) AND (BQT2.MediumB.IntKey <= 20)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(5), new Integer(5) }),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(8), new Integer(8) }),
+ Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(11) }),
+ Arrays.asList(new Object[] { new Integer(12), new Integer(12) }),
+ Arrays.asList(new Object[] { new Integer(13), new Integer(13) }),
+ Arrays.asList(new Object[] { new Integer(14), new Integer(14) }),
+ Arrays.asList(new Object[] { new Integer(15), new Integer(15) })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey FROM BQT1.SmallA LEFT OUTER JOIN BQT2.MediumB ON BQT1.SmallA.IntKey = BQT2.MediumB.IntKey WHERE (BQT1.SmallA.IntKey >= 0) AND (BQT1.SmallA.IntKey <= 15) AND (BQT2.MediumB.IntKey >= 5) AND (BQT2.MediumB.IntKey <= 20) */
+ @Test public void testDefect7770_LeftOuter() {
+ // Create query
+ String sql = "SELECT BQT1.SmallA.IntKey AS SmallA_IntKey, BQT2.MediumB.IntKey AS MediumB_IntKey FROM BQT1.SmallA LEFT OUTER JOIN BQT2.MediumB ON BQT1.SmallA.IntKey = BQT2.MediumB.IntKey WHERE (BQT1.SmallA.IntKey >= 0) AND (BQT1.SmallA.IntKey <= 15) AND (BQT2.MediumB.IntKey >= 5) AND (BQT2.MediumB.IntKey <= 20)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(5), new Integer(5) }),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(8), new Integer(8) }),
+ Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(11) }),
+ Arrays.asList(new Object[] { new Integer(12), new Integer(12) }),
+ Arrays.asList(new Object[] { new Integer(13), new Integer(13) }),
+ Arrays.asList(new Object[] { new Integer(14), new Integer(14) }),
+ Arrays.asList(new Object[] { new Integer(15), new Integer(15) })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testReorder1() {
+ // Create query
+ String sql = "SELECT e1 AS x, {b'false'}, e2+e4, e3 FROM pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", Boolean.FALSE, new Double(2.0), Boolean.FALSE }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { null, Boolean.FALSE, new Double(2.0), Boolean.FALSE }),
+ Arrays.asList(new Object[] { "a", Boolean.FALSE, new Double(10.0), Boolean.TRUE }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", Boolean.FALSE, null, Boolean.TRUE }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", Boolean.FALSE, new Double(2.0), Boolean.FALSE }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", Boolean.FALSE, new Double(2.0), Boolean.FALSE }) //$NON-NLS-1$
+ };
+
+ // 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 testTwoFullOuterJoins1() {
+ // Create query
+ String sql = "SELECT A.IntKey AS A_IntKey, B.IntKey AS B_IntKey, C.IntKey AS C_IntKey " + //$NON-NLS-1$
+ "FROM (BQT1.SmallA AS A FULL OUTER JOIN BQT2.SmallA AS B ON A.IntKey = B.IntKey) FULL OUTER JOIN BQT3.SmallA AS C ON B.IntKey = C.IntKey " + //$NON-NLS-1$
+ "WHERE (A.IntKey >= 0) AND (A.IntKey <= 15) " + //$NON-NLS-1$
+ "AND (B.IntKey >= 5) AND (B.IntKey <= 20) " + //$NON-NLS-1$
+ "AND (C.IntKey >= 10) AND (C.IntKey <= 30)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(10), new Integer(10), new Integer(10) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(11), new Integer(11) }),
+ Arrays.asList(new Object[] { new Integer(12), new Integer(12), new Integer(12) }),
+ Arrays.asList(new Object[] { new Integer(13), new Integer(13), new Integer(13) }),
+ Arrays.asList(new Object[] { new Integer(14), new Integer(14), new Integer(14) }),
+ Arrays.asList(new Object[] { new Integer(15), new Integer(15), new Integer(15) })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testSelectDistinctOnBQT() {
+ // Create query
+ String sql = "SELECT DISTINCT IntKey FROM BQT1.SmallA"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(5) }),
+ Arrays.asList(new Object[] { new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(8) }),
+ Arrays.asList(new Object[] { new Integer(9) }),
+ Arrays.asList(new Object[] { new Integer(10) }),
+ Arrays.asList(new Object[] { new Integer(11) }),
+ Arrays.asList(new Object[] { new Integer(12) }),
+ Arrays.asList(new Object[] { new Integer(13) }),
+ Arrays.asList(new Object[] { new Integer(14) }),
+ Arrays.asList(new Object[] { new Integer(15) }),
+ Arrays.asList(new Object[] { new Integer(16) }),
+ Arrays.asList(new Object[] { new Integer(17) }),
+ Arrays.asList(new Object[] { new Integer(18) }),
+ Arrays.asList(new Object[] { new Integer(19) })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testSelectWithNoFrom() {
+ // Create query
+ String sql = "SELECT 5"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(5) })
+ };
+
+ // 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 testBetween() {
+ // Create query
+ String sql = "SELECT * FROM pm1.g1 WHERE e2 BETWEEN 1 AND 2"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, new Integer(1), Boolean.FALSE, new Double(1.0) }),
+ 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$
+ };
+
+ // 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 <code>QueryProcessor</code>'s ability to process a query containing
+ * a <code>CASE</code> expression in which a <code>BETWEEN</code>
+ * comparison is used in the queries <code>SELECT</code> statement.
+ * <p>
+ * For example:
+ * <p>
+ * SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1
+ */
+ @Test public void testBetweenInCase() {
+ // Create query
+ final String sql = "SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(-1) }),
+ Arrays.asList(new Object[] { new Integer(-1) }),
+ Arrays.asList(new Object[] { new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(-1) }),
+ Arrays.asList(new Object[] { new Integer(-1) }),
+ Arrays.asList(new Object[] { new Integer(-1) })
+ };
+
+ // 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 <code>QueryProcessor</code>'s ability to process a query containing
+ * an aggregate SUM with a <code>CASE</code> expression in which a
+ * <code>BETWEEN</code> comparison is used in the queries <code>SELECT</code>
+ * statement.
+ * <p>
+ * For example:
+ * <p>
+ * SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1
+ */
+ @Test public void testBetweenInCaseInSum() {
+ // Create query
+ final String sql = "SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Long(-2) })
+ };
+
+ // 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 <code>QueryProcessor</code>'s ability to process a query containing
+ * an aggregate SUM with a <code>CASE</code> expression in which a
+ * <code>BETWEEN</code> comparison is used in the queries <code>SELECT</code>
+ * statement and a GROUP BY is specified.
+ * <p>
+ * For example:
+ * <p>
+ * SELECT e1, SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END)
+ * FROM pm1.g1 GROUP BY e1 ORDER BY e1
+ */
+ @Test public void testBetweenInCaseInSumWithGroupBy() {
+ // Create query
+ final String sql = "SELECT e1, SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1 GROUP BY e1 ORDER BY e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, new Long(-1) }),
+ Arrays.asList(new Object[] { "a", new Long(1) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Long(-1) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c", new Long(-1) }) //$NON-NLS-1$
+ };
+
+ // 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 <code>QueryProcessor</code>'s ability to process a query containing
+ * an aggregate COUNT with a <code>CASE</code> expression in which a
+ * <code>BETWEEN</code> comparison is used in the queries <code>SELECT</code>
+ * statement.
+ * <p>
+ * For example:
+ * <p>
+ * SELECT COUNT(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 END) FROM pm1.g1
+ */
+ @Test public void testBetweenInCaseInCount() {
+ // Create query
+ final String sql = "SELECT COUNT(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 END) FROM pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1) })
+ };
+
+ // 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 testCase() {
+ // Create query
+ String sql = "SELECT e2, CASE e2 WHEN 1 THEN 2 ELSE 3 END FROM pm1.g1 WHERE e2 BETWEEN 1 AND 2"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(3) })
+ };
+
+ // 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 testSelectNoFrom1() {
+ // Create query
+ String sql = "SELECT 1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1) })
+ };
+
+ // 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 testSelectNoFrom2() {
+ // Create query
+ String sql = "SELECT 1, {b'true'}, 2.0 AS x, {d'2003-11-04'}"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), Boolean.TRUE, new Double(2.0), TimestampUtil.createDate(103, 10, 4) })
+ };
+
+ // 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 testCase1566() throws Exception {
+ // Create query
+ String sql = "SELECT x, COUNT(*) FROM (SELECT convert(TimestampValue, date) AS x FROM bqt1.smalla) as y GROUP BY x"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { java.sql.Date.valueOf("2002-01-01"), new Integer(2) }),
+ Arrays.asList(new Object[] { java.sql.Date.valueOf("2002-01-02"), new Integer(3) }) };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT_case1566(dataManager);
+
+ // Create capabilities
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ // Parse query
+ Command command = QueryParser.getQueryParser().parseCommand(sql);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.exampleBQTCached(), capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testDefect10976(){
+ String sql = "SELECT * FROM vm1.g28"; //$NON-NLS-1$
+
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { "A", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "B", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "C", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // 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 testDefect10976_2(){
+ String sql = "SELECT * FROM vm1.g29"; //$NON-NLS-1$
+
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { "A", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "B", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "C", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // 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 testDefect10976_3(){
+ String sql = "SELECT * FROM vm1.g30"; //$NON-NLS-1$
+
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // 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 testDefect10976_4(){
+ String sql = "SELECT * FROM vm1.g31 order by x"; //$NON-NLS-1$
+
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // 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 testDefect10976_5(){
+ String sql = "SELECT * FROM vm1.g32"; //$NON-NLS-1$
+
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", "c" }) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // 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 testDefect11236_MergeJoinWithFunctions() {
+ // Create query
+ String sql = "SELECT pm1.g1.e2, pm2.g1.e2 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e2 = (pm2.g1.e2+1) order by pm1.g1.e2, pm2.g1.e2"; //$NON-NLS-1$
+ boolean pushDown = false;
+ boolean dependent = false;
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(2) })
+ };
+
+ helpTestMergeJoinWithExpression(sql, pushDown, dependent, expected);
+ }
+
+ @Test public void testMergeJoinWithFunctionsPushDown() {
+ // Create query
+ String sql = "SELECT pm1.g1.e2, pm2.g1.e2 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e2 = (pm2.g1.e2+1)"; //$NON-NLS-1$
+ boolean pushDown = true;
+ boolean dependent = false;
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(2) })
+ };
+
+ helpTestMergeJoinWithExpression(sql, pushDown, dependent, expected);
+ }
+
+ @Test public void testMergeJoinWithFunctionsPushDownDependent() {
+ // Create query
+ String sql = "SELECT pm1.g1.e2, pm2.g1.e2 FROM pm1.g1, pm2.g1 WHERE pm1.g1.e2 = (pm2.g1.e2+1) option makedep pm1.g1"; //$NON-NLS-1$
+ boolean pushDown = true;
+ boolean dependent = true;
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(2) })
+ };
+
+ helpTestMergeJoinWithExpression(sql, pushDown, dependent, expected);
+ }
+
+
+ /**
+ * @param sql
+ * @param pushDown
+ * @param expected
+ */
+ private void helpTestMergeJoinWithExpression(String sql,
+ boolean pushDown,
+ boolean dependent,
+ List[] expected) {
+ // Construct data manager with data
+ ProcessorDataManager dataManager = null;
+ if (!pushDown) {
+ FakeDataManager fakeDataManager = new FakeDataManager();
+ sampleData1(fakeDataManager);
+ dataManager = fakeDataManager;
+ } else {
+ HardcodedDataManager hardCoded = new HardcodedDataManager();
+ List[] results = new List[] {
+ Arrays.asList(new Object[] {new Integer(0), new Integer(1)}),
+ Arrays.asList(new Object[] {new Integer(0), new Integer(1)}),
+ Arrays.asList(new Object[] {new Integer(1), new Integer(2)}),
+ Arrays.asList(new Object[] {new Integer(1), new Integer(2)}),
+ Arrays.asList(new Object[] {new Integer(2), new Integer(3)}),
+ Arrays.asList(new Object[] {new Integer(3), new Integer(4)}),
+ };
+ hardCoded.addData("SELECT g_0.e2 AS c_0, (g_0.e2 + 1) AS c_1 FROM pm2.g1 AS g_0 ORDER BY c_1", results); //$NON-NLS-1$
+ if (!dependent) {
+ results = new List[] {
+ Arrays.asList(new Object[] {new Integer(0),}),
+ Arrays.asList(new Object[] {new Integer(0),}),
+ Arrays.asList(new Object[] {new Integer(1),}),
+ Arrays.asList(new Object[] {new Integer(1),}),
+ Arrays.asList(new Object[] {new Integer(2),}),
+ Arrays.asList(new Object[] {new Integer(3),}),
+ };
+ hardCoded.addData("SELECT g_0.e2 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", results); //$NON-NLS-1$
+ } else {
+ results = new List[] {
+ Arrays.asList(new Object[] {new Integer(1),}),
+ Arrays.asList(new Object[] {new Integer(2),}),
+ Arrays.asList(new Object[] {new Integer(1),}),
+ };
+ hardCoded.addData("SELECT g_0.e2 AS c_0 FROM pm1.g1 AS g_0 WHERE g_0.e2 IN (1, 2)", results); //$NON-NLS-1$
+ results = new List[] {
+ Arrays.asList(new Object[] {new Integer(3),}),
+ };
+ hardCoded.addData("SELECT g_0.e2 AS c_0 FROM pm1.g1 AS g_0 WHERE g_0.e2 IN (3, 4)", results); //$NON-NLS-1$
+ }
+ dataManager = hardCoded;
+ }
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, pushDown);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, pushDown);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(2));
+ caps.setFunctionSupport("+", pushDown); //$NON-NLS-1$
+ finder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ finder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, finder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCase2() {
+ // Create query
+ String sql = "SELECT e2, CASE e2 WHEN 1 THEN 2 END FROM pm1.g1 WHERE e2 BETWEEN 1 AND 2"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2), null })
+ };
+
+ // 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 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$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2), null })
+ };
+
+ // 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);
+ }
+
+ /** nested scalar subquery */
+ @Test public void testCase4() {
+ // Create query
+ String nestedExpression = "(SELECT e1 FROM pm1.g2 WHERE e2 = 3)"; //$NON-NLS-1$
+ String sql = "SELECT e2, CASE e2 WHEN 1 THEN " + nestedExpression + " ELSE null END FROM pm1.g1 WHERE e2 BETWEEN 1 AND 2"; //$NON-NLS-1$ //$NON-NLS-2$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(1), "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(2), null })
+ };
+
+ // 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);
+ }
+
+ /** nested correlated scalar subquery */
+ @Test public void testCase5() {
+ // Create query
+ String nestedExpression = "(SELECT e2 FROM pm1.g2 WHERE pm1.g1.e2 = (e4 + 2))"; //$NON-NLS-1$
+ String sql = "SELECT e2, CASE e2 WHEN " + nestedExpression + " THEN 1 ELSE null END FROM pm1.g1"; //$NON-NLS-1$ //$NON-NLS-2$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0), null }),
+ Arrays.asList(new Object[] { new Integer(1), null }),
+ Arrays.asList(new Object[] { new Integer(3), null }),
+ Arrays.asList(new Object[] { new Integer(1), null }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(0), null })
+ };
+
+ // 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);
+ }
+
+ /**
+ * NOTE: this test depends on the ProcessorPlan being executed
+ * twice and reset in between, which currently is done in the
+ * helpProcess method
+ */
+ @Test public void testDefect12135(){
+ String sql = "SELECT pm1.g1.e1, pm1.g2.e1 FROM pm1.g1 LEFT OUTER JOIN pm1.g2 ON pm1.g1.e1=pm1.g2.e1"; //$NON-NLS-1$
+
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", null }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testDefect12081(){
+ String sql = "SELECT DISTINCT vm1.g1.e1, upper(vm1.g1.e1) as Nuge, pm1.g1.e1, upper(pm1.g1.e1) as Nuge FROM vm1.g1, pm1.g1"; //$NON-NLS-1$
+
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", "A", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "a", "A", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "a", "A", "c", "C" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "b", "B", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "b", "B", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "b", "B", "c", "C" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "c", "C", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "c", "C", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "c", "C", "c", "C" }) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testDefect12081_2(){
+ String sql = "SELECT DISTINCT vm1.g1b.e1, vm1.g1b.e1Upper, pm1.g1.e1, upper(pm1.g1.e1) as e1Upper FROM vm1.g1b, pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", "A", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "a", "A", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "a", "A", "c", "C" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "b", "B", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "b", "B", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "b", "B", "c", "C" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "c", "C", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "c", "C", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "c", "C", "c", "C" }) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testDefect12081_3(){
+ String sql = "SELECT DISTINCT vm1.g1b.e1, vm1.g1b.e1Upper, pm1.g1.e1, vm1.g1b.e1Upper FROM vm1.g1b, pm1.g1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", "A", "a", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "a", "A", "b", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "a", "A", "c", "A" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "b", "B", "a", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "b", "B", "b", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "b", "B", "c", "B" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "c", "C", "a", "C" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "c", "C", "b", "C" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { "c", "C", "c", "C" }) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Basically the same as above, but with a limit node between the dup removal and the project
+ */
+ @Test public void testDefect12081_4(){
+ String sql = "SELECT DISTINCT e1, e1 FROM pm1.g1 where e1 = 'a' LIMIT 1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", "a"}), //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testDefect12719(){
+ String sql = "SELECT e1_, e2_, e2 FROM vm1.g34, pm1.g2 WHERE vm1.g34.e1_ = pm1.g2.e1 order by e1_, e2_"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0), new Integer(1) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(0), new Integer(0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(0), new Integer(5) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(0), new Integer(2) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(1), new Integer(0) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(1), new Integer(5) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(1), new Integer(2) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "d", new Integer(3), new Integer(2) }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testDefect13034() {
+ String sql = "SELECT CONCAT('http://', CONCAT(CASE WHEN (HOST IS NULL) OR (HOST = '') THEN 'soap_host' ELSE HOST END, CASE WHEN (PORT IS NULL) OR (PORT = '') THEN '/metamatrix-soap/services/DataService' ELSE CONCAT(':', CONCAT(PORT, '/metamatrix-soap/services/DataService')) END)) AS location " + //$NON-NLS-1$
+ "FROM (SELECT env('soap_host') AS HOST, env('soap_port') AS PORT) AS props"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "http://my.host.com:12345/metamatrix-soap/services/DataService" }), //$NON-NLS-1$
+ };
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, new FakeDataManager(), expected);
+
+ }
+
+ /** see also integer average defect 11682 */
+ @Test public void testIntAvgDefect11682() {
+ // Create query
+ String sql = "SELECT AVG(IntKey), AVG(IntNum), AVG(FloatNum), AVG(LongNum), AVG(DoubleNum), AVG(ByteNum), AVG(ShortValue), AVG(BigIntegerValue), AVG(BigDecimalValue) FROM BQT1.SmallA"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Double(1.5), new Double(1.5), new Double(1.5), new Double(1.5), new Double(1.5), new Double(1.5), new Double(1.5), new BigDecimal("1.500000000"), new BigDecimal("1.500000000") }), //$NON-NLS-1$//$NON-NLS-2$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT_defect11682(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testNonJoinCriteriaInFrom() {
+ String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a LEFT OUTER JOIN pm2.g1 b ON a.e1=b.e1 AND b.e2 = 0"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", null, null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", "b", new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", null, null }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testNonJoinCriteriaInWhere() {
+ String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a LEFT OUTER JOIN pm2.g1 b ON a.e1=b.e1 WHERE b.e2 = 0"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "b", "b", new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testNonJoinCriteriaInWhere2() {
+ String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a LEFT OUTER JOIN pm1.g2 b ON a.e1=b.e1 WHERE (a.e2 + b.e2 = 1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", "a", new Integer(1) }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b", new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testNonJoinCriteriaInWhere3() {
+ String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a LEFT OUTER JOIN pm1.g2 b ON a.e1=b.e1 WHERE (a.e2 = 0) OR (b.e2 = 0)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", "a", new Integer(1) }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b", new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testNonJoinCriteriaInFromNestedInVirtual() {
+ String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a LEFT OUTER JOIN (SELECT c.e1, d.e2 FROM pm2.g1 c JOIN pm2.g1 d ON c.e1=d.e1 AND d.e2 >= 0) b ON a.e1=b.e1 AND b.e2 = 0"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", null, null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", "b", new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", null, null }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testNonJoinCriteriaInFromUsingDependentJoin() {
+ String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a LEFT OUTER JOIN pm2.g1 b ON a.e1=b.e1 AND b.e2 = 0"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", null, null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", "b", new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", null, null }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2a(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testDefect13700() {
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(10) }),
+ };
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan("EXEC pm1.vsp36(5)", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+
+ // Run query
+ helpProcess(plan, new FakeDataManager(), expected);
+
+ }
+
+ @Test public void testDefect13920() throws Exception {
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, false);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, false);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ 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,
+ RealMetadataFactory.example1Cached(), capFinder);
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ 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);
+ cal.set(Calendar.MILLISECOND, 0);
+ Timestamp t1 = new Timestamp(cal.getTime().getTime());
+ cal.clear();
+ cal.set(2004, Calendar.AUGUST, 1, 0, 0, 0);
+ cal.set(Calendar.MILLISECOND, 0);
+ Timestamp t2 = new Timestamp(cal.getTime().getTime());
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { t1, new Integer(1), Boolean.TRUE, null }),
+ Arrays.asList(new Object[] { t2, new Integer(2), Boolean.FALSE, new Double(0.0) }),
+ };
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ /** RLM Case 2077
+ * @throws Exception */
+ @Test public void testComplexJoinExpressionsUsingDependentJoin() throws Exception {
+ String sql = "SELECT a.e1, b.e1, b.e2 FROM pm1.g1 a, pm2.g1 b where rtrim(a.e1)=(b.e1 || b.e1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "bb ", "b", new Integer(0) }) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
+ caps.setFunctionSupport("||", true); //$NON-NLS-1$
+ caps.setFunctionSupport("rtrim", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-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);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder,context);
+
+ //Verify a dependent join (not merge join) was used
+ assertTrue(plan instanceof RelationalPlan);
+ RelationalPlan relationalPlan = (RelationalPlan)plan;
+ RelationalNode project = relationalPlan.getRootNode();
+ RelationalNode join = project.getChildren()[0];
+ assertTrue("Expected instance of JoinNode (for dep join) but got " + join.getClass(), join instanceof JoinNode); //$NON-NLS-1$
+
+ // Run query
+ helpProcess(plan, context, dataManager, expected);
+ }
+
+ /** RLM Case 2077
+ * @throws Exception */
+ @Test public void testComplexJoinExpressionsUsingDependentJoinWithAccessPattern() throws Exception {
+ String sql = "SELECT a.e1, b.e1, b.e2 FROM pm4.g1 a, pm2.g1 b where rtrim(a.e1)=(b.e1 || b.e1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "bb ", "b", new Integer(0) }) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
+ caps.setFunctionSupport("||", true); //$NON-NLS-1$
+ caps.setFunctionSupport("rtrim", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm4", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-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);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder, context);
+
+ //Verify a dependent join (not merge join) was used
+ assertTrue(plan instanceof RelationalPlan);
+ RelationalPlan relationalPlan = (RelationalPlan)plan;
+ RelationalNode project = relationalPlan.getRootNode();
+ RelationalNode join = project.getChildren()[0];
+ assertTrue("Expected instance of JoinNode (for dep join) but got " + join.getClass(), join instanceof JoinNode); //$NON-NLS-1$
+
+ // Run query
+ helpProcess(plan, context, dataManager, expected);
+ }
+
+ @Test public void testPushingCriteriaUnderJoinButNotToSource() {
+ // Create query
+ String sql = "SELECT A.IntKey AS A_IntKey, B.IntKey AS B_IntKey, C.IntKey AS C_IntKey " + //$NON-NLS-1$
+ "FROM (BQT1.SmallA AS A FULL OUTER JOIN BQT2.SmallA AS B ON A.IntKey = B.IntKey) LEFT OUTER JOIN BQT3.SmallA AS C ON B.IntKey = C.IntKey " + //$NON-NLS-1$
+ "WHERE (sin(A.IntKey) >= 0) " + //$NON-NLS-1$
+ "AND (C.IntKey >= 10)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(13), new Integer(13), new Integer(13) }),
+ Arrays.asList(new Object[] { new Integer(14), new Integer(14), new Integer(14) }),
+ Arrays.asList(new Object[] { new Integer(15), new Integer(15), new Integer(15) }),
+ Arrays.asList(new Object[] { new Integer(19), new Integer(19), new Integer(19) }),
+ Arrays.asList(new Object[] { new Integer(20), new Integer(20), new Integer(20) }),
+ Arrays.asList(new Object[] { new Integer(21), new Integer(21), new Integer(21) }),
+ Arrays.asList(new Object[] { new Integer(26), new Integer(26), new Integer(26) }),
+ Arrays.asList(new Object[] { new Integer(27), new Integer(27), new Integer(27) }),
+ Arrays.asList(new Object[] { new Integer(28), new Integer(28), new Integer(28) })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testPushdownLiteralInSelectUnderAggregate() {
+ String sql = "SELECT COUNT(*) FROM (SELECT '' AS y, a.IntKey FROM BQT1.SmallA a union all select '', b.intkey from bqt1.smallb b) AS x"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(30) })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT2(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testPushdownLiteralInSelectWithOrderBy() {
+ String sql = "SELECT 1, concat('a', 'b' ) AS X FROM BQT1.SmallA where intkey = 0 " + //$NON-NLS-1$
+ "UNION ALL " + //$NON-NLS-1$
+ "select 2, 'Hello2' from BQT1.SmallA where intkey = 1 order by X desc"; //$NON-NLS-1$
+
+
+ // Create expected results - would expect these to be:
+ // 1, "ab"
+ // 2, "Hello2"
+ // but our fake tuple source is too dumb to return anything reasonable, so instead get:
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQTSmall(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /** defect 15348
+ * @throws Exception */
+ @Test public void testPreparedStatementDefect15348() throws Exception{
+ String sql = "SELECT e1 from pm1.g1 where myrtrim(?)=e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2a(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setFunctionSupport("myrtrim", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(RealMetadataFactory.example1Cached().getMetadataStore(), "example1", new FunctionTree("foo", new FakeFunctionMetadataSource(), true));
+
+ processPreparedStatement(sql, expected, dataManager, capFinder,
+ metadata, Arrays.asList("a "));
+ }
+
+ static void processPreparedStatement(String sql, List[] expected,
+ ProcessorDataManager dataManager, CapabilitiesFinder capFinder,
+ QueryMetadataInterface metadata, List<?> values) throws Exception {
+ Command command = helpParse(sql);
+ CommandContext context = createCommandContext();
+ context.setMetadata(metadata);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder, context);
+
+ // Collect reference, set value
+ VariableContext vc = new VariableContext();
+ Iterator<?> valIter = values.iterator();
+ for (Reference ref : ReferenceCollectorVisitor.getReferences(command)) {
+ vc.setGlobalValue(ref.getContextSymbol(), valIter.next()); //$NON-NLS-1$
+ }
+ context.setVariableContext(vc);
+ // Run query
+ helpProcess(plan, context, dataManager, expected);
+ }
+
+ /** defect 15348
+ * @throws Exception */
+ @Test public void testPreparedStatementDefect15348b() throws Exception{
+ String sql = "SELECT e1 from pm4.g1 where myrtrim(concat(?, 'a '))=e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "aa" }) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2a(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setFunctionSupport("myrtrim", true); //$NON-NLS-1$
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+ capFinder.addCapabilities("pm4", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(RealMetadataFactory.example1Cached().getMetadataStore(), "example1", new FunctionTree("foo", new FakeFunctionMetadataSource(), true));
+
+ processPreparedStatement(sql, expected, dataManager, capFinder,
+ metadata, Arrays.asList("a"));
+ }
+
+ @Test public void testSourceDoesntSupportGroupAlias() {
+ String sql = "SELECT a.IntKey, b.IntKey FROM BQT1.SmallA a, BQT1.SmallB b WHERE a.IntKey = 5 AND A.IntKey = b.IntKey"; //$NON-NLS-1$
+
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ Set atomicQueries = TestOptimizer.getAtomicQueries(plan);
+ assertEquals("Expected one query to get pushed down", 1, atomicQueries.size()); //$NON-NLS-1$
+ String atomicSql = atomicQueries.iterator().next().toString();
+ String expectedSql = "SELECT BQT1.SmallA.IntKey, BQT1.SmallB.IntKey FROM BQT1.SmallA, BQT1.SmallB WHERE (BQT1.SmallA.IntKey = BQT1.SmallB.IntKey) AND (BQT1.SmallA.IntKey = 5) AND (BQT1.SmallB.IntKey = 5)"; //$NON-NLS-1$
+ assertEquals(expectedSql, atomicSql);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(5), new Integer(5)}),
+ };
+
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData(expectedSql, expected);
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testSourceDoesntSupportGroupAliasOrCriteria() {
+ String sql = "SELECT a.IntKey, b.IntKey FROM BQT1.SmallA a, BQT1.SmallB b WHERE a.StringKey = '5' AND A.IntKey = b.IntKey"; //$NON-NLS-1$
+
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ Set atomicQueries = TestOptimizer.getAtomicQueries(plan);
+ assertEquals("Expected 2 queries to get pushed down", 2, atomicQueries.size()); //$NON-NLS-1$
+
+ String expectedSql = "SELECT BQT1.SmallA.StringKey, BQT1.SmallA.IntKey FROM BQT1.SmallA"; //$NON-NLS-1$
+ String expectedSql2 = "SELECT BQT1.SmallB.IntKey FROM BQT1.SmallB"; //$NON-NLS-1$
+ Set expectedQueries = new HashSet();
+ expectedQueries.add(expectedSql);
+ expectedQueries.add(expectedSql2);
+ assertEquals(expectedQueries, atomicQueries);
+
+ List[] input1 = new List[] {
+ Arrays.asList(new Object[] { "5", new Integer(5)}), //$NON-NLS-1$
+ };
+ List[] input2 = new List[] {Arrays.asList(new Object[] {new Integer(5)}),
+ };
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData(expectedSql, input1);
+ dataManager.addData(expectedSql2, input2);
+
+ List[] expected = new List[] {Arrays.asList(new Object[] {new Integer(5), new Integer(5)}),
+ };
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Same as testSourceDoesntSupportGroupAlias, but query is in an inline view and only
+ * the first column is selected.
+ *
+ * @since 4.2
+ */
+ @Test public void testSourceDoesntSupportGroupAliasInVirtual() {
+ String sql = "SELECT x FROM (SELECT a.IntKey as x, b.IntKey as y FROM BQT1.SmallA a, BQT1.SmallB b WHERE a.IntKey = 5 AND A.IntKey = b.IntKey) AS z, BQT2.SmallA WHERE y = IntKey"; //$NON-NLS-1$
+
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ Set atomicQueries = TestOptimizer.getAtomicQueries(plan);
+ assertEquals("Expected 2 queries to get pushed down", 2, atomicQueries.size()); //$NON-NLS-1$
+
+ String expectedSql = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA, BQT1.SmallB WHERE (BQT1.SmallA.IntKey = BQT1.SmallB.IntKey) AND (BQT1.SmallA.IntKey = 5) AND (BQT1.SmallB.IntKey = 5)"; //$NON-NLS-1$
+ String expectedSql2 = "SELECT BQT2.SmallA.IntKey FROM BQT2.SmallA WHERE BQT2.SmallA.IntKey = 5"; //$NON-NLS-1$
+
+ Set expectedQueries = new HashSet();
+ expectedQueries.add(expectedSql);
+ expectedQueries.add(expectedSql2);
+ assertEquals(expectedQueries, atomicQueries);
+
+ List[] input1 = new List[] {
+ Arrays.asList(new Object[] { new Integer(5), new Integer(5)}),
+ };
+ List[] input2 = new List[] {
+ Arrays.asList(new Object[] { new Integer(5)}),
+ };
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData(expectedSql, input1);
+ dataManager.addData(expectedSql2, input2);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(5)}),
+ };
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCaseInGroupBy() {
+ 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_SEARCHED_CASE, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ Set actualQueries = TestOptimizer.getAtomicQueries(plan);
+ String expectedSql = "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$
+ assertEquals(1, actualQueries.size());
+ assertEquals(expectedSql, actualQueries.iterator().next().toString());
+
+ List[] input1 = new List[] {
+ Arrays.asList(new Object[] { new Integer(5), new Integer(10)}),
+ };
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData(expectedSql, input1);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(5), new Integer(10)}),
+ };
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCaseInGroupByAndHavingCantPush() {
+ 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$
+ "HAVING case when IntKey>=5000 then '5000 +' else '0-999' end = '5000 +'"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, false); // Can't push GROUP BY
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ Set actualQueries = TestOptimizer.getAtomicQueries(plan);
+ String expectedSql = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA"; //$NON-NLS-1$
+ assertEquals(1, actualQueries.size());
+ assertEquals(expectedSql, actualQueries.iterator().next().toString());
+
+ List[] input1 = new List[] {
+ Arrays.asList(new Object[] { new Integer(2)}),
+ Arrays.asList(new Object[] { new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(10000)}),
+ Arrays.asList(new Object[] { new Integer(10002)}),
+ };
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData(expectedSql, input1);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Long(20002), "5000 +"}), //$NON-NLS-1$
+ };
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCaseInGroupByAndHavingCantPush2() {
+ String sql = "SELECT sum (IntKey), case when IntKey>=5000 then '5000 +' else '0-999' end || 'x' " + //$NON-NLS-1$
+ "FROM BQT1.SmallA GROUP BY case when IntKey>=5000 then '5000 +' else '0-999' end " + //$NON-NLS-1$
+ "HAVING length(case when IntKey>=5000 then '5000 +' else '0-999' end) > 5"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, false); // Can't push GROUP BY
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ Set actualQueries = TestOptimizer.getAtomicQueries(plan);
+ String expectedSql = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA"; //$NON-NLS-1$
+ assertEquals(1, actualQueries.size());
+ assertEquals(expectedSql, actualQueries.iterator().next().toString());
+
+ List[] input1 = new List[] {
+ Arrays.asList(new Object[] { new Integer(2)}),
+ Arrays.asList(new Object[] { new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(10000)}),
+ Arrays.asList(new Object[] { new Integer(10002)}),
+ };
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData(expectedSql, input1);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Long(20002), "5000 +x"}), //$NON-NLS-1$
+ };
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCaseInGroupByAndHavingCantPush3() {
+ String sql = "SELECT s, c FROM (" + //$NON-NLS-1$
+ "SELECT sum (IntKey) s, case when IntKey>=5000 then '5000 +' else '0-999' end || 'x' c " + //$NON-NLS-1$
+ "FROM BQT1.SmallA GROUP BY case when IntKey>=5000 then '5000 +' else '0-999' end " + //$NON-NLS-1$
+ ") AS x WHERE length(c) > 5 AND s = 20002"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, false); // Can't push GROUP BY
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ Set actualQueries = TestOptimizer.getAtomicQueries(plan);
+ String expectedSql = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA"; //$NON-NLS-1$
+ assertEquals(1, actualQueries.size());
+ assertEquals(expectedSql, actualQueries.iterator().next().toString());
+
+ List[] input1 = new List[] {
+ Arrays.asList(new Object[] { new Integer(2)}),
+ Arrays.asList(new Object[] { new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(10000)}),
+ Arrays.asList(new Object[] { new Integer(10002)}),
+ };
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData(expectedSql, input1);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Long(20002), "5000 +x"}), //$NON-NLS-1$
+ };
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testFunctionOfAggregateCantPush() {
+ String sql = "SELECT StringKey || 'x', SUM(length(StringKey || 'x')) + 1 AS x FROM BQT1.SmallA GROUP BY StringKey || 'x' HAVING space(MAX(length((StringKey || 'x') || 'y'))) = ' '"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ Set actualQueries = TestOptimizer.getAtomicQueries(plan);
+ String expectedSql = "SELECT BQT1.SmallA.StringKey FROM BQT1.SmallA"; //$NON-NLS-1$
+ assertEquals(1, actualQueries.size());
+ assertEquals(expectedSql, actualQueries.iterator().next().toString());
+
+ List[] input1 = new List[] {
+ Arrays.asList(new Object[] { "0"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "1"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "10"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "11"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "100"}), //$NON-NLS-1$
+ };
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData(expectedSql, input1);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "0x", new Long(3)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "1x", new Long(3)}), //$NON-NLS-1$
+ };
+ helpProcess(plan, dataManager, expected);
+ }
+
+
+ @Test public void testCase2634() {
+
+ String sql = "SELECT x, IntKey FROM (SELECT IntKey, 'a' AS x FROM BQT1.SmallA UNION ALL SELECT IntKey, 'b' AS x FROM BQT1.SmallB) as Z"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ Set actualQueries = TestOptimizer.getAtomicQueries(plan);
+ String expectedSql = "SELECT 'a' AS c_0, BQT1.SmallA.IntKey AS c_1 FROM BQT1.SmallA UNION ALL SELECT 'b' AS c_0, BQT1.SmallB.IntKey AS c_1 FROM BQT1.SmallB"; //$NON-NLS-1$
+ assertEquals(1, actualQueries.size());
+ assertEquals(expectedSql, actualQueries.iterator().next().toString());
+
+ List[] input1 = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(1)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(0)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(1)}), //$NON-NLS-1$
+ };
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData(expectedSql, input1);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(0)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(1)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(0)}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", new Integer(1)}), //$NON-NLS-1$
+ };
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ @Test public void testQueryWithoutFromWithOrderBy() {
+
+ String sql = "select 'three' as x ORDER BY x"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "three"} ), //$NON-NLS-1$
+ };
+ // 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 testQueryWithoutFromWithOrderBy2() {
+
+ String sql = "select concat('three', ' sixteen') as x ORDER BY x"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "three sixteen"} ), //$NON-NLS-1$
+ };
+ // 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 testQueryWithoutFromWithOrderBy3() {
+
+ String sql = "SELECT CONCAT('yy', 'z') as c1234567890123456789012345678901234567890, " + //$NON-NLS-1$
+ "CONCAT('21', '12') AS EXPR ORDER BY c1234567890123456789012345678901234567890"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "yyz", "2112"} ), //$NON-NLS-1$ //$NON-NLS-2$
+ };
+ // 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 testCase2507_3(){
+
+ String sql = "SELECT CONCAT('yy', 'z') AS c1234567890123456789012345678901234567890, " + //$NON-NLS-1$
+ "CONCAT('21', '12') AS EXPR ORDER BY c1234567890123456789012345678901234567890"; //$NON-NLS-1$
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+ caps.setFunctionSupport("concat", true); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[0] ,
+ TestOptimizer.SHOULD_SUCCEED );
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 0, // 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
+ 0 // UnionAll
+ });
+
+ // TEST PROCESSING
+
+ List[] expectedResults = new List[] {
+ Arrays.asList(new Object[] { "yyz", "2112"}), //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT1(dataManager);
+
+ // Run query
+ helpProcess(plan, dataManager, expectedResults);
+
+ }
+
+ @Test public void testMultiGroupJoinCriteria() {
+
+ String sql = "SELECT X.NEWFIELD FROM " + //$NON-NLS-1$
+ "(SELECT SMALLA.STRINGNUM, " + //$NON-NLS-1$
+ "CASE WHEN SMALLA.STRINGNUM LIKE '1%' THEN SMALLA.INTKEY " + //$NON-NLS-1$
+ "WHEN SMALLA.STRINGNUM LIKE '2%' THEN SMALLB.INTNUM " + //$NON-NLS-1$
+ "WHEN SMALLA.STRINGNUM LIKE '3%' THEN MEDIUMA.INTKEY " + //$NON-NLS-1$
+ "END AS NEWFIELD " + //$NON-NLS-1$
+ "FROM BQT1.SMALLA, BQT1.SMALLB, BQT1.MEDIUMA " + //$NON-NLS-1$
+ "WHERE SMALLA.INTKEY = SMALLB.INTKEY AND SMALLA.INTKEY = MEDIUMA.INTKEY) AS X " + //$NON-NLS-1$
+ "WHERE X.NEWFIELD = -3"; //$NON-NLS-1$
+
+ String expectedAtomic1 = "SELECT BQT1.SMALLB.INTKEY, BQT1.SMALLB.INTNUM FROM BQT1.SMALLB"; //$NON-NLS-1$
+ String expectedAtomic2 = "SELECT BQT1.MEDIUMA.INTKEY FROM BQT1.MEDIUMA"; //$NON-NLS-1$
+ String expectedAtomic3 = "SELECT BQT1.SMALLA.INTKEY, BQT1.SMALLA.STRINGNUM FROM BQT1.SMALLA"; //$NON-NLS-1$
+
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql,
+ metadata,
+ null, capFinder,
+ new String[] {expectedAtomic1, expectedAtomic2, expectedAtomic3} ,
+ TestOptimizer.SHOULD_SUCCEED );
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 3, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 2, // MergeJoin
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ // TEST PROCESSING
+
+ List[] expectedResults = new List[] {
+ Arrays.asList(new Object[] { new Integer(-3) }),
+ };
+
+ // Construct data manager with data
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ List[] input1 = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(-4)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(-3)}),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(-2)}),
+ };
+ dataManager.addData(expectedAtomic1, input1);
+ List[] input2 = new List[] {
+ Arrays.asList(new Object[] { new Integer(1)}),
+ Arrays.asList(new Object[] { new Integer(2)}),
+ Arrays.asList(new Object[] { new Integer(3)}),
+ };
+ dataManager.addData(expectedAtomic2, input2);
+ List[] input3 = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new String("1")}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(2), new String("2")}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(3), new String("3")}), //$NON-NLS-1$
+ };
+ dataManager.addData(expectedAtomic3, input3);
+
+ // Run query
+ helpProcess(plan, dataManager, expectedResults);
+
+ }
+
+ /**
+ * Cross-source join with group by on top but no aggregate functions - running some special cases
+ * where there are no "aggregate groups" (the groups of the aggregate expressions) because there
+ * are no aggregate expressions. In this case, need to switch the aggregate groups to be all the grouping
+ * columns because they are all being "grouped on".
+ *
+ * @since 4.3
+ */
+ @Test public void testDefect18360(){
+
+ String sql = "SELECT a.intkey, a.intnum FROM bqt1.smalla a join bqt2.mediumb b on a.stringkey = b.stringkey " + //$NON-NLS-1$
+ "group by a.intkey, a.intnum"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ capFinder.addCapabilities("BQT1", new BasicSourceCapabilities()); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", new BasicSourceCapabilities()); //$NON-NLS-1$
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.exampleBQTCached(), capFinder);
+
+ // Construct data manager with data
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ List[] data1 = new List[] {
+ Arrays.asList(new Object[] { "1", new Integer(1), new Integer(5) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2", new Integer(2), new Integer(6) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "3", new Integer(3), new Integer(7) }), //$NON-NLS-1$
+ };
+ dataManager.addData("SELECT bqt1.smalla.stringkey, bqt1.smalla.intkey, bqt1.smalla.intnum FROM bqt1.smalla", data1); //$NON-NLS-1$
+
+ List[] data2 = new List[] {
+ Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "3" }), //$NON-NLS-1$
+ };
+ dataManager.addData("SELECT bqt2.mediumb.stringkey FROM bqt2.mediumb", data2); //$NON-NLS-1$
+
+ // Run query
+ List[] expectedResults = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(5) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(7) }),
+ };
+ helpProcess(plan, dataManager, expectedResults);
+
+ }
+
+ @Test public void testDefect17407(){
+ String sql = "select pm1.g1.e1 from pm1.g1, g7 MAKEDEP WHERE pm1.g1.e2=g7.e2 order by e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null}),
+ Arrays.asList(new Object[] { null}),
+ 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$
+ Arrays.asList(new Object[] { "c"}),//$NON-NLS-1$
+ };
+ // 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 testDecodeAsCriteria() {
+ // Create query
+ String sql = "SELECT x.foo, e2 FROM (select decodestring(e1, 'a,q,b,w') as foo, e2 from vm1.g1) as x where x.foo = 'w'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "w", new Integer(2) }), //$NON-NLS-1$
+ };
+
+ // 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 testInputParamInNestedExecParam() {
+ // Create query
+ String sql = "EXEC pm1.vsp48('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, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testVariableInExecParam() {
+ // Create query
+ String sql = "EXEC pm1.vsp49()"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "b", new Integer(2) }), //$NON-NLS-1$
+ };
+
+ // 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 testVariableInNestedExecParam() {
+ // Create query
+ String sql = "EXEC pm1.vsp50()"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ };
+
+ // 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 testVariableInNestedExecParamInLoop() {
+ // Create query
+ String sql = "EXEC pm1.vsp51()"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "bb" }), //$NON-NLS-1$
+ };
+
+ // 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 testVariableInNestedExecParamInAssignment() {
+ // Create query
+ String sql = "EXEC pm1.vsp52()"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ };
+
+ // 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 testInputParamInNestedExecParamInLoop() {
+ // Create query
+ String sql = "EXEC pm1.vsp53('b')"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "bb" }), //$NON-NLS-1$
+ };
+
+ // 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 testInputParamInNestedExecParamInAssignment() {
+ // Create query
+ String sql = "EXEC pm1.vsp54('c')"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ };
+
+ // 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 testBitwiseAggregateProc() throws Exception {
+ // Create query
+ String sql = "EXEC virt.agg()"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0), "a", new Integer(19) }), //$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(3) }), //$NON-NLS-1$
+ };
+
+ // Plan query
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBitwise();
+ ProcessorPlan plan = helpGetPlan(sql, metadata);
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBitwise(dataManager, metadata);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ 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() {
+ // Create query
+ String sql = "SELECT lower(vm1.g1.e1) from vm1.g1, vm1.g2a where vm1.g1.e1 = vm1.g2a.e1 group by lower(vm1.g1.e1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ 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();
+ sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ 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$
+
+ 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$
+ 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$
+ 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$
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "projectError");
+ }
+
+ @Test public void testProjectionErrorOverUnionWithConvert() {
+ // Create query
+ QueryMetadataInterface metadata = createProjectErrorMetadata();
+ String sql = "SELECT COUNT(*) FROM v1.u1"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ capFinder.addCapabilities("p1", caps); //$NON-NLS-1$
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(2) }),
+ };
+
+ // Construct data manager with data
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("SELECT 1 AS c_0 FROM p1.t AS g_1 UNION ALL SELECT 1 AS c_0 FROM p1.t AS g_0", //$NON-NLS-1$
+ new List[] { Arrays.asList(1), Arrays.asList(1)});
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testUpdatesInLoop() {
+ String sql = "update vm1.g39 set e2=3"; //$NON-NLS-1$
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+
+ // Construct data manager with data
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("SELECT g_0.e2 FROM pm1.g1 AS g_0 WHERE g_0.e2 = 3", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(3) } )});
+ dataManager.addData("UPDATE pm1.g1 SET e2 = 3 WHERE pm1.g1.e2 = 3", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(1) } )});
+
+ // Create expected results
+ List[] expected = new List[] { Arrays.asList(0)};
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ @Test public void testRand() {
+ // Create query
+ String sql = "SELECT RAND(E2) FROM pm1.g1 where pm1.g1.e2=3"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] {new Double(0.731057369148862)}),
+ };
+
+ // 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);
+ }
+
+ /*
+ * Prior to case 3994 testInsertTempTableCreation1 worked, but testInsertTempTableCreation did not.
+ * Now they should both pass
+ *
+ */
+ @Test public void testInsertTempTableCreation() {
+ 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$
+ 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");
+
+ ProcessorPlan plan = helpGetPlan("exec v1.vp()", metadata); //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1) })
+ };
+ helpProcess(plan, new FakeDataManager(), expected);
+ }
+
+ @Test public void testInsertTempTableCreation1() {
+ 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$
+ 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");
+
+ ProcessorPlan plan = helpGetPlan("exec v1.vp()", metadata); //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2) })
+ };
+ helpProcess(plan, new FakeDataManager(), expected);
+ }
+
+ @Test public void testCase4531() {
+ String sql = "select intkey, intnum from (select intnum as intkey, 1 as intnum from bqt1.smalla union all select intkey, intnum from bqt1.smalla union all select intkey, intnum from bqt2.smalla) x"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_UNION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.exampleBQTCached(), capFinder);
+
+ // Run query
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ };
+
+ // Construct data manager with data
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.addData("SELECT g_0.intkey, g_0.intnum FROM bqt2.smalla AS g_0", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(1), new Integer(1) })});
+ dataManager.addData("SELECT g_1.intnum AS c_0, 1 AS c_1 FROM bqt1.smalla AS g_1 UNION ALL SELECT g_0.IntKey AS c_0, g_0.IntNum AS c_1 FROM bqt1.smalla AS g_0", //$NON-NLS-1$
+ new List[] { Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) })});
+ helpProcess(plan, dataManager, expected);
+ }
+
+ private void sampleDataBQT2a(FakeDataManager dataMgr) throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ String[] groups = new String[] {"bqt1.smalla", "bqt2.smalla", "bqt3.smalla" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ for(int groupIndex=0; groupIndex<groups.length; groupIndex++) {
+ String groupName = groups[groupIndex];
+
+ List[] tuples = new List[3];
+ for(int row=0; row<tuples.length; row++) {
+ tuples[row] = new ArrayList(17);
+ tuples[row].add(new Integer(row)); //IntKey
+ tuples[row].add(String.valueOf(row)); //StringKey
+ tuples[row].add(new Integer(row)); //IntNum
+ tuples[row].add(String.valueOf(row)); //StringNum
+ for(int col=0; col<10; col++) { //FloatNum, LongNum, DoubleNum, ByteNum, DateValue, TimeValue, TimestampValue, BooleanValue, CharValue, ShortValue
+ tuples[row].add(null);
+ }
+ tuples[row].add(new BigInteger(String.valueOf(row))); //BigIntegerValue
+ tuples[row].add(new BigDecimal(row)); //BigDecimalValue
+ tuples[row].add(null); //ObjectValue
+ }
+ dataMgr.registerTuples(metadata, groupName, tuples);
+ }
+ }
+
+ @Test public void testDefect15355() throws Exception {
+
+ String sql = "SELECT e1, e1 FROM pm1.g1 " //$NON-NLS-1$
+ +"UNION ALL " //$NON-NLS-1$
+ +"SELECT e1, (SELECT e1 FROM pm2.g1 WHERE pm2.g1.e2 = pm1.g2.e2) FROM pm1.g2"; //$NON-NLS-1$
+
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", "a" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "c", "c" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "a", "e" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b", null }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "d", null }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testDefect15355b() throws Exception {
+
+ String sql = "SELECT StringKey, BigIntegerValue FROM BQT1.SmallA " //$NON-NLS-1$
+ +"UNION ALL " //$NON-NLS-1$
+ +"SELECT StringKey, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"; //$NON-NLS-1$
+
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "0", new BigInteger("0") }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "1", new BigInteger("1") }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "2", new BigInteger("2") }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "0", new BigInteger("0") }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "1", new BigInteger("1") }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "2", new BigInteger("2") }), //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT2a(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ @Test public void testDefect15355c() throws Exception {
+
+ String sql = "SELECT StringKey, BigIntegerValue FROM VQT.Defect15355 WHERE StringKey = '0'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "0", new BigInteger("0") }), //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT2a(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ @Test public void testDefect15355d() throws Exception {
+
+ String sql = "SELECT StringKey, BigIntegerValue FROM VQT.Defect15355a WHERE StringKey = '0'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "0", new BigInteger("0") }), //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT2a(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ @Test public void testDefect15355e() throws Exception {
+
+ String sql = "SELECT BigIntegerValue, StringKey FROM VQT.Defect15355 WHERE StringKey = '0'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new BigInteger("0"), "0" }), //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT2a(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ @Test public void testDefect15355f() throws Exception {
+
+ String sql = "SELECT BigIntegerValue FROM VQT.Defect15355 WHERE StringKey = '0'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new BigInteger("0") }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT2a(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ @Test public void testDefect15355f2() throws Exception {
+
+ String sql = "SELECT BigIntegerValue FROM VQT.Defect15355 WHERE StringKey LIKE '%0' AND StringKey LIKE '0%'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new BigInteger("0") }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT2a(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ @Test public void testDefect15355g() throws Exception {
+
+ String sql = "SELECT BigIntegerValue AS a, BigIntegerValue AS b FROM VQT.Defect15355 WHERE StringKey = '0'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new BigInteger("0"), new BigInteger("0") }), //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT2a(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ @Test public void testDefect15355h() throws Exception {
+
+ String sql = "SELECT BigIntegerValue FROM VQT.Defect15355 WHERE BigIntegerValue = '0'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new BigInteger("0") }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT2a(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ @Test public void testDefect15355i() throws Exception {
+
+ String sql = "SELECT BigIntegerValue FROM VQT.Defect15355b WHERE BigIntegerValue = '0'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new BigInteger("0") }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT2a(dataManager);
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
+ capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ /**
+ * The inner most A.e1 was mistakenly getting transformed into pm1.g3.e1
+ */
+ @Test public void testInnerCorrelatedReference() throws Exception {
+
+ String sql = "SELECT DISTINCT A.e1 FROM pm1.g3 AS A WHERE (A.e1 IN (SELECT A.e1 FROM pm1.g3))"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ };
+
+ // Construct data manager with data
+ 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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ // Plan query
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ Command command = helpParse(sql);
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+
+ }
+
+ @Test public void testCase5413() throws Exception {
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ // Plan query
+ String sql = "SELECT e1 FROM pm1.g2 WHERE LOOKUP('pm1.g1','e1', 'e2', 0) = e1";//$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ Command command = TestProcessor.helpParse(sql);
+ CommandContext context = createCommandContext();
+ ProcessorPlan plan = helpGetPlan(command, metadata, capFinder, context);
+
+ // Run query
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ FakeDataStore.sampleData2(dataManager);
+
+ helpProcess(plan, context, dataManager, expected);
+ }
+
+ @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), RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 0, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 1, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0)}),
+ };
+
+ helpProcess(plan, new FakeDataManager(), expected);
+
+ }
+
+ /*
+ * Test for Case6219
+ */
+ @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), RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 0, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 3, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+
+ List[] expected = new List[] {
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+
+ }
+
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null}),
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { Boolean.FALSE}),
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ //note that the e1 column is not used in the source query
+ assertEquals("SELECT pm1.g1.e3, pm1.g1.e2 FROM pm1.g1", manager.getQueries().iterator().next()); //$NON-NLS-1$
+ }
+
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0) }),
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ /**
+ * A more direct test of 1, where the nested order by is unrelated
+ */
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { Boolean.FALSE }),
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY_UNRELATED, false);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, new DefaultCapabilitiesFinder(caps));
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { Boolean.FALSE }),
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ 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 testCountWithHaving() {
+ String sql = "select e1, count(*) from pm1.g1 group by e1 having count(*) > 1"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" , new Integer(3)}), //$NON-NLS-1$
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ @Test public void testLimitZero() {
+ String sql = "select e1 from pm1.g1 limit 0"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ TestOptimizer.checkNodeTypes(plan, TestRuleRaiseNull.FULLY_NULL);
+
+ List[] expected = new List[] {
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 0, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", null }), //$NON-NLS-1$
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ @Test public void testLimitZero2() {
+ String sql = "select vm1.g1.e1 from vm1.g1 union select e1 from pm1.g2 limit 0"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ List[] expected = new List[] {
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ @Test public void testLimitZero3() {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ String sql = "select e1 from pm1.g2 limit 0"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, capFinder);
+
+ List[] expected = new List[] {
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "2", "b" }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { "b", "2" }), //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ /**
+ * Tests non-deterministic evaluation in the select clause.
+ *
+ * The evaluation of the rand function is delayed until processing time (which actually has predictable
+ * values since the test initializes the command context with the same seed)
+ *
+ * If this function were deterministic, it would be evaluated during rewrite to a single value.
+ */
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(240) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(637) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(550) }), //$NON-NLS-1$
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ /**
+ * here the rand function is deterministic and should yield a single value
+ */
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a", new Integer(730) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(730) }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "a", new Integer(730) }), //$NON-NLS-1$
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ @Test public void testEmptyAggregate() throws Exception {
+ String sql = "select count(e1) from pm1.g1 where 1 = 0"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0) })
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(0), null })
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ /**
+ * here the presence of a group by causes no rows to be returned
+ */
+ @Test public void testNullAggregate1() throws Exception {
+ String sql = "select e1 from pm1.g1 where 1 = 0 group by e1"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ List[] expected = new List[] {
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ @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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ List[] expected = new List[] {};
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ /**
+ * Here a merge join will be used since there is at least one equi join predicate.
+ * TODO: this can be optimized further
+ */
+ @Test public void testCase6193_1() throws Exception {
+ // Create query
+ String sql = "select a.INTKEY, b.intkey from bqt1.smalla a LEFT OUTER JOIN bqt2.SMALLA b on a.intkey=b.intkey and a.intkey=5 where a.intkey <10 "; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ capFinder.addCapabilities("BQT2", caps);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0), null }),
+ Arrays.asList(new Object[] { new Integer(1), null }),
+ Arrays.asList(new Object[] { new Integer(2), null }),
+ Arrays.asList(new Object[] { new Integer(3), null }),
+ Arrays.asList(new Object[] { new Integer(4), null }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(5) }),
+ Arrays.asList(new Object[] { new Integer(6), null }),
+ Arrays.asList(new Object[] { new Integer(7), null }),
+ Arrays.asList(new Object[] { new Integer(8), null }),
+ Arrays.asList(new Object[] { new Integer(9), null })
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataBQT2(dataManager);
+
+ // Plan query
+ 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 1, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Here a merge join will be used since there is at least one equi join predicate.
+ */
+ @Test public void testCase6193_2() throws Exception {
+ // Create query
+ String sql = "select a.e2, b.e2 from pm1.g1 a LEFT OUTER JOIN pm1.g2 b on a.e4=b.e4 and (a.e2+b.e2)=4 order by a.e2"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0), null }),
+ Arrays.asList(new Object[] { new Integer(0), null }),
+ Arrays.asList(new Object[] { new Integer(1), null }),
+ Arrays.asList(new Object[] { new Integer(1), null }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(3), null }),
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ // Plan query
+ 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 1, // Sort
+ 0 // UnionAll
+ });
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * Here a merge join will be used since there is at least one equi join predicate.
+ * The inner merge join is also a dependent join
+ */
+ @Test public void testCase6193_3() throws Exception {
+ // Create query
+ String sql = "select a.x, b.y from (select 4 x union select 1) a LEFT OUTER JOIN (select (a.e2 + b.e2) y from pm1.g1 a LEFT OUTER JOIN pm1.g2 b on a.e4=b.e4) b on (a.x = b.y)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), null }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ // Plan query
+ 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[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 4, // Project
+ 0, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+
+ TestOptimizer.checkDependentJoinCount(plan, 1);
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ /**
+ * This is a control test. It should work regardless of whether the reference is aliased
+ * since accessnodes are now fully positional
+ */
+ @Test public void testPushdownNonAliasedSelectLiteral() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ List[] expected = new List[] {
+ Arrays.asList("a", "b"), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList("a", "c") //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ HardcodedDataManager manager = new HardcodedDataManager();
+ 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"));
+ }
+
+ @Test public void testCase6486() {
+ // Create query
+ String sql = "select pm2.g1.e1 from pm1.g2, pm2.g1 where pm1.g2.e1=pm2.g1.e1 group by pm2.g1.e1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "b"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "d"}) //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ // Run query
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testNonPushedOffset() throws Exception {
+ String sql = "SELECT e1 FROM pm1.g1 LIMIT 1, 5"; //$NON-NLS-1$
+
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "b"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c"}), //$NON-NLS-1$
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData2(dataManager);
+
+ 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);
+ }
+
+ @Test public void testNonCorrelatedSubQueryExecution() throws Exception {
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1)"; //$NON-NLS-1$
+
+ // Construct data manager with data
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+ dataManager.setBlockOnce(true);
+ dataManager.addData("SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1", new List[] { //$NON-NLS-1$
+ Arrays.asList(Integer.valueOf(1), "a"), //$NON-NLS-1$
+ Arrays.asList(Integer.valueOf(2), "b") //$NON-NLS-1$
+ });
+ dataManager.addData("SELECT pm2.g1.e2 FROM pm2.g1", new List[] { //$NON-NLS-1$
+ Arrays.asList(Integer.valueOf(2))
+ });
+
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+ };
+
+ doProcess(plan, dataManager, expected, createCommandContext());
+
+ //we expect 2 queries, 1 for the outer and 1 for the subquery
+ assertEquals(2, dataManager.getCommandHistory().size());
+ }
+
+ /**
+ * Test a query that uses ambiguous alias names in the top level query and
+ * its sub-query and uses columns belonging to the alias as a parameter to a
+ * function.
+ * <p>
+ * For example, <code>SELECT CONVERT(A.e2, biginteger) AS e2 FROM (SELECT
+ * CONVERT(e2, long) AS e2 FROM pm1.g1 AS A) AS A</code>
+ * <p>
+ * The test is to ensure that A.e2 from the top level is not confused with
+ * e2 in the second level.
+ * <p>
+ * Related Defects: JBEDSP-1137
+ */
+ @Test public void testAliasReuseInFunctionInSubQuery() throws Exception {
+ // Create query
+ String sql = "SELECT CONVERT(A.e2, biginteger) AS e2 FROM (" + //$NON-NLS-1$
+ " SELECT CONVERT(e2, long) AS e2 FROM pm1.g1 AS A WHERE e1 = 'a'" + //$NON-NLS-1$
+ ") AS A"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new BigInteger("0") }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new BigInteger("3") }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new BigInteger("0") }), //$NON-NLS-1$
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ sampleData1(manager);
+ helpProcess(plan, manager, expected);
+ }
+
+ @Test public void testImplicitAggregateWithInlineView() {
+ String sql = "SELECT * FROM (SELECT b.count, enterprise_id FROM (SELECT COUNT(*), 2 AS enterprise_id FROM (SELECT 'A Name' AS Name, 1 AS enterprise_id) c ) b ) a WHERE enterprise_id = 1"; //$NON-NLS-1$
+
+ List[] expected = new List[] {};
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedNestedTable() {
+ String sql = "select y.e2, x.e1, x.e2 from (select * from pm1.g1) y, table (select * from pm1.g3 where e2 = y.e2) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(0, "a", 0),
+ Arrays.asList(0, "a", 0),
+ Arrays.asList(1, null, 1),
+ Arrays.asList(1, "c", 1),
+ Arrays.asList(3, "a", 3),
+ Arrays.asList(1, null, 1),
+ Arrays.asList(1, "c", 1),
+ Arrays.asList(2, "b", 2),
+ Arrays.asList(0, "a", 0),
+ Arrays.asList(0, "a", 0),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedNestedTable1() {
+ String sql = "select y.e2, z.e2, x.e1, x.e2 from (select * from pm1.g1 order by e2 desc limit 2) y inner join pm1.g2 z on y.e1 = z.e1, table (select * from pm1.g3 where e2 = y.e2 + z.e2) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(3, 0, "a", 3),
+ Arrays.asList(3, 0, "a", 3),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedNestedTable2() {
+ String sql = "select y.e1, x.e1 from (select distinct e1 from pm1.g1 where e1 is not null) y, table (call pm1.sq3b(\"in\" = e1, in3 = 'something')) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("a", "a"),
+ Arrays.asList("a", "a"),
+ Arrays.asList("a", "a"),
+ Arrays.asList("b", "b"),
+ Arrays.asList("c", "c"),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedNestedTable3() {
+ String sql = "select y.e1, x.e1 from (select * from pm1.g1) y left outer join table (call pm1.sq3b(\"in\" = e2, in3 = 'something')) x on (1=1)"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("a", null),
+ Arrays.asList(null, null),
+ Arrays.asList("a", null),
+ Arrays.asList("c", null),
+ Arrays.asList("b", null),
+ Arrays.asList("a", null),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedNestedTable4() {
+ String sql = "select y.e1, y.e2, z.e2 from (select * from pm1.g1) y inner join table (select * from pm1.g3 where e2 = y.e2) x left outer join (select null as e1, e2 from pm1.g2) z on (x.e1 = z.e1) on (x.e1 = y.e1)"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("a", 0, null),
+ Arrays.asList("a", 0, null),
+ Arrays.asList("a", 3, null),
+ Arrays.asList("c", 1, null),
+ Arrays.asList("b", 2, null),
+ Arrays.asList("a", 0, null),
+ Arrays.asList("a", 0, null),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testCorrelatedNestedTable5() {
+ String sql = "select y.e1, y.e2, z.e2 from (exec pm1.sq1()) y, table (exec pm1.sq2(y.e1)) x, table (exec pm1.sq2(x.e1)) z where y.e2 = 2"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("b", 2, 2),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testUncorrelatedScalarSubqueryPushdown() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan("select pm1.g1.e1 from pm1.g1 where e1 < (select max(vm1.g1.e1) from vm1.g1)", metadata, //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 < (SELECT MAX(g_0.e1) FROM pm1.g1 AS g_0)" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+
+ HardcodedDataManager hdm = new HardcodedDataManager();
+ hdm.addData("SELECT MAX(g_0.e1) FROM pm1.g1 AS g_0", new List[] {Arrays.asList("c")});
+ hdm.addData("SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 < 'c'", new List[] {Arrays.asList("a")});
+ hdm.setBlockOnce(true);
+ List[] expected = new List[] {
+ Arrays.asList("a"),
+ };
+
+ helpProcess(plan, hdm, expected);
+ }
+
+ @Test public void testNonDeterministicScalarSubquery() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan("select count(distinct x) from (select (select uuid()) as x from pm1.g1) as v", metadata, //$NON-NLS-1
+ null, capFinder,
+ new String[] { "SELECT 1 FROM pm1.g1 AS g_0" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+
+ HardcodedDataManager hdm = new HardcodedDataManager();
+ hdm.addData("SELECT 1 FROM pm1.g1 AS g_0", new List[] {Arrays.asList(1), Arrays.asList(1)});
+ hdm.setBlockOnce(true);
+ List[] expected = new List[] {
+ Arrays.asList(2),
+ };
+
+ helpProcess(plan, hdm, expected);
+ }
+
+ @Test public void testUncorrelatedScalarSubqueryPushdown1() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan("select pm1.g1.e1 from pm1.g1 where e1 < (select e1 from (EXEC pm1.sq1()) x order by e2 limit 1)", metadata, //$NON-NLS-1$
+ null, capFinder,
+ new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 < (SELECT e1 FROM (EXEC pm1.sq1()) AS x ORDER BY e2 LIMIT 1)" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+ checkNodeTypes(plan, FULL_PUSHDOWN);
+
+ HardcodedDataManager hdm = new HardcodedDataManager();
+ hdm.addData("SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 < 'z'", new List[] {Arrays.asList("c")});
+ hdm.addData("SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0", new List[] {Arrays.asList("z", 1), Arrays.asList("b", 2)});
+ hdm.setBlockOnce(true);
+ List[] expected = new List[] {
+ Arrays.asList("c"),
+ };
+
+ helpProcess(plan, hdm, expected);
+ }
+
+ @Test public void testStoredProcedureSubqueryInput() {
+ String sql = "exec pm1.sp2((select e2 from pm1.g1 order by e1 limit 1))"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("b", 2),
+ };
+
+ 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), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testInlineViewWith() {
+ String sql = "select * from (with x as (select e1 from pm1.g1) select x.e1 from x order by e1 nulls last limit 1) y"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("a"),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testDeleteCompensation() {
+ String sql = "delete from pm1.g1 where e1 = 'a' and e2 in (select e2 from pm1.g2)"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(3),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example4(), TestOptimizer.getGenericFinder());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testUpdateCompensation() {
+ String sql = "update pm1.g1 set e4 = null where e1 = 'a' and exists (select 1 from pm1.g2 where e2 = pm1.g1.e2)"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(3),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ 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)});
+ }
+
+ private static final boolean DEBUG = false;
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,405 +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;
-
-import static org.teiid.query.processor.TestProcessor.*;
-
-import java.io.FileInputStream;
-import java.io.InputStreamReader;
-import java.nio.charset.Charset;
-import java.sql.Timestamp;
-import java.util.Arrays;
-import java.util.List;
-import java.util.TimeZone;
-
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.core.types.BlobImpl;
-import org.teiid.core.types.BlobType;
-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.query.optimizer.capabilities.DefaultCapabilitiesFinder;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.TimestampUtil;
-
- at SuppressWarnings({"nls", "unchecked"})
-public class TestSQLXMLProcessing {
-
- @Test public void testXmlElementTextContent() throws Exception {
- String sql = "SELECT xmlelement(foo, '<bar>', convert('<bar1/>', xml))"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<foo><bar><bar1/></foo>"),
- };
-
- process(sql, expected);
- }
-
- /**
- * Repeat of the above test, but with a document declaration. Because of the way we do event filtering, we end
- * up with a slightly different, but equivalent answer.
- */
- @Test public void testXmlElementTextContent1() throws Exception {
- String sql = "SELECT xmlelement(foo, '<bar>', convert('<?xml version=\"1.0\" encoding=\"UTF-8\"?><bar1/>', xml))"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<foo><bar><bar1></bar1></foo>"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlElement() throws Exception {
- String sql = "SELECT xmlelement(e1, e2) from pm1.g1 order by e1, e2"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<e1>1</e1>"),
- Arrays.asList("<e1>0</e1>"),
- Arrays.asList("<e1>0</e1>"),
- Arrays.asList("<e1>3</e1>"),
- Arrays.asList("<e1>2</e1>"),
- Arrays.asList("<e1>1</e1>"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlElementWithConcat() throws Exception {
- String sql = "SELECT xmlelement(e1, e2, xmlconcat(xmlelement(x), xmlelement(y, e3))) from pm1.g1 order by e1, e2"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<e1>1<x></x><y>false</y></e1>"),
- Arrays.asList("<e1>0<x></x><y>false</y></e1>"),
- Arrays.asList("<e1>0<x></x><y>false</y></e1>"),
- Arrays.asList("<e1>3<x></x><y>true</y></e1>"),
- Arrays.asList("<e1>2<x></x><y>false</y></e1>"),
- Arrays.asList("<e1>1<x></x><y>true</y></e1>"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlElementWithForest() throws Exception {
- String sql = "SELECT xmlelement(x, xmlforest(e1, e2, '1' as val)) from pm1.g1 order by e1, e2 limit 2"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<x><e2>1</e2><val>1</val></x>"), //note e1 is not present, because it's null
- Arrays.asList("<x><e1>a</e1><e2>0</e2><val>1</val></x>"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlElementWithAttributes() throws Exception {
- String sql = "SELECT xmlelement(x, xmlattributes(e1, e2, '1' as val)) from pm1.g1 order by e1, e2 limit 2"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<x e2=\"1\" val=\"1\"></x>"), //note e1 is not present, because it's null
- Arrays.asList("<x e1=\"a\" e2=\"0\" val=\"1\"></x>"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlElementWithPi() throws Exception {
- String sql = "SELECT xmlelement(x, xmlpi(name e1, ' 1'))"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<x><?e1 1?></x>"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlElementWithNamespaces() throws Exception {
- String sql = "SELECT xmlelement(x, xmlnamespaces(no default, 'http://foo' as x, 'http://foo1' as y), xmlattributes(e1), e2) from pm1.g1 order by e1, e2 limit 2"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<x xmlns=\"\" xmlns:x=\"http://foo\" xmlns:y=\"http://foo1\">1</x>"), //note e1 is not present, because it's null
- Arrays.asList("<x xmlns=\"\" xmlns:x=\"http://foo\" xmlns:y=\"http://foo1\" e1=\"a\">0</x>"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlAgg() throws Exception {
- String sql = "SELECT xmlelement(parent, xmlAgg(xmlelement(x, xmlattributes(e1, e2)))) from pm1.g1"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<parent><x e1=\"a\" e2=\"0\"></x><x e2=\"1\"></x><x e1=\"a\" e2=\"3\"></x><x e1=\"c\" e2=\"1\"></x><x e1=\"b\" e2=\"2\"></x><x e1=\"a\" e2=\"0\"></x></parent>"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlAggOrderBy() throws Exception {
- String sql = "SELECT xmlelement(parent, xmlAgg(xmlelement(x, xmlattributes(e1, e2)) order by e2)) from pm1.g1"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<parent><x e1=\"a\" e2=\"0\"></x><x e1=\"a\" e2=\"0\"></x><x e2=\"1\"></x><x e1=\"c\" e2=\"1\"></x><x e1=\"b\" e2=\"2\"></x><x e1=\"a\" e2=\"3\"></x></parent>"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlSerialize() throws Exception {
- String sql = "SELECT xmlserialize(document xmlelement(parent) as string)"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<parent></parent>"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlTable() throws Exception {
- String sql = "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$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList(null, "first"),
- Arrays.asList("attr", "second"),
- };
-
- process(sql, 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$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList(-1, "rev"),
- Arrays.asList(1, "rev"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlTableReturnXml() throws Exception {
- 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>"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlTableNoColumns() throws Exception {
- String sql = "select * from xmltable('/a' passing convert('<a><b>first</b><b x=\"1\">second</b></a>', xml)) as x"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<a><b>first</b><b x=\"1\">second</b></a>"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlTablePassing() throws Exception {
- String sql = "select * from xmltable('<root>{for $x in $a/a/b return <c>{$x}</c>}</root>' passing convert('<a><b>first</b><b x=\"1\">second</b></a>', xml) as a columns x xml path 'c[1]/b') as x"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<b>first</b>"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlTableForOrdinalityAndDefaultPath() throws Exception {
- String sql = "select * from xmltable('/a/b' passing convert('<a><b><c>1</c></b><b>1</b><b><c>1</c></b><b>1</b></a>', xml) columns x for ordinality, c integer) as x"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList(1, 1),
- Arrays.asList(2, null),
- Arrays.asList(3, 1),
- Arrays.asList(4, null),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlTableDescendantPath() throws Exception {
- String sql = "select * from xmltable('<a>{for $i in (1 to 5) return $i}</a>' columns x string path '//text()') as x"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("1 2 3 4 5"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlQuery() throws Exception {
- String sql = "select xmlquery('for $i in (1 to 5) return $i')"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("1 2 3 4 5"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlQueryEmptyNull() throws Exception {
- String sql = "select xmlquery('/a' passing xmlparse(document '<x/>') null on empty)"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList((String)null)
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlNameEscaping() throws Exception {
- String sql = "select xmlforest(\"xml\") from (select 1 as \"xml\") x"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<_u0078_ml>1</_u0078_ml>")
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlParseDoc() throws Exception {
- String sql = "select xmlparse(document '<a/>')"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("<a/>")
- };
-
- process(sql, expected);
- }
-
- @Test(expected=ExpressionEvaluationException.class) public void testXmlParseDocException() throws Exception {
- String sql = "select xmlparse(document 'a<a/>')"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlParseContent() throws Exception {
- String sql = "select xmlparse(content 'a<a/>')"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("a<a/>")
- };
-
- process(sql, expected);
- }
-
- @Test(expected=ExpressionEvaluationException.class) public void testXmlParseContentException() throws Exception {
- String sql = "select xmlparse(content 'a<')"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- };
-
- process(sql, expected);
- }
-
- //by pass the validation
- @Test public void testXmlParseContentWellformed() throws Exception {
- String sql = "select xmlparse(content 'a<' WELLFORMED)"; //$NON-NLS-1$
-
- List<?>[] expected = new List<?>[] {
- Arrays.asList("a<")
- };
-
- process(sql, expected);
- }
-
- @Test public void testXmlParseClob() throws Exception {
- String sql = "select xmlparse(document cast(? as clob)) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(ObjectConverterUtil.convertToString(new FileInputStream(UnitTestUtil.getTestDataFile("udf.xmi")))),
- };
-
- processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(TestTextTable.clobFromFile("udf.xmi")));
- }
-
- @Test public void testXmlParseBlob() throws Exception {
- String sql = "select xmlparse(document cast(? as blob)) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(ObjectConverterUtil.convertToString(new FileInputStream(UnitTestUtil.getTestDataFile("udf.xmi")))),
- };
-
- processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(blobFromFile("udf.xmi")));
- }
-
- @Test public void testXmlParseBlobWithEncoding() throws Exception {
- String sql = "select xmlparse(document cast(? as blob)) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- 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")));
- }
-
- @Test public void testXmlTableTypes() throws Exception {
- String sql = "select * from xmltable('/a' passing xmlparse(document '<a>2000-01-01T01:01:00.2-06:00</a>') columns x timestamp path 'xs:dateTime(./text())', y timestamp path '.') as x"; //$NON-NLS-1$
- Timestamp ts = TimestampUtil.createTimestamp(100, 0, 1, 1, 1, 0, 200000000);
- List<?>[] expected = new List<?>[] {
- Arrays.asList(ts, 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)";
-
- List[] expected = new List[] {
- Arrays.asList("attr", "c"),
- };
-
- process(sql, expected);
- }
-
- private static FakeDataManager dataManager = new FakeDataManager();
-
- @BeforeClass public static void oneTimeSetUp() {
- TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("GMT-06:00")); //$NON-NLS-1$
- sampleData1(dataManager);
- }
-
- @AfterClass public static void oneTimeTearDown() {
- TimestampWithTimezone.resetCalendar(null); //$NON-NLS-1$
- }
-
- private void process(String sql, List<?>[] expected) throws Exception {
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached(), new DefaultCapabilitiesFinder(), createCommandContext());
-
- helpProcess(plan, createCommandContext(), dataManager, expected);
- }
-
- public static BlobType blobFromFile(final String file) {
- return new BlobType(new BlobImpl(new InputStreamFactory.FileInputStreamFactory(UnitTestUtil.getTestDataFile(file))));
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,405 @@
+/*
+ * 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.processor.TestProcessor.*;
+
+import java.io.FileInputStream;
+import java.io.InputStreamReader;
+import java.nio.charset.Charset;
+import java.sql.Timestamp;
+import java.util.Arrays;
+import java.util.List;
+import java.util.TimeZone;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.core.types.BlobImpl;
+import org.teiid.core.types.BlobType;
+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.query.optimizer.capabilities.DefaultCapabilitiesFinder;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.unittest.TimestampUtil;
+
+ at SuppressWarnings({"nls", "unchecked"})
+public class TestSQLXMLProcessing {
+
+ @Test public void testXmlElementTextContent() throws Exception {
+ String sql = "SELECT xmlelement(foo, '<bar>', convert('<bar1/>', xml))"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<foo><bar><bar1/></foo>"),
+ };
+
+ process(sql, expected);
+ }
+
+ /**
+ * Repeat of the above test, but with a document declaration. Because of the way we do event filtering, we end
+ * up with a slightly different, but equivalent answer.
+ */
+ @Test public void testXmlElementTextContent1() throws Exception {
+ String sql = "SELECT xmlelement(foo, '<bar>', convert('<?xml version=\"1.0\" encoding=\"UTF-8\"?><bar1/>', xml))"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<foo><bar><bar1></bar1></foo>"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlElement() throws Exception {
+ String sql = "SELECT xmlelement(e1, e2) from pm1.g1 order by e1, e2"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<e1>1</e1>"),
+ Arrays.asList("<e1>0</e1>"),
+ Arrays.asList("<e1>0</e1>"),
+ Arrays.asList("<e1>3</e1>"),
+ Arrays.asList("<e1>2</e1>"),
+ Arrays.asList("<e1>1</e1>"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlElementWithConcat() throws Exception {
+ String sql = "SELECT xmlelement(e1, e2, xmlconcat(xmlelement(x), xmlelement(y, e3))) from pm1.g1 order by e1, e2"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<e1>1<x></x><y>false</y></e1>"),
+ Arrays.asList("<e1>0<x></x><y>false</y></e1>"),
+ Arrays.asList("<e1>0<x></x><y>false</y></e1>"),
+ Arrays.asList("<e1>3<x></x><y>true</y></e1>"),
+ Arrays.asList("<e1>2<x></x><y>false</y></e1>"),
+ Arrays.asList("<e1>1<x></x><y>true</y></e1>"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlElementWithForest() throws Exception {
+ String sql = "SELECT xmlelement(x, xmlforest(e1, e2, '1' as val)) from pm1.g1 order by e1, e2 limit 2"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<x><e2>1</e2><val>1</val></x>"), //note e1 is not present, because it's null
+ Arrays.asList("<x><e1>a</e1><e2>0</e2><val>1</val></x>"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlElementWithAttributes() throws Exception {
+ String sql = "SELECT xmlelement(x, xmlattributes(e1, e2, '1' as val)) from pm1.g1 order by e1, e2 limit 2"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<x e2=\"1\" val=\"1\"></x>"), //note e1 is not present, because it's null
+ Arrays.asList("<x e1=\"a\" e2=\"0\" val=\"1\"></x>"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlElementWithPi() throws Exception {
+ String sql = "SELECT xmlelement(x, xmlpi(name e1, ' 1'))"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<x><?e1 1?></x>"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlElementWithNamespaces() throws Exception {
+ String sql = "SELECT xmlelement(x, xmlnamespaces(no default, 'http://foo' as x, 'http://foo1' as y), xmlattributes(e1), e2) from pm1.g1 order by e1, e2 limit 2"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<x xmlns=\"\" xmlns:x=\"http://foo\" xmlns:y=\"http://foo1\">1</x>"), //note e1 is not present, because it's null
+ Arrays.asList("<x xmlns=\"\" xmlns:x=\"http://foo\" xmlns:y=\"http://foo1\" e1=\"a\">0</x>"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlAgg() throws Exception {
+ String sql = "SELECT xmlelement(parent, xmlAgg(xmlelement(x, xmlattributes(e1, e2)))) from pm1.g1"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<parent><x e1=\"a\" e2=\"0\"></x><x e2=\"1\"></x><x e1=\"a\" e2=\"3\"></x><x e1=\"c\" e2=\"1\"></x><x e1=\"b\" e2=\"2\"></x><x e1=\"a\" e2=\"0\"></x></parent>"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlAggOrderBy() throws Exception {
+ String sql = "SELECT xmlelement(parent, xmlAgg(xmlelement(x, xmlattributes(e1, e2)) order by e2)) from pm1.g1"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<parent><x e1=\"a\" e2=\"0\"></x><x e1=\"a\" e2=\"0\"></x><x e2=\"1\"></x><x e1=\"c\" e2=\"1\"></x><x e1=\"b\" e2=\"2\"></x><x e1=\"a\" e2=\"3\"></x></parent>"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlSerialize() throws Exception {
+ String sql = "SELECT xmlserialize(document xmlelement(parent) as string)"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<parent></parent>"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlTable() throws Exception {
+ String sql = "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$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList(null, "first"),
+ Arrays.asList("attr", "second"),
+ };
+
+ process(sql, 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$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList(-1, "rev"),
+ Arrays.asList(1, "rev"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlTableReturnXml() throws Exception {
+ 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>"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlTableNoColumns() throws Exception {
+ String sql = "select * from xmltable('/a' passing convert('<a><b>first</b><b x=\"1\">second</b></a>', xml)) as x"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<a><b>first</b><b x=\"1\">second</b></a>"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlTablePassing() throws Exception {
+ String sql = "select * from xmltable('<root>{for $x in $a/a/b return <c>{$x}</c>}</root>' passing convert('<a><b>first</b><b x=\"1\">second</b></a>', xml) as a columns x xml path 'c[1]/b') as x"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<b>first</b>"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlTableForOrdinalityAndDefaultPath() throws Exception {
+ String sql = "select * from xmltable('/a/b' passing convert('<a><b><c>1</c></b><b>1</b><b><c>1</c></b><b>1</b></a>', xml) columns x for ordinality, c integer) as x"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList(1, 1),
+ Arrays.asList(2, null),
+ Arrays.asList(3, 1),
+ Arrays.asList(4, null),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlTableDescendantPath() throws Exception {
+ String sql = "select * from xmltable('<a>{for $i in (1 to 5) return $i}</a>' columns x string path '//text()') as x"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("1 2 3 4 5"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlQuery() throws Exception {
+ String sql = "select xmlquery('for $i in (1 to 5) return $i')"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("1 2 3 4 5"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlQueryEmptyNull() throws Exception {
+ String sql = "select xmlquery('/a' passing xmlparse(document '<x/>') null on empty)"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList((String)null)
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlNameEscaping() throws Exception {
+ String sql = "select xmlforest(\"xml\") from (select 1 as \"xml\") x"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<_u0078_ml>1</_u0078_ml>")
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlParseDoc() throws Exception {
+ String sql = "select xmlparse(document '<a/>')"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("<a/>")
+ };
+
+ process(sql, expected);
+ }
+
+ @Test(expected=ExpressionEvaluationException.class) public void testXmlParseDocException() throws Exception {
+ String sql = "select xmlparse(document 'a<a/>')"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlParseContent() throws Exception {
+ String sql = "select xmlparse(content 'a<a/>')"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("a<a/>")
+ };
+
+ process(sql, expected);
+ }
+
+ @Test(expected=ExpressionEvaluationException.class) public void testXmlParseContentException() throws Exception {
+ String sql = "select xmlparse(content 'a<')"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ };
+
+ process(sql, expected);
+ }
+
+ //by pass the validation
+ @Test public void testXmlParseContentWellformed() throws Exception {
+ String sql = "select xmlparse(content 'a<' WELLFORMED)"; //$NON-NLS-1$
+
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList("a<")
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testXmlParseClob() throws Exception {
+ String sql = "select xmlparse(document cast(? as clob)) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(ObjectConverterUtil.convertToString(new FileInputStream(UnitTestUtil.getTestDataFile("udf.xmi")))),
+ };
+
+ processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(TestTextTable.clobFromFile("udf.xmi")));
+ }
+
+ @Test public void testXmlParseBlob() throws Exception {
+ String sql = "select xmlparse(document cast(? as blob)) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(ObjectConverterUtil.convertToString(new FileInputStream(UnitTestUtil.getTestDataFile("udf.xmi")))),
+ };
+
+ processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(blobFromFile("udf.xmi")));
+ }
+
+ @Test public void testXmlParseBlobWithEncoding() throws Exception {
+ String sql = "select xmlparse(document cast(? as blob)) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(ObjectConverterUtil.convertToString(new InputStreamReader(new FileInputStream(UnitTestUtil.getTestDataFile("encoding.xml")), Charset.forName("ISO-8859-1")))),
+ };
+
+ processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(blobFromFile("encoding.xml")));
+ }
+
+ @Test public void testXmlTableTypes() throws Exception {
+ String sql = "select * from xmltable('/a' passing xmlparse(document '<a>2000-01-01T01:01:00.2-06:00</a>') columns x timestamp path 'xs:dateTime(./text())', y timestamp path '.') as x"; //$NON-NLS-1$
+ Timestamp ts = TimestampUtil.createTimestamp(100, 0, 1, 1, 1, 0, 200000000);
+ List<?>[] expected = new List<?>[] {
+ Arrays.asList(ts, 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)";
+
+ List[] expected = new List[] {
+ Arrays.asList("attr", "c"),
+ };
+
+ process(sql, expected);
+ }
+
+ private static FakeDataManager dataManager = new FakeDataManager();
+
+ @BeforeClass public static void oneTimeSetUp() {
+ TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("GMT-06:00")); //$NON-NLS-1$
+ sampleData1(dataManager);
+ }
+
+ @AfterClass public static void oneTimeTearDown() {
+ TimestampWithTimezone.resetCalendar(null); //$NON-NLS-1$
+ }
+
+ private void process(String sql, List<?>[] expected) throws Exception {
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached(), new DefaultCapabilitiesFinder(), createCommandContext());
+
+ helpProcess(plan, createCommandContext(), dataManager, expected);
+ }
+
+ public static BlobType blobFromFile(final String file) {
+ return new BlobType(new BlobImpl(new InputStreamFactory.FileInputStreamFactory(UnitTestUtil.getTestDataFile(file))));
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,95 +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;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.teiid.core.TeiidComponentException;
-import org.teiid.query.eval.SecurityFunctionEvaluator;
-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.util.CommandContext;
-
-import junit.framework.TestCase;
-
-
-public class TestSecurityFunctions extends TestCase {
-
- /**
- * hasRole should be true without a service
- */
- public void testHasRoleWithoutService() throws Exception {
-
- String sql = "select pm1.g1.e2 from pm1.g1 where true = hasRole('data', pm1.g1.e1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0) }),
- };
-
- // Construct data manager with data
- HardcodedDataManager dataManager = new HardcodedDataManager();
-
- dataManager.addData("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1", new List[] { //$NON-NLS-1$
- Arrays.asList(new Object[] { "fooRole", new Integer(0) }), //$NON-NLS-1$
- });
-
- Command command = TestProcessor.helpParse(sql);
- ProcessorPlan plan = TestProcessor.helpGetPlan(command, FakeMetadataFactory.example1Cached());
-
- // Run query
- TestProcessor.helpProcess(plan, dataManager, expected);
- }
-
- public void testHasRoleWithService() throws Exception {
-
- String sql = "select pm1.g1.e2 from pm1.g1 where true = hasRole('data', pm1.g1.e1)"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] { };
-
- // Construct data manager with data
- HardcodedDataManager dataManager = new HardcodedDataManager();
-
- dataManager.addData("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1", new List[] { //$NON-NLS-1$
- Arrays.asList(new Object[] { "fooRole", new Integer(0) }), //$NON-NLS-1$
- });
-
- CommandContext context = new CommandContext();
- context.setSecurityFunctionEvaluator(new SecurityFunctionEvaluator() {
- public boolean hasRole(String roleType,
- String roleName) throws TeiidComponentException {
- return false;
- }});
-
- Command command = TestProcessor.helpParse(sql);
- ProcessorPlan plan = TestProcessor.helpGetPlan(command, FakeMetadataFactory.example1Cached(), new DefaultCapabilitiesFinder(), context);
-
- // Run query
- TestProcessor.helpProcess(plan, context, dataManager, expected);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,95 @@
+/*
+ * 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 java.util.Arrays;
+import java.util.List;
+
+import org.teiid.core.TeiidComponentException;
+import org.teiid.query.eval.SecurityFunctionEvaluator;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+import junit.framework.TestCase;
+
+
+public class TestSecurityFunctions extends TestCase {
+
+ /**
+ * hasRole should be true without a service
+ */
+ public void testHasRoleWithoutService() throws Exception {
+
+ String sql = "select pm1.g1.e2 from pm1.g1 where true = hasRole('data', pm1.g1.e1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0) }),
+ };
+
+ // Construct data manager with data
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+
+ dataManager.addData("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1", new List[] { //$NON-NLS-1$
+ Arrays.asList(new Object[] { "fooRole", new Integer(0) }), //$NON-NLS-1$
+ });
+
+ Command command = TestProcessor.helpParse(sql);
+ ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached());
+
+ // Run query
+ TestProcessor.helpProcess(plan, dataManager, expected);
+ }
+
+ public void testHasRoleWithService() throws Exception {
+
+ String sql = "select pm1.g1.e2 from pm1.g1 where true = hasRole('data', pm1.g1.e1)"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] { };
+
+ // Construct data manager with data
+ HardcodedDataManager dataManager = new HardcodedDataManager();
+
+ dataManager.addData("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1", new List[] { //$NON-NLS-1$
+ Arrays.asList(new Object[] { "fooRole", new Integer(0) }), //$NON-NLS-1$
+ });
+
+ CommandContext context = new CommandContext();
+ context.setSecurityFunctionEvaluator(new SecurityFunctionEvaluator() {
+ public boolean hasRole(String roleType,
+ String roleName) throws TeiidComponentException {
+ return false;
+ }});
+
+ Command command = TestProcessor.helpParse(sql);
+ ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), new DefaultCapabilitiesFinder(), context);
+
+ // Run query
+ TestProcessor.helpProcess(plan, context, dataManager, expected);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,87 +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;
-
-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.DefaultCapabilitiesFinder;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
-
-public class TestSetProcessing {
-
- @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$
-
- List<?>[] expected = new List[] {
- Arrays.asList(new Object[] {"a", 0}), //$NON-NLS-1$
- Arrays.asList(new Object[] {"a", 3}), //$NON-NLS-1$
- Arrays.asList(new Object[] {"b", 2}), //$NON-NLS-1$
- };
-
- FakeDataManager manager = new FakeDataManager();
- TestProcessor.sampleData1(manager);
- TestProcessor.helpProcess(plan, manager, expected);
- }
-
- @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$
-
- List<?>[] expected = new List[] {
- Arrays.asList(new Object[] {null, 1}),
- Arrays.asList(new Object[] {"c", 1}), //$NON-NLS-1$
- };
-
- FakeDataManager manager = new FakeDataManager();
- TestProcessor.sampleData1(manager);
- TestProcessor.helpProcess(plan, manager, expected);
- }
-
- @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$
-
- List<?>[] expected = new List[] {
- Arrays.asList(new Object[] {null, 1}),
- Arrays.asList(new Object[] {"a", 0}), //$NON-NLS-1$
- Arrays.asList(new Object[] {"a", 3}), //$NON-NLS-1$
- Arrays.asList(new Object[] {"b", 2}), //$NON-NLS-1$
- Arrays.asList(new Object[] {"c", 1}), //$NON-NLS-1$
- };
-
- FakeDataManager manager = new FakeDataManager();
- TestProcessor.sampleData1(manager);
- TestProcessor.helpProcess(plan, manager, expected);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,87 @@
+/*
+ * 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 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.DefaultCapabilitiesFinder;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+
+public class TestSetProcessing {
+
+ @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, 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$
+ Arrays.asList(new Object[] {"a", 3}), //$NON-NLS-1$
+ Arrays.asList(new Object[] {"b", 2}), //$NON-NLS-1$
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ TestProcessor.sampleData1(manager);
+ TestProcessor.helpProcess(plan, manager, expected);
+ }
+
+ @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, 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}),
+ Arrays.asList(new Object[] {"c", 1}), //$NON-NLS-1$
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ TestProcessor.sampleData1(manager);
+ TestProcessor.helpProcess(plan, manager, expected);
+ }
+
+ @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, 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}),
+ Arrays.asList(new Object[] {"a", 0}), //$NON-NLS-1$
+ Arrays.asList(new Object[] {"a", 3}), //$NON-NLS-1$
+ Arrays.asList(new Object[] {"b", 2}), //$NON-NLS-1$
+ Arrays.asList(new Object[] {"c", 1}), //$NON-NLS-1$
+ };
+
+ FakeDataManager manager = new FakeDataManager();
+ TestProcessor.sampleData1(manager);
+ TestProcessor.helpProcess(plan, manager, expected);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestTempTables.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,326 +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;
-
-import static org.junit.Assert.*;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.concurrent.Executor;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.BufferManagerFactory;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.dqp.internal.process.CachedResults;
-import org.teiid.dqp.internal.process.SessionAwareCache;
-import org.teiid.metadata.FunctionMethod.Determinism;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.optimizer.TestOptimizer;
-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.util.CommandContext;
-
- at SuppressWarnings({"nls", "unchecked"})
-public class TestTempTables {
-
- private TempMetadataAdapter metadata;
- private TempTableDataManager dataManager;
- private TempTableStore tempStore;
-
- private ProcessorPlan execute(String sql, List[] expectedResults) throws Exception {
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, metadata);
- execute(plan, expectedResults);
- return plan;
- }
-
- private void execute(ProcessorPlan processorPlan, List[] expectedResults) throws Exception {
- CommandContext cc = TestProcessor.createCommandContext();
- cc.setMetadata(metadata);
- cc.setTempTableStore(tempStore);
- TestProcessor.doProcess(processorPlan, dataManager, expectedResults, cc);
- assertTrue(Determinism.SESSION_DETERMINISTIC.compareTo(cc.getDeterminismLevel()) <= 0);
- }
-
- @Before public void setUp() {
- tempStore = new TempTableStore("1"); //$NON-NLS-1$
- metadata = new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), tempStore.getMetadataStore());
- metadata.setSession(true);
- FakeDataManager fdm = new FakeDataManager();
- TestProcessor.sampleData1(fdm);
- BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();
- SessionAwareCache<CachedResults> cache = new SessionAwareCache<CachedResults>();
- cache.setBufferManager(bm);
- Executor executor = new Executor() {
- @Override
- public void execute(Runnable command) {
- command.run();
- }
- };
- dataManager = new TempTableDataManager(fdm, bm, executor, cache, null, null);
- }
-
- @Test public void testInsertWithQueryExpression() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) select e2, e1 from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
- execute("update x set e1 = e2 where e2 > 1", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
- }
-
- @Test public void testOutofOrderInsert() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("select e1, e2 from x", new List[] {Arrays.asList("one", 1)}); //$NON-NLS-1$
- }
-
- @Test public void testUpdate() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("select e1, e2 into x from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
- execute("update x set e1 = e2 where e2 > 1", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
- execute("select e1 from x where e2 > 0 order by e1", new List[] { //$NON-NLS-1$
- Arrays.asList((String)null),
- Arrays.asList("2"), //$NON-NLS-1$
- Arrays.asList("3"), //$NON-NLS-1$
- Arrays.asList("c"), //$NON-NLS-1$
- Arrays.asList("one")}); //$NON-NLS-1$
- }
-
- @Test public void testDelete() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("select e1, e2 into x from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
- execute("delete from x where ascii(e1) > e2", new List[] {Arrays.asList(5)}); //$NON-NLS-1$
- execute("select e1 from x order by e1", new List[] {Arrays.asList((String)null)}); //$NON-NLS-1$
- }
-
- @Test public void testDelete1() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("select e1, e2 into x from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
- execute("delete from x", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
- execute("select e1 from x order by e1", new List[] {}); //$NON-NLS-1$
- }
-
- @Test(expected=TeiidProcessingException.class) public void testDuplicatePrimaryKey() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- }
-
- @Test public void testAtomicUpdate() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- try {
- execute("update x set e2 = 3", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- } catch (TeiidProcessingException e) {
- //should be a duplicate key
- }
- //should revert back to original
- execute("select count(*) from x", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
- }
-
- @Test public void testAtomicDelete() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- try {
- execute("delete from x where 1/(e2 - 2) <> 4", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- } catch (TeiidProcessingException e) {
- //should be a duplicate key
- }
- //should revert back to original
- execute("select count(*) from x", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
- }
-
- @Test public void testPrimaryKeyMetadata() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- Collection c = metadata.getUniqueKeysInGroup(metadata.getGroupID("x"));
- assertEquals(1, c.size());
- assertEquals(1, (metadata.getElementIDsInKey(c.iterator().next()).size()));
- }
-
- @Test public void testProjection() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("select * from x where e2 = 1", new List[] {Arrays.asList("one", 1)}); //$NON-NLS-1$
- execute("select e2, e1 from x where e2 = 1", new List[] {Arrays.asList(1, "one")}); //$NON-NLS-1$
- }
-
- @Test public void testOrderByWithIndex() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (3, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("select * from x as y order by e2 desc", new List[] {Arrays.asList("one", 3), Arrays.asList("one", 2)}); //$NON-NLS-1$
- }
-
- @Test public void testOrderByWithoutIndex() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (3, 'a')", 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 order by e1", new List[] {Arrays.asList("a", 3), Arrays.asList("b", 2)}); //$NON-NLS-1$
- }
-
- @Test public void testCompareEqualsWithIndex() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (3, 'a')", 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 e2 = 3", new List[] {Arrays.asList("a", 3)}); //$NON-NLS-1$
- }
-
- @Test public void testLikeWithIndex() 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, 'a')", 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 'z%'", new List[0]); //$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$
- execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("select * from x where e1 is null", new List[] {Arrays.asList(null, 3)}); //$NON-NLS-1$
- }
-
- @Test public void testInWithIndex() 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, 'a')", 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("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (0, 'd')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (-1, 'e')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("select * from x where e1 in ('a', 'c', 'e', 'f', 'g')", new List[] {Arrays.asList("a", 3), Arrays.asList("c", 1), Arrays.asList("e", -1)}); //$NON-NLS-1$
- }
-
- @Test public void testInWithIndexUpdate() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer, e3 string, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (3, 'a')", 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("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (0, 'd')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("insert into x (e2, e1, e3) values (-1, 'e', 'e')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("update x set e2 = 5 where e1 in ('a', 'c')", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
- execute("select * from x where e1 in ('b', e3)", new List[] {Arrays.asList("b", 2, null), Arrays.asList("e", -1, "e")}); //$NON-NLS-1$
- }
-
- @Test public void testCompositeKeyCompareEquals() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (3, 'a')", 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("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("select * from x where e1 = 'b' and e2 = 2", new List[] {Arrays.asList("b", 2)}); //$NON-NLS-1$
- }
-
- @Test public void testCompositeKeyPartial() throws Exception {
- sampleTable();
- execute("select * from x where e1 = 'b'", new List[] {Arrays.asList("b", 2), Arrays.asList("b", 3)}); //$NON-NLS-1$
- }
-
- @Test public void testCompositeKeyPartial1() throws Exception {
- sampleTable();
- execute("select * from x where e1 < 'c'", new List[] {Arrays.asList("a", 1), Arrays.asList("b", 2), Arrays.asList("b", 3)}); //$NON-NLS-1$
- }
-
- @Test public void testCompositeKeyPartial2() throws Exception {
- sampleTable();
- execute("select * from x where e2 = 1", new List[] {Arrays.asList("a", 1), Arrays.asList("c", 1)}); //$NON-NLS-1$
- }
-
- @Test public void testCompositeKeyPartial3() throws Exception {
- sampleTable();
- execute("select * from x where e1 >= 'b'", new List[] {Arrays.asList("b", 2), Arrays.asList("b", 3), Arrays.asList("c", 1)}); //$NON-NLS-1$
- }
-
- @Test public void testCompositeKeyPartial4() throws Exception {
- sampleTable();
- execute("select * from x where e1 >= 'b' order by e1 desc, e2 desc", new List[] {Arrays.asList("c", 1), Arrays.asList("b", 3), Arrays.asList("b", 2)}); //$NON-NLS-1$
- }
-
- @Test public void testCompositeKeyPartial5() throws Exception {
- sampleTable();
- execute("select * from x where e1 in ('a', 'b')", new List[] {Arrays.asList("a", 1), Arrays.asList("b", 2), Arrays.asList("b", 3)}); //$NON-NLS-1$
- }
-
- @Test public void testCompositeKeyPartial6() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("select * from x where e1 in ('a', 'b') order by e1 desc", new List[0]); //$NON-NLS-1$
- }
-
- @Test public void testCountStar() throws Exception {
- sampleTable();
- execute("select count(*) a from x", new List[] {Arrays.asList(4)});
- execute("select count(*) a from x where e2 = 1 order by a", new List[] {Arrays.asList(2)});
- }
-
- @Test public void testAutoIncrement() throws Exception {
- execute("create local temporary table x (e1 serial, e2 integer, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2) values (1)", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("insert into x (e2) values (3)", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("select * from x", new List[] {Arrays.asList(1, 1), Arrays.asList(2, 3)});
- }
-
- @Test(expected=TeiidProcessingException.class) public void testNotNull() throws Exception {
- execute("create local temporary table x (e1 serial, e2 integer not null, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e1, e2) values ((select null), 1)", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- }
-
- @Test(expected=TeiidProcessingException.class) public void testNotNull1() throws Exception {
- execute("create local temporary table x (e1 serial, e2 integer not null, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2) values ((select null))", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- }
-
- /**
- * If the session metadata is still visible, then the procedure will fail due to the conflicting
- * definitions of temp_table
- */
- @Test public void testSessionResolving() throws Exception {
- execute("create local temporary table temp_table (column1 integer)", new List[] {Arrays.asList(0)});
- execute("exec pm1.vsp60()", new List[] {Arrays.asList("First"), Arrays.asList("Second"), Arrays.asList("Third")});
- }
-
- /**
- * Note that the order by reflects the key order, not the order in which the criteria was entered
- */
- @Test public void testCompositeKeyJoinUsesKeyOrder() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", 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 * from x, x1 where x.e2 = x1.e2 and x.e1 = x1.e1", this.metadata, new String[] {"SELECT x1.e2, x1.e1 FROM x1 ORDER BY x1.e1, x1.e2", "SELECT x.e2, x.e1 FROM x ORDER BY x.e1, x.e2"}, ComparisonMode.EXACT_COMMAND_STRING);
- }
-
- @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);
- }
-
- private void sampleTable() throws Exception {
- execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (3, 'b')", 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("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- execute("insert into x (e2, e1) values (1, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestTempTables.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,329 @@
+/*
+ * 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.junit.Assert.*;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.Executor;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.BufferManagerFactory;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.dqp.internal.process.CachedResults;
+import org.teiid.dqp.internal.process.SessionAwareCache;
+import org.teiid.metadata.FunctionMethod.Determinism;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.optimizer.TestOptimizer;
+import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
+import org.teiid.query.tempdata.TempTableDataManager;
+import org.teiid.query.tempdata.TempTableStore;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+ at SuppressWarnings({"nls", "unchecked"})
+public class TestTempTables {
+
+ private TempMetadataAdapter metadata;
+ private TempTableDataManager dataManager;
+ private TempTableStore tempStore;
+
+ private ProcessorPlan execute(String sql, List[] expectedResults) throws Exception {
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, metadata);
+ execute(plan, expectedResults);
+ return plan;
+ }
+
+ private void execute(ProcessorPlan processorPlan, List[] expectedResults) throws Exception {
+ CommandContext cc = TestProcessor.createCommandContext();
+ cc.setMetadata(metadata);
+ cc.setTempTableStore(tempStore);
+ TestProcessor.doProcess(processorPlan, dataManager, expectedResults, cc);
+ assertTrue(Determinism.SESSION_DETERMINISTIC.compareTo(cc.getDeterminismLevel()) <= 0);
+ }
+
+ @Before public void setUp() {
+ tempStore = new TempTableStore("1"); //$NON-NLS-1$
+ metadata = new TempMetadataAdapter(RealMetadataFactory.example1Cached(), tempStore.getMetadataStore());
+ metadata.setSession(true);
+ FakeDataManager fdm = new FakeDataManager();
+ TestProcessor.sampleData1(fdm);
+ BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();
+ SessionAwareCache<CachedResults> cache = new SessionAwareCache<CachedResults>();
+ cache.setBufferManager(bm);
+ Executor executor = new Executor() {
+ @Override
+ public void execute(Runnable command) {
+ command.run();
+ }
+ };
+ dataManager = new TempTableDataManager(fdm, bm, executor, cache, null, null);
+ }
+
+ @Test public void testInsertWithQueryExpression() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) select e2, e1 from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
+ execute("update x set e1 = e2 where e2 > 1", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
+ }
+
+ @Test public void testOutofOrderInsert() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("select e1, e2 from x", new List[] {Arrays.asList("one", 1)}); //$NON-NLS-1$
+ }
+
+ @Test public void testUpdate() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("select e1, e2 into x from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
+ execute("update x set e1 = e2 where e2 > 1", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
+ execute("select e1 from x where e2 > 0 order by e1", new List[] { //$NON-NLS-1$
+ Arrays.asList((String)null),
+ Arrays.asList("2"), //$NON-NLS-1$
+ Arrays.asList("3"), //$NON-NLS-1$
+ Arrays.asList("c"), //$NON-NLS-1$
+ Arrays.asList("one")}); //$NON-NLS-1$
+ }
+
+ @Test public void testDelete() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("select e1, e2 into x from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
+ execute("delete from x where ascii(e1) > e2", new List[] {Arrays.asList(5)}); //$NON-NLS-1$
+ execute("select e1 from x order by e1", new List[] {Arrays.asList((String)null)}); //$NON-NLS-1$
+ }
+
+ @Test public void testDelete1() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("select e1, e2 into x from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
+ execute("delete from x", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
+ execute("select e1 from x order by e1", new List[] {}); //$NON-NLS-1$
+ }
+
+ @Test(expected=TeiidProcessingException.class) public void testDuplicatePrimaryKey() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ }
+
+ @Test public void testAtomicUpdate() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ try {
+ execute("update x set e2 = 3", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ } catch (TeiidProcessingException e) {
+ //should be a duplicate key
+ }
+ //should revert back to original
+ execute("select count(*) from x", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
+ }
+
+ @Test public void testAtomicDelete() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ try {
+ execute("delete from x where 1/(e2 - 2) <> 4", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ } catch (TeiidProcessingException e) {
+ //should be a duplicate key
+ }
+ //should revert back to original
+ execute("select count(*) from x", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
+ }
+
+ @Test public void testPrimaryKeyMetadata() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ Collection c = metadata.getUniqueKeysInGroup(metadata.getGroupID("x"));
+ assertEquals(1, c.size());
+ assertEquals(1, (metadata.getElementIDsInKey(c.iterator().next()).size()));
+ }
+
+ @Test public void testProjection() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("select * from x where e2 = 1", new List[] {Arrays.asList("one", 1)}); //$NON-NLS-1$
+ execute("select e2, e1 from x where e2 = 1", new List[] {Arrays.asList(1, "one")}); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderByWithIndex() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (3, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("select * from x as y order by e2 desc", new List[] {Arrays.asList("one", 3), Arrays.asList("one", 2)}); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderByWithoutIndex() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (3, 'a')", 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 order by e1", new List[] {Arrays.asList("a", 3), Arrays.asList("b", 2)}); //$NON-NLS-1$
+ }
+
+ @Test public void testCompareEqualsWithIndex() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (3, 'a')", 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 e2 = 3", new List[] {Arrays.asList("a", 3)}); //$NON-NLS-1$
+ }
+
+ @Test public void testLikeWithIndex() 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, 'a')", 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 'z%'", new List[0]); //$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$
+ execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("select * from x where e1 is null", new List[] {Arrays.asList(null, 3)}); //$NON-NLS-1$
+ }
+
+ @Test public void testInWithIndex() 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, 'a')", 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("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (0, 'd')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (-1, 'e')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("select * from x where e1 in ('a', 'c', 'e', 'f', 'g')", new List[] {Arrays.asList("a", 3), Arrays.asList("c", 1), Arrays.asList("e", -1)}); //$NON-NLS-1$
+ }
+
+ @Test public void testInWithIndexUpdate() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer, e3 string, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (3, 'a')", 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("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (0, 'd')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1, e3) values (-1, 'e', 'e')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("update x set e2 = 5 where e1 in ('a', 'c')", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
+ execute("select * from x where e1 in ('b', e3)", new List[] {Arrays.asList("b", 2, null), Arrays.asList("e", -1, "e")}); //$NON-NLS-1$
+ }
+
+ @Test public void testCompositeKeyCompareEquals() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (3, 'a')", 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("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("select * from x where e1 = 'b' and e2 = 2", new List[] {Arrays.asList("b", 2)}); //$NON-NLS-1$
+ }
+
+ @Test public void testCompositeKeyPartial() throws Exception {
+ sampleTable();
+ execute("select * from x where e1 = 'b'", new List[] {Arrays.asList("b", 2), Arrays.asList("b", 3)}); //$NON-NLS-1$
+ }
+
+ @Test public void testCompositeKeyPartial1() throws Exception {
+ sampleTable();
+ execute("select * from x where e1 < 'c'", new List[] {Arrays.asList("a", 1), Arrays.asList("b", 2), Arrays.asList("b", 3)}); //$NON-NLS-1$
+ }
+
+ @Test public void testCompositeKeyPartial2() throws Exception {
+ sampleTable();
+ execute("select * from x where e2 = 1", new List[] {Arrays.asList("a", 1), Arrays.asList("c", 1)}); //$NON-NLS-1$
+ }
+
+ @Test public void testCompositeKeyPartial3() throws Exception {
+ sampleTable();
+ execute("select * from x where e1 >= 'b'", new List[] {Arrays.asList("b", 2), Arrays.asList("b", 3), Arrays.asList("c", 1)}); //$NON-NLS-1$
+ }
+
+ @Test public void testCompositeKeyPartial4() throws Exception {
+ sampleTable();
+ execute("select * from x where e1 >= 'b' order by e1 desc, e2 desc", new List[] {Arrays.asList("c", 1), Arrays.asList("b", 3), Arrays.asList("b", 2)}); //$NON-NLS-1$
+ }
+
+ @Test public void testCompositeKeyPartial5() throws Exception {
+ sampleTable();
+ execute("select * from x where e1 in ('a', 'b')", new List[] {Arrays.asList("a", 1), Arrays.asList("b", 2), Arrays.asList("b", 3)}); //$NON-NLS-1$
+ }
+
+ @Test public void testCompositeKeyPartial6() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("select * from x where e1 in ('a', 'b') order by e1 desc", new List[0]); //$NON-NLS-1$
+ }
+
+ @Test public void testCountStar() throws Exception {
+ sampleTable();
+ execute("select count(*) a from x", new List[] {Arrays.asList(4)});
+ execute("select count(*) a from x where e2 = 1 order by a", new List[] {Arrays.asList(2)});
+ }
+
+ @Test public void testAutoIncrement() throws Exception {
+ execute("create local temporary table x (e1 serial, e2 integer, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2) values (1)", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("insert into x (e2) values (3)", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("select * from x", new List[] {Arrays.asList(1, 1), Arrays.asList(2, 3)});
+ }
+
+ @Test(expected=TeiidProcessingException.class) public void testNotNull() throws Exception {
+ execute("create local temporary table x (e1 serial, e2 integer not null, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e1, e2) values ((select null), 1)", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ }
+
+ @Test(expected=TeiidProcessingException.class) public void testNotNull1() throws Exception {
+ execute("create local temporary table x (e1 serial, e2 integer not null, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2) values ((select null))", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ }
+
+ /**
+ * If the session metadata is still visible, then the procedure will fail due to the conflicting
+ * definitions of temp_table
+ */
+ @Test public void testSessionResolving() throws Exception {
+ execute("create local temporary table temp_table (column1 integer)", new List[] {Arrays.asList(0)});
+ execute("exec pm1.vsp60()", new List[] {Arrays.asList("First"), Arrays.asList("Second"), Arrays.asList("Third")});
+ }
+
+ /**
+ * Note that the order by reflects the key order, not the order in which the criteria was entered
+ */
+ @Test public void testCompositeKeyJoinUsesKeyOrder() throws Exception {
+ execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", 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 * from x, x1 where x.e2 = x1.e2 and x.e1 = x1.e1", this.metadata, new String[] {"SELECT x1.e2, x1.e1 FROM x1 ORDER BY x1.e1, x1.e2", "SELECT x.e2, x.e1 FROM x ORDER BY x.e1, x.e2"}, ComparisonMode.EXACT_COMMAND_STRING);
+ }
+
+ @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 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 {
+ execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (3, 'b')", 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("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ execute("insert into x (e2, e1) values (1, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTextTable.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestTextTable.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTextTable.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,323 +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;
-
-import static org.teiid.query.optimizer.TestOptimizer.*;
-import static org.teiid.query.processor.TestProcessor.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import javax.sql.rowset.serial.SerialClob;
-
-import org.junit.Test;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.ClobImpl;
-import org.teiid.core.types.ClobType;
-import org.teiid.core.types.InputStreamFactory;
-import org.teiid.core.util.UnitTestUtil;
-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;
-
- at SuppressWarnings({"unchecked", "nls"})
-public class TestTextTable {
-
- @Test public void testCorrelatedTextTable() throws Exception {
- String sql = "select x.* from pm1.g1, texttable(e1 || ',' || e2 COLUMNS x string, y integer) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("a", 0),
- Arrays.asList("a", 3),
- Arrays.asList("c", 1),
- Arrays.asList("b", 2),
- Arrays.asList("a", 0),
- };
-
- process(sql, expected);
- }
-
- @Test public void testTextTableFixed() throws Exception {
- String sql = "select max(compkey), max(cdm_id), max(currency), max(\"start\"), max(maturity), max(amount), count(*) from texttable(? COLUMNS compkey string width 76, CDM_ID string width 14, CURRENCY string width 9, \"START\" string width 31, MATURITY string width 31, AMOUNT double width 21, RECORDSOURCE string width 13, SUMMIT_ID string width 15, RATE double width 20, SPREAD double width 20, DESK string width 14) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("000369USD05/20/200405/20/2007", "000369", "USD", "12/18/2000", "12/19/2005", 6.7209685146E8, 52),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/cdm_dos.txt")));
- }
-
- @Test public void testTextTableFixedWin() throws Exception {
- String sql = "select max(compkey), max(cdm_id), max(currency), max(\"start\"), max(maturity), max(amount), count(*) from texttable(? COLUMNS compkey string width 76, CDM_ID string width 14, CURRENCY string width 9, \"START\" string width 31, MATURITY string width 31, AMOUNT double width 21, RECORDSOURCE string width 13, SUMMIT_ID string width 15, RATE double width 20, SPREAD double width 20, DESK string width 14) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("000369USD05/20/200405/20/2007", "000369", "USD", "12/18/2000", "12/19/2005", 6.7209685146E8, 52),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/cdm_dos_win.txt")));
- }
-
- @Test public void testTextTableFixedPartial() throws Exception {
- String sql = "select max(length(compkey)) from texttable(? COLUMNS compkey string width 76) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(30),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/cdm_dos.txt")));
- }
-
- @Test public void testNamedMultilineHeader() throws Exception {
- String sql = "SELECT * from texttable(? COLUMNS Col3Head string HEADER) x";
-
- List[] expected = new List[] {
- Arrays.asList("VAL2"),
- Arrays.asList("VAL4"),
- Arrays.asList("abc"),
- Arrays.asList("VAL9"),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/test-file.txt.csv")));
- }
-
- @Test public void testHeaderWithSkip() throws Exception {
- String sql = "select count(*) from texttable(? COLUMNS PARTNAME string HEADER 3 SKIP 5) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(21),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/TextParts_HeaderRow2.csv")));
- }
-
- @Test public void testEscape() throws Exception {
- String sql = "select * from texttable('a\\,b,c\\\na\na,b\\\\' COLUMNS c1 string, c2 string ESCAPE '\\') x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("a,b", "c\na"),
- Arrays.asList("a", "b\\"),
- };
-
- process(sql, expected);
- }
-
- @Test(expected=TeiidProcessingException.class) public void testEscapeError() throws Exception {
- String sql = "select * from texttable('axq' COLUMNS c1 string ESCAPE 'x') x"; //$NON-NLS-1$
-
- List[] expected = new List[] {};
-
- process(sql, expected);
- }
-
- @Test public void testDelimiter() throws Exception {
- String sql = "select * from texttable('\na\\,b,c' COLUMNS c1 string, c2 string DELIMITER 'b') x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("a\\,", ",c"),
- };
-
- 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$
-
- List[] expected = new List[] {};
-
- process(sql, expected);
- }
-
- @Test public void testQuote() throws Exception {
- String sql = "select * from texttable(' \" a\", \" \"\" \"' COLUMNS c1 string, c2 string) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(" a", " \" ")
- };
-
- process(sql, expected);
- }
-
- @Test(expected=TeiidProcessingException.class) public void testUnclosedQuoteError() throws Exception {
- String sql = "select * from texttable(' \" a\", \" \"\"' COLUMNS c1 string, c2 string) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {};
-
- process(sql, expected);
- }
-
- @Test(expected=TeiidProcessingException.class) public void testQuoteError() throws Exception {
- String sql = "select * from texttable(' \" a\", x\" \"\" \"' COLUMNS c1 string, c2 string) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {};
-
- process(sql, expected);
- }
-
- @Test(expected=TeiidProcessingException.class) public void testHeaderError() throws Exception {
- String sql = "select * from texttable('notc1,notc2' COLUMNS c1 string, c2 string HEADER) x"; //$NON-NLS-1$
-
- List[] expected = new List[] {};
-
- process(sql, expected);
- }
-
- @Test public void testTextTableCriteria() throws Exception {
- String sql = "select x.* from texttable('a' || ',' || '1' COLUMNS x string, y integer) x where x.y = 1"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("a", 1),
- };
-
- process(sql, expected);
- }
-
- @Test public void testTextTableGroupBy() throws Exception {
- String sql = "select max(x) from texttable('a' || ',' || '1' COLUMNS x string, y integer) x group by y"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("a"),
- };
-
- process(sql, expected);
- }
-
- @Test public void testTextTableSubquery() throws Exception {
- String sql = "select x.* from pm1.g1, texttable(e1 || ',' || e2 COLUMNS x string, y integer) x where y < (select avg(e2) from pm1.g1 as x)";
-
- List[] expected = new List[] {
- Arrays.asList("a", 0),
- Arrays.asList("c", 1),
- Arrays.asList("a", 0),
- };
-
- process(sql, expected);
- }
-
- @Test public void testTextTableMultiBatch() throws Exception {
- String sql = "select x.* from (select * from pm1.g1 where e1 = 'c') y, texttable(e1 || '\n' || e2 || '\n' || e3 COLUMNS x string) x";
-
- List[] expected = new List[] {
- Arrays.asList("c"),
- Arrays.asList("1"),
- Arrays.asList("true"),
- };
-
- process(sql, expected);
- }
-
- public static void process(String sql, List[] expectedResults) throws Exception {
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
- helpProcess(plan, createCommandContext(), dataManager, expectedResults);
- }
-
- public static ClobType clobFromFile(final String file) {
- return new ClobType(new ClobImpl(new InputStreamFactory.FileInputStreamFactory(UnitTestUtil.getTestDataFile(file)), -1));
- }
-
- @Test public void testTextAgg() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan("select convert(to_chars(textagg(for pm1.g1.e1, pm1.g1.e2 header order by e2), 'UTF-8'), string) as x from pm1.g1", metadata, null, capFinder, //$NON-NLS-1$
- new String[] { "SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
-
- HardcodedDataManager hdm = new HardcodedDataManager();
- hdm.addData("SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0", new List[] {Arrays.asList("z", 2), Arrays.asList("b", 1)});
- hdm.setBlockOnce(true);
-
- String nl = System.getProperty("line.separator");
- ArrayList list = new ArrayList();
- list.add("\"e1\",\"e2\""+nl+"\"b\",\"1\""+nl+"\"z\",\"2\""+nl);
- List[] expected = new List[] {
- list,
- };
-
- helpProcess(plan, hdm, expected);
- }
-
- @Test public void testTextAggOrderByUnrelated() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- BasicSourceCapabilities caps = getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
- caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
- capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = helpPlan("select convert(to_chars(textagg(for pm1.g1.e1 header order by e2), 'UTF-8'), string) as x from pm1.g1", metadata, null, capFinder, //$NON-NLS-1$
- new String[] { "SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
-
- HardcodedDataManager hdm = new HardcodedDataManager();
- hdm.addData("SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0", new List[] {Arrays.asList("z", 2), Arrays.asList("b", 1)});
- hdm.setBlockOnce(true);
-
- String nl = System.getProperty("line.separator");
- ArrayList list = new ArrayList();
- list.add("\"e1\""+nl+"\"b\""+nl+"\"z\""+nl);
- List[] expected = new List[] {
- list,
- };
-
- helpProcess(plan, hdm, expected);
- }
-
- @Test(expected=TeiidProcessingException.class) public void testTextTableInvalidData() throws Exception {
- String sql = "select count(*) from texttable(? COLUMNS PARTNAME string) x"; //$NON-NLS-1$
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- char[] data = new char[5000];
- processPreparedStatement(sql, null, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(new ClobType(new SerialClob(data))));
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTextTable.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestTextTable.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTextTable.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTextTable.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,323 @@
+/*
+ * 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.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.sql.rowset.serial.SerialClob;
+
+import org.junit.Test;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.ClobImpl;
+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.RealMetadataFactory;
+
+ at SuppressWarnings({"unchecked", "nls"})
+public class TestTextTable {
+
+ @Test public void testCorrelatedTextTable() throws Exception {
+ String sql = "select x.* from pm1.g1, texttable(e1 || ',' || e2 COLUMNS x string, y integer) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("a", 0),
+ Arrays.asList("a", 3),
+ Arrays.asList("c", 1),
+ Arrays.asList("b", 2),
+ Arrays.asList("a", 0),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testTextTableFixed() throws Exception {
+ String sql = "select max(compkey), max(cdm_id), max(currency), max(\"start\"), max(maturity), max(amount), count(*) from texttable(? COLUMNS compkey string width 76, CDM_ID string width 14, CURRENCY string width 9, \"START\" string width 31, MATURITY string width 31, AMOUNT double width 21, RECORDSOURCE string width 13, SUMMIT_ID string width 15, RATE double width 20, SPREAD double width 20, DESK string width 14) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("000369USD05/20/200405/20/2007", "000369", "USD", "12/18/2000", "12/19/2005", 6.7209685146E8, 52),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/cdm_dos.txt")));
+ }
+
+ @Test public void testTextTableFixedWin() throws Exception {
+ String sql = "select max(compkey), max(cdm_id), max(currency), max(\"start\"), max(maturity), max(amount), count(*) from texttable(? COLUMNS compkey string width 76, CDM_ID string width 14, CURRENCY string width 9, \"START\" string width 31, MATURITY string width 31, AMOUNT double width 21, RECORDSOURCE string width 13, SUMMIT_ID string width 15, RATE double width 20, SPREAD double width 20, DESK string width 14) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("000369USD05/20/200405/20/2007", "000369", "USD", "12/18/2000", "12/19/2005", 6.7209685146E8, 52),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/cdm_dos_win.txt")));
+ }
+
+ @Test public void testTextTableFixedPartial() throws Exception {
+ String sql = "select max(length(compkey)) from texttable(? COLUMNS compkey string width 76) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(30),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/cdm_dos.txt")));
+ }
+
+ @Test public void testNamedMultilineHeader() throws Exception {
+ String sql = "SELECT * from texttable(? COLUMNS Col3Head string HEADER) x";
+
+ List[] expected = new List[] {
+ Arrays.asList("VAL2"),
+ Arrays.asList("VAL4"),
+ Arrays.asList("abc"),
+ Arrays.asList("VAL9"),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/test-file.txt.csv")));
+ }
+
+ @Test public void testHeaderWithSkip() throws Exception {
+ String sql = "select count(*) from texttable(? COLUMNS PARTNAME string HEADER 3 SKIP 5) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(21),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/TextParts_HeaderRow2.csv")));
+ }
+
+ @Test public void testEscape() throws Exception {
+ String sql = "select * from texttable('a\\,b,c\\\na\na,b\\\\' COLUMNS c1 string, c2 string ESCAPE '\\') x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("a,b", "c\na"),
+ Arrays.asList("a", "b\\"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test(expected=TeiidProcessingException.class) public void testEscapeError() throws Exception {
+ String sql = "select * from texttable('axq' COLUMNS c1 string ESCAPE 'x') x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {};
+
+ process(sql, expected);
+ }
+
+ @Test public void testDelimiter() throws Exception {
+ String sql = "select * from texttable('\na\\,b,c' COLUMNS c1 string, c2 string DELIMITER 'b') x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("a\\,", ",c"),
+ };
+
+ 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$
+
+ List[] expected = new List[] {};
+
+ process(sql, expected);
+ }
+
+ @Test public void testQuote() throws Exception {
+ String sql = "select * from texttable(' \" a\", \" \"\" \"' COLUMNS c1 string, c2 string) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(" a", " \" ")
+ };
+
+ process(sql, expected);
+ }
+
+ @Test(expected=TeiidProcessingException.class) public void testUnclosedQuoteError() throws Exception {
+ String sql = "select * from texttable(' \" a\", \" \"\"' COLUMNS c1 string, c2 string) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {};
+
+ process(sql, expected);
+ }
+
+ @Test(expected=TeiidProcessingException.class) public void testQuoteError() throws Exception {
+ String sql = "select * from texttable(' \" a\", x\" \"\" \"' COLUMNS c1 string, c2 string) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {};
+
+ process(sql, expected);
+ }
+
+ @Test(expected=TeiidProcessingException.class) public void testHeaderError() throws Exception {
+ String sql = "select * from texttable('notc1,notc2' COLUMNS c1 string, c2 string HEADER) x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {};
+
+ process(sql, expected);
+ }
+
+ @Test public void testTextTableCriteria() throws Exception {
+ String sql = "select x.* from texttable('a' || ',' || '1' COLUMNS x string, y integer) x where x.y = 1"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("a", 1),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testTextTableGroupBy() throws Exception {
+ String sql = "select max(x) from texttable('a' || ',' || '1' COLUMNS x string, y integer) x group by y"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("a"),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testTextTableSubquery() throws Exception {
+ String sql = "select x.* from pm1.g1, texttable(e1 || ',' || e2 COLUMNS x string, y integer) x where y < (select avg(e2) from pm1.g1 as x)";
+
+ List[] expected = new List[] {
+ Arrays.asList("a", 0),
+ Arrays.asList("c", 1),
+ Arrays.asList("a", 0),
+ };
+
+ process(sql, expected);
+ }
+
+ @Test public void testTextTableMultiBatch() throws Exception {
+ String sql = "select x.* from (select * from pm1.g1 where e1 = 'c') y, texttable(e1 || '\n' || e2 || '\n' || e3 COLUMNS x string) x";
+
+ List[] expected = new List[] {
+ Arrays.asList("c"),
+ Arrays.asList("1"),
+ Arrays.asList("true"),
+ };
+
+ process(sql, expected);
+ }
+
+ public static void process(String sql, List[] expectedResults) throws Exception {
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+ helpProcess(plan, createCommandContext(), dataManager, expectedResults);
+ }
+
+ public static ClobType clobFromFile(final String file) {
+ return new ClobType(new ClobImpl(new InputStreamFactory.FileInputStreamFactory(UnitTestUtil.getTestDataFile(file)), -1));
+ }
+
+ @Test public void testTextAgg() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan("select convert(to_chars(textagg(for pm1.g1.e1, pm1.g1.e2 header order by e2), 'UTF-8'), string) as x from pm1.g1", metadata, null, capFinder, //$NON-NLS-1$
+ new String[] { "SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+
+ HardcodedDataManager hdm = new HardcodedDataManager();
+ hdm.addData("SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0", new List[] {Arrays.asList("z", 2), Arrays.asList("b", 1)});
+ hdm.setBlockOnce(true);
+
+ String nl = System.getProperty("line.separator");
+ ArrayList list = new ArrayList();
+ list.add("\"e1\",\"e2\""+nl+"\"b\",\"1\""+nl+"\"z\",\"2\""+nl);
+ List[] expected = new List[] {
+ list,
+ };
+
+ helpProcess(plan, hdm, expected);
+ }
+
+ @Test public void testTextAggOrderByUnrelated() throws Exception {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ BasicSourceCapabilities caps = getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
+ caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+ capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = helpPlan("select convert(to_chars(textagg(for pm1.g1.e1 header order by e2), 'UTF-8'), string) as x from pm1.g1", metadata, null, capFinder, //$NON-NLS-1$
+ new String[] { "SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+
+ HardcodedDataManager hdm = new HardcodedDataManager();
+ hdm.addData("SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0", new List[] {Arrays.asList("z", 2), Arrays.asList("b", 1)});
+ hdm.setBlockOnce(true);
+
+ String nl = System.getProperty("line.separator");
+ ArrayList list = new ArrayList();
+ list.add("\"e1\""+nl+"\"b\""+nl+"\"z\""+nl);
+ List[] expected = new List[] {
+ list,
+ };
+
+ helpProcess(plan, hdm, expected);
+ }
+
+ @Test(expected=TeiidProcessingException.class) public void testTextTableInvalidData() throws Exception {
+ String sql = "select count(*) from texttable(? COLUMNS PARTNAME string) x"; //$NON-NLS-1$
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ char[] data = new char[5000];
+ processPreparedStatement(sql, null, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(new ClobType(new SerialClob(data))));
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,768 +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;
-
-import static org.junit.Assert.*;
-
-import java.math.BigDecimal;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.TupleBuffer;
-import org.teiid.common.buffer.impl.BufferManagerImpl;
-import org.teiid.common.buffer.impl.MemoryStorageManager;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.mapping.relational.QueryNode;
-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.TimestampUtil;
-import org.teiid.query.util.CommandContext;
-import org.teiid.query.validator.TestValidator;
-
-
-public class TestVirtualDepJoin {
-
- /**
- * @param usAcctsElem
- * @param is
- * @param is2
- * @param object
- * @param object2
- * @since 4.3
- */
- private static void setStats(List 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();
- if(ndvs != null) {
- obj.putProperty(FakeMetadataObject.Props.DISTINCT_VALUES, new Integer(ndvs[i]));
- }
- if(nnvs != null) {
- obj.putProperty(FakeMetadataObject.Props.NULL_VALUES, new Integer(nnvs[i]));
- }
- if(mins != null) {
- obj.putProperty(FakeMetadataObject.Props.MIN_VALUE, mins[i]);
- }
- if(maxs != null) {
- obj.putProperty(FakeMetadataObject.Props.MAX_VALUE, 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,
- 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,
- new int[] { 1000, 1250, 4, 1000000, 800000}, // NDV per column
- new int[] { 0, 0, 0, 0, 0}, // NNV per column
- new String[] {"0", null, null, null, "-10"}, // min per column - use defaults //$NON-NLS-1$ //$NON-NLS-2$
- 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,
- 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,
- new int[] { 10000, 1000000, 4, 1000000, 750000}, // NDV per column
- new int[] { 0, 0, 0, 0, 0}, // NNV per column
- null, // min per column - use defaults
- 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,
- 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,
- new int[] { 1000, 800, 800, 365}, // NDV per column
- new int[] { 0, 0, 0, 0}, // NNV per column
- 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,
- new String[] { "id", "location" }, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.STRING });
- setStats(locationsElem,
- new int[] { 1000, 2}, // NDV per column
- new int[] { 0, 0, 0, 0}, // NNV per column
- null, // min per column - use defaults
- null // max per column - use defaults
- );
-
- FakeMetadataObject vAccts = FakeMetadataFactory.createVirtualModel("Accounts"); //$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,
- 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$
- 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,
- 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);
- }
-
- @Test public void testVirtualDepJoinNoValues() throws Exception {
- // Create query
- String sql = "select first, last, sum(amount) from Europe.CustAccts e join CustomerMaster.Customers c on c.id=e.id where c.first=-9999 group by c.id, first, last"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- };
-
- // Construct data manager with data
- FakeMetadataFacade metadata = exampleVirtualDepJoin();
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataVirtualDepJoin(dataManager, metadata);
-
- // Plan query
- CommandContext context = TestProcessor.createCommandContext();
-
- Command command = TestProcessor.helpParse(sql);
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- 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);
-
- TestOptimizer.checkDependentJoinCount(plan, 1);
- // Run query
- TestProcessor.helpProcess(plan, context, dataManager, expected);
-
- // Second query *will not be run* as no values were passed and dependent side has always false criteria
- // So, the list should contain only the first query
- assertEquals(3, dataManager.getQueries().size());
- }
-
- public void helpTestVirtualDepJoinSourceSelection(boolean setPushdown) throws Exception {
- // Create query
- String sql = "select c.id as CustomerID, First, Last, a.account_id as AccountID, transaction_id as TransactionID, txn_type AS TxnCode, Amount, source from (CustomerMaster.Customers c join CustomerMaster.Locations l on c.id=l.id) join Accounts.Accounts a on c.id=a.customer_id and l.location=a.source where c.first='Miles' order by accountid option makenotdep c, l"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1002), new Integer(1), new BigDecimal("7.20"), "EU" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1003), new Integer(2), new BigDecimal("1000.00"), "EU" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(123), new Integer(1), new BigDecimal("100.00"), "US" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(127), new Integer(2), new BigDecimal("250.00"), "US" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(128), new Integer(3), new BigDecimal("1000.00"), "US" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(134), new Integer(1), new BigDecimal("10.00"), "US" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(201), new Integer(1), new BigDecimal("10.00"), "US" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- };
-
- // Construct data manager with data
- FakeMetadataFacade metadata = exampleVirtualDepJoin();
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataVirtualDepJoin(dataManager, metadata);
-
- // Plan query
- CommandContext context = TestProcessor.createCommandContext();
-
- Command command = TestProcessor.helpParse(sql);
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
- caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, false);
- caps.setCapabilitySupport(Capability.CRITERIA_IN, setPushdown);
- 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);
-
- // Check plan contents
- int selectCount = !setPushdown ? 3 : 0;
- int accessCount = setPushdown ? 1 : 4;
- int depAccessCount = 4 - accessCount;
- TestOptimizer.checkNodeTypes(plan, new int[] {
- accessCount, // Access
- depAccessCount, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 3, // Project
- selectCount, // Select
- 1, // Sort
- 1 // UnionAll
- });
-
- // Run query
- TestProcessor.helpProcess(plan, context, dataManager, expected);
- }
-
- @Test public void testVirtualDepJoinSourceSelectionPushdown() throws Exception {
- helpTestVirtualDepJoinSourceSelection(true);
- }
-
- @Test public void testVirtualDepJoinSourceSelectionNoPushdown() throws Exception {
- helpTestVirtualDepJoinSourceSelection(false);
- }
-
- @Test public void testVirtualDepJoinPartialPushdown() throws Exception {
- // Create query
- String sql = "SELECT * from Master.Transactions where last = 'Davis'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(123), new Integer(1), new BigDecimal("100.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(127), new Integer(2), new BigDecimal("250.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(128), new Integer(3), new BigDecimal("1000.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(134), new Integer(1), new BigDecimal("10.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(201), new Integer(1), new BigDecimal("10.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1002), new Integer(1), new BigDecimal("7.20") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1003), new Integer(2), new BigDecimal("1000.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- };
-
- // Construct data manager with data
- FakeMetadataFacade metadata = exampleVirtualDepJoin();
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataVirtualDepJoin(dataManager, metadata);
-
- // Plan query
- CommandContext context = TestProcessor.createCommandContext();
-
- Command command = TestProcessor.helpParse(sql);
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps1 = TestOptimizer.getTypicalCapabilities();
- BasicSourceCapabilities caps2 = TestOptimizer.getTypicalCapabilities();
- caps2.setCapabilitySupport(Capability.CRITERIA_IN, false);
- 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);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 3, // Project
- 1, // Select
- 0, // Sort
- 1 // UnionAll
- });
-
- TestOptimizer.checkDependentJoinCount(plan, 1);
- // Run query
- TestProcessor.helpProcess(plan, context, dataManager, expected);
- }
-
- @Test public void testVirtualDepJoinOverAggregates() throws Exception {
- // Create query
- String sql = "select first, last, sum(amount) from Europe.CustAccts e join CustomerMaster.Customers c on c.id=e.id where c.first='Miles' group by c.id, first, last"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Miles", "Davis", new BigDecimal("1007.20") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- };
-
- // Construct data manager with data
- FakeMetadataFacade metadata = exampleVirtualDepJoin();
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataVirtualDepJoin(dataManager, metadata);
-
- // Plan query
- CommandContext context = TestProcessor.createCommandContext();
-
- Command command = TestProcessor.helpParse(sql);
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- 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);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // 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
- });
-
- TestOptimizer.checkDependentJoinCount(plan, 1);
- // Run query
- TestProcessor.helpProcess(plan, context, dataManager, expected);
-
- 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$
- }
-
- assertEquals(expectedQueries, dataManager.getQueries());
- }
-
- @Test public void testVirtualDepJoinSelects() throws Exception {
- helpTestVirtualDepJoin(false);
- }
-
- @Test public void testVirtualDepJoinPushdown() throws Exception {
- helpTestVirtualDepJoin(true);
- }
-
- @Test public void testVirtualDepMultipleDependentBatches() throws Exception {
- helpTestMultipleBatches(true);
- }
-
- @Test public void testVirtualDepMultipleDependentBatchesNonUnique() throws Exception {
- helpTestMultipleBatches(false);
- }
-
- private void helpTestMultipleBatches(boolean unique) throws Exception,
- TeiidComponentException,
- TeiidException,
- SQLException {
- // Create query
- String sql = "SELECT * from Master.Transactions where last = 'Davis' order by CustomerID, TransactionID"; //$NON-NLS-1$
-
- List expected = new LinkedList();
-
-
- // Create expected results
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(123), new Integer(1), new BigDecimal("100.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (!unique) {
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(123), new Integer(1), new BigDecimal("100.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(127), new Integer(2), new BigDecimal("250.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (!unique) {
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(127), new Integer(2), new BigDecimal("250.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(128), new Integer(3), new BigDecimal("1000.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (!unique) {
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(128), new Integer(3), new BigDecimal("1000.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(134), new Integer(1), new BigDecimal("10.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (!unique) {
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(134), new Integer(1), new BigDecimal("10.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(201), new Integer(1), new BigDecimal("10.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (!unique) {
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(201), new Integer(1), new BigDecimal("10.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1002), new Integer(1), new BigDecimal("7.20") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (!unique) {
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1002), new Integer(1), new BigDecimal("7.20") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1003), new Integer(2), new BigDecimal("1000.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (!unique) {
- expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1003), new Integer(2), new BigDecimal("1000.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- expected.add(Arrays.asList(new Object[] { new Long(200), "CloneA", "Davis", new Long(16000), new Long(207), new Integer(3), new BigDecimal("12.34") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- expected.add(Arrays.asList(new Object[] { new Long(200), "CloneA", "Davis", new Long(16000), new Long(299), new Integer(3), new BigDecimal("950.34") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- expected.add(Arrays.asList(new Object[] { new Long(200), "CloneA", "Davis", new Long(550), new Long(1004), new Integer(3), new BigDecimal("542.20") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- expected.add(Arrays.asList(new Object[] { new Long(200), "CloneA", "Davis", new Long(550), new Long(1005), new Integer(1), new BigDecimal("99.99") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- expected.add(Arrays.asList(new Object[] { new Long(300), "CloneB", "Davis", new Long(620), new Long(1006), new Integer(1), new BigDecimal("10000.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- expected.add(Arrays.asList(new Object[] { new Long(300), "CloneB", "Davis", new Long(620), new Long(1007), new Integer(2), new BigDecimal("0.75") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- 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();
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataVirtualDepJoin(dataManager, metadata);
- overrideVirtualDepJoinData(dataManager, metadata, unique);
-
- // Plan query
- CommandContext context = TestProcessor.createCommandContext();
-
- Command command = TestProcessor.helpParse(sql);
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
- 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);
-
- // Run query
- BufferManager bufferMgr = createCustomBufferMgr(2);
- QueryProcessor processor = new QueryProcessor(plan, context, bufferMgr, dataManager);
- processor.setNonBlocking(true);
- BatchCollector collector = processor.createBatchCollector();
- TupleBuffer id = collector.collectTuples();
-
- TestProcessor.examineResults((List[])expected.toArray(new List[expected.size()]), bufferMgr, id);
- }
-
- private BufferManager createCustomBufferMgr(int batchSize) throws TeiidComponentException {
- BufferManagerImpl bufferMgr = new BufferManagerImpl();
- bufferMgr.setConnectorBatchSize(batchSize);
- bufferMgr.setProcessorBatchSize(batchSize);
- bufferMgr.initialize();
-
- // Add unmanaged memory storage manager
- bufferMgr.setStorageManager(new MemoryStorageManager());
-
- return bufferMgr;
- }
-
- public void helpTestVirtualDepJoin(boolean pushCriteria) throws Exception {
- // Create query
- String sql = "SELECT * from Master.Transactions where last = 'Davis'"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(123), new Integer(1), new BigDecimal("100.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(127), new Integer(2), new BigDecimal("250.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(128), new Integer(3), new BigDecimal("1000.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(134), new Integer(1), new BigDecimal("10.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(201), new Integer(1), new BigDecimal("10.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1002), new Integer(1), new BigDecimal("7.20") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1003), new Integer(2), new BigDecimal("1000.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- };
-
- // Construct data manager with data
- FakeMetadataFacade metadata = exampleVirtualDepJoin();
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataVirtualDepJoin(dataManager, metadata);
-
- // Plan query
- Command command = TestProcessor.helpParse(sql);
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setCapabilitySupport(Capability.CRITERIA_IN, pushCriteria);
- 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);
-
- // Run query
- CommandContext context = TestProcessor.createCommandContext();
- TestProcessor.helpProcess(plan, context, dataManager, expected);
- }
-
- private void sampleDataVirtualDepJoin(FakeDataManager dataMgr, FakeMetadataFacade 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$
- } );
-
- // 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$
- } );
-
- // 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$
- } );
-
- // 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$
- } );
- }
-
- private void overrideVirtualDepJoinData(FakeDataManager dataMgr, FakeMetadataFacade 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);
-
- 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$
- 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(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$
-
- dataMgr.registerTuples(
- groupID,
- elementSymbols, (List[])data.toArray(new List[data.size()]));
- }
-
- @Test public void testVirtualAccessVirtualDep() throws Exception {
- String sql = "SELECT a.e0, b.e2 FROM vTest.vGroup a inner join vTest.vGroup b on (a.e0 = b.e2 and a.e1 = b.e2) where b.e0=1 and b.e1='2'"; //$NON-NLS-1$
-
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- finder.addCapabilities("test", caps); //$NON-NLS-1$
-
- ProcessorPlan plan = TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, finder,
- new String[] {"SELECT g_0.e2 AS c_0 FROM test.\"group\" AS g_0 WHERE (g_0.e0 = 1) AND (g_0.e1 = '2') ORDER BY c_0", //$NON-NLS-1$
- "SELECT g_0.e0 AS c_0, g_0.e1 AS c_1, g_0.e0 AS c_2 FROM test.\"group\" AS g_0 WHERE (g_0.e0 IN (<dependent values>)) AND (g_0.e1 IN (<dependent values>)) ORDER BY c_2, c_1"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 1, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
- }
-
- /**
- * Here the virtual makenotdep hint causes us to throw an exception
- *
- */
- @Test public void testVirtualAccessVirtualDep2() {
- String sql = "SELECT a.e0, b.e2 FROM vTest.vGroup a makenotdep inner join vTest.vGroup b on (a.e0 = b.e2 and a.e1 = b.e2) where b.e0=1 and b.e1='2'"; //$NON-NLS-1$
-
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- finder.addCapabilities("test", caps); //$NON-NLS-1$
-
- TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, finder,
- new String[] {}, TestOptimizer.SHOULD_FAIL);
-
- }
-
- /**
- * same as testVirtualDepJoinOverAggregate, but the makenotdep hint prevents the
- * dependent join from happening
- */
- @Test public void testVirtualDepJoinOverAggregates2() throws Exception {
- // Create query
- String sql = "select first, last, sum(amount) from Europe.CustAccts e makenotdep join CustomerMaster.Customers c on c.id=e.id where c.first='Miles' group by c.id, first, last"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Miles", "Davis", new BigDecimal("1007.20") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- };
-
- // Construct data manager with data
- FakeMetadataFacade metadata = exampleVirtualDepJoin();
- FakeDataManager dataManager = new FakeDataManager();
- sampleDataVirtualDepJoin(dataManager, metadata);
-
- // Plan query
- CommandContext context = TestProcessor.createCommandContext();
-
- Command command = TestProcessor.helpParse(sql);
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
- 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);
-
- 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
- });
-
- TestOptimizer.checkDependentJoinCount(plan, 0);
- // Run query
- TestProcessor.helpProcess(plan, context, dataManager, expected);
- }
-
-
- @Test public void testVirtualMakeDepHint() throws Exception {
- // Create query
- String sql = "select distinct pm1.g1.e1 from (pm1.g1 inner join pm1.g2 on g1.e1 = g2.e1) makedep inner join pm2.g1 on pm2.g1.e1 = pm1.g1.e1 where pm2.g1.e3 = 1"; //$NON-NLS-1$
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
- };
-
- // Construct data manager with data
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = TestProcessor.helpGetPlan(sql, metadata);
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 3, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 1, // DupRemove
- 0, // Grouping
- 0, // NestedLoopJoinStrategy
- 2, // MergeJoinStrategy
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 2, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- TestOptimizer.checkDependentJoinCount(plan, 1);
- // Run query
- TestProcessor.helpProcess(plan, new CommandContext(), dataManager, expected);
- }
-
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,711 @@
+/*
+ * 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.junit.Assert.*;
+
+import java.math.BigDecimal;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.common.buffer.impl.BufferManagerImpl;
+import org.teiid.common.buffer.impl.MemoryStorageManager;
+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.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 {
+
+ /**
+ * @param usAcctsElem
+ * @param is
+ * @param is2
+ * @param object
+ * @param object2
+ * @since 4.3
+ */
+ private static void setStats(List<Column> elementObjects,
+ int[] ndvs,
+ int[] nnvs,
+ String[] mins,
+ String[] maxs) {
+ for (int i = 0; i < elementObjects.size(); i++) {
+ Column obj = elementObjects.get(i);
+ if(ndvs != null) {
+ obj.setDistinctValues(ndvs[i]);
+ }
+ if(nnvs != null) {
+ obj.setNullValues(nnvs[i]);
+ }
+ if(mins != null) {
+ obj.setMinimumValue(mins[i]);
+ }
+ if(maxs != null) {
+ obj.setMaximumValue(maxs[i]);
+ }
+ }
+ }
+
+ 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,
+ new int[] { 1000, 1250, 4, 1000000, 800000}, // NDV per column
+ new int[] { 0, 0, 0, 0, 0}, // NNV per column
+ new String[] {"0", null, null, null, "-10"}, // min per column - use defaults //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] {"1000", null, null, null, "-5"} // max per column - use defaults //$NON-NLS-1$ //$NON-NLS-2$
+ );
+
+ 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,
+ new int[] { 10000, 1000000, 4, 1000000, 750000}, // NDV per column
+ new int[] { 0, 0, 0, 0, 0}, // NNV per column
+ null, // min per column - use defaults
+ null // max per column - use defaults
+ );
+
+ 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,
+ new int[] { 1000, 800, 800, 365}, // NDV per column
+ new int[] { 0, 0, 0, 0}, // NNV per column
+ null, // min per column - use defaults
+ null // max per column - use defaults
+ );
+ 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,
+ new int[] { 1000, 2}, // NDV per column
+ new int[] { 0, 0, 0, 0}, // NNV per column
+ null, // min per column - use defaults
+ null // max per column - use defaults
+ );
+
+ 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$
+ 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 });
+
+ 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$
+ 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 });
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "virtualDepJoin");
+ }
+
+ @Test public void testVirtualDepJoinNoValues() throws Exception {
+ // Create query
+ String sql = "select first, last, sum(amount) from Europe.CustAccts e join CustomerMaster.Customers c on c.id=e.id where c.first=-9999 group by c.id, first, last"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ };
+
+ // Construct data manager with data
+ QueryMetadataInterface metadata = exampleVirtualDepJoin();
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataVirtualDepJoin(dataManager, metadata);
+
+ // Plan query
+ CommandContext context = TestProcessor.createCommandContext();
+
+ Command command = TestProcessor.helpParse(sql);
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ 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, metadata, finder, context);
+
+ TestOptimizer.checkDependentJoinCount(plan, 1);
+ // Run query
+ TestProcessor.helpProcess(plan, context, dataManager, expected);
+
+ // Second query *will not be run* as no values were passed and dependent side has always false criteria
+ // So, the list should contain only the first query
+ assertEquals(3, dataManager.getQueries().size());
+ }
+
+ public void helpTestVirtualDepJoinSourceSelection(boolean setPushdown) throws Exception {
+ // Create query
+ String sql = "select c.id as CustomerID, First, Last, a.account_id as AccountID, transaction_id as TransactionID, txn_type AS TxnCode, Amount, source from (CustomerMaster.Customers c join CustomerMaster.Locations l on c.id=l.id) join Accounts.Accounts a on c.id=a.customer_id and l.location=a.source where c.first='Miles' order by accountid option makenotdep c, l"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1002), new Integer(1), new BigDecimal("7.20"), "EU" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1003), new Integer(2), new BigDecimal("1000.00"), "EU" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(123), new Integer(1), new BigDecimal("100.00"), "US" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(127), new Integer(2), new BigDecimal("250.00"), "US" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(128), new Integer(3), new BigDecimal("1000.00"), "US" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(134), new Integer(1), new BigDecimal("10.00"), "US" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(201), new Integer(1), new BigDecimal("10.00"), "US" }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ };
+
+ // Construct data manager with data
+ QueryMetadataInterface metadata = exampleVirtualDepJoin();
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataVirtualDepJoin(dataManager, metadata);
+
+ // Plan query
+ CommandContext context = TestProcessor.createCommandContext();
+
+ Command command = TestProcessor.helpParse(sql);
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, false);
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, setPushdown);
+ 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, metadata, finder, context);
+
+ // Check plan contents
+ int selectCount = !setPushdown ? 3 : 0;
+ int accessCount = setPushdown ? 1 : 4;
+ int depAccessCount = 4 - accessCount;
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ accessCount, // Access
+ depAccessCount, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 3, // Project
+ selectCount, // Select
+ 1, // Sort
+ 1 // UnionAll
+ });
+
+ // Run query
+ TestProcessor.helpProcess(plan, context, dataManager, expected);
+ }
+
+ @Test public void testVirtualDepJoinSourceSelectionPushdown() throws Exception {
+ helpTestVirtualDepJoinSourceSelection(true);
+ }
+
+ @Test public void testVirtualDepJoinSourceSelectionNoPushdown() throws Exception {
+ helpTestVirtualDepJoinSourceSelection(false);
+ }
+
+ @Test public void testVirtualDepJoinPartialPushdown() throws Exception {
+ // Create query
+ String sql = "SELECT * from Master.Transactions where last = 'Davis'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(123), new Integer(1), new BigDecimal("100.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(127), new Integer(2), new BigDecimal("250.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(128), new Integer(3), new BigDecimal("1000.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(134), new Integer(1), new BigDecimal("10.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(201), new Integer(1), new BigDecimal("10.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1002), new Integer(1), new BigDecimal("7.20") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1003), new Integer(2), new BigDecimal("1000.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ };
+
+ // Construct data manager with data
+ QueryMetadataInterface metadata = exampleVirtualDepJoin();
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataVirtualDepJoin(dataManager, metadata);
+
+ // Plan query
+ CommandContext context = TestProcessor.createCommandContext();
+
+ Command command = TestProcessor.helpParse(sql);
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps1 = TestOptimizer.getTypicalCapabilities();
+ BasicSourceCapabilities caps2 = TestOptimizer.getTypicalCapabilities();
+ caps2.setCapabilitySupport(Capability.CRITERIA_IN, false);
+ 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, metadata, finder, context);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 3, // Project
+ 1, // Select
+ 0, // Sort
+ 1 // UnionAll
+ });
+
+ TestOptimizer.checkDependentJoinCount(plan, 1);
+ // Run query
+ TestProcessor.helpProcess(plan, context, dataManager, expected);
+ }
+
+ @Test public void testVirtualDepJoinOverAggregates() throws Exception {
+ // Create query
+ String sql = "select first, last, sum(amount) from Europe.CustAccts e join CustomerMaster.Customers c on c.id=e.id where c.first='Miles' group by c.id, first, last"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "Miles", "Davis", new BigDecimal("1007.20") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ };
+
+ // Construct data manager with data
+ QueryMetadataInterface metadata = exampleVirtualDepJoin();
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataVirtualDepJoin(dataManager, metadata);
+
+ // Plan query
+ CommandContext context = TestProcessor.createCommandContext();
+
+ Command command = TestProcessor.helpParse(sql);
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ 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, metadata, finder, context);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // 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
+ });
+
+ TestOptimizer.checkDependentJoinCount(plan, 1);
+ // Run query
+ TestProcessor.helpProcess(plan, context, dataManager, expected);
+
+ 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$
+ }
+
+ assertEquals(expectedQueries, dataManager.getQueries());
+ }
+
+ @Test public void testVirtualDepJoinSelects() throws Exception {
+ helpTestVirtualDepJoin(false);
+ }
+
+ @Test public void testVirtualDepJoinPushdown() throws Exception {
+ helpTestVirtualDepJoin(true);
+ }
+
+ @Test public void testVirtualDepMultipleDependentBatches() throws Exception {
+ helpTestMultipleBatches(true);
+ }
+
+ @Test public void testVirtualDepMultipleDependentBatchesNonUnique() throws Exception {
+ helpTestMultipleBatches(false);
+ }
+
+ private void helpTestMultipleBatches(boolean unique) throws Exception,
+ TeiidComponentException,
+ TeiidException,
+ SQLException {
+ // Create query
+ String sql = "SELECT * from Master.Transactions where last = 'Davis' order by CustomerID, TransactionID"; //$NON-NLS-1$
+
+ List<List<Object>> expected = new LinkedList<List<Object>>();
+
+
+ // Create expected results
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(123), new Integer(1), new BigDecimal("100.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ if (!unique) {
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(123), new Integer(1), new BigDecimal("100.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(127), new Integer(2), new BigDecimal("250.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ if (!unique) {
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(127), new Integer(2), new BigDecimal("250.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(128), new Integer(3), new BigDecimal("1000.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ if (!unique) {
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(128), new Integer(3), new BigDecimal("1000.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(134), new Integer(1), new BigDecimal("10.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ if (!unique) {
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(134), new Integer(1), new BigDecimal("10.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(201), new Integer(1), new BigDecimal("10.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ if (!unique) {
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(201), new Integer(1), new BigDecimal("10.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1002), new Integer(1), new BigDecimal("7.20") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ if (!unique) {
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1002), new Integer(1), new BigDecimal("7.20") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1003), new Integer(2), new BigDecimal("1000.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ if (!unique) {
+ expected.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1003), new Integer(2), new BigDecimal("1000.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ expected.add(Arrays.asList(new Object[] { new Long(200), "CloneA", "Davis", new Long(16000), new Long(207), new Integer(3), new BigDecimal("12.34") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ expected.add(Arrays.asList(new Object[] { new Long(200), "CloneA", "Davis", new Long(16000), new Long(299), new Integer(3), new BigDecimal("950.34") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ expected.add(Arrays.asList(new Object[] { new Long(200), "CloneA", "Davis", new Long(550), new Long(1004), new Integer(3), new BigDecimal("542.20") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ expected.add(Arrays.asList(new Object[] { new Long(200), "CloneA", "Davis", new Long(550), new Long(1005), new Integer(1), new BigDecimal("99.99") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ expected.add(Arrays.asList(new Object[] { new Long(300), "CloneB", "Davis", new Long(620), new Long(1006), new Integer(1), new BigDecimal("10000.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ expected.add(Arrays.asList(new Object[] { new Long(300), "CloneB", "Davis", new Long(620), new Long(1007), new Integer(2), new BigDecimal("0.75") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ 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
+ QueryMetadataInterface metadata = exampleVirtualDepJoin();
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataVirtualDepJoin(dataManager, metadata);
+ overrideVirtualDepJoinData(dataManager, metadata, unique);
+
+ // Plan query
+ CommandContext context = TestProcessor.createCommandContext();
+
+ Command command = TestProcessor.helpParse(sql);
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1));
+ 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, metadata, finder, context);
+
+ // Run query
+ BufferManager bufferMgr = createCustomBufferMgr(2);
+ QueryProcessor processor = new QueryProcessor(plan, context, bufferMgr, dataManager);
+ processor.setNonBlocking(true);
+ BatchCollector collector = processor.createBatchCollector();
+ TupleBuffer id = collector.collectTuples();
+
+ TestProcessor.examineResults((List[])expected.toArray(new List[expected.size()]), bufferMgr, id);
+ }
+
+ private BufferManager createCustomBufferMgr(int batchSize) throws TeiidComponentException {
+ BufferManagerImpl bufferMgr = new BufferManagerImpl();
+ bufferMgr.setConnectorBatchSize(batchSize);
+ bufferMgr.setProcessorBatchSize(batchSize);
+ bufferMgr.initialize();
+
+ // Add unmanaged memory storage manager
+ bufferMgr.setStorageManager(new MemoryStorageManager());
+
+ return bufferMgr;
+ }
+
+ public void helpTestVirtualDepJoin(boolean pushCriteria) throws Exception {
+ // Create query
+ String sql = "SELECT * from Master.Transactions where last = 'Davis'"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(123), new Integer(1), new BigDecimal("100.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(127), new Integer(2), new BigDecimal("250.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15000), new Long(128), new Integer(3), new BigDecimal("1000.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(134), new Integer(1), new BigDecimal("10.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(15001), new Long(201), new Integer(1), new BigDecimal("10.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1002), new Integer(1), new BigDecimal("7.20") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", new Long(540), new Long(1003), new Integer(2), new BigDecimal("1000.00") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ };
+
+ // Construct data manager with data
+ QueryMetadataInterface metadata = exampleVirtualDepJoin();
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataVirtualDepJoin(dataManager, metadata);
+
+ // Plan query
+ Command command = TestProcessor.helpParse(sql);
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setCapabilitySupport(Capability.CRITERIA_IN, pushCriteria);
+ 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, metadata, finder);
+
+ // Run query
+ CommandContext context = TestProcessor.createCommandContext();
+ TestProcessor.helpProcess(plan, context, dataManager, expected);
+ }
+
+ private void sampleDataVirtualDepJoin(FakeDataManager dataMgr, QueryMetadataInterface metadata) throws Exception {
+ dataMgr.setBlockOnce();
+
+ dataMgr.registerTuples(
+ 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$
+ } );
+
+ dataMgr.registerTuples(
+ 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$
+ } );
+
+ 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$
+ } );
+
+ 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, QueryMetadataInterface metadata, boolean unique) throws Exception {
+ // Group CustomerMaster.Customers
+ List<List<?>> data = new LinkedList<List<?>>();
+
+ 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", TimestampUtil.createDate(1926, 4, 25) })); //$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(
+ metadata,
+ "CustomerMaster.Customers", (List[])data.toArray(new List[data.size()]));
+ }
+
+ @Test public void testVirtualAccessVirtualDep() throws Exception {
+ String sql = "SELECT a.e0, b.e2 FROM vTest.vGroup a inner join vTest.vGroup b on (a.e0 = b.e2 and a.e1 = b.e2) where b.e0=1 and b.e1='2'"; //$NON-NLS-1$
+
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ finder.addCapabilities("test", caps); //$NON-NLS-1$
+
+ ProcessorPlan plan = TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, finder,
+ new String[] {"SELECT g_0.e2 AS c_0 FROM test.\"group\" AS g_0 WHERE (g_0.e0 = 1) AND (g_0.e1 = '2') ORDER BY c_0", //$NON-NLS-1$
+ "SELECT g_0.e0 AS c_0, g_0.e1 AS c_1, g_0.e0 AS c_2 FROM test.\"group\" AS g_0 WHERE (g_0.e0 IN (<dependent values>)) AND (g_0.e1 IN (<dependent values>)) ORDER BY c_2, c_1"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 1, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+ }
+
+ /**
+ * Here the virtual makenotdep hint causes us to throw an exception
+ *
+ */
+ @Test public void testVirtualAccessVirtualDep2() {
+ String sql = "SELECT a.e0, b.e2 FROM vTest.vGroup a makenotdep inner join vTest.vGroup b on (a.e0 = b.e2 and a.e1 = b.e2) where b.e0=1 and b.e1='2'"; //$NON-NLS-1$
+
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ finder.addCapabilities("test", caps); //$NON-NLS-1$
+
+ TestOptimizer.helpPlan(sql, TestValidator.exampleMetadata4(), null, finder,
+ new String[] {}, TestOptimizer.SHOULD_FAIL);
+
+ }
+
+ /**
+ * same as testVirtualDepJoinOverAggregate, but the makenotdep hint prevents the
+ * dependent join from happening
+ */
+ @Test public void testVirtualDepJoinOverAggregates2() throws Exception {
+ // Create query
+ String sql = "select first, last, sum(amount) from Europe.CustAccts e makenotdep join CustomerMaster.Customers c on c.id=e.id where c.first='Miles' group by c.id, first, last"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "Miles", "Davis", new BigDecimal("1007.20") }), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ };
+
+ // Construct data manager with data
+ QueryMetadataInterface metadata = exampleVirtualDepJoin();
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleDataVirtualDepJoin(dataManager, metadata);
+
+ // Plan query
+ CommandContext context = TestProcessor.createCommandContext();
+
+ Command command = TestProcessor.helpParse(sql);
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+ 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, metadata, finder, context);
+
+ 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
+ });
+
+ TestOptimizer.checkDependentJoinCount(plan, 0);
+ // Run query
+ TestProcessor.helpProcess(plan, context, dataManager, expected);
+ }
+
+
+ @Test public void testVirtualMakeDepHint() throws Exception {
+ // Create query
+ String sql = "select distinct pm1.g1.e1 from (pm1.g1 inner join pm1.g2 on g1.e1 = g2.e1) makedep inner join pm2.g1 on pm2.g1.e1 = pm1.g1.e1 where pm2.g1.e3 = 1"; //$NON-NLS-1$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "c" }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = TestProcessor.helpGetPlan(sql, metadata);
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 3, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 1, // DupRemove
+ 0, // Grouping
+ 0, // NestedLoopJoinStrategy
+ 2, // MergeJoinStrategy
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 2, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ TestOptimizer.checkDependentJoinCount(plan, 1);
+ // Run query
+ TestProcessor.helpProcess(plan, new CommandContext(), dataManager, expected);
+ }
+
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,73 +0,0 @@
-package org.teiid.query.processor;
-
-import static org.teiid.query.processor.TestProcessor.*;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.core.TeiidException;
-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.FakeCapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
- at SuppressWarnings({"nls", "unchecked"})
-public class TestWithClauseProcessing {
-
- @Test public void testSingleItem() {
- String sql = "with a (x, y, z) as (select e1, e2, e3 from pm1.g1) SELECT pm1.g2.e2, a.x from pm1.g2, a where e1 = x and z = 1 order by x"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList(0, "a"),
- Arrays.asList(3, "a"),
- Arrays.asList(0, "a"),
- Arrays.asList(1, "c"),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testMultipleItems() {
- String sql = "with a (x, y, z) as (select e1, e2, e3 from pm1.g1), b as (SELECT * from pm1.g2, a where e1 = x and z = 1 order by e2 limit 2) SELECT a.x, b.e1 from a, b where a.x = b.e1"; //$NON-NLS-1$
-
- List[] expected = new List[] {
- Arrays.asList("a", "a"),
- Arrays.asList("a", "a"),
- Arrays.asList("a", "a"),
- Arrays.asList("a", "a"),
- Arrays.asList("a", "a"),
- Arrays.asList("a", "a"),
- };
-
- FakeDataManager dataManager = new FakeDataManager();
- sampleData1(dataManager);
-
- ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
-
- helpProcess(plan, dataManager, expected);
- }
-
- @Test public void testWithPushdown() 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, z) as (select e1, e2, e3 from pm1.g1) SELECT a.x from a, a z"; //$NON-NLS-1$
-
- 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);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,88 @@
+package org.teiid.query.processor;
+
+import static org.teiid.query.processor.TestProcessor.*;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.core.TeiidException;
+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.FakeCapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+ at SuppressWarnings({"nls", "unchecked"})
+public class TestWithClauseProcessing {
+
+ @Test public void testSingleItem() {
+ String sql = "with a (x, y, z) as (select e1, e2, e3 from pm1.g1) SELECT pm1.g2.e2, a.x from pm1.g2, a where e1 = x and z = 1 order by x"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(0, "a"),
+ Arrays.asList(3, "a"),
+ Arrays.asList(0, "a"),
+ Arrays.asList(1, "c"),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testMultipleItems() {
+ String sql = "with a (x, y, z) as (select e1, e2, e3 from pm1.g1), b as (SELECT * from pm1.g2, a where e1 = x and z = 1 order by e2 limit 2) SELECT a.x, b.e1 from a, b where a.x = b.e1"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("a", "a"),
+ Arrays.asList("a", "a"),
+ Arrays.asList("a", "a"),
+ Arrays.asList("a", "a"),
+ Arrays.asList("a", "a"),
+ Arrays.asList("a", "a"),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testWithPushdown() 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, z) as (select e1, e2, e3 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, 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);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/eval/TestExpressionEvaluator.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/eval/TestExpressionEvaluator.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/eval/TestExpressionEvaluator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,435 +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.eval;
-
-import static org.junit.Assert.*;
-
-import java.io.Serializable;
-import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.junit.Test;
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.eval.Evaluator;
-import org.teiid.query.function.FunctionDescriptor;
-import org.teiid.query.processor.FakeDataManager;
-import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.resolver.TestFunctionResolving;
-import org.teiid.query.sql.lang.CollectionValueIterator;
-import org.teiid.query.sql.lang.IsNullCriteria;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.SubqueryContainer;
-import org.teiid.query.sql.symbol.CaseExpression;
-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.sql.symbol.ScalarSubquery;
-import org.teiid.query.sql.symbol.SearchedCaseExpression;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-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.util.CommandContext;
-
- at SuppressWarnings("nls")
-public class TestExpressionEvaluator {
-
- public void helpTestEval(Expression expr, SingleElementSymbol[] elementList, Object[] valueList, ProcessorDataManager dataMgr, CommandContext context, Object expectedValue) {
- try {
- Object actualValue = helpEval(expr, elementList, valueList, dataMgr, context);
- assertEquals("Did not get expected result", expectedValue, actualValue); //$NON-NLS-1$
- } catch(TeiidException e) {
- fail("Received unexpected exception: " + e.getFullMessage()); //$NON-NLS-1$
- }
- }
-
- public Object helpEval(Expression expr, SingleElementSymbol[] elementList, Object[] valueList, ProcessorDataManager dataMgr, CommandContext context) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
- Map elements = new HashMap();
- if (elementList != null) {
- for(int i=0; i<elementList.length; i++) {
- elements.put(elementList[i], new Integer(i));
- }
- }
-
- List tuple = new ArrayList();
- if (valueList != null) {
- for(int i=0; i<valueList.length; i++) {
- tuple.add(valueList[i]);
- }
- }
- return new Evaluator(elements, dataMgr, context).evaluate(expr, tuple);
- }
-
- @Test public void testCaseExpression1() {
- CaseExpression expr = TestCaseExpression.example(3);
- expr.setExpression(new Constant("a")); //$NON-NLS-1$
- helpTestEval(expr, null, null, null, null, new Integer(0));
- expr.setExpression(new Constant("b")); //$NON-NLS-1$
- helpTestEval(expr, null, null, null, null, new Integer(1));
- expr.setExpression(new Constant("c")); //$NON-NLS-1$
- helpTestEval(expr, null, null, null, null, new Integer(2));
- expr.setExpression(new Constant("d")); //$NON-NLS-1$
- helpTestEval(expr, null, null, null, null, new Integer(9999));
- }
-
- @Test public void testSearchedCaseExpression1() {
- SearchedCaseExpression expr = TestSearchedCaseExpression.example(3);
- helpTestEval(expr,
- new SingleElementSymbol[] {new ElementSymbol("x")}, //$NON-NLS-1$
- new Object[] {new Integer(0)},
- null,
- null,
- new Integer(0));
- helpTestEval(expr,
- new SingleElementSymbol[] {new ElementSymbol("x")}, //$NON-NLS-1$
- new Object[] {new Integer(1)},
- null,
- null,
- new Integer(1));
- helpTestEval(expr,
- new SingleElementSymbol[] {new ElementSymbol("x")}, //$NON-NLS-1$
- new Object[] {new Integer(2)},
- null,
- null,
- new Integer(2));
- helpTestEval(expr,
- new SingleElementSymbol[] {new ElementSymbol("x")}, //$NON-NLS-1$
- new Object[] {new Integer(3)},
- null,
- null,
- new Integer(9999));
- }
-
- @Test public void testConstant() {
- helpTestEval(new Constant("xyz", String.class), new SingleElementSymbol[0], new Object[0], null, null, "xyz"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testElement1() {
- ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
- ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
-
- SingleElementSymbol[] elements = new SingleElementSymbol[] {
- e1, e2
- };
-
- Object[] values = new Object[] {
- "xyz", "abc" //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- helpTestEval(e1, elements, values, null, null, "xyz"); //$NON-NLS-1$
- }
-
- @Test public void testElement2() {
- ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
- ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
-
- SingleElementSymbol[] elements = new SingleElementSymbol[] {
- e1, e2
- };
-
- Object[] values = new Object[] {
- "xyz", "abc" //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- helpTestEval(e2, elements, values, null, null, "abc"); //$NON-NLS-1$
- }
-
- /**
- * Element Symbols must have values set during evaluation
- */
- @Test public void testElement3() throws Exception {
- ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
-
- SingleElementSymbol[] elements = new SingleElementSymbol[] {};
-
- Object[] values = new Object[] {
- "xyz", "abc" //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- try {
- helpEval(e2, elements, values, null, null);
- fail("Exception expected"); //$NON-NLS-1$
- } catch (TeiidComponentException e){
- //this should be a componentexception, since it is unexpected
- assertEquals(e.getMessage(), "Error Code:ERR.015.006.0033 Message:Unable to evaluate e2: No value was available"); //$NON-NLS-1$
- }
- }
-
- @Test public void testFunction1() {
- ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
- e1.setType(String.class);
- ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
- 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$
- func.setFunctionDescriptor(desc);
-
- SingleElementSymbol[] elements = new SingleElementSymbol[] {
- e1, e2
- };
-
- Object[] values = new Object[] {
- "xyz", "abc" //$NON-NLS-1$ //$NON-NLS-2$
- };
-
-
- helpTestEval(func, elements, values, null, null, "xyzabc"); //$NON-NLS-1$
- }
-
- @Test public void testFunction2() {
- ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
- e1.setType(String.class);
- ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
- 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$
- func.setFunctionDescriptor(desc);
-
- SingleElementSymbol[] elements = new SingleElementSymbol[] {
- e1, e2
- };
-
- Object[] values = new Object[] {
- "xyz", "abc" //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- helpTestEval(func, elements, values, null, null, "abcxyz"); //$NON-NLS-1$
- }
-
- @Test public void testLookupFunction() {
- ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
- e1.setType(String.class);
- ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
- 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$
- func.setFunctionDescriptor(desc);
-
- SingleElementSymbol[] elements = new SingleElementSymbol[] {
- e1, e2
- };
-
- Object[] values = new Object[] {
- "xyz", new Integer(5) //$NON-NLS-1$
- };
-
- FakeDataManager dataMgr = new FakeDataManager();
- Map valueMap = new HashMap();
- valueMap.put("xyz", new Integer(5)); //$NON-NLS-1$
- dataMgr.defineCodeTable("pm1.g1", "e1", "e2", valueMap); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- helpTestEval(func, elements, values, dataMgr, null, new Integer(5));
- }
-
- @Test public void testScalarSubquery() throws Exception{
- ScalarSubquery expr = new ScalarSubquery(new Query());
- ArrayList values = new ArrayList(1);
- values.add("a"); //$NON-NLS-1$
- Object expected = "a"; //$NON-NLS-1$
- helpTestWithValueIterator(expr, values, expected);
- }
-
- private void helpTestWithValueIterator(ScalarSubquery expr,
- List<?> values, Object expected)
- throws BlockedException,
- TeiidComponentException, ExpressionEvaluationException {
- final CollectionValueIterator valueIter = new CollectionValueIterator(values);
- CommandContext cc = new CommandContext();
- assertEquals(expected, new Evaluator(Collections.emptyMap(), null, cc) {
- @Override
- protected ValueIterator evaluateSubquery(
- SubqueryContainer container, List tuple)
- throws TeiidProcessingException, BlockedException,
- TeiidComponentException {
- return valueIter;
- }
- }.evaluate(expr, null) );
- }
-
- @Test public void testScalarSubquery2() throws Exception{
- ScalarSubquery expr = new ScalarSubquery(new Query());
- ArrayList values = new ArrayList(1);
- values.add(null);
- helpTestWithValueIterator(expr, values, null);
- }
-
- @Test public void testScalarSubquery3() throws Exception{
- ScalarSubquery expr = new ScalarSubquery(new Query());
- helpTestWithValueIterator(expr, Collections.emptyList(), null);
- }
-
- @Test public void testScalarSubqueryFails() throws Exception{
- ScalarSubquery expr = new ScalarSubquery(new Query());
- ArrayList values = new ArrayList(2);
- values.add("a"); //$NON-NLS-1$
- values.add("b"); //$NON-NLS-1$
-
- try {
- helpTestWithValueIterator(expr, values, null);
- fail("Expected ExpressionEvaluationException but got none"); //$NON-NLS-1$
- } catch (ExpressionEvaluationException e) {
- assertEquals("Error Code:ERR.015.006.0058 Message:Unable to evaluate (<undefined>): Error Code:ERR.015.006.0058 Message:The command of this scalar subquery returned more than one value: <undefined>", e.getMessage()); //$NON-NLS-1$
- }
- }
-
- @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$
- func.setFunctionDescriptor(desc);
-
- FakeDataManager dataMgr = new FakeDataManager();
- CommandContext context = new CommandContext(new Long(1), null, null, null, 0);
- context.setUserName("logon"); //$NON-NLS-1$
- assertEquals(context.getUserName(), new Evaluator(Collections.emptyMap(), dataMgr, context).evaluate(func, Collections.emptyList()) );
- }
-
- /*
- * This is the only test that depends upon the the testsrc/metamatrix.properties
- * and testsrc/config.xml. If the implementation is changed, please update/remove
- * these files.
- * @throws Exception
- */
- @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$
- func.setFunctionDescriptor(desc);
-
- FakeDataManager dataMgr = new FakeDataManager();
-
- Properties props = new Properties();
- props.setProperty("http_host", "testHostName"); //$NON-NLS-1$ //$NON-NLS-2$
- props.setProperty("http_port", "8000"); //$NON-NLS-1$ //$NON-NLS-2$
- CommandContext context = new CommandContext(new Long(1), null, null, null, null, 0, props, false);
-
- func.setArgs(new Expression[] {new Constant("http_host")}); //$NON-NLS-1$
- assertEquals("testHostName", new Evaluator(Collections.emptyMap(), dataMgr, context).evaluate(func, Collections.emptyList())); //$NON-NLS-1$
-
- func.setArgs(new Expression[] {new Constant("http_port")}); //$NON-NLS-1$
- assertEquals("8000", new Evaluator(Collections.emptyMap(), dataMgr, context).evaluate(func, Collections.emptyList())); //$NON-NLS-1$
- }
-
- public void helpTestCommandPayload(Serializable payload, String property, String expectedValue) throws Exception {
- Function func = new Function("commandpayload", new Expression[] {}); //$NON-NLS-1$
-
- Class[] parameterSignature = null;
- if(property == null) {
- parameterSignature = new Class[] {};
- } else {
- parameterSignature = new Class[] { String.class };
- }
- FunctionDescriptor desc = FakeMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("commandpayload", parameterSignature ); //$NON-NLS-1$
- func.setFunctionDescriptor(desc);
-
- FakeDataManager dataMgr = new FakeDataManager();
- CommandContext context = new CommandContext(new Long(-1), null, "user", payload, "vdb", 1, null, false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- if(property != null) {
- func.setArgs(new Expression[] {new Constant(property)});
- }
- String actual = (String) new Evaluator(Collections.emptyMap(), dataMgr, context).evaluate(func, Collections.emptyList());
- assertEquals(expectedValue, actual);
- }
-
- @Test public void testCommandPayloadNoArgsWithPayload() throws Exception {
- helpTestCommandPayload("blah", null, "blah"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCommandPayloadNoArgsWithoutPayload() throws Exception {
- helpTestCommandPayload(null, null, null);
- }
-
- @Test public void testCommandPayloadNoArgsWithNonStringPayload() throws Exception {
- helpTestCommandPayload(Boolean.TRUE, null, "true"); //$NON-NLS-1$
- }
-
- @Test public void testCommandPayloadArgWithPayload() throws Exception {
- Properties props = new Properties();
- props.setProperty("p1", "v1"); //$NON-NLS-1$ //$NON-NLS-2$
- props.setProperty("p2", "v2"); //$NON-NLS-1$ //$NON-NLS-2$
- helpTestCommandPayload(props, "p1", "v1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCommandPayloadArgWithPayloadMissingProp() throws Exception {
- Properties props = new Properties();
- props.setProperty("p1", "v1"); //$NON-NLS-1$ //$NON-NLS-2$
- props.setProperty("p2", "v2"); //$NON-NLS-1$ //$NON-NLS-2$
- helpTestCommandPayload(props, "BOGUS", null); //$NON-NLS-1$
- }
-
- @Test public void testCommandPayloadArgWithoutPayload() throws Exception {
- Properties props = new Properties();
- props.setProperty("p1", "v1"); //$NON-NLS-1$ //$NON-NLS-2$
- props.setProperty("p2", "v2"); //$NON-NLS-1$ //$NON-NLS-2$
- helpTestCommandPayload(null, "BOGUS", null); //$NON-NLS-1$
- }
-
- @Test(expected=ExpressionEvaluationException.class) public void testCommandPayloadArgWithBadPayload() throws Exception {
- helpTestCommandPayload(Boolean.TRUE, "BOGUS", null); //$NON-NLS-1$
- }
-
- @Test public void testBigDecimalFromDoubleDivision() throws Exception {
- Expression ex = TestFunctionResolving.getExpression("convert(1.0, bigdecimal)/3");
- assertEquals(new BigDecimal("0.3333333333333333"), Evaluator.evaluate(ex));
- }
-
- @Test public void testBigDecimalDivision() throws Exception {
- Expression ex = TestFunctionResolving.getExpression("1/convert('3.0', bigdecimal)");
- assertEquals(new BigDecimal("0.3333333333333333"), Evaluator.evaluate(ex));
- }
-
- @Test public void testIsNull() throws Exception {
- assertEquals(Boolean.TRUE, Evaluator.evaluate(new IsNullCriteria(new Constant(null, DataTypeManager.DefaultDataClasses.BOOLEAN))));
- }
-
- @Test public void testIsNull1() throws Exception {
- assertEquals(Boolean.FALSE, Evaluator.evaluate(new IsNullCriteria(new Constant(Boolean.TRUE, DataTypeManager.DefaultDataClasses.BOOLEAN))));
- }
-
- @Test public void testIsNull3() throws Exception {
- IsNullCriteria inc = new IsNullCriteria(new Constant(null, DataTypeManager.DefaultDataClasses.BOOLEAN));
- inc.setNegated(true);
- assertEquals(Boolean.FALSE, Evaluator.evaluate(inc));
- }
-
- @Test public void testIsNull4() throws Exception {
- IsNullCriteria inc = new IsNullCriteria(new Constant(Boolean.TRUE, DataTypeManager.DefaultDataClasses.BOOLEAN));
- inc.setNegated(true);
- assertEquals(Boolean.TRUE, Evaluator.evaluate(inc));
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/eval/TestExpressionEvaluator.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/eval/TestExpressionEvaluator.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/eval/TestExpressionEvaluator.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/eval/TestExpressionEvaluator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,435 @@
+/*
+ * 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.eval;
+
+import static org.junit.Assert.*;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import org.junit.Test;
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.query.eval.Evaluator;
+import org.teiid.query.function.FunctionDescriptor;
+import org.teiid.query.processor.FakeDataManager;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.resolver.TestFunctionResolving;
+import org.teiid.query.sql.lang.CollectionValueIterator;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.SubqueryContainer;
+import org.teiid.query.sql.symbol.CaseExpression;
+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.sql.symbol.ScalarSubquery;
+import org.teiid.query.sql.symbol.SearchedCaseExpression;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+ at SuppressWarnings("nls")
+public class TestExpressionEvaluator {
+
+ public void helpTestEval(Expression expr, SingleElementSymbol[] elementList, Object[] valueList, ProcessorDataManager dataMgr, CommandContext context, Object expectedValue) {
+ try {
+ Object actualValue = helpEval(expr, elementList, valueList, dataMgr, context);
+ assertEquals("Did not get expected result", expectedValue, actualValue); //$NON-NLS-1$
+ } catch(TeiidException e) {
+ fail("Received unexpected exception: " + e.getFullMessage()); //$NON-NLS-1$
+ }
+ }
+
+ public Object helpEval(Expression expr, SingleElementSymbol[] elementList, Object[] valueList, ProcessorDataManager dataMgr, CommandContext context) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+ Map elements = new HashMap();
+ if (elementList != null) {
+ for(int i=0; i<elementList.length; i++) {
+ elements.put(elementList[i], new Integer(i));
+ }
+ }
+
+ List tuple = new ArrayList();
+ if (valueList != null) {
+ for(int i=0; i<valueList.length; i++) {
+ tuple.add(valueList[i]);
+ }
+ }
+ return new Evaluator(elements, dataMgr, context).evaluate(expr, tuple);
+ }
+
+ @Test public void testCaseExpression1() {
+ CaseExpression expr = TestCaseExpression.example(3);
+ expr.setExpression(new Constant("a")); //$NON-NLS-1$
+ helpTestEval(expr, null, null, null, null, new Integer(0));
+ expr.setExpression(new Constant("b")); //$NON-NLS-1$
+ helpTestEval(expr, null, null, null, null, new Integer(1));
+ expr.setExpression(new Constant("c")); //$NON-NLS-1$
+ helpTestEval(expr, null, null, null, null, new Integer(2));
+ expr.setExpression(new Constant("d")); //$NON-NLS-1$
+ helpTestEval(expr, null, null, null, null, new Integer(9999));
+ }
+
+ @Test public void testSearchedCaseExpression1() {
+ SearchedCaseExpression expr = TestSearchedCaseExpression.example(3);
+ helpTestEval(expr,
+ new SingleElementSymbol[] {new ElementSymbol("x")}, //$NON-NLS-1$
+ new Object[] {new Integer(0)},
+ null,
+ null,
+ new Integer(0));
+ helpTestEval(expr,
+ new SingleElementSymbol[] {new ElementSymbol("x")}, //$NON-NLS-1$
+ new Object[] {new Integer(1)},
+ null,
+ null,
+ new Integer(1));
+ helpTestEval(expr,
+ new SingleElementSymbol[] {new ElementSymbol("x")}, //$NON-NLS-1$
+ new Object[] {new Integer(2)},
+ null,
+ null,
+ new Integer(2));
+ helpTestEval(expr,
+ new SingleElementSymbol[] {new ElementSymbol("x")}, //$NON-NLS-1$
+ new Object[] {new Integer(3)},
+ null,
+ null,
+ new Integer(9999));
+ }
+
+ @Test public void testConstant() {
+ helpTestEval(new Constant("xyz", String.class), new SingleElementSymbol[0], new Object[0], null, null, "xyz"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testElement1() {
+ ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
+
+ SingleElementSymbol[] elements = new SingleElementSymbol[] {
+ e1, e2
+ };
+
+ Object[] values = new Object[] {
+ "xyz", "abc" //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ helpTestEval(e1, elements, values, null, null, "xyz"); //$NON-NLS-1$
+ }
+
+ @Test public void testElement2() {
+ ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
+
+ SingleElementSymbol[] elements = new SingleElementSymbol[] {
+ e1, e2
+ };
+
+ Object[] values = new Object[] {
+ "xyz", "abc" //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ helpTestEval(e2, elements, values, null, null, "abc"); //$NON-NLS-1$
+ }
+
+ /**
+ * Element Symbols must have values set during evaluation
+ */
+ @Test public void testElement3() throws Exception {
+ ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
+
+ SingleElementSymbol[] elements = new SingleElementSymbol[] {};
+
+ Object[] values = new Object[] {
+ "xyz", "abc" //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ try {
+ helpEval(e2, elements, values, null, null);
+ fail("Exception expected"); //$NON-NLS-1$
+ } catch (TeiidComponentException e){
+ //this should be a componentexception, since it is unexpected
+ assertEquals(e.getMessage(), "Error Code:ERR.015.006.0033 Message:Unable to evaluate e2: No value was available"); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testFunction1() {
+ ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ e1.setType(String.class);
+ ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
+ e2.setType(String.class);
+
+ Function func = new Function("concat", new Expression[] { e1, e2 }); //$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[] {
+ e1, e2
+ };
+
+ Object[] values = new Object[] {
+ "xyz", "abc" //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+
+ helpTestEval(func, elements, values, null, null, "xyzabc"); //$NON-NLS-1$
+ }
+
+ @Test public void testFunction2() {
+ ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ e1.setType(String.class);
+ ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
+ e2.setType(String.class);
+
+ Function func = new Function("concat", new Expression[] { e2, e1 }); //$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[] {
+ e1, e2
+ };
+
+ Object[] values = new Object[] {
+ "xyz", "abc" //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ helpTestEval(func, elements, values, null, null, "abcxyz"); //$NON-NLS-1$
+ }
+
+ @Test public void testLookupFunction() {
+ ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ e1.setType(String.class);
+ ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
+ 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 = 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[] {
+ e1, e2
+ };
+
+ Object[] values = new Object[] {
+ "xyz", new Integer(5) //$NON-NLS-1$
+ };
+
+ FakeDataManager dataMgr = new FakeDataManager();
+ Map valueMap = new HashMap();
+ valueMap.put("xyz", new Integer(5)); //$NON-NLS-1$
+ dataMgr.defineCodeTable("pm1.g1", "e1", "e2", valueMap); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ helpTestEval(func, elements, values, dataMgr, null, new Integer(5));
+ }
+
+ @Test public void testScalarSubquery() throws Exception{
+ ScalarSubquery expr = new ScalarSubquery(new Query());
+ ArrayList values = new ArrayList(1);
+ values.add("a"); //$NON-NLS-1$
+ Object expected = "a"; //$NON-NLS-1$
+ helpTestWithValueIterator(expr, values, expected);
+ }
+
+ private void helpTestWithValueIterator(ScalarSubquery expr,
+ List<?> values, Object expected)
+ throws BlockedException,
+ TeiidComponentException, ExpressionEvaluationException {
+ final CollectionValueIterator valueIter = new CollectionValueIterator(values);
+ CommandContext cc = new CommandContext();
+ assertEquals(expected, new Evaluator(Collections.emptyMap(), null, cc) {
+ @Override
+ protected ValueIterator evaluateSubquery(
+ SubqueryContainer container, List tuple)
+ throws TeiidProcessingException, BlockedException,
+ TeiidComponentException {
+ return valueIter;
+ }
+ }.evaluate(expr, null) );
+ }
+
+ @Test public void testScalarSubquery2() throws Exception{
+ ScalarSubquery expr = new ScalarSubquery(new Query());
+ ArrayList values = new ArrayList(1);
+ values.add(null);
+ helpTestWithValueIterator(expr, values, null);
+ }
+
+ @Test public void testScalarSubquery3() throws Exception{
+ ScalarSubquery expr = new ScalarSubquery(new Query());
+ helpTestWithValueIterator(expr, Collections.emptyList(), null);
+ }
+
+ @Test public void testScalarSubqueryFails() throws Exception{
+ ScalarSubquery expr = new ScalarSubquery(new Query());
+ ArrayList values = new ArrayList(2);
+ values.add("a"); //$NON-NLS-1$
+ values.add("b"); //$NON-NLS-1$
+
+ try {
+ helpTestWithValueIterator(expr, values, null);
+ fail("Expected ExpressionEvaluationException but got none"); //$NON-NLS-1$
+ } catch (ExpressionEvaluationException e) {
+ assertEquals("Error Code:ERR.015.006.0058 Message:Unable to evaluate (<undefined>): Error Code:ERR.015.006.0058 Message:The command of this scalar subquery returned more than one value: <undefined>", e.getMessage()); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testUser() throws Exception {
+ Function func = new Function("user", new Expression[] {}); //$NON-NLS-1$
+ FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("user", new Class[] {} ); //$NON-NLS-1$
+ func.setFunctionDescriptor(desc);
+
+ FakeDataManager dataMgr = new FakeDataManager();
+ CommandContext context = new CommandContext(new Long(1), null, null, null, 0);
+ context.setUserName("logon"); //$NON-NLS-1$
+ assertEquals(context.getUserName(), new Evaluator(Collections.emptyMap(), dataMgr, context).evaluate(func, Collections.emptyList()) );
+ }
+
+ /*
+ * This is the only test that depends upon the the testsrc/metamatrix.properties
+ * and testsrc/config.xml. If the implementation is changed, please update/remove
+ * these files.
+ * @throws Exception
+ */
+ @Test public void testEnv() throws Exception {
+ Function func = new Function("env", new Expression[] {}); //$NON-NLS-1$
+ FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("env", new Class[] {String.class} ); //$NON-NLS-1$
+ func.setFunctionDescriptor(desc);
+
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ Properties props = new Properties();
+ props.setProperty("http_host", "testHostName"); //$NON-NLS-1$ //$NON-NLS-2$
+ props.setProperty("http_port", "8000"); //$NON-NLS-1$ //$NON-NLS-2$
+ CommandContext context = new CommandContext(new Long(1), null, null, null, null, 0, props, false);
+
+ func.setArgs(new Expression[] {new Constant("http_host")}); //$NON-NLS-1$
+ assertEquals("testHostName", new Evaluator(Collections.emptyMap(), dataMgr, context).evaluate(func, Collections.emptyList())); //$NON-NLS-1$
+
+ func.setArgs(new Expression[] {new Constant("http_port")}); //$NON-NLS-1$
+ assertEquals("8000", new Evaluator(Collections.emptyMap(), dataMgr, context).evaluate(func, Collections.emptyList())); //$NON-NLS-1$
+ }
+
+ public void helpTestCommandPayload(Serializable payload, String property, String expectedValue) throws Exception {
+ Function func = new Function("commandpayload", new Expression[] {}); //$NON-NLS-1$
+
+ Class[] parameterSignature = null;
+ if(property == null) {
+ parameterSignature = new Class[] {};
+ } else {
+ parameterSignature = new Class[] { String.class };
+ }
+ FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("commandpayload", parameterSignature ); //$NON-NLS-1$
+ func.setFunctionDescriptor(desc);
+
+ FakeDataManager dataMgr = new FakeDataManager();
+ CommandContext context = new CommandContext(new Long(-1), null, "user", payload, "vdb", 1, null, false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ if(property != null) {
+ func.setArgs(new Expression[] {new Constant(property)});
+ }
+ String actual = (String) new Evaluator(Collections.emptyMap(), dataMgr, context).evaluate(func, Collections.emptyList());
+ assertEquals(expectedValue, actual);
+ }
+
+ @Test public void testCommandPayloadNoArgsWithPayload() throws Exception {
+ helpTestCommandPayload("blah", null, "blah"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCommandPayloadNoArgsWithoutPayload() throws Exception {
+ helpTestCommandPayload(null, null, null);
+ }
+
+ @Test public void testCommandPayloadNoArgsWithNonStringPayload() throws Exception {
+ helpTestCommandPayload(Boolean.TRUE, null, "true"); //$NON-NLS-1$
+ }
+
+ @Test public void testCommandPayloadArgWithPayload() throws Exception {
+ Properties props = new Properties();
+ props.setProperty("p1", "v1"); //$NON-NLS-1$ //$NON-NLS-2$
+ props.setProperty("p2", "v2"); //$NON-NLS-1$ //$NON-NLS-2$
+ helpTestCommandPayload(props, "p1", "v1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCommandPayloadArgWithPayloadMissingProp() throws Exception {
+ Properties props = new Properties();
+ props.setProperty("p1", "v1"); //$NON-NLS-1$ //$NON-NLS-2$
+ props.setProperty("p2", "v2"); //$NON-NLS-1$ //$NON-NLS-2$
+ helpTestCommandPayload(props, "BOGUS", null); //$NON-NLS-1$
+ }
+
+ @Test public void testCommandPayloadArgWithoutPayload() throws Exception {
+ Properties props = new Properties();
+ props.setProperty("p1", "v1"); //$NON-NLS-1$ //$NON-NLS-2$
+ props.setProperty("p2", "v2"); //$NON-NLS-1$ //$NON-NLS-2$
+ helpTestCommandPayload(null, "BOGUS", null); //$NON-NLS-1$
+ }
+
+ @Test(expected=ExpressionEvaluationException.class) public void testCommandPayloadArgWithBadPayload() throws Exception {
+ helpTestCommandPayload(Boolean.TRUE, "BOGUS", null); //$NON-NLS-1$
+ }
+
+ @Test public void testBigDecimalFromDoubleDivision() throws Exception {
+ Expression ex = TestFunctionResolving.getExpression("convert(1.0, bigdecimal)/3");
+ assertEquals(new BigDecimal("0.3333333333333333"), Evaluator.evaluate(ex));
+ }
+
+ @Test public void testBigDecimalDivision() throws Exception {
+ Expression ex = TestFunctionResolving.getExpression("1/convert('3.0', bigdecimal)");
+ assertEquals(new BigDecimal("0.3333333333333333"), Evaluator.evaluate(ex));
+ }
+
+ @Test public void testIsNull() throws Exception {
+ assertEquals(Boolean.TRUE, Evaluator.evaluate(new IsNullCriteria(new Constant(null, DataTypeManager.DefaultDataClasses.BOOLEAN))));
+ }
+
+ @Test public void testIsNull1() throws Exception {
+ assertEquals(Boolean.FALSE, Evaluator.evaluate(new IsNullCriteria(new Constant(Boolean.TRUE, DataTypeManager.DefaultDataClasses.BOOLEAN))));
+ }
+
+ @Test public void testIsNull3() throws Exception {
+ IsNullCriteria inc = new IsNullCriteria(new Constant(null, DataTypeManager.DefaultDataClasses.BOOLEAN));
+ inc.setNegated(true);
+ assertEquals(Boolean.FALSE, Evaluator.evaluate(inc));
+ }
+
+ @Test public void testIsNull4() throws Exception {
+ IsNullCriteria inc = new IsNullCriteria(new Constant(Boolean.TRUE, DataTypeManager.DefaultDataClasses.BOOLEAN));
+ inc.setNegated(true);
+ assertEquals(Boolean.TRUE, Evaluator.evaluate(inc));
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/proc/TestProcedureProcessor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/proc/TestProcedureProcessor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/proc/TestProcedureProcessor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,2738 +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 static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Test;
-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.types.DataTypeManager;
-import org.teiid.query.analysis.AnalysisRecord;
-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.QueryOptimizer;
-import org.teiid.query.optimizer.TestOptimizer;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.FakeDataManager;
-import org.teiid.query.processor.FakeDataStore;
-import org.teiid.query.processor.HardcodedDataManager;
-import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.TestProcessor;
-import org.teiid.query.processor.xml.TestXMLPlanningEnhancements;
-import org.teiid.query.processor.xml.TestXMLProcessor;
-import org.teiid.query.resolver.QueryResolver;
-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;
-import org.teiid.query.validator.ValidatorFailure;
-import org.teiid.query.validator.ValidatorReport;
-
- at SuppressWarnings({"unchecked", "nls"})
-public class TestProcedureProcessor {
-
- public static ProcessorPlan getProcedurePlan(String userQuery, QueryMetadataInterface metadata) throws Exception {
- return getProcedurePlan(userQuery, metadata, /*capabilitiesFinder*/null);
- }
-
- public static ProcessorPlan getProcedurePlan(String userQuery, QueryMetadataInterface metadata, CapabilitiesFinder capabilitiesFinder) throws Exception {
- Command userCommand = QueryParser.getQueryParser().parseCommand(userQuery);
- QueryResolver.resolveCommand(userCommand, metadata);
- ValidatorReport report = Validator.validate(userCommand, metadata);
-
- if (report.hasItems()) {
- ValidatorFailure firstFailure = report.getItems().iterator().next();
- throw new QueryValidatorException(firstFailure.getMessage());
- }
- QueryRewriter.rewrite(userCommand, metadata, new CommandContext());
-
- AnalysisRecord analysisRecord = new AnalysisRecord(false, DEBUG);
- try {
- if ( capabilitiesFinder == null ) capabilitiesFinder = new DefaultCapabilitiesFinder();
- ProcessorPlan plan = QueryOptimizer.optimizePlan(userCommand, metadata, null, capabilitiesFinder, analysisRecord, null);
-
- return plan;
- } finally {
- if(DEBUG) {
- System.out.println(analysisRecord.getDebugLog());
- }
- }
- }
-
- public static void helpTestProcess(ProcessorPlan procPlan, List[] expectedResults, ProcessorDataManager dataMgr, QueryMetadataInterface metadata) throws Exception {
- CommandContext context = new CommandContext("pID", null, null, null, 1); //$NON-NLS-1$
- if (!(metadata instanceof TempMetadataAdapter)) {
- metadata = new TempMetadataAdapter(metadata, new TempMetadataStore());
- }
- context.setMetadata(metadata);
-
- TestProcessor.helpProcess(procPlan, context, dataMgr, expectedResults);
- assertNotNull("Expected processing to fail", expectedResults);
- }
-
- private void helpTestProcessFailure(ProcessorPlan procPlan, FakeDataManager dataMgr,
- String failMessage, QueryMetadataInterface metadata) throws Exception {
- try {
- helpTestProcess(procPlan, null, dataMgr, metadata);
- } catch(TeiidException ex) {
- assertEquals(failMessage, ex.getMessage());
- }
- }
-
- private void helpTestProcess(ProcessorPlan procPlan, int expectedRows, FakeDataManager dataMgr, QueryMetadataInterface metadata) throws Exception {
- 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 {
- 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$
- } );
-
- 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$
- } );
-
- return dataMgr;
- }
-
- private FakeDataManager exampleDataManager2(FakeMetadataFacade metadata) throws QueryMetadataException, TeiidComponentException {
- 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$
- } );
-
- 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$
- } );
-
- 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$
- } );
-
- 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$
- } );
-
- return dataMgr;
- }
-
- private FakeDataManager exampleDataManagerPm5(FakeMetadataFacade metadata) throws QueryMetadataException, TeiidComponentException {
- 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$
- } );
-
- return dataMgr;
- }
-
- // procedure does nothing returns zero update count
- @Test public void testProcedureProcessor1() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1 = 0;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, 0, dataMgr, metadata);
- }
-
- // testing if statement
- @Test public void testProcedureProcessor2() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, 5, dataMgr, metadata);
- }
-
- // testing if statement
- @Test public void testProcedureProcessor2WithBlockedException() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
- dataMgr.setBlockOnce();
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, 5, dataMgr, metadata);
- }
-
- // testing rows updated incremented, Input and assignment statements
- @Test public void testProcedureProcessor3() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = INPUT.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e2=40"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, 45, dataMgr, metadata);
- }
-
- // if/else test
- @Test public void testProcedureProcessor4() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ELSE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e1, pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = INPUT.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e2=45"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, 5, dataMgr, metadata);
- }
-
- @Test public void testProcedureProcessor4WithBlockedException() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ELSE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e1, pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = INPUT.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e2=45"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
- dataMgr.setBlockOnce();
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, 5, dataMgr, metadata);
- }
-
- // if/else test
- @Test public void testProcedureProcessor5() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where e2=15;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ELSE\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = INPUT.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e2=45"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, 50, dataMgr, metadata);
- }
-
- // more rows than expected
- @Test public void testProcedureProcessor6() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcessFailure(plan, dataMgr, "Error Code:ERR.015.006.0058 Message:Unable to evaluate (SELECT pm1.g1.e2 FROM pm1.g1 LIMIT 2): Error Code:ERR.015.006.0058 Message:The command of this scalar subquery returned more than one value: SELECT pm1.g1.e2 FROM pm1.g1 LIMIT 2", metadata); //$NON-NLS-1$
- }
-
- // error statement
- @Test public void testProcedureProcessor7() throws Exception {
- String errorValue = "'MY ERROR'"; //$NON-NLS-1$
- helpTestErrorStatment(errorValue, "MY ERROR"); //$NON-NLS-1$
- }
-
- @Test public void testProcedureProcessor8() throws Exception {
- String errorValue = "var1"; //$NON-NLS-1$
- helpTestErrorStatment(errorValue, "5"); //$NON-NLS-1$
- }
-
- @Test public void testProcedureProcessor9() throws Exception {
- String errorValue = "var1||'MY ERROR'"; //$NON-NLS-1$
- helpTestErrorStatment(errorValue, "5MY ERROR"); //$NON-NLS-1$
- }
-
- @Test public void testProcedureProcessor10() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "loop on (Select pm1.g1.e2 from pm1.g1 where e2 = 5) as mycursor\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ERROR (mycursor.e2||'MY ERROR');\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcessFailure(plan, dataMgr, ErrorInstruction.ERROR_PREFIX + "5MY ERROR", metadata); //$NON-NLS-1$
- }
-
- private void helpTestErrorStatment(String errorValue, String expected) throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = 5;\n"; //$NON-NLS-1$
- procedure = procedure + "ERROR "+errorValue+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
- procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcessFailure(plan, dataMgr, ErrorInstruction.ERROR_PREFIX + expected, metadata);
- }
-
- /** test if statement's if block with lookup in if condition */
- @Test public void testLookupFunction1() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var2;\n"; //$NON-NLS-1$
- procedure = procedure + "if('a' = lookup('pm1.g1','e1', 'e2', 0))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "var2 = INPUT.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED +1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ELSE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "var2 = 100;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED +13;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e2=30"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
- FakeDataManager dataMgr = new FakeDataManager();
- FakeDataStore.sampleData2(dataMgr);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
- helpTestProcess(plan, 1, dataMgr, metadata);
-
- }
-
- /** test if statement's else block with lookup in if condition */
- @Test public void testLookupFunction2() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var2;\n"; //$NON-NLS-1$
- procedure = procedure + "if('a' = lookup('pm1.g1','e1', 'e2', 5))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "var2 = INPUT.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED +1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ELSE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "var2 = 100;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED +12;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e2=30"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
- FakeDataManager dataMgr = new FakeDataManager();
- FakeDataStore.sampleData2(dataMgr);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
- helpTestProcess(plan, 12, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp2()"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedureWithBlockedException() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp2()"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
- dataMgr.setBlockOnce();
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure2() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp3()"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure3() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp4()"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure4() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp5()"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure5() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp6()"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Second"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure6() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp7(5)"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Second"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure7() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp8(51)"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure8() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp9(51)"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure9() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp10(51)"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {};
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
-
- @Test public void testVirtualProcedure10() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp13()"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Third", new Integer(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();
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure12() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp15()"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- } );
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- //Defect17447_testVirtualProcedure13
- @Test public void testVirtualProcedure13() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp16()"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- } );
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure14() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp17()"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure15() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp19()"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure16() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp20()"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Fourth"})}; //$NON-NLS-1$
- CommandContext context = new CommandContext("pID", null, null, null, 1); //$NON-NLS-1$
- context.setMetadata(metadata);
- context.setProcessorBatchSize(1); //ensure that the final temp result set will not be deleted prematurely
-
- TestProcessor.helpProcess(plan, context, dataMgr, expected);
- }
-
- @Test public void testVirtualProcedure17() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp21(7)"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- //Set up data
- FakeDataManager dataMgr = exampleDataManager(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[] { "Fourth", new Integer(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();
- //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[] { "Third", new Integer(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();
- //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$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure19WithBlockedException() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp23(7)"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedureNoDataInTempTable() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp25()"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- //Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {};
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- //procedure with Has Criteria and Translate Criteria
- @Test public void testDefect13625() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "IF(HAS CRITERIA ON (vm1.g4.e2))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA ON (vm1.g4.e2);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE g4 SET e1='x' where e2=5"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, 5, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure30() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp30()"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"}) }; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure31() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp31(51)"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Third"}) }; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedureDefect14282() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp24()"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Second"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDefect16193() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp35(51)"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Third"}) }; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedure16602() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp37()"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.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);
-
- 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)})};
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDefect16649_1() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp38()"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Second"}) }; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDefect16649_2() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp39()"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Second"}) }; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDefect16694() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp40()"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "Second"}) }; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDefect16707() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp44(2)"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDefect16707_1() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp43(2)"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDefect17451() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp45()"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- } );
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- //Defect 17447
- @Test public void testVirtualProcedure46() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp46()"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDefect17650() throws Exception {
- String procedure1 = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure1 = procedure1 + "BEGIN\n"; //$NON-NLS-1$
- procedure1 = procedure1 + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure1 = procedure1 + "IF(HAS CRITERIA ON (vm1.g1.e2))\n"; //$NON-NLS-1$
- procedure1 = procedure1 + "BEGIN\n"; //$NON-NLS-1$
- procedure1 = procedure1 + "ROWS_UPDATED = UPDATE vm1.g2 SET e1='x' where TRANSLATE = CRITERIA ON (vm1.g1.e2);\n"; //$NON-NLS-1$
- procedure1 = procedure1 + "END\n"; //$NON-NLS-1$
- procedure1 = procedure1 + "END"; //$NON-NLS-1$
-
- String procedure2 = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure2 = procedure2 + "BEGIN\n"; //$NON-NLS-1$
- procedure2 = procedure2 + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure2 = procedure2 + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE CRITERIA;\n";//$NON-NLS-1$
- procedure2 = procedure2 + "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
- procedure2 = procedure2 + "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x' where e2=5"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure1, procedure2);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, 5, dataMgr, metadata);
- }
-
- @Test public void testDefect19982() throws Exception {
- String userUpdateStr = "EXEC pm1.vsp55(5)"; //$NON-NLS-1$
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(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(5)}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third", new Integer(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();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
-// Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
-// Arrays.asList(new Object[] { "Third"}), //$NON-NLS-1$
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- //procedure with Has Criteria and Translate Criteria and changing
- @Test public void testDynamicCommandWithTranslate() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "IF(HAS CRITERIA ON (vm1.g4.e2))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "execute string 'Select pm1.g1.e2 x, changing.e1 y from pm1.g1 where TRANSLATE = CRITERIA ON (vm1.g4.e2)' as x integer, y boolean into #temp;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = select x from #temp;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE g4 SET e1='x' where e2=5"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, 5, dataMgr, metadata);
- }
-
- @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$
-
- 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);
-
- //Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First" }), //$NON-NLS-1$
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDynamicCommandWithIntoAndLoop() throws Exception {
-
- //Test INTO clause with loop
- 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$
- 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$
- procedure.append("execute string 'SELECT e1, e2 FROM pm1.g1' as e1 string, e2 integer into #temp;\n"); //$NON-NLS-1$
- procedure.append("loop on (Select e2 from #temp where e2 > 2) as mycursor\n"); //$NON-NLS-1$
- procedure.append("BEGIN\n"); //$NON-NLS-1$
- procedure.append("IF (mycursor.e2>5) \n"); //$NON-NLS-1$
- procedure.append("VARIABLES.e2_total=VARIABLES.e2_total+mycursor.e2;\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$
-
- 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);
-
- String userUpdateStr = "EXEC pm1.sq1()"; //$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(66)}),
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDynamicCommandWithParameter() 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", "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$
-
- metadata.getStore().addObject(rs2);
- metadata.getStore().addObject(sq2);
-
- String userUpdateStr = "EXEC pm1.sq2('First')"; //$NON-NLS-1$
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First", new Integer(5) }), //$NON-NLS-1$
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDynamicCommandWithUsing() 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", "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);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First", new Integer(5) }), //$NON-NLS-1$
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDynamicCommandWithVariable() 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", "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);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First", new Integer(5) }), //$NON-NLS-1$
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDynamicCommandValidationFails() 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", "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);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- try {
- helpTestProcess(plan, null, dataMgr, metadata);
- fail("exception expected");
- } catch (QueryProcessingException e) {
- assertTrue(e.getCause() instanceof QueryValidatorException);
- }
- }
-
- @Test public void testDynamicCommandWithSingleSelect() throws Exception {
- //Test select of a single value in a DynamicCommand
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
-
- metadata.getStore().addObject(rs1);
- metadata.getStore().addObject(sq1);
-
- String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "26" }), //$NON-NLS-1$
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
-
- //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);
-
- String userUpdateStr = "EXEC pm1.sq2('First')"; //$NON-NLS-1$
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "5" }), //$NON-NLS-1$
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDynamicCommandRecursion() 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", "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);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcessFailure(plan,
- dataMgr,
- "Couldn't execute the dynamic SQL command \"EXECUTE 'EXEC pm1.sq2(''First'')' AS e1 string, e2 integer\" with the SQL statement \"'EXEC pm1.sq2(''First'')'\" due to: There is a recursive invocation of group 'PM1.SQ2'. Please correct the SQL.", metadata); //$NON-NLS-1$
- }
-
- @Test public void testDynamicCommandIncorrectProjectSymbolCount() throws Exception {
- //Tests dynamic query with incorrect number of elements
- 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("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$
-
- metadata.getStore().addObject(rs2);
- metadata.getStore().addObject(sq1);
- metadata.getStore().addObject(sq2);
-
- String userUpdateStr = "EXEC pm1.sq2('test')"; //$NON-NLS-1$
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcessFailure(plan, dataMgr, "Couldn't execute the dynamic SQL command \"EXECUTE 'EXEC pm1.sq1(''First'')' AS e1 string, e2 integer\" with the SQL statement \"'EXEC pm1.sq1(''First'')'\" due to: The dynamic sql string contains an incorrect number of elements.", metadata); //$NON-NLS-1$
- }
-
- @Test public void testDynamicCommandPositional() throws Exception {
- //Tests dynamic query with incorrect number of elements
- 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", "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);
-
- helpTestProcess(plan, new List[] {Arrays.asList("First", "5"), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList("Second", "15"), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList("Third", "51")}, dataMgr, metadata); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @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();
-
- 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("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$
-
- 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);
-
- helpTestProcessFailure(plan, dataMgr, "Couldn't execute the dynamic SQL command \"EXECUTE 'select e1 from pm1.g1'\" with the SQL statement \"'select e1 from pm1.g1'\" due to: The datatype 'string' for element 'e1' in the dynamic SQL cannot be implicitly converted to 'integer'.", metadata); //$NON-NLS-1$
- }
-
- @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();
-
- FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$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$
- 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);
-
- 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$
-
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testAssignmentWithCase() throws Exception {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-
- String sql = new StringBuffer("declare integer caseValue = ") //$NON-NLS-1$
- .append("CASE") //$NON-NLS-1$
- .append(" WHEN pm1.sq1.param='a' THEN 0") //$NON-NLS-1$
- .append(" WHEN pm1.sq1.param='b' THEN 1") //$NON-NLS-1$
- .append(" WHEN pm1.sq1.param='c' THEN 2") //$NON-NLS-1$
- .append(" WHEN pm1.sq1.param='d' THEN 3") //$NON-NLS-1$
- .append(" ELSE 9999") //$NON-NLS-1$
- .append(" END").toString(); //$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);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(3) }),
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @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();
-
- 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$
-
- metadata.getStore().addObject(rs1);
- metadata.getStore().addObject(sq1);
-
- 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$
-
- 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();
-
- 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$
-
- metadata.getStore().addObject(rs1);
- metadata.getStore().addObject(sq1);
-
- String userUpdateStr = "EXEC pm5.sq1(convert(5,short))"; //$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 Short((short)5)})}; //$NON-NLS-1$
-
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedureWithCreate() throws Exception{
- String userUpdateStr = "EXEC pm1.vsp60()"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedureWithCreateAndDrop() throws Exception{
- String userUpdateStr = "EXEC pm1.vsp61()"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testVirtualProcedureWithCreateAndSelectInto() throws Exception{
- String userUpdateStr = "EXEC pm1.vsp62()"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDifferentlyScopedTempTables() 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$
- 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$
- procedure.append("if (e2_total = 0)"); //$NON-NLS-1$
- procedure.append("BEGIN\n"); //$NON-NLS-1$
- procedure.append("select e1 into #temp from pm1.g1;\n"); //$NON-NLS-1$
- procedure.append("VARIABLES.e2_total=select count(*) from #temp;\n"); //$NON-NLS-1$
- procedure.append("END\n"); //$NON-NLS-1$
- procedure.append("if (e2_total = 3)"); //$NON-NLS-1$
- procedure.append("BEGIN\n"); //$NON-NLS-1$
- procedure.append("select e1 into #temp from pm1.g1;\n"); //$NON-NLS-1$
- procedure.append("VARIABLES.e2_total=select count(*) from #temp;\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$
-
- 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);
-
- String userUpdateStr = "EXEC pm1.sq1()"; //$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(3)}),
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testLoopsWithBreak() 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$
- 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$
- procedure.append("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("break;\n"); //$NON-NLS-1$
- procedure.append("END\n"); //$NON-NLS-1$
- procedure.append("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;"); //$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$
-
- 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);
-
- String userUpdateStr = "EXEC pm1.sq1()"; //$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);
- }
-
- @Test public void testCreateWithoutDrop() 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$
- 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$
- procedure.append("create local temporary table t1 (e1 integer);\n"); //$NON-NLS-1$
- 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);
-
- String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcessFailure(plan, dataMgr, "Temporary table \"T1\" already exists.", metadata); //$NON-NLS-1$
- }
-
- /**
- * We allow drops to silently fail
- */
- @Test public void testDoubleDrop() 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$
- 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$
- procedure.append("select e1 into t1 from pm1.g1;\n"); //$NON-NLS-1$
- procedure.append("drop table t1;\n"); //$NON-NLS-1$
- procedure.append("drop table t1;\n"); //$NON-NLS-1$
- 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);
-
- String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, new List[] {Arrays.asList(1)}, dataMgr, metadata);
- }
-
- /**
- * defect 23975
- */
- @Test public void testFunctionInput() throws Exception {
- FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$NON-NLS-1$
-
- FakeMetadataObject p1 = FakeMetadataFactory.createParameter("v1.vp1.in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null); //$NON-NLS-1$
- 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$
-
- 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$
-
- FakeMetadataObject p2 = FakeMetadataFactory.createParameter("v1.vp2.in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null); //$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$
-
- 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);
-
- // Construct data manager with data
- // Plan query
- ProcessorPlan plan = getProcedurePlan(sql, metadata);
- // Run query
- helpTestProcess(plan, expected, new FakeDataManager(), metadata);
- }
-
- /**
- * defect 23976
- * Also, even after the bug for passing procedure inputs to non-execs was fixed, the special case of
- * if (below) and while statements popped up.
- */
- @Test public void testIfEvaluation() throws Exception {
- String procedure1 = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure1 += "BEGIN\n"; //$NON-NLS-1$
- procedure1 += "DECLARE string var1 = INPUT.e1;\n"; //$NON-NLS-1$
- procedure1 += "ROWS_UPDATED = UPDATE vm1.g2 SET e1=var1;\n"; //$NON-NLS-1$
- procedure1 += "END"; //$NON-NLS-1$
-
- String procedure2 = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure2 += "BEGIN\n"; //$NON-NLS-1$
- procedure2 += "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure2 += "IF (INPUT.e1 = 1)\n"; //$NON-NLS-1$
- procedure2 += "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
- procedure2 += "ELSE\n"; //$NON-NLS-1$
- procedure2 += "ROWS_UPDATED = 4;\n"; //$NON-NLS-1$
- procedure2 += "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x' where e2=5"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure1, procedure2);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, 4, new FakeDataManager(), metadata);
- }
-
- /**
- * This is a slight variation of TestProcessor.testVariableInExecParam, where the proc wrapper can be
- * removed after rewrite
- */
- @Test public void testReferenceForwarding() throws Exception {
- // Create query
- String sql = "EXEC pm1.vsp49()"; //$NON-NLS-1$
-
- 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[] { "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$
- };
-
- // Construct data manager with data
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
-
- // Plan query
- ProcessorPlan plan = getProcedurePlan(sql, metadata);
-
- // Run query
- helpTestProcess(plan, expected, dataManager, metadata);
- }
-
- @Test public void testInsertAfterCreate() 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$
- 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$
- .append("\n insert into #temp (e1) values ('a');") //$NON-NLS-1$
- .append("\n insert into #temp (e2) values ('b');") //$NON-NLS-1$
- .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);
-
- String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, new List[] {
- Arrays.asList(new Object[] {null}),
- Arrays.asList(new Object[] {"b"})}, dataMgr, metadata); //$NON-NLS-1$
-
- }
-
- /**
- * the update will not be executed, but the assignment value should still be 0
- */
- @Test public void testUpdateAssignmentNotExecuted() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1 = UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e2;"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = var1 + 1;\n"; //$NON-NLS-1$
- procedure = procedure + "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE g4 SET e1='x' where e2=5"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, 1, dataMgr, metadata);
-
- assertTrue(plan.requiresTransaction(false));
- }
-
- @Test public void testUpdateAssignmentNotExecutedVirtual() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1 = UPDATE vm1.g2 SET e1 = INPUT.e2;"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = var1 + 1;\n"; //$NON-NLS-1$
- procedure = procedure + "END"; //$NON-NLS-1$
-
- String procedure2 = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure2 += "BEGIN\n"; //$NON-NLS-1$
- procedure2 += "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure2 += "IF (INPUT.e1 = 1)\n"; //$NON-NLS-1$
- procedure2 += "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
- procedure2 += "ELSE\n"; //$NON-NLS-1$
- procedure2 += "ROWS_UPDATED = 4;\n"; //$NON-NLS-1$
- procedure2 += "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x' where e2=5"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure, procedure2);
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, 1, dataMgr, metadata);
- }
-
- @Test public void testEvaluatableSelectWithOrderBy() 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 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);
-
- String userUpdateStr = "EXEC pm1.sq1(1)"; //$NON-NLS-1$
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, new List[] {
- Arrays.asList(new Object[] {"1"})}, dataMgr, metadata); //$NON-NLS-1$
-
- }
-
- @Test public void testEvaluatableSelectWithOrderBy1() 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 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);
-
- String userUpdateStr = "EXEC pm1.sq1(1)"; //$NON-NLS-1$
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, new List[] {
- Arrays.asList(new Object[] {"1"}), //$NON-NLS-1$
- Arrays.asList(new Object[] {"First"}), //$NON-NLS-1$
- }, dataMgr, metadata);
-
- }
-
- /**
- * Tests non-deterministic evaluation of the rand function. There are two important things happening
- * 1. is that the evaluation of the rand function is delayed until processing time (which actually has predictable
- * values since the test initializes the command context with the same seed)
- * 2. The values are different, meaning that we got individual evaluations
- *
- * If this function were deterministic, it would be evaluated during rewrite to a single value.
- */
- @Test public void testNonDeterministicEvaluation() throws Exception {
- StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n") //$NON-NLS-1$
- .append("BEGIN\n") //$NON-NLS-1$
- .append("DECLARE integer x = 0;\n") //$NON-NLS-1$
- .append("CREATE LOCAL TEMPORARY TABLE #TEMP (e1 integer);\n") //$NON-NLS-1$
- .append("while (x < 2)\n") //$NON-NLS-1$
- .append("BEGIN\n") //$NON-NLS-1$
- .append("insert into #temp (e1) values (convert(rand() * 1000, integer));\n") //$NON-NLS-1$
- .append("x = x + 1;\n") //$NON-NLS-1$
- .append("END\n") //$NON-NLS-1$
- .append("SELECT * FROM #TEMP;\n") //$NON-NLS-1$
- .append("END"); //$NON-NLS-1$
-
- FakeMetadataFacade metadata = createProcedureMetadata(procedure.toString());
-
- String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
-
- helpTestProcess(plan, new List[] {
- Arrays.asList(new Object[] {new Integer(240)}),
- Arrays.asList(new Object[] {new Integer(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);
- return metadata;
- }
-
- @Test public void testTempTableTypeConversion() throws Exception {
-
- String procedure = "CREATE VIRTUAL PROCEDURE\n"; //$NON-NLS-1$
- procedure += "BEGIN\n"; //$NON-NLS-1$
- procedure += "CREATE local temporary table temp (x string, y integer);\n"; //$NON-NLS-1$
- procedure += "Select pm1.g1.e2 as e1, pm1.g1.e2 into temp from pm1.g1 order by pm1.g1.e2 limit 1;\n"; //$NON-NLS-1$
- procedure += "Select x from temp;\n"; //$NON-NLS-1$
- procedure += "END\n"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = createProcedureMetadata(procedure);
-
- String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- helpTestProcess(plan, new List[] {
- Arrays.asList(new Object[] {"5"}), //$NON-NLS-1$
- }, dataMgr, metadata);
- }
-
- /**
- * wraps {@link TestXMLPlanningEnhancements.testNested2WithContextCriteria5d1} in a procedure
- */
- @Test public void testXMLWithExternalCriteria() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
- 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$
-
- 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$
- 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);
-
- String userUpdateStr = "EXEC xqttest.proc(5)"; //$NON-NLS-1$
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { expectedDoc }),
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testXMLWithExternalCriteria_InXMLVar() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
- 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$
-
- 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$
- 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$
-
- metadata.getStore().addObject(rs2);
- metadata.getStore().addObject(sq2);
-
- String userUpdateStr = "EXEC xqttest.proc(5)"; //$NON-NLS-1$
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { expectedDoc }),
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- /**
- * wraps {@link TestXMLProcessor.testNested2WithCriteria2} in a procedure
- *
- * This one will successfully auto-stage
- */
- @Test public void testXMLWithExternalCriteria1() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$
- "<Catalogs>\n" + //$NON-NLS-1$
- " <Catalog>\n" + //$NON-NLS-1$
- " <Items>\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\n" + //$NON-NLS-1$
- " <Name>Lamp</Name>\n" + //$NON-NLS-1$
- " <Quantity>5</Quantity>\n" + //$NON-NLS-1$
- " <Suppliers>\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\n" + //$NON-NLS-1$
- " <Orders>\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\n" + //$NON-NLS-1$
- " </Order>\n" + //$NON-NLS-1$
- " </Orders>\n" + //$NON-NLS-1$
- " </Supplier>\n" + //$NON-NLS-1$
- " </Suppliers>\n" + //$NON-NLS-1$
- " </Item>\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\n" + //$NON-NLS-1$
- " <Name>Screwdriver</Name>\n" + //$NON-NLS-1$
- " <Quantity>100</Quantity>\n" + //$NON-NLS-1$
- " <Suppliers/>\n" + //$NON-NLS-1$
- " </Item>\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\n" + //$NON-NLS-1$
- " <Name>Goat</Name>\n" + //$NON-NLS-1$
- " <Quantity>4</Quantity>\n" + //$NON-NLS-1$
- " <Suppliers/>\n" + //$NON-NLS-1$
- " </Item>\n" + //$NON-NLS-1$
- " </Items>\n" + //$NON-NLS-1$
- " </Catalog>\n" + //$NON-NLS-1$
- "</Catalogs>"; //$NON-NLS-1$
-
- FakeMetadataObject pm1 = metadata.getStore().findObject("xmltest",FakeMetadataObject.MODEL); //$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$
- 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);
-
- String userUpdateStr = "EXEC xmltest.proc(52)"; //$NON-NLS-1$
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { expectedDoc }),
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testCase174806() throws Exception{
- String userUpdateStr = "EXEC pm1.vsp63()"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "c"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @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();
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- // Set up data
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- // Create expected results
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
- Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- /**
- * Test the procedure <code>DECLARE</code> statement using a query as the assignment value
- *
- * <p>The use of a query as the assignment value to a <code>DECLARE</code>
- * statement should execute without error as long as the query
- * is valid and fully resolvable.</p>
- *
- * <p>This test is related to JBEDSP-818 in which the query in the
- * <code>LOOP</code> statement would fail due to a query being used as the
- * assigned value in the <code>DECLARE</code> statement.</p>
- * @throws Exception
- */
- @Test public void testDeclareWithQueryAssignment() throws Exception {
- // procedure comes from test case IT236455 / JBEDSP-818
- String procedure = "CREATE VIRTUAL PROCEDURE \n"; //$NON-NLS-1$
- procedure += "BEGIN\n"; //$NON-NLS-1$
- procedure += " DECLARE integer VARIABLES.var1 = 0;\n"; //$NON-NLS-1$
- procedure += " /* the following DECLARE with ASSIGNMENT to a query should work "; //$NON-NLS-1$
- procedure += " but in IT236455 it results in the assignment inside the LOOP "; //$NON-NLS-1$
- procedure += " to fail */ "; //$NON-NLS-1$
- procedure += " DECLARE integer VARIABLES.NLEVELS = SELECT COUNT(*) FROM (\n"; //$NON-NLS-1$
- procedure += " SELECT 'Col1' AS ACol1, 'Col2' AS ACol2, convert(3, integer) AS ACol3\n"; //$NON-NLS-1$
- procedure += " ) AS Src;\n"; //$NON-NLS-1$
- procedure += " LOOP ON (\n"; //$NON-NLS-1$
- procedure += " SELECT StaticTable.BCol1, StaticTable.BCol2, StaticTable.BCol3 FROM (\n"; //$NON-NLS-1$
- procedure += " SELECT 'Col 1' AS BCol1, 'Col 2' AS BCol2, convert(3, integer) AS BCol3\n"; //$NON-NLS-1$
- procedure += " ) AS StaticTable\n"; //$NON-NLS-1$
- procedure += " ) AS L1\n"; //$NON-NLS-1$
- procedure += " BEGIN\n"; //$NON-NLS-1$
- procedure += " /* In IT236455 the following would fail as the results from "; //$NON-NLS-1$
- procedure += " the LOOP (L1) are not in scope when the assignment is being "; //$NON-NLS-1$
- procedure += " performed due to the query earlier being part of a DECLARE "; //$NON-NLS-1$
- procedure += " statement. */ "; //$NON-NLS-1$
- procedure += " VARIABLES.var1 = L1.BCol3;\n"; //$NON-NLS-1$
- procedure += " END\n"; //$NON-NLS-1$
- procedure += " SELECT VARIABLES.Var1 AS e1;\n"; //$NON-NLS-1$
- procedure += "END\n"; //$NON-NLS-1$
-
- FakeMetadataFacade 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)})};
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testDefect8693() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where e2 = 5;\n"; //$NON-NLS-1$
- procedure = procedure + "if (5 in (select 5 from pm1.g1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
- FakeDataManager dataMgr = exampleDataManager(metadata);
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
- helpTestProcess(plan, 5, dataMgr, metadata);
- }
-
- @Test public void testWhileWithSubquery() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1 = 2;\n"; //$NON-NLS-1$
- procedure = procedure + "WHILE (5 in (select var1 from pm1.g1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
- FakeDataManager dataMgr = exampleDataManager(metadata);
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
- helpTestProcess(plan, 0, dataMgr, metadata);
- }
-
- @Test public void testDefect18404() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1 = 5 + (select count(e2) from pm1.g1);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
- FakeDataManager dataMgr = exampleDataManager(metadata);
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
- helpTestProcess(plan, 8, dataMgr, metadata);
- }
-
- /**
- * Test the use of a procedure variable in the criteria of a LEFT OUTER
- * JOIN which will be optimized out as non-JOIN criteria.
- * <p>
- * This test case verifies that the procedure variable will not be pushed
- * to the data manager when a federated source JOIN is performed.
- *
- * @throws Exception
- */
- @Test public void testRemovalOfNonJoinCritWithReference() throws Exception {
- String proc = ""; //$NON-NLS-1$
-
- String sql = ""; //$NON-NLS-1$
- sql += "SELECT " + //$NON-NLS-1$
- " pm1.g1.e1 AS pm1g1e1, " + //$NON-NLS-1$
- " pm2.g2.e1 AS pm2g2e1, " + //$NON-NLS-1$
- " pm1.g1.e2 AS pm1g1e2, " + //$NON-NLS-1$
- " pm2.g2.e2 AS pm2g2e2 " + //$NON-NLS-1$
- "FROM " + //$NON-NLS-1$
- " pm1.g1 " + //$NON-NLS-1$
- "LEFT OUTER JOIN pm2.g2 " + //$NON-NLS-1$
- " ON pm1.g1.e1 = pm2.g2.e1 " + //$NON-NLS-1$
- " AND pm2.g2.e2 = VARIABLES.myVar "; //$NON-NLS-1$
-
- proc += "CREATE VIRTUAL PROCEDURE " + //$NON-NLS-1$
- "BEGIN " + //$NON-NLS-1$
- " declare integer myVar = 5;" + //$NON-NLS-1$
- " " + sql + ";" + //$NON-NLS-1$ //$NON-NLS-2$
- "END"; //$NON-NLS-1$
-
- FakeMetadataFacade 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$
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
-
- assertTrue(!plan.requiresTransaction(false));
- }
-
- /**
- * Test the use of a procedure variable in the criteria of a LEFT OUTER
- * JOIN which will be optimized out as non-JOIN criteria.
- * <p>
- * This test case verifies that the procedure variable will not be pushed
- * to the data manager when a federated source JOIN is performed and the
- * physical source supports all capabilities.
- *
- * @throws Exception
- */
- @Test public void testRemovalOfNonJoinCritWithReference2() throws Exception {
- String proc = ""; //$NON-NLS-1$
-
- String sql = ""; //$NON-NLS-1$
- sql += "SELECT " + //$NON-NLS-1$
- " pm1.g1.e1 AS pm1g1e1, " + //$NON-NLS-1$
- " pm2.g2.e1 AS pm2g2e1, " + //$NON-NLS-1$
- " pm1.g1.e2 AS pm1g1e2, " + //$NON-NLS-1$
- " pm2.g2.e2 AS pm2g2e2 " + //$NON-NLS-1$
- "FROM " + //$NON-NLS-1$
- " pm1.g1 " + //$NON-NLS-1$
- "LEFT OUTER JOIN pm2.g2 " + //$NON-NLS-1$
- " ON pm1.g1.e1 = pm2.g2.e1 " + //$NON-NLS-1$
- " AND pm2.g2.e2 = VARIABLES.myVar "; //$NON-NLS-1$
-
- proc += "CREATE VIRTUAL PROCEDURE " + //$NON-NLS-1$
- "BEGIN " + //$NON-NLS-1$
- " declare integer myVar = 5;" + //$NON-NLS-1$
- " " + sql + ";" + //$NON-NLS-1$ //$NON-NLS-2$
- "END"; //$NON-NLS-1$
-
- FakeMetadataFacade 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$
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testUpdateDeleteTemp() throws Exception {
- String proc = "CREATE VIRTUAL PROCEDURE " + //$NON-NLS-1$
- "BEGIN " + //$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 e1 from #t1;\n" + //$NON-NLS-1$
- "END"; //$NON-NLS-1$
-
- FakeMetadataFacade 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[] { String.valueOf(1) } ),
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testTempSubqueryInput() throws Exception {
- String proc = "CREATE VIRTUAL PROCEDURE " + //$NON-NLS-1$
- "BEGIN " + //$NON-NLS-1$
- " create local temporary table t1 (e1 string);\n" + //$NON-NLS-1$
- " select e1 into t1 from pm1.g1;\n" + //$NON-NLS-1$
- " select e2 from (exec pm1.sq2((select max(e1) from t1))) x;\n" + //$NON-NLS-1$
- "END"; //$NON-NLS-1$
-
- FakeMetadataFacade 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( 51 ),
- };
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testUnambiguousVirtualProc() throws Exception {
- String userQuery = "EXEC MMSP6('1')"; //$NON-NLS-1$
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
- ProcessorPlan plan = getProcedurePlan(userQuery, metadata, TestOptimizer.getGenericFinder());
-
- List[] expected = new List[] {
- Arrays.asList( "1" ),
- };
- helpTestProcess(plan, expected, new HardcodedDataManager(), metadata);
- }
-
- @Test public void testParameterAssignments() throws Exception {
- TransformationMetadata metadata = RealMetadataFactory.exampleBQTCached();
- String userQuery = "EXEC TEIIDSP7(1)"; //$NON-NLS-1$
- HardcodedDataManager dataMgr = new HardcodedDataManager();
- ProcessorPlan plan = getProcedurePlan(userQuery, metadata);
- dataMgr.addData("x = EXEC spTest9(1)", new List[] {Arrays.asList(3)});
- dataMgr.addData("EXEC spTest11(3, null)", new List[] {Arrays.asList("1", 1, null), Arrays.asList(null, null, 4)});
- List[] expected = new List[] {Arrays.asList("34")};
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @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$
-
- StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n"); //$NON-NLS-1$
- procedure.append("BEGIN\n"); //$NON-NLS-1$
- procedure.append("create local temporary table x (y string);\n"); //$NON-NLS-1$
- procedure.append("declare string s = 'foo';\n"); //$NON-NLS-1$
- procedure.append("update x set y = in1 || s;\n"); //$NON-NLS-1$
- procedure.append("update pm1.g1 set e1 = lookup('pm1.g1', 'e1', 'e2', in1);\n"); //$NON-NLS-1$
- 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$
-
- metadata.getStore().addObject(rs2);
- metadata.getStore().addObject(sq1);
-
- String userUpdateStr = "EXEC pm1.sq1(1)"; //$NON-NLS-1$
-
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-
- //Create expected results
- List[] expected = new List[0];
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test public void testReturnParamWithNoResultSetVirtual() throws Exception {
- String sql = "EXEC TEIIDSP8(51)"; //$NON-NLS-1$
- TransformationMetadata metadata = RealMetadataFactory.exampleBQTCached();
- ProcessorPlan plan = getProcedurePlan(sql, metadata);
-
- // Set up data
- FakeDataManager dataMgr = new FakeDataManager();
-
- // Create expected results
- List[] expected = new List[] { Arrays.asList(51) }; //$NON-NLS-1$
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- @Test(expected=QueryProcessingException.class) public void testParamsWithResultSetVirtualNotNull() throws Exception {
- String sql = "{? = call TEIIDSP9(51)}"; //$NON-NLS-1$
- TransformationMetadata metadata = RealMetadataFactory.exampleBQTCached();
- ProcessorPlan plan = getProcedurePlan(sql, metadata);
-
- FakeDataManager dataMgr = new FakeDataManager();
-
- helpTestProcess(plan, null, dataMgr, metadata);
- }
-
- @Test public void testParamsWithResultSetVirtual() throws Exception {
- String sql = "{? = call TEIIDSP9(1)}"; //$NON-NLS-1$
- TransformationMetadata metadata = RealMetadataFactory.exampleBQTCached();
- ProcessorPlan plan = getProcedurePlan(sql, metadata);
-
- FakeDataManager dataMgr = new FakeDataManager();
-
- List[] expected = new List[] { Arrays.asList("hello", null, null),
- Arrays.asList(null, 1, 10) }; //$NON-NLS-1$
-
- helpTestProcess(plan, expected, dataMgr, metadata);
- }
-
- private static final boolean DEBUG = false;
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/proc/TestProcedureProcessor.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/proc/TestProcedureProcessor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/proc/TestProcedureProcessor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/proc/TestProcedureProcessor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,2438 @@
+/*
+ * 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 static org.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+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.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.query.analysis.AnalysisRecord;
+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.QueryOptimizer;
+import org.teiid.query.optimizer.TestOptimizer;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.FakeDataManager;
+import org.teiid.query.processor.FakeDataStore;
+import org.teiid.query.processor.HardcodedDataManager;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.TestProcessor;
+import org.teiid.query.processor.xml.TestXMLPlanningEnhancements;
+import org.teiid.query.processor.xml.TestXMLProcessor;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.SPParameter;
+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;
+
+ at SuppressWarnings({"unchecked", "nls"})
+public class TestProcedureProcessor {
+
+ public static ProcessorPlan getProcedurePlan(String userQuery, QueryMetadataInterface metadata) throws Exception {
+ return getProcedurePlan(userQuery, metadata, /*capabilitiesFinder*/null);
+ }
+
+ public static ProcessorPlan getProcedurePlan(String userQuery, QueryMetadataInterface metadata, CapabilitiesFinder capabilitiesFinder) throws Exception {
+ Command userCommand = QueryParser.getQueryParser().parseCommand(userQuery);
+ QueryResolver.resolveCommand(userCommand, metadata);
+ ValidatorReport report = Validator.validate(userCommand, metadata);
+
+ if (report.hasItems()) {
+ ValidatorFailure firstFailure = report.getItems().iterator().next();
+ throw new QueryValidatorException(firstFailure.getMessage());
+ }
+ QueryRewriter.rewrite(userCommand, metadata, new CommandContext());
+
+ AnalysisRecord analysisRecord = new AnalysisRecord(false, DEBUG);
+ try {
+ if ( capabilitiesFinder == null ) capabilitiesFinder = new DefaultCapabilitiesFinder();
+ ProcessorPlan plan = QueryOptimizer.optimizePlan(userCommand, metadata, null, capabilitiesFinder, analysisRecord, null);
+
+ return plan;
+ } finally {
+ if(DEBUG) {
+ System.out.println(analysisRecord.getDebugLog());
+ }
+ }
+ }
+
+ public static void helpTestProcess(ProcessorPlan procPlan, List[] expectedResults, ProcessorDataManager dataMgr, QueryMetadataInterface metadata) throws Exception {
+ CommandContext context = new CommandContext("pID", null, null, null, 1); //$NON-NLS-1$
+ if (!(metadata instanceof TempMetadataAdapter)) {
+ metadata = new TempMetadataAdapter(metadata, new TempMetadataStore());
+ }
+ context.setMetadata(metadata);
+
+ TestProcessor.helpProcess(procPlan, context, dataMgr, expectedResults);
+ assertNotNull("Expected processing to fail", expectedResults);
+ }
+
+ private void helpTestProcessFailure(ProcessorPlan procPlan, FakeDataManager dataMgr,
+ String failMessage, QueryMetadataInterface metadata) throws Exception {
+ try {
+ helpTestProcess(procPlan, null, dataMgr, metadata);
+ } catch(TeiidException ex) {
+ assertEquals(failMessage, ex.getMessage());
+ }
+ }
+
+ private void helpTestProcess(ProcessorPlan procPlan, int expectedRows, FakeDataManager dataMgr, QueryMetadataInterface metadata) throws Exception {
+ helpTestProcess(procPlan, new List[] {Arrays.asList(expectedRows)}, dataMgr, metadata);
+ }
+
+ private FakeDataManager exampleDataManager(QueryMetadataInterface metadata) throws TeiidException {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ dataMgr.registerTuples(
+ 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$
+ } );
+
+ dataMgr.registerTuples(
+ 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(QueryMetadataInterface metadata) throws TeiidException {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ dataMgr.registerTuples(
+ 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$
+ } );
+
+ dataMgr.registerTuples(
+ 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$
+ } );
+
+ dataMgr.registerTuples(
+ 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$
+ } );
+
+ dataMgr.registerTuples(
+ 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(QueryMetadataInterface metadata) throws TeiidException {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ dataMgr.registerTuples(
+ 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;
+ }
+
+ // procedure does nothing returns zero update count
+ @Test public void testProcedureProcessor1() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1 = 0;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, 0, dataMgr, metadata);
+ }
+
+ // testing if statement
+ @Test public void testProcedureProcessor2() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, 5, dataMgr, metadata);
+ }
+
+ // testing if statement
+ @Test public void testProcedureProcessor2WithBlockedException() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ dataMgr.setBlockOnce();
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, 5, dataMgr, metadata);
+ }
+
+ // testing rows updated incremented, Input and assignment statements
+ @Test public void testProcedureProcessor3() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = INPUT.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e2=40"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, 45, dataMgr, metadata);
+ }
+
+ // if/else test
+ @Test public void testProcedureProcessor4() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ELSE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e1, pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = INPUT.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e2=45"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, 5, dataMgr, metadata);
+ }
+
+ @Test public void testProcedureProcessor4WithBlockedException() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ELSE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e1, pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = INPUT.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e2=45"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ dataMgr.setBlockOnce();
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, 5, dataMgr, metadata);
+ }
+
+ // if/else test
+ @Test public void testProcedureProcessor5() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where e2=15;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ELSE\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where e2=5;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = INPUT.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e2=45"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, 50, dataMgr, metadata);
+ }
+
+ // more rows than expected
+ @Test public void testProcedureProcessor6() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcessFailure(plan, dataMgr, "Error Code:ERR.015.006.0058 Message:Unable to evaluate (SELECT pm1.g1.e2 FROM pm1.g1 LIMIT 2): Error Code:ERR.015.006.0058 Message:The command of this scalar subquery returned more than one value: SELECT pm1.g1.e2 FROM pm1.g1 LIMIT 2", metadata); //$NON-NLS-1$
+ }
+
+ // error statement
+ @Test public void testProcedureProcessor7() throws Exception {
+ String errorValue = "'MY ERROR'"; //$NON-NLS-1$
+ helpTestErrorStatment(errorValue, "MY ERROR"); //$NON-NLS-1$
+ }
+
+ @Test public void testProcedureProcessor8() throws Exception {
+ String errorValue = "var1"; //$NON-NLS-1$
+ helpTestErrorStatment(errorValue, "5"); //$NON-NLS-1$
+ }
+
+ @Test public void testProcedureProcessor9() throws Exception {
+ String errorValue = "var1||'MY ERROR'"; //$NON-NLS-1$
+ helpTestErrorStatment(errorValue, "5MY ERROR"); //$NON-NLS-1$
+ }
+
+ @Test public void testProcedureProcessor10() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "loop on (Select pm1.g1.e2 from pm1.g1 where e2 = 5) as mycursor\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ERROR (mycursor.e2||'MY ERROR');\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcessFailure(plan, dataMgr, ErrorInstruction.ERROR_PREFIX + "5MY ERROR", metadata); //$NON-NLS-1$
+ }
+
+ private void helpTestErrorStatment(String errorValue, String expected) throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = 5;\n"; //$NON-NLS-1$
+ procedure = procedure + "ERROR "+errorValue+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
+ procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcessFailure(plan, dataMgr, ErrorInstruction.ERROR_PREFIX + expected, metadata);
+ }
+
+ /** test if statement's if block with lookup in if condition */
+ @Test public void testLookupFunction1() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var2;\n"; //$NON-NLS-1$
+ procedure = procedure + "if('a' = lookup('pm1.g1','e1', 'e2', 0))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "var2 = INPUT.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED +1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ELSE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "var2 = 100;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED +13;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e2=30"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+ FakeDataManager dataMgr = new FakeDataManager();
+ FakeDataStore.sampleData2(dataMgr);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+ helpTestProcess(plan, 1, dataMgr, metadata);
+
+ }
+
+ /** test if statement's else block with lookup in if condition */
+ @Test public void testLookupFunction2() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var2;\n"; //$NON-NLS-1$
+ procedure = procedure + "if('a' = lookup('pm1.g1','e1', 'e2', 5))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "var2 = INPUT.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED +1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ELSE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "var2 = 100;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED +12;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e2=30"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+ FakeDataManager dataMgr = new FakeDataManager();
+ FakeDataStore.sampleData2(dataMgr);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+ helpTestProcess(plan, 12, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp2()"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedureWithBlockedException() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp2()"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ dataMgr.setBlockOnce();
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure2() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp3()"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure3() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp4()"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure4() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp5()"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure5() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp6()"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "Second"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure6() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp7(5)"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "Second"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure7() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp8(51)"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure8() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp9(51)"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure9() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp10(51)"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {};
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+
+ @Test public void testVirtualProcedure10() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp13()"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ 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$
+ 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[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure12() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp15()"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ // Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ dataMgr.registerTuples(
+ 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[] {
+ Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ //Defect17447_testVirtualProcedure13
+ @Test public void testVirtualProcedure13() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp16()"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ // Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ dataMgr.registerTuples(
+ 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[] {
+ Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure14() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp17()"; //$NON-NLS-1$
+ 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[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure15() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp19()"; //$NON-NLS-1$
+ 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[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure16() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp20()"; //$NON-NLS-1$
+ 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[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Fourth"})}; //$NON-NLS-1$
+ CommandContext context = new CommandContext("pID", null, null, null, 1); //$NON-NLS-1$
+ context.setMetadata(metadata);
+ context.setProcessorBatchSize(1); //ensure that the final temp result set will not be deleted prematurely
+
+ TestProcessor.helpProcess(plan, context, dataMgr, expected);
+ }
+
+ @Test public void testVirtualProcedure17() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp21(7)"; //$NON-NLS-1$
+ 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[] { "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$
+ 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", 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$
+ 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", 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$
+ 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", 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$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ //Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {};
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ //procedure with Has Criteria and Translate Criteria
+ @Test public void testDefect13625() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "IF(HAS CRITERIA ON (vm1.g4.e2))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA ON (vm1.g4.e2);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE g4 SET e1='x' where e2=5"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, 5, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure30() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp30()"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"}) }; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure31() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp31(51)"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+ // Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "Third"}) }; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedureDefect14282() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp24()"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "Second"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDefect16193() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp35(51)"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "Third"}) }; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedure16602() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp37()"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+
+ // Set up data
+ HardcodedDataManager dataMgr = new HardcodedDataManager();
+ dataMgr.addData("INSERT INTO pm1.g1 (e1, e2, e3, e4) VALUES (null, 5, UNKNOWN, null)", new List[] {Arrays.asList(1)});
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(1)};
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDefect16649_1() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp38()"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "Second"}) }; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDefect16649_2() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp39()"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "Second"}) }; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDefect16694() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp40()"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "Second"}) }; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDefect16707() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp44(2)"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDefect16707_1() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp43(2)"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDefect17451() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp45()"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ //Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ dataMgr.registerTuples(
+ 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[] {
+ Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ //Defect 17447
+ @Test public void testVirtualProcedure46() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp46()"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDefect17650() throws Exception {
+ String procedure1 = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure1 = procedure1 + "BEGIN\n"; //$NON-NLS-1$
+ procedure1 = procedure1 + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure1 = procedure1 + "IF(HAS CRITERIA ON (vm1.g1.e2))\n"; //$NON-NLS-1$
+ procedure1 = procedure1 + "BEGIN\n"; //$NON-NLS-1$
+ procedure1 = procedure1 + "ROWS_UPDATED = UPDATE vm1.g2 SET e1='x' where TRANSLATE = CRITERIA ON (vm1.g1.e2);\n"; //$NON-NLS-1$
+ procedure1 = procedure1 + "END\n"; //$NON-NLS-1$
+ procedure1 = procedure1 + "END"; //$NON-NLS-1$
+
+ String procedure2 = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure2 = procedure2 + "BEGIN\n"; //$NON-NLS-1$
+ procedure2 = procedure2 + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure2 = procedure2 + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE CRITERIA;\n";//$NON-NLS-1$
+ procedure2 = procedure2 + "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
+ procedure2 = procedure2 + "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x' where e2=5"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure1, procedure2);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, 5, dataMgr, metadata);
+ }
+
+ @Test public void testDefect19982() throws Exception {
+ String userUpdateStr = "EXEC pm1.vsp55(5)"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ 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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+// Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+// Arrays.asList(new Object[] { "Third"}), //$NON-NLS-1$
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ //procedure with Has Criteria and Translate Criteria and changing
+ @Test public void testDynamicCommandWithTranslate() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "IF(HAS CRITERIA ON (vm1.g4.e2))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "execute string 'Select pm1.g1.e2 x, changing.e1 y from pm1.g1 where TRANSLATE = CRITERIA ON (vm1.g4.e2)' as x integer, y boolean into #temp;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = select x from #temp;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 = 5)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE g4 SET e1='x' where e2=5"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, 5, dataMgr, metadata);
+ }
+
+ @Test public void testDynamicCommandWithIntoExpression() throws Exception {
+
+ //Test INTO clause with expression
+ 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";
+
+ addProc(metadata, query);
+
+ String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ //Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First" }), //$NON-NLS-1$
+ };
+ 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
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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$
+ procedure.append("execute string 'SELECT e1, e2 FROM pm1.g1' as e1 string, e2 integer into #temp;\n"); //$NON-NLS-1$
+ procedure.append("loop on (Select e2 from #temp where e2 > 2) as mycursor\n"); //$NON-NLS-1$
+ procedure.append("BEGIN\n"); //$NON-NLS-1$
+ procedure.append("IF (mycursor.e2>5) \n"); //$NON-NLS-1$
+ procedure.append("VARIABLES.e2_total=VARIABLES.e2_total+mycursor.e2;\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, procedure.toString());
+
+ String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ //Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { Integer.valueOf(66)}),
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDynamicCommandWithParameter() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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});
+
+ String userUpdateStr = "EXEC pm1.sq2('First')"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First", Integer.valueOf(5) }), //$NON-NLS-1$
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDynamicCommandWithUsing() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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});
+
+ String userUpdateStr = "EXEC pm1.sq2('First')"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First", Integer.valueOf(5) }), //$NON-NLS-1$
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDynamicCommandWithVariable() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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});
+
+ String userUpdateStr = "EXEC pm1.sq2('First')"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First", Integer.valueOf(5) }), //$NON-NLS-1$
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDynamicCommandValidationFails() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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});
+
+ String userUpdateStr = "EXEC pm1.sq2('First')"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ try {
+ helpTestProcess(plan, null, dataMgr, metadata);
+ fail("exception expected");
+ } catch (QueryProcessingException e) {
+ assertTrue(e.getCause() instanceof QueryValidatorException);
+ }
+ }
+
+ @Test public void testDynamicCommandWithSingleSelect() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ addProc(metadata, "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+ + "execute string 'SELECT 26'; END");
+
+ String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "26" }), //$NON-NLS-1$
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+
+ //converts e1 from integer to string, with a different name
+ @Test public void testDynamicCommandTypeConversion() throws Exception {
+ 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);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "5" }), //$NON-NLS-1$
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDynamicCommandRecursion() throws Exception {
+ 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});
+
+ String userUpdateStr = "EXEC pm1.sq2('First')"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcessFailure(plan,
+ dataMgr,
+ "Couldn't execute the dynamic SQL command \"EXECUTE 'EXEC pm1.sq2(''First'')' AS e1 string, e2 integer\" with the SQL statement \"'EXEC pm1.sq2(''First'')'\" due to: There is a recursive invocation of group 'PM1.SQ2'. Please correct the SQL.", metadata); //$NON-NLS-1$
+ }
+
+ @Test public void testDynamicCommandIncorrectProjectSymbolCount() throws Exception {
+ //Tests dynamic query with incorrect number of elements
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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});
+
+ 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);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcessFailure(plan, dataMgr, "Couldn't execute the dynamic SQL command \"EXECUTE 'EXEC pm1.sq1(''First'')' AS e1 string, e2 integer\" with the SQL statement \"'EXEC pm1.sq1(''First'')'\" due to: The dynamic sql string contains an incorrect number of elements.", metadata); //$NON-NLS-1$
+ }
+
+ @Test public void testDynamicCommandPositional() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, new List[] {Arrays.asList("First", "5"), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList("Second", "15"), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList("Third", "51")}, dataMgr, metadata); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDynamicCommandIncorrectProjectSymbolDatatypes() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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$
+
+ String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcessFailure(plan, dataMgr, "Couldn't execute the dynamic SQL command \"EXECUTE 'select e1 from pm1.g1'\" with the SQL statement \"'select e1 from pm1.g1'\" due to: The datatype 'string' for element 'e1' in the dynamic SQL cannot be implicitly converted to 'integer'.", metadata); //$NON-NLS-1$
+ }
+
+ @Test public void testDynamicCommandWithTwoDynamicStatements() throws Exception {
+ //Tests dynamic query with two consecutive DynamicCommands. The first without an AS clause and returning different results.
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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]);
+
+ String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ 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 {
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ String sql = new StringBuffer("declare integer caseValue = ") //$NON-NLS-1$
+ .append("CASE") //$NON-NLS-1$
+ .append(" WHEN pm1.sq1.param='a' THEN 0") //$NON-NLS-1$
+ .append(" WHEN pm1.sq1.param='b' THEN 1") //$NON-NLS-1$
+ .append(" WHEN pm1.sq1.param='c' THEN 2") //$NON-NLS-1$
+ .append(" WHEN pm1.sq1.param='d' THEN 3") //$NON-NLS-1$
+ .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$
+
+ String userUpdateStr = "EXEC pm1.sq1('d')"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { Integer.valueOf(3) }),
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @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
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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$
+
+ String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManagerPm5(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ 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.
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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$
+
+ String userUpdateStr = "EXEC pm1.sq1(convert(5,short))"; //$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 Short((short)5)})}; //$NON-NLS-1$
+
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedureWithCreate() throws Exception{
+ String userUpdateStr = "EXEC pm1.vsp60()"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedureWithCreateAndDrop() throws Exception{
+ String userUpdateStr = "EXEC pm1.vsp61()"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testVirtualProcedureWithCreateAndSelectInto() throws Exception{
+ String userUpdateStr = "EXEC pm1.vsp62()"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDifferentlyScopedTempTables() throws Exception {
+
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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$
+ procedure.append("if (e2_total = 0)"); //$NON-NLS-1$
+ procedure.append("BEGIN\n"); //$NON-NLS-1$
+ procedure.append("select e1 into #temp from pm1.g1;\n"); //$NON-NLS-1$
+ procedure.append("VARIABLES.e2_total=select count(*) from #temp;\n"); //$NON-NLS-1$
+ procedure.append("END\n"); //$NON-NLS-1$
+ procedure.append("if (e2_total = 3)"); //$NON-NLS-1$
+ procedure.append("BEGIN\n"); //$NON-NLS-1$
+ procedure.append("select e1 into #temp from pm1.g1;\n"); //$NON-NLS-1$
+ procedure.append("VARIABLES.e2_total=select count(*) from #temp;\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, procedure.toString());
+
+ String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ //Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { Integer.valueOf(3)}),
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testLoopsWithBreak() throws Exception {
+
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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$
+ procedure.append("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("break;\n"); //$NON-NLS-1$
+ procedure.append("END\n"); //$NON-NLS-1$
+ procedure.append("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;"); //$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, procedure.toString());
+
+ String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ //Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { Integer.valueOf(76)}),
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testCreateWithoutDrop() throws Exception {
+
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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$
+ procedure.append("create local temporary table t1 (e1 integer);\n"); //$NON-NLS-1$
+ procedure.append("SELECT e1 from t1;\n"); //$NON-NLS-1$
+ procedure.append("END"); //$NON-NLS-1$
+
+ addProc(metadata, procedure.toString());
+
+ String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcessFailure(plan, dataMgr, "Temporary table \"T1\" already exists.", metadata); //$NON-NLS-1$
+ }
+
+ /**
+ * We allow drops to silently fail
+ */
+ @Test public void testDoubleDrop() throws Exception {
+
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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$
+ procedure.append("select e1 into t1 from pm1.g1;\n"); //$NON-NLS-1$
+ procedure.append("drop table t1;\n"); //$NON-NLS-1$
+ procedure.append("drop table t1;\n"); //$NON-NLS-1$
+ procedure.append("SELECT 1;\n"); //$NON-NLS-1$
+ procedure.append("END"); //$NON-NLS-1$
+
+ addProc(metadata, procedure.toString());
+
+ String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, new List[] {Arrays.asList(1)}, dataMgr, metadata);
+ }
+
+ /**
+ * defect 23975
+ */
+ @Test public void testFunctionInput() throws Exception {
+ MetadataStore metadataStore = new MetadataStore();
+ Schema v1 = RealMetadataFactory.createVirtualModel("v1", metadataStore); //$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$
+ Procedure vt1 = RealMetadataFactory.createVirtualProcedure("vp1", v1, Arrays.asList(p1), n1); //$NON-NLS-1$
+ vt1.setResultSet(rs1);
+
+ 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$
+ 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$
+
+ String sql = "exec v1.vp1('1')"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "11" }), //$NON-NLS-1$
+ };
+
+ QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
+
+ // Construct data manager with data
+ // Plan query
+ ProcessorPlan plan = getProcedurePlan(sql, metadata);
+ // Run query
+ helpTestProcess(plan, expected, new FakeDataManager(), metadata);
+ }
+
+ /**
+ * defect 23976
+ * Also, even after the bug for passing procedure inputs to non-execs was fixed, the special case of
+ * if (below) and while statements popped up.
+ */
+ @Test public void testIfEvaluation() throws Exception {
+ String procedure1 = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure1 += "BEGIN\n"; //$NON-NLS-1$
+ procedure1 += "DECLARE string var1 = INPUT.e1;\n"; //$NON-NLS-1$
+ procedure1 += "ROWS_UPDATED = UPDATE vm1.g2 SET e1=var1;\n"; //$NON-NLS-1$
+ procedure1 += "END"; //$NON-NLS-1$
+
+ String procedure2 = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure2 += "BEGIN\n"; //$NON-NLS-1$
+ procedure2 += "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure2 += "IF (INPUT.e1 = 1)\n"; //$NON-NLS-1$
+ procedure2 += "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
+ procedure2 += "ELSE\n"; //$NON-NLS-1$
+ procedure2 += "ROWS_UPDATED = 4;\n"; //$NON-NLS-1$
+ procedure2 += "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x' where e2=5"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure1, procedure2);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, 4, new FakeDataManager(), metadata);
+ }
+
+ /**
+ * This is a slight variation of TestProcessor.testVariableInExecParam, where the proc wrapper can be
+ * removed after rewrite
+ */
+ @Test public void testReferenceForwarding() throws Exception {
+ // Create query
+ String sql = "EXEC pm1.vsp49()"; //$NON-NLS-1$
+
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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$
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "b", Integer.valueOf(2) }), //$NON-NLS-1$
+ };
+
+ // Construct data manager with data
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+
+ // Plan query
+ ProcessorPlan plan = getProcedurePlan(sql, metadata);
+
+ // Run query
+ helpTestProcess(plan, expected, dataManager, metadata);
+ }
+
+ @Test public void testInsertAfterCreate() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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$
+ .append("\n insert into #temp (e1) values ('a');") //$NON-NLS-1$
+ .append("\n insert into #temp (e2) values ('b');") //$NON-NLS-1$
+ .append("SELECT e2 as e1 from #temp;\n") //$NON-NLS-1$
+ .append("END"); //$NON-NLS-1$
+
+ addProc(metadata, procedure.toString());
+
+ String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, new List[] {
+ Arrays.asList(new Object[] {null}),
+ Arrays.asList(new Object[] {"b"})}, dataMgr, metadata); //$NON-NLS-1$
+
+ }
+
+ /**
+ * the update will not be executed, but the assignment value should still be 0
+ */
+ @Test public void testUpdateAssignmentNotExecuted() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1 = UPDATE pm1.g1 SET pm1.g1.e1 = INPUT.e2;"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = var1 + 1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE g4 SET e1='x' where e2=5"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, 1, dataMgr, metadata);
+
+ assertTrue(plan.requiresTransaction(false));
+ }
+
+ @Test public void testUpdateAssignmentNotExecutedVirtual() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1 = UPDATE vm1.g2 SET e1 = INPUT.e2;"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = var1 + 1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END"; //$NON-NLS-1$
+
+ String procedure2 = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure2 += "BEGIN\n"; //$NON-NLS-1$
+ procedure2 += "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure2 += "IF (INPUT.e1 = 1)\n"; //$NON-NLS-1$
+ procedure2 += "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
+ procedure2 += "ELSE\n"; //$NON-NLS-1$
+ procedure2 += "ROWS_UPDATED = 4;\n"; //$NON-NLS-1$
+ procedure2 += "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x' where e2=5"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure, procedure2);
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, 1, dataMgr, metadata);
+ }
+
+ @Test public void testEvaluatableSelectWithOrderBy() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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$
+
+ 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$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, new List[] {
+ Arrays.asList(new Object[] {"1"})}, dataMgr, metadata); //$NON-NLS-1$
+
+ }
+
+ @Test public void testEvaluatableSelectWithOrderBy1() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ 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$
+
+ 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$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, new List[] {
+ Arrays.asList(new Object[] {"1"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] {"First"}), //$NON-NLS-1$
+ }, dataMgr, metadata);
+
+ }
+
+ /**
+ * Tests non-deterministic evaluation of the rand function. There are two important things happening
+ * 1. is that the evaluation of the rand function is delayed until processing time (which actually has predictable
+ * values since the test initializes the command context with the same seed)
+ * 2. The values are different, meaning that we got individual evaluations
+ *
+ * If this function were deterministic, it would be evaluated during rewrite to a single value.
+ */
+ @Test public void testNonDeterministicEvaluation() throws Exception {
+ StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n") //$NON-NLS-1$
+ .append("BEGIN\n") //$NON-NLS-1$
+ .append("DECLARE integer x = 0;\n") //$NON-NLS-1$
+ .append("CREATE LOCAL TEMPORARY TABLE #TEMP (e1 integer);\n") //$NON-NLS-1$
+ .append("while (x < 2)\n") //$NON-NLS-1$
+ .append("BEGIN\n") //$NON-NLS-1$
+ .append("insert into #temp (e1) values (convert(rand() * 1000, integer));\n") //$NON-NLS-1$
+ .append("x = x + 1;\n") //$NON-NLS-1$
+ .append("END\n") //$NON-NLS-1$
+ .append("SELECT * FROM #TEMP;\n") //$NON-NLS-1$
+ .append("END"); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = createProcedureMetadata(procedure.toString());
+
+ String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+
+ helpTestProcess(plan, new List[] {
+ Arrays.asList(new Object[] {Integer.valueOf(240)}),
+ Arrays.asList(new Object[] {Integer.valueOf(637)})}, dataMgr, metadata);
+ }
+
+ 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;
+ }
+
+ @Test public void testTempTableTypeConversion() throws Exception {
+
+ String procedure = "CREATE VIRTUAL PROCEDURE\n"; //$NON-NLS-1$
+ procedure += "BEGIN\n"; //$NON-NLS-1$
+ procedure += "CREATE local temporary table temp (x string, y integer);\n"; //$NON-NLS-1$
+ procedure += "Select pm1.g1.e2 as e1, pm1.g1.e2 into temp from pm1.g1 order by pm1.g1.e2 limit 1;\n"; //$NON-NLS-1$
+ procedure += "Select x from temp;\n"; //$NON-NLS-1$
+ procedure += "END\n"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = createProcedureMetadata(procedure);
+
+ String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ helpTestProcess(plan, new List[] {
+ Arrays.asList(new Object[] {"5"}), //$NON-NLS-1$
+ }, dataMgr, metadata);
+ }
+
+ /**
+ * wraps {@link TestXMLPlanningEnhancements.testNested2WithContextCriteria5d1} in a procedure
+ */
+ @Test public void testXMLWithExternalCriteria() throws Exception {
+ TransformationMetadata metadata = TestXMLProcessor.exampleMetadata();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+ String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5d.xml"; //$NON-NLS-1$
+ String expectedDoc = TestXMLProcessor.readFile(resultFile);
+
+ Schema pm1 = metadata.getMetadataStore().getSchemas().get("XMLTEST"); //$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 = 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 proc(5)"; //$NON-NLS-1$
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { expectedDoc }),
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testXMLWithExternalCriteria_InXMLVar() throws Exception {
+ 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$
+ Schema pm1 = metadata.getMetadataStore().getSchemas().get("XMLTEST"); //$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 = 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);
+
+ String userUpdateStr = "EXEC proc(5)"; //$NON-NLS-1$
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { expectedDoc }),
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ /**
+ * wraps {@link TestXMLProcessor.testNested2WithCriteria2} in a procedure
+ *
+ * This one will successfully auto-stage
+ */
+ @Test public void testXMLWithExternalCriteria1() throws Exception {
+ TransformationMetadata metadata = TestXMLProcessor.exampleMetadata();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$
+ "<Catalogs>\n" + //$NON-NLS-1$
+ " <Catalog>\n" + //$NON-NLS-1$
+ " <Items>\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\n" + //$NON-NLS-1$
+ " <Name>Lamp</Name>\n" + //$NON-NLS-1$
+ " <Quantity>5</Quantity>\n" + //$NON-NLS-1$
+ " <Suppliers>\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\n" + //$NON-NLS-1$
+ " <Orders>\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\n" + //$NON-NLS-1$
+ " </Order>\n" + //$NON-NLS-1$
+ " </Orders>\n" + //$NON-NLS-1$
+ " </Supplier>\n" + //$NON-NLS-1$
+ " </Suppliers>\n" + //$NON-NLS-1$
+ " </Item>\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\n" + //$NON-NLS-1$
+ " <Name>Screwdriver</Name>\n" + //$NON-NLS-1$
+ " <Quantity>100</Quantity>\n" + //$NON-NLS-1$
+ " <Suppliers/>\n" + //$NON-NLS-1$
+ " </Item>\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\n" + //$NON-NLS-1$
+ " <Name>Goat</Name>\n" + //$NON-NLS-1$
+ " <Quantity>4</Quantity>\n" + //$NON-NLS-1$
+ " <Suppliers/>\n" + //$NON-NLS-1$
+ " </Item>\n" + //$NON-NLS-1$
+ " </Items>\n" + //$NON-NLS-1$
+ " </Catalog>\n" + //$NON-NLS-1$
+ "</Catalogs>"; //$NON-NLS-1$
+
+ Schema pm1 = metadata.getMetadataStore().getSchemas().get("XMLTEST"); //$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$
+ 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);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { expectedDoc }),
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testCase174806() throws Exception{
+ String userUpdateStr = "EXEC pm1.vsp63()"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "c"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @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$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ // Set up data
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ // Create expected results
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "First"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Second"}), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "Third"})}; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ /**
+ * Test the procedure <code>DECLARE</code> statement using a query as the assignment value
+ *
+ * <p>The use of a query as the assignment value to a <code>DECLARE</code>
+ * statement should execute without error as long as the query
+ * is valid and fully resolvable.</p>
+ *
+ * <p>This test is related to JBEDSP-818 in which the query in the
+ * <code>LOOP</code> statement would fail due to a query being used as the
+ * assigned value in the <code>DECLARE</code> statement.</p>
+ * @throws Exception
+ */
+ @Test public void testDeclareWithQueryAssignment() throws Exception {
+ // procedure comes from test case IT236455 / JBEDSP-818
+ String procedure = "CREATE VIRTUAL PROCEDURE \n"; //$NON-NLS-1$
+ procedure += "BEGIN\n"; //$NON-NLS-1$
+ procedure += " DECLARE integer VARIABLES.var1 = 0;\n"; //$NON-NLS-1$
+ procedure += " /* the following DECLARE with ASSIGNMENT to a query should work "; //$NON-NLS-1$
+ procedure += " but in IT236455 it results in the assignment inside the LOOP "; //$NON-NLS-1$
+ procedure += " to fail */ "; //$NON-NLS-1$
+ procedure += " DECLARE integer VARIABLES.NLEVELS = SELECT COUNT(*) FROM (\n"; //$NON-NLS-1$
+ procedure += " SELECT 'Col1' AS ACol1, 'Col2' AS ACol2, convert(3, integer) AS ACol3\n"; //$NON-NLS-1$
+ procedure += " ) AS Src;\n"; //$NON-NLS-1$
+ procedure += " LOOP ON (\n"; //$NON-NLS-1$
+ procedure += " SELECT StaticTable.BCol1, StaticTable.BCol2, StaticTable.BCol3 FROM (\n"; //$NON-NLS-1$
+ procedure += " SELECT 'Col 1' AS BCol1, 'Col 2' AS BCol2, convert(3, integer) AS BCol3\n"; //$NON-NLS-1$
+ procedure += " ) AS StaticTable\n"; //$NON-NLS-1$
+ procedure += " ) AS L1\n"; //$NON-NLS-1$
+ procedure += " BEGIN\n"; //$NON-NLS-1$
+ procedure += " /* In IT236455 the following would fail as the results from "; //$NON-NLS-1$
+ procedure += " the LOOP (L1) are not in scope when the assignment is being "; //$NON-NLS-1$
+ procedure += " performed due to the query earlier being part of a DECLARE "; //$NON-NLS-1$
+ procedure += " statement. */ "; //$NON-NLS-1$
+ procedure += " VARIABLES.var1 = L1.BCol3;\n"; //$NON-NLS-1$
+ procedure += " END\n"; //$NON-NLS-1$
+ procedure += " SELECT VARIABLES.Var1 AS e1;\n"; //$NON-NLS-1$
+ procedure += "END\n"; //$NON-NLS-1$
+
+ 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[] {Integer.valueOf(3)})};
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testDefect8693() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where e2 = 5;\n"; //$NON-NLS-1$
+ procedure = procedure + "if (5 in (select 5 from pm1.g1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+ helpTestProcess(plan, 5, dataMgr, metadata);
+ }
+
+ @Test public void testWhileWithSubquery() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1 = 2;\n"; //$NON-NLS-1$
+ procedure = procedure + "WHILE (5 in (select var1 from pm1.g1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+ helpTestProcess(plan, 0, dataMgr, metadata);
+ }
+
+ @Test public void testDefect18404() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1 = 5 + (select count(e2) from pm1.g1);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+ helpTestProcess(plan, 8, dataMgr, metadata);
+ }
+
+ /**
+ * Test the use of a procedure variable in the criteria of a LEFT OUTER
+ * JOIN which will be optimized out as non-JOIN criteria.
+ * <p>
+ * This test case verifies that the procedure variable will not be pushed
+ * to the data manager when a federated source JOIN is performed.
+ *
+ * @throws Exception
+ */
+ @Test public void testRemovalOfNonJoinCritWithReference() throws Exception {
+ String proc = ""; //$NON-NLS-1$
+
+ String sql = ""; //$NON-NLS-1$
+ sql += "SELECT " + //$NON-NLS-1$
+ " pm1.g1.e1 AS pm1g1e1, " + //$NON-NLS-1$
+ " pm2.g2.e1 AS pm2g2e1, " + //$NON-NLS-1$
+ " pm1.g1.e2 AS pm1g1e2, " + //$NON-NLS-1$
+ " pm2.g2.e2 AS pm2g2e2 " + //$NON-NLS-1$
+ "FROM " + //$NON-NLS-1$
+ " pm1.g1 " + //$NON-NLS-1$
+ "LEFT OUTER JOIN pm2.g2 " + //$NON-NLS-1$
+ " ON pm1.g1.e1 = pm2.g2.e1 " + //$NON-NLS-1$
+ " AND pm2.g2.e2 = VARIABLES.myVar "; //$NON-NLS-1$
+
+ proc += "CREATE VIRTUAL PROCEDURE " + //$NON-NLS-1$
+ "BEGIN " + //$NON-NLS-1$
+ " declare integer myVar = 5;" + //$NON-NLS-1$
+ " " + sql + ";" + //$NON-NLS-1$ //$NON-NLS-2$
+ "END"; //$NON-NLS-1$
+
+ 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", 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);
+
+ assertTrue(!plan.requiresTransaction(false));
+ }
+
+ /**
+ * Test the use of a procedure variable in the criteria of a LEFT OUTER
+ * JOIN which will be optimized out as non-JOIN criteria.
+ * <p>
+ * This test case verifies that the procedure variable will not be pushed
+ * to the data manager when a federated source JOIN is performed and the
+ * physical source supports all capabilities.
+ *
+ * @throws Exception
+ */
+ @Test public void testRemovalOfNonJoinCritWithReference2() throws Exception {
+ String proc = ""; //$NON-NLS-1$
+
+ String sql = ""; //$NON-NLS-1$
+ sql += "SELECT " + //$NON-NLS-1$
+ " pm1.g1.e1 AS pm1g1e1, " + //$NON-NLS-1$
+ " pm2.g2.e1 AS pm2g2e1, " + //$NON-NLS-1$
+ " pm1.g1.e2 AS pm1g1e2, " + //$NON-NLS-1$
+ " pm2.g2.e2 AS pm2g2e2 " + //$NON-NLS-1$
+ "FROM " + //$NON-NLS-1$
+ " pm1.g1 " + //$NON-NLS-1$
+ "LEFT OUTER JOIN pm2.g2 " + //$NON-NLS-1$
+ " ON pm1.g1.e1 = pm2.g2.e1 " + //$NON-NLS-1$
+ " AND pm2.g2.e2 = VARIABLES.myVar "; //$NON-NLS-1$
+
+ proc += "CREATE VIRTUAL PROCEDURE " + //$NON-NLS-1$
+ "BEGIN " + //$NON-NLS-1$
+ " declare integer myVar = 5;" + //$NON-NLS-1$
+ " " + sql + ";" + //$NON-NLS-1$ //$NON-NLS-2$
+ "END"; //$NON-NLS-1$
+
+ 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", 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);
+ }
+
+ @Test public void testUpdateDeleteTemp() throws Exception {
+ String proc = "CREATE VIRTUAL PROCEDURE " + //$NON-NLS-1$
+ "BEGIN " + //$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 e1 from #t1;\n" + //$NON-NLS-1$
+ "END"; //$NON-NLS-1$
+
+ 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[] { String.valueOf(1) } ),
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testTempSubqueryInput() throws Exception {
+ String proc = "CREATE VIRTUAL PROCEDURE " + //$NON-NLS-1$
+ "BEGIN " + //$NON-NLS-1$
+ " create local temporary table t1 (e1 string);\n" + //$NON-NLS-1$
+ " select e1 into t1 from pm1.g1;\n" + //$NON-NLS-1$
+ " select e2 from (exec pm1.sq2((select max(e1) from t1))) x;\n" + //$NON-NLS-1$
+ "END"; //$NON-NLS-1$
+
+ 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( 51 ),
+ };
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testUnambiguousVirtualProc() throws Exception {
+ String userQuery = "EXEC MMSP6('1')"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+ ProcessorPlan plan = getProcedurePlan(userQuery, metadata, TestOptimizer.getGenericFinder());
+
+ List[] expected = new List[] {
+ Arrays.asList( "1" ),
+ };
+ helpTestProcess(plan, expected, new HardcodedDataManager(), metadata);
+ }
+
+ @Test public void testParameterAssignments() throws Exception {
+ TransformationMetadata metadata = RealMetadataFactory.exampleBQTCached();
+ String userQuery = "EXEC TEIIDSP7(1)"; //$NON-NLS-1$
+ HardcodedDataManager dataMgr = new HardcodedDataManager();
+ ProcessorPlan plan = getProcedurePlan(userQuery, metadata);
+ dataMgr.addData("x = EXEC spTest9(1)", new List[] {Arrays.asList(3)});
+ dataMgr.addData("EXEC spTest11(3, null)", new List[] {Arrays.asList("1", 1, null), Arrays.asList(null, null, 4)});
+ List[] expected = new List[] {Arrays.asList("34")};
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testNonQueryPushdownValidation() throws Exception {
+
+ TransformationMetadata metadata = RealMetadataFactory.example1();
+
+ StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n"); //$NON-NLS-1$
+ procedure.append("BEGIN\n"); //$NON-NLS-1$
+ procedure.append("create local temporary table x (y string);\n"); //$NON-NLS-1$
+ procedure.append("declare string s = 'foo';\n"); //$NON-NLS-1$
+ procedure.append("update x set y = in1 || s;\n"); //$NON-NLS-1$
+ procedure.append("update pm1.g1 set e1 = lookup('pm1.g1', 'e1', 'e2', in1);\n"); //$NON-NLS-1$
+ procedure.append("exec pm1.sq2(in1 || 'foo');\n"); //$NON-NLS-1$
+ procedure.append("END"); //$NON-NLS-1$
+
+ addProc(metadata, "sq1", procedure.toString(), new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }, new String[] {"in1"}, new String[] {DataTypeManager.DefaultDataTypes.INTEGER});
+
+ String userUpdateStr = "EXEC pm1.sq1(1)"; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
+
+ //Create expected results
+ List[] expected = new List[0];
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test public void testReturnParamWithNoResultSetVirtual() throws Exception {
+ String sql = "EXEC TEIIDSP8(51)"; //$NON-NLS-1$
+ TransformationMetadata metadata = RealMetadataFactory.exampleBQTCached();
+ ProcessorPlan plan = getProcedurePlan(sql, metadata);
+
+ // Set up data
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ // Create expected results
+ List[] expected = new List[] { Arrays.asList(51) }; //$NON-NLS-1$
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ @Test(expected=QueryProcessingException.class) public void testParamsWithResultSetVirtualNotNull() throws Exception {
+ String sql = "{? = call TEIIDSP9(51)}"; //$NON-NLS-1$
+ TransformationMetadata metadata = RealMetadataFactory.exampleBQTCached();
+ ProcessorPlan plan = getProcedurePlan(sql, metadata);
+
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ helpTestProcess(plan, null, dataMgr, metadata);
+ }
+
+ @Test public void testParamsWithResultSetVirtual() throws Exception {
+ String sql = "{? = call TEIIDSP9(1)}"; //$NON-NLS-1$
+ TransformationMetadata metadata = RealMetadataFactory.exampleBQTCached();
+ ProcessorPlan plan = getProcedurePlan(sql, metadata);
+
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ List[] expected = new List[] { Arrays.asList("hello", null, null),
+ Arrays.asList(null, 1, 10) }; //$NON-NLS-1$
+
+ helpTestProcess(plan, expected, dataMgr, metadata);
+ }
+
+ private static final boolean DEBUG = false;
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestAccessNode.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/relational/TestAccessNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestAccessNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,127 +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 static org.junit.Assert.*;
-
-import java.util.Arrays;
-
-import org.junit.Test;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.BufferManagerFactory;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.FakeDataManager;
-import org.teiid.query.processor.TestProcessor;
-import org.teiid.query.resolver.TestResolver;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.IsNullCriteria;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.SetClauseList;
-import org.teiid.query.sql.lang.Update;
-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.util.CommandContext;
-
-
-
-/**
- * @since 4.2
- */
-public class TestAccessNode {
-
- private void helpTestOpen(Command command, String expectedCommand, boolean shouldRegisterRequest) throws Exception {
- // Setup
- AccessNode node = new AccessNode(1);
- node.setCommand(command);
- CommandContext context = new CommandContext();
- context.setProcessorID("processorID"); //$NON-NLS-1$
- BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
- node.setElements(command.getProjectedSymbols());
- node.initialize(context, bm, dataManager);
- node.setShouldEvaluateExpressions(true);
- // Call open()
- node.open();
- if (shouldRegisterRequest) {
- assertEquals(Arrays.asList(expectedCommand), dataManager.getQueries());
- } else {
- assertEquals(0, dataManager.getQueries().size());
- }
- }
-
- @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$
- IsNullCriteria nullCrit = (IsNullCriteria)((CompoundCriteria)query.getCriteria()).getCriteria(1);
- nullCrit.setExpression(new Constant(null));
-
- helpTestOpen(query, "SELECT e1, e2 FROM pm1.g1 WHERE e2 = 5", true); //$NON-NLS-1$
- }
-
- @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$
- IsNullCriteria nullCrit = (IsNullCriteria)((CompoundCriteria)query.getCriteria()).getCriteria(1);
- nullCrit.setExpression(new Constant(null));
-
- helpTestOpen(query, null, false);
- }
-
- @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$
- node.setCommand(query);
- CommandContext context = new CommandContext();
- context.setProcessorID("processorID"); //$NON-NLS-1$
- BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();
- FakeDataManager dataManager = new FakeDataManager();
- TestProcessor.sampleData1(dataManager);
- node.setElements(query.getProjectedSymbols());
- node.initialize(context, bm, dataManager);
- // Call open()
- node.open();
- assertEquals(Arrays.asList("SELECT e1, e2 FROM pm1.g1 WHERE e2 = 5"), dataManager.getQueries()); //$NON-NLS-1$
- }
-
- @Test public void testShouldExecuteUpdate() throws Exception {
- Update update = new Update();
-
- update.setGroup(new GroupSymbol("test")); //$NON-NLS-1$
-
- update.addChange(new ElementSymbol("e1"), new Constant("1")); //$NON-NLS-1$ //$NON-NLS-2$
-
- assertTrue(RelationalNodeUtil.shouldExecute(update, false));
-
- update.setChangeList(new SetClauseList());
-
- assertFalse(RelationalNodeUtil.shouldExecute(update, false));
- }
-
- @Test public void testShouldExecuteLimitZero() throws Exception {
- Query query = (Query)QueryParser.getQueryParser().parseCommand("SELECT e1, e2 FROM pm1.g1 LIMIT 0"); //$NON-NLS-1$
- assertFalse(RelationalNodeUtil.shouldExecute(query, false));
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestAccessNode.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/relational/TestAccessNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestAccessNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestAccessNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,127 @@
+/*
+ * 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 static org.junit.Assert.*;
+
+import java.util.Arrays;
+
+import org.junit.Test;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.BufferManagerFactory;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.FakeDataManager;
+import org.teiid.query.processor.TestProcessor;
+import org.teiid.query.resolver.TestResolver;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.SetClauseList;
+import org.teiid.query.sql.lang.Update;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+
+
+/**
+ * @since 4.2
+ */
+public class TestAccessNode {
+
+ private void helpTestOpen(Command command, String expectedCommand, boolean shouldRegisterRequest) throws Exception {
+ // Setup
+ AccessNode node = new AccessNode(1);
+ node.setCommand(command);
+ CommandContext context = new CommandContext();
+ context.setProcessorID("processorID"); //$NON-NLS-1$
+ BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+ node.setElements(command.getProjectedSymbols());
+ node.initialize(context, bm, dataManager);
+ node.setShouldEvaluateExpressions(true);
+ // Call open()
+ node.open();
+ if (shouldRegisterRequest) {
+ assertEquals(Arrays.asList(expectedCommand), dataManager.getQueries());
+ } else {
+ assertEquals(0, dataManager.getQueries().size());
+ }
+ }
+
+ @Test public void testOpen_Defect16059() throws Exception {
+ 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));
+
+ helpTestOpen(query, "SELECT e1, e2 FROM pm1.g1 WHERE e2 = 5", true); //$NON-NLS-1$
+ }
+
+ @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", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ IsNullCriteria nullCrit = (IsNullCriteria)((CompoundCriteria)query.getCriteria()).getCriteria(1);
+ nullCrit.setExpression(new Constant(null));
+
+ helpTestOpen(query, null, false);
+ }
+
+ @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", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ node.setCommand(query);
+ CommandContext context = new CommandContext();
+ context.setProcessorID("processorID"); //$NON-NLS-1$
+ BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
+ node.setElements(query.getProjectedSymbols());
+ node.initialize(context, bm, dataManager);
+ // Call open()
+ node.open();
+ assertEquals(Arrays.asList("SELECT e1, e2 FROM pm1.g1 WHERE e2 = 5"), dataManager.getQueries()); //$NON-NLS-1$
+ }
+
+ @Test public void testShouldExecuteUpdate() throws Exception {
+ Update update = new Update();
+
+ update.setGroup(new GroupSymbol("test")); //$NON-NLS-1$
+
+ update.addChange(new ElementSymbol("e1"), new Constant("1")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ assertTrue(RelationalNodeUtil.shouldExecute(update, false));
+
+ update.setChangeList(new SetClauseList());
+
+ assertFalse(RelationalNodeUtil.shouldExecute(update, false));
+ }
+
+ @Test public void testShouldExecuteLimitZero() throws Exception {
+ Query query = (Query)QueryParser.getQueryParser().parseCommand("SELECT e1, e2 FROM pm1.g1 LIMIT 0"); //$NON-NLS-1$
+ assertFalse(RelationalNodeUtil.shouldExecute(query, false));
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestBatchedUpdateNode.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/relational/TestBatchedUpdateNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestBatchedUpdateNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,256 +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 static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.TupleBatch;
-import org.teiid.common.buffer.TupleSource;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.events.EventDistributor;
-import org.teiid.metadata.MetadataRepository;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.TestBatchedUpdatePlanner;
-import org.teiid.query.processor.ProcessorDataManager;
-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.util.CommandContext;
-
-
-
-/**
- * @since 4.2
- */
-public class TestBatchedUpdateNode {
-
- private BatchedUpdateNode helpGetNode(String[] sql, QueryMetadataInterface md, ProcessorDataManager pdm) throws Exception {
- List<Command> commands = TestBatchedUpdatePlanner.helpGetCommands(sql, md);
- List<Boolean> shouldEvaluate = new ArrayList<Boolean>(commands.size());
- for (Command command : commands) {
- shouldEvaluate.add(EvaluatableVisitor.needsProcessingEvaluation(command));
- }
- BatchedUpdateNode node = new BatchedUpdateNode(1, commands, Collections.EMPTY_LIST, shouldEvaluate, "myModelName"); //$NON-NLS-1$
- CommandContext context = new CommandContext();
- context.setProcessorID("myProcessorID"); //$NON-NLS-1$
- context.setMetadata(md);
- node.initialize(context, Mockito.mock(BufferManager.class), pdm);
- return node;
- }
-
- private BatchedUpdateNode helpOpen(String[] commands, ProcessorDataManager pdm) throws Exception {
- BatchedUpdateNode node = helpGetNode(commands, FakeMetadataFactory.example1Cached(), pdm);
- node.open();
- return node;
- }
-
- private void helpTestOpen(String[] commands, String[] expectedCommands) throws Exception {
- FakePDM pdm = new FakePDM(expectedCommands.length);
- helpOpen(commands, pdm);
- assertEquals(Arrays.asList(expectedCommands), pdm.commands);
- }
-
- private FakePDM helpTestNextBatch(String[] commands, int[] expectedResults) throws Exception {
- int numExecutedCommands = 0;
- for (int i = 0; i < expectedResults.length; i++) {
- numExecutedCommands += expectedResults[i];
- }
- FakePDM fakePDM = new FakePDM(numExecutedCommands);
- BatchedUpdateNode node = helpOpen(commands, fakePDM);
- TupleBatch batch = null;
- try {
- batch = node.nextBatch();
- } catch (BlockedException e) {
- batch = node.nextBatch();
- }
- assertNotNull(batch);
- assertTrue(batch.getTerminationFlag());
- assertEquals(expectedResults.length, batch.getRowCount());
- for (int i = 0; i < expectedResults.length; i++) {
- List tuple = batch.getTuple(i+1);
- assertNotNull(tuple);
- Object result = tuple.get(0);
- assertNotNull(result);
- assertEquals(new Integer(expectedResults[i]), result);
- }
- return fakePDM;
- }
-
- @Test public void testOpen1() throws Exception {
- String[] sql = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
- "INSERT INTO pm1.g2 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)" //$NON-NLS-1$
- };
- String[] expectedCommands = {"BatchedUpdate{I,I}"}; //$NON-NLS-1$
- helpTestOpen(sql, expectedCommands);
- }
-
- @Test public void testOpen2() throws Exception {
- String[] sql = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
- "UPDATE pm1.g1 SET e2 = 50 WHERE e1 = 'criteria'", //$NON-NLS-1$
- "DELETE FROM pm1.g2 WHERE e2 = 50", //$NON-NLS-1$
- "DELETE FROM pm1.g2 WHERE e2 = 100" //$NON-NLS-1$
- };
- String[] expectedCommands = {"BatchedUpdate{I,U,D,D}"}; //$NON-NLS-1$
- helpTestOpen(sql, expectedCommands);
- }
-
- @Test public void testOpenAllCommandsExecuted() throws Exception {
- String[] sql = {"UPDATE pm1.g1 SET e2 = 50 WHERE e1 = 'criteria'", //$NON-NLS-1$
- "DELETE FROM pm1.g2 WHERE e2 = 50", //$NON-NLS-1$
- "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE e1 = 'myrow'" //$NON-NLS-1$
- };
- String[] expectedCommands = {"BatchedUpdate{U,D,U}"}; //$NON-NLS-1$
- helpTestOpen(sql, expectedCommands);
- }
-
- @Test public void testOpenNoCommandsExecuted() throws Exception {
- String[] sql = {"UPDATE pm1.g1 SET e2 = 50 WHERE 1 = 0", //$NON-NLS-1$
- "DELETE FROM pm1.g2 WHERE 1 = 0", //$NON-NLS-1$
- "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE 1 = 0" //$NON-NLS-1$
- };
- String[] expectedCommands = {};
- helpTestOpen(sql, expectedCommands);
- }
-
- @Test public void testOpenSomeCommandsExecuted() throws Exception {
- String[] sql = {"UPDATE pm1.g1 SET e2 = 50 WHERE e1 = 'criteria'", //$NON-NLS-1$
- "DELETE FROM pm1.g2 WHERE 1 = 0", //$NON-NLS-1$
- "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE e1 = 'myrow'" //$NON-NLS-1$
- };
- String[] expectedCommands = {"BatchedUpdate{U,U}"}; //$NON-NLS-1$
- helpTestOpen(sql, expectedCommands);
- }
-
- @Test public void testNextBatch1() throws Exception {
- String[] commands = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
- "INSERT INTO pm1.g2 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)" //$NON-NLS-1$
- };
- int[] expectedResults = {1,1};
- helpTestNextBatch(commands, expectedResults);
- }
-
- @Test public void testNextBatch2() throws Exception {
- String[] commands = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
- "UPDATE pm1.g1 SET e2 = 50 WHERE e1 = 'criteria'", //$NON-NLS-1$
- "DELETE FROM pm1.g2 WHERE e2 = 50", //$NON-NLS-1$
- "DELETE FROM pm1.g2 WHERE e2 = 100" //$NON-NLS-1$
- };
- int[] expectedResults = {1,1,1,1};
- helpTestNextBatch(commands, expectedResults);
- }
-
- @Test public void testNextBatchAllcommandsExecuted() throws Exception {
- String[] commands = {"UPDATE pm1.g1 SET e2 = 50 WHERE e1 = 'criteria'", //$NON-NLS-1$
- "DELETE FROM pm1.g2 WHERE e2 = 50", //$NON-NLS-1$
- "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE e1 = 'myrow'" //$NON-NLS-1$
- };
- int[] expectedResults = {1,1,1};
- helpTestNextBatch(commands, expectedResults);
- }
-
- @Test public void testNextBatchNoCommandsExecuted() throws Exception {
- String[] commands = {"UPDATE pm1.g1 SET e2 = 50 WHERE 1 = 0", //$NON-NLS-1$
- "DELETE FROM pm1.g2 WHERE 1 = 0", //$NON-NLS-1$
- "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE 1 = 0" //$NON-NLS-1$
- };
- int[] expectedResults = {0,0,0};
- helpTestNextBatch(commands, expectedResults);
- }
-
- @Test public void testNextBatchSomeCommandsExecuted() throws Exception {
- String[] commands = {"DELETE FROM pm1.g2 WHERE 1 = 0", //$NON-NLS-1$
- "UPDATE pm1.g1 SET e2 = 50 WHERE e1 = 'criteria'", //$NON-NLS-1$
- "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE e1 = 'myrow'", //$NON-NLS-1$
- "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE 1 = 0" //$NON-NLS-1$
- };
- int[] expectedResults = {0,1,1,0};
- helpTestNextBatch(commands, expectedResults);
- }
-
- @Test public void testNextBatchCommandNeedsEvaluated() throws Exception {
- String[] commands = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values (commandpayload(), 1, {b'true'}, 1.0)" //$NON-NLS-1$
- };
- int[] expectedResults = {1};
- FakePDM fpdm = helpTestNextBatch(commands, expectedResults);
- assertEquals("INSERT INTO pm1.g1 (e1, e2, e3, e4) VALUES (null, 1, TRUE, 1.0)", ((BatchedUpdateCommand)fpdm.actualCommands.get(0)).getUpdateCommands().get(0).toString()); //$NON-NLS-1$
- }
-
- private static final class FakePDM implements ProcessorDataManager {
- private int numExecutedCommands;
- private List<String> commands = new ArrayList<String>();
- private List<Command> actualCommands = new ArrayList<Command>();
- private FakePDM(int numExecutedCommands) {
- this.numExecutedCommands = numExecutedCommands;
- }
- public Object lookupCodeValue(CommandContext context,String codeTableName,String returnElementName,String keyElementName,Object keyValue) throws BlockedException,TeiidComponentException {return null;}
- public TupleSource registerRequest(CommandContext context,Command command,String modelName,String connectorBindingId, int nodeID, int limit) throws TeiidComponentException {
- assertEquals("myProcessorID", context.getProcessorID()); //$NON-NLS-1$
- assertEquals("myModelName", modelName); //$NON-NLS-1$
- assertEquals(1, nodeID);
- commands.add(command.toString());
- actualCommands.add(command);
- return new FakeTupleSource(numExecutedCommands);
- }
- @Override
- public EventDistributor getEventDistributor() {
- // TODO Auto-generated method stub
- return null;
- }
- @Override
- public MetadataRepository getMetadataRepository() {
- // TODO Auto-generated method stub
- return null;
- }
- }
- private static final class FakeTupleSource implements TupleSource {
- private int currentTuple = 0;
- private int numCommands;
- private boolean first = true;
- private FakeTupleSource(int numCommands) {
- this.numCommands = numCommands;
- }
- public void closeSource() {}
- public List nextTuple() throws TeiidComponentException {
- if (first) {
- first = false;
- throw BlockedException.INSTANCE;
- }
- if (currentTuple++ < numCommands) {
- return Arrays.asList(new Object[] {new Integer(1)});
- }
- return null;
- }
-
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestBatchedUpdateNode.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/relational/TestBatchedUpdateNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestBatchedUpdateNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestBatchedUpdateNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,256 @@
+/*
+ * 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 static org.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.TupleBatch;
+import org.teiid.common.buffer.TupleSource;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.events.EventDistributor;
+import org.teiid.metadata.MetadataRepository;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.TestBatchedUpdatePlanner;
+import org.teiid.query.processor.ProcessorDataManager;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+
+
+/**
+ * @since 4.2
+ */
+public class TestBatchedUpdateNode {
+
+ private BatchedUpdateNode helpGetNode(String[] sql, QueryMetadataInterface md, ProcessorDataManager pdm) throws Exception {
+ List<Command> commands = TestBatchedUpdatePlanner.helpGetCommands(sql, md);
+ List<Boolean> shouldEvaluate = new ArrayList<Boolean>(commands.size());
+ for (Command command : commands) {
+ shouldEvaluate.add(EvaluatableVisitor.needsProcessingEvaluation(command));
+ }
+ BatchedUpdateNode node = new BatchedUpdateNode(1, commands, Collections.EMPTY_LIST, shouldEvaluate, "myModelName"); //$NON-NLS-1$
+ CommandContext context = new CommandContext();
+ context.setProcessorID("myProcessorID"); //$NON-NLS-1$
+ context.setMetadata(md);
+ node.initialize(context, Mockito.mock(BufferManager.class), pdm);
+ return node;
+ }
+
+ private BatchedUpdateNode helpOpen(String[] commands, ProcessorDataManager pdm) throws Exception {
+ BatchedUpdateNode node = helpGetNode(commands, RealMetadataFactory.example1Cached(), pdm);
+ node.open();
+ return node;
+ }
+
+ private void helpTestOpen(String[] commands, String[] expectedCommands) throws Exception {
+ FakePDM pdm = new FakePDM(expectedCommands.length);
+ helpOpen(commands, pdm);
+ assertEquals(Arrays.asList(expectedCommands), pdm.commands);
+ }
+
+ private FakePDM helpTestNextBatch(String[] commands, int[] expectedResults) throws Exception {
+ int numExecutedCommands = 0;
+ for (int i = 0; i < expectedResults.length; i++) {
+ numExecutedCommands += expectedResults[i];
+ }
+ FakePDM fakePDM = new FakePDM(numExecutedCommands);
+ BatchedUpdateNode node = helpOpen(commands, fakePDM);
+ TupleBatch batch = null;
+ try {
+ batch = node.nextBatch();
+ } catch (BlockedException e) {
+ batch = node.nextBatch();
+ }
+ assertNotNull(batch);
+ assertTrue(batch.getTerminationFlag());
+ assertEquals(expectedResults.length, batch.getRowCount());
+ for (int i = 0; i < expectedResults.length; i++) {
+ List tuple = batch.getTuple(i+1);
+ assertNotNull(tuple);
+ Object result = tuple.get(0);
+ assertNotNull(result);
+ assertEquals(new Integer(expectedResults[i]), result);
+ }
+ return fakePDM;
+ }
+
+ @Test public void testOpen1() throws Exception {
+ String[] sql = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
+ "INSERT INTO pm1.g2 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)" //$NON-NLS-1$
+ };
+ String[] expectedCommands = {"BatchedUpdate{I,I}"}; //$NON-NLS-1$
+ helpTestOpen(sql, expectedCommands);
+ }
+
+ @Test public void testOpen2() throws Exception {
+ String[] sql = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
+ "UPDATE pm1.g1 SET e2 = 50 WHERE e1 = 'criteria'", //$NON-NLS-1$
+ "DELETE FROM pm1.g2 WHERE e2 = 50", //$NON-NLS-1$
+ "DELETE FROM pm1.g2 WHERE e2 = 100" //$NON-NLS-1$
+ };
+ String[] expectedCommands = {"BatchedUpdate{I,U,D,D}"}; //$NON-NLS-1$
+ helpTestOpen(sql, expectedCommands);
+ }
+
+ @Test public void testOpenAllCommandsExecuted() throws Exception {
+ String[] sql = {"UPDATE pm1.g1 SET e2 = 50 WHERE e1 = 'criteria'", //$NON-NLS-1$
+ "DELETE FROM pm1.g2 WHERE e2 = 50", //$NON-NLS-1$
+ "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE e1 = 'myrow'" //$NON-NLS-1$
+ };
+ String[] expectedCommands = {"BatchedUpdate{U,D,U}"}; //$NON-NLS-1$
+ helpTestOpen(sql, expectedCommands);
+ }
+
+ @Test public void testOpenNoCommandsExecuted() throws Exception {
+ String[] sql = {"UPDATE pm1.g1 SET e2 = 50 WHERE 1 = 0", //$NON-NLS-1$
+ "DELETE FROM pm1.g2 WHERE 1 = 0", //$NON-NLS-1$
+ "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE 1 = 0" //$NON-NLS-1$
+ };
+ String[] expectedCommands = {};
+ helpTestOpen(sql, expectedCommands);
+ }
+
+ @Test public void testOpenSomeCommandsExecuted() throws Exception {
+ String[] sql = {"UPDATE pm1.g1 SET e2 = 50 WHERE e1 = 'criteria'", //$NON-NLS-1$
+ "DELETE FROM pm1.g2 WHERE 1 = 0", //$NON-NLS-1$
+ "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE e1 = 'myrow'" //$NON-NLS-1$
+ };
+ String[] expectedCommands = {"BatchedUpdate{U,U}"}; //$NON-NLS-1$
+ helpTestOpen(sql, expectedCommands);
+ }
+
+ @Test public void testNextBatch1() throws Exception {
+ String[] commands = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
+ "INSERT INTO pm1.g2 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)" //$NON-NLS-1$
+ };
+ int[] expectedResults = {1,1};
+ helpTestNextBatch(commands, expectedResults);
+ }
+
+ @Test public void testNextBatch2() throws Exception {
+ String[] commands = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values ('string1', 1, {b'true'}, 1.0)", //$NON-NLS-1$
+ "UPDATE pm1.g1 SET e2 = 50 WHERE e1 = 'criteria'", //$NON-NLS-1$
+ "DELETE FROM pm1.g2 WHERE e2 = 50", //$NON-NLS-1$
+ "DELETE FROM pm1.g2 WHERE e2 = 100" //$NON-NLS-1$
+ };
+ int[] expectedResults = {1,1,1,1};
+ helpTestNextBatch(commands, expectedResults);
+ }
+
+ @Test public void testNextBatchAllcommandsExecuted() throws Exception {
+ String[] commands = {"UPDATE pm1.g1 SET e2 = 50 WHERE e1 = 'criteria'", //$NON-NLS-1$
+ "DELETE FROM pm1.g2 WHERE e2 = 50", //$NON-NLS-1$
+ "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE e1 = 'myrow'" //$NON-NLS-1$
+ };
+ int[] expectedResults = {1,1,1};
+ helpTestNextBatch(commands, expectedResults);
+ }
+
+ @Test public void testNextBatchNoCommandsExecuted() throws Exception {
+ String[] commands = {"UPDATE pm1.g1 SET e2 = 50 WHERE 1 = 0", //$NON-NLS-1$
+ "DELETE FROM pm1.g2 WHERE 1 = 0", //$NON-NLS-1$
+ "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE 1 = 0" //$NON-NLS-1$
+ };
+ int[] expectedResults = {0,0,0};
+ helpTestNextBatch(commands, expectedResults);
+ }
+
+ @Test public void testNextBatchSomeCommandsExecuted() throws Exception {
+ String[] commands = {"DELETE FROM pm1.g2 WHERE 1 = 0", //$NON-NLS-1$
+ "UPDATE pm1.g1 SET e2 = 50 WHERE e1 = 'criteria'", //$NON-NLS-1$
+ "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE e1 = 'myrow'", //$NON-NLS-1$
+ "UPDATE pm1.g2 set e2 = 5, e3 = {b'false'}, e4 = 3.33 WHERE 1 = 0" //$NON-NLS-1$
+ };
+ int[] expectedResults = {0,1,1,0};
+ helpTestNextBatch(commands, expectedResults);
+ }
+
+ @Test public void testNextBatchCommandNeedsEvaluated() throws Exception {
+ String[] commands = {"INSERT INTO pm1.g1 (e1, e2, e3, e4) values (commandpayload(), 1, {b'true'}, 1.0)" //$NON-NLS-1$
+ };
+ int[] expectedResults = {1};
+ FakePDM fpdm = helpTestNextBatch(commands, expectedResults);
+ assertEquals("INSERT INTO pm1.g1 (e1, e2, e3, e4) VALUES (null, 1, TRUE, 1.0)", ((BatchedUpdateCommand)fpdm.actualCommands.get(0)).getUpdateCommands().get(0).toString()); //$NON-NLS-1$
+ }
+
+ private static final class FakePDM implements ProcessorDataManager {
+ private int numExecutedCommands;
+ private List<String> commands = new ArrayList<String>();
+ private List<Command> actualCommands = new ArrayList<Command>();
+ private FakePDM(int numExecutedCommands) {
+ this.numExecutedCommands = numExecutedCommands;
+ }
+ public Object lookupCodeValue(CommandContext context,String codeTableName,String returnElementName,String keyElementName,Object keyValue) throws BlockedException,TeiidComponentException {return null;}
+ public TupleSource registerRequest(CommandContext context,Command command,String modelName,String connectorBindingId, int nodeID, int limit) throws TeiidComponentException {
+ assertEquals("myProcessorID", context.getProcessorID()); //$NON-NLS-1$
+ assertEquals("myModelName", modelName); //$NON-NLS-1$
+ assertEquals(1, nodeID);
+ commands.add(command.toString());
+ actualCommands.add(command);
+ return new FakeTupleSource(numExecutedCommands);
+ }
+ @Override
+ public EventDistributor getEventDistributor() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+ @Override
+ public MetadataRepository getMetadataRepository() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+ }
+ private static final class FakeTupleSource implements TupleSource {
+ private int currentTuple = 0;
+ private int numCommands;
+ private boolean first = true;
+ private FakeTupleSource(int numCommands) {
+ this.numCommands = numCommands;
+ }
+ public void closeSource() {}
+ public List nextTuple() throws TeiidComponentException {
+ if (first) {
+ first = false;
+ throw BlockedException.INSTANCE;
+ }
+ if (currentTuple++ < numCommands) {
+ return Arrays.asList(new Object[] {new Integer(1)});
+ }
+ return null;
+ }
+
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,441 +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 static org.junit.Assert.assertEquals;
-
-import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-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.common.buffer.impl.BufferManagerImpl;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.function.FunctionDescriptor;
-import org.teiid.query.function.aggregate.AggregateFunction;
-import org.teiid.query.processor.FakeDataManager;
-import org.teiid.query.processor.FakeTupleSource;
-import org.teiid.query.processor.ProcessorDataManager;
-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.util.CommandContext;
-
-
-public class TestGroupingNode {
-
- public static FakeTupleSource createTupleSource1() {
- List<ElementSymbol> symbols = new ArrayList<ElementSymbol>();
- symbols.add(new ElementSymbol("col1")); //$NON-NLS-1$
- symbols.get(0).setType(DataTypeManager.DefaultDataClasses.INTEGER);
- symbols.add(new ElementSymbol("col2")); //$NON-NLS-1$
- symbols.get(1).setType(DataTypeManager.DefaultDataClasses.INTEGER);
- List[] tuples = new List[] {
- Arrays.asList(new Object[] { new Integer(5), new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(4), null }),
- Arrays.asList(new Object[] { null, new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(0), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(6), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(6), new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { null, null }),
- };
-
- return new FakeTupleSource(symbols, tuples);
- }
-
- private void helpProcess(BufferManager mgr,
- GroupingNode node,
- CommandContext context,
- List[] expected, ProcessorDataManager dataMgr) throws TeiidComponentException,
- BlockedException,
- TeiidProcessingException {
- FakeTupleSource dataSource = createTupleSource1();
- helpProcess(mgr, node, context, expected, dataSource, dataMgr);
- }
-
- private void helpProcess(BufferManager mgr,
- GroupingNode node,
- CommandContext context,
- List[] expected,
- FakeTupleSource dataSource, ProcessorDataManager dataMgr) throws TeiidComponentException,
- BlockedException,
- TeiidProcessingException {
- RelationalNode dataNode = new FakeRelationalNode(0, dataSource, mgr.getProcessorBatchSize());
- dataNode.setElements(dataSource.getSchema());
- node.addChild(dataNode);
- node.initialize(context, mgr, dataMgr);
- node.open();
-
- int currentRow = 1;
- while(true) {
- try {
- TupleBatch batch = node.nextBatch();
- for(int row = currentRow; row <= batch.getEndRow(); row++) {
- List tuple = batch.getTuple(row);
- assertEquals("Rows don't match at " + row, expected[row-1], tuple); //$NON-NLS-1$
- }
- currentRow += batch.getRowCount();
- if(batch.getTerminationFlag()) {
- break;
- }
- } catch (BlockedException e) {
- //ignore
- }
- }
- assertEquals(expected.length, currentRow -1);
- }
-
- // ################################## ACTUAL TESTS ################################
-
- @Test public void test1() throws Exception {
- BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
-
- // Set up
- GroupingNode node = new GroupingNode(1);
- List outputElements = new ArrayList();
- ElementSymbol col1 = new ElementSymbol("col1"); //$NON-NLS-1$
- col1.setType(Integer.class);
- ElementSymbol col2 = new ElementSymbol("col2"); //$NON-NLS-1$
- col2.setType(Integer.class);
- outputElements.add(col1);
- outputElements.add(new AggregateSymbol("countAll", "COUNT", false, null)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("count", "COUNT", false, col2)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("countDist", "COUNT", true, col2)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("sum", "SUM", false, col2)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("sumDist", "SUM", true, col2)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("avg", "AVG", false, col2)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("avgDist", "AVG", true, col2)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("min", "MIN", false, col2)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("minDist", "MIN", true, col2)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("max", "MAX", false, col2)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("maxDist", "MAX", true, col2)); //$NON-NLS-1$ //$NON-NLS-2$
- node.setElements(outputElements);
-
- List groupingElements = new ArrayList();
- groupingElements.add(col1);
- node.setGroupingElements(groupingElements);
- CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, new Integer(2), new Integer(1), new Integer(1), new Long(3), new Long(3), new Double(3.0), new Double(3.0), new Integer(3), new Integer(3), new Integer(3), new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(0), new Integer(1), new Integer(1), new Integer(1), new Long(4), new Long(4), new Double(4.0), new Double(4.0), new Integer(4), new Integer(4), new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(1), new Integer(1), new Integer(1), new Long(2), new Long(2), new Double(2.0), new Double(2.0), new Integer(2), new Integer(2), new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(4), new Integer(4), new Integer(2), new Long(5), new Long(3), new Double(1.25), new Double(1.5), new Integer(1), new Integer(1), new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(1), new Integer(1), new Integer(1), new Long(0), new Long(0), new Double(0.0), new Double(0.0), new Integer(0), new Integer(0), new Integer(0), new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(3), new Integer(2), new Integer(2), new Long(5), new Long(5), new Double(2.5), new Double(2.5), new Integer(2), new Integer(2), new Integer(3), new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(1), new Integer(1), new Integer(1), new Long(3), new Long(3), new Double(3.0), new Double(3.0), new Integer(3), new Integer(3), new Integer(3), new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(6), new Integer(2), new Integer(2), new Integer(2), new Long(7), new Long(7), new Double(3.5), new Double(3.5), new Integer(3), new Integer(3), new Integer(4), new Integer(4) })
- };
-
- helpProcess(mgr, node, context, expected, null);
-
- //ensure that the distinct input type is correct
- AggregateFunction[] functions = node.getFunctions();
- AggregateFunction countDist = functions[5];
- SortingFilter dup = (SortingFilter)countDist;
- assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((ElementSymbol)dup.getElements().get(0)).getType());
- }
-
- @Test public void test2() throws Exception {
- BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
-
- GroupingNode node = getExampleGroupingNode();
- CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(6), new Integer(2) })
- };
-
- helpProcess(mgr, node, context, expected, null);
- }
-
- // Same as test2, but uses processor batch size smaller than number of groups
- @Test public void test3() throws Exception {
- BufferManagerImpl mgr = BufferManagerFactory.createBufferManager();
- mgr.setProcessorBatchSize(5);
-
- GroupingNode node = getExampleGroupingNode();
- CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(6), new Integer(2) })
- };
-
- helpProcess(mgr, node, context, expected, null);
- }
-
- @Test public void testDefect5769() throws Exception {
- BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
-
- ElementSymbol bigDecimal = new ElementSymbol("value"); //$NON-NLS-1$
- bigDecimal.setType(DataTypeManager.DefaultDataClasses.BIG_DECIMAL);
-
- // Set up
- GroupingNode node = new GroupingNode(1);
- List outputElements = new ArrayList();
- outputElements.add(new AggregateSymbol("bigSum", "SUM", false, bigDecimal)); //$NON-NLS-1$ //$NON-NLS-2$
- 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[] {
- Arrays.asList(new Object[] { new BigDecimal("0.0") }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new BigDecimal("1.0") }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new BigDecimal("2.0") }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new BigDecimal("3.0") }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new BigDecimal("4.0") }) //$NON-NLS-1$
- };
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new BigDecimal("10.0"), new BigDecimal("2.000000000") }) //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- List symbols = new ArrayList();
- symbols.add(bigDecimal);
- FakeTupleSource dataSource = new FakeTupleSource(symbols, data);
- helpProcess(mgr, node, context, expected, dataSource, null);
- }
-
- @Test public void testdefect9842() throws Exception {
- BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
-
- ElementSymbol col1 = new ElementSymbol("col1"); //$NON-NLS-1$
- col1.setType(Integer.class);
- ElementSymbol bigDecimal = new ElementSymbol("value"); //$NON-NLS-1$
- bigDecimal.setType(DataTypeManager.DefaultDataClasses.BIG_DECIMAL);
-
- // Set up
- GroupingNode node = new GroupingNode(1);
- List outputElements = new ArrayList();
- outputElements.add(col1);
- outputElements.add(new AggregateSymbol("bigSum", "SUM", false, bigDecimal)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("bigAvg", "AVG", false, bigDecimal)); //$NON-NLS-1$ //$NON-NLS-2$
- node.setElements(outputElements);
-
- // Set grouping elements to null
- List groupingElements = new ArrayList();
- groupingElements.add(col1);
- node.setGroupingElements(groupingElements);
- CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
-
- List[] data = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new BigDecimal("0.0") }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(1), new BigDecimal("1.0") }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(2), new BigDecimal("2.0") }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(2), new BigDecimal("3.0") }), //$NON-NLS-1$
- Arrays.asList(new Object[] { new Integer(2), new BigDecimal("4.0") }) //$NON-NLS-1$
- };
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new BigDecimal("1.0"), new BigDecimal("0.500000000") }), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList(new Object[] { new Integer(2), new BigDecimal("9.0"), new BigDecimal("3.000000000") }) //$NON-NLS-1$ //$NON-NLS-2$
- };
-
- List symbols = new ArrayList();
- symbols.add(col1);
- symbols.add(bigDecimal);
- FakeTupleSource dataSource = new FakeTupleSource(symbols, data);
- helpProcess(mgr, node, context, expected, dataSource, null);
- }
-
- private void helpTestLookupFunctionInAggregate(int batchSize) throws Exception {
- BufferManagerImpl mgr = BufferManagerFactory.createBufferManager();
- mgr.setProcessorBatchSize(batchSize);
-
- // Set up
- GroupingNode node = new GroupingNode(1);
- List outputElements = new ArrayList();
- ElementSymbol col1 = new ElementSymbol("col1"); //$NON-NLS-1$
- col1.setType(Integer.class);
- ElementSymbol col2 = new ElementSymbol("col2"); //$NON-NLS-1$
- 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$
- func.setFunctionDescriptor(desc);
- func.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-
- outputElements.add(col1);
- outputElements.add(new AggregateSymbol("count", "COUNT", false, func)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("sum", "SUM", false, func)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("sumDist", "SUM", true, func)); //$NON-NLS-1$ //$NON-NLS-2$
- node.setElements(outputElements);
-
- List groupingElements = new ArrayList();
- groupingElements.add(col1);
- node.setGroupingElements(groupingElements);
- CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
-
- FakeDataManager dataMgr = new FakeDataManager();
- dataMgr.setThrowBlocked(true);
- Map valueMap = new HashMap();
- valueMap.put(new Integer(0), new Integer(1));
- valueMap.put(new Integer(1), new Integer(2));
- valueMap.put(new Integer(2), new Integer(3));
- valueMap.put(new Integer(3), new Integer(4));
- valueMap.put(new Integer(4), new Integer(5));
- dataMgr.defineCodeTable("pm1.g1", "e1", "e2", valueMap); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, new Integer(1), new Long(4), new Long(4) }),
- Arrays.asList(new Object[] { new Integer(0), new Integer(1), new Long(5), new Long(5) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(1), new Long(3), new Long(3) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(4), new Long(9), new Long(5) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(1), new Long(1), new Long(1) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(2), new Long(7), new Long(7) }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(1), new Long(4), new Long(4) }),
- Arrays.asList(new Object[] { new Integer(6), new Integer(2), new Long(9), new Long(9) })
- };
-
- helpProcess(mgr, node, context, expected, dataMgr);
- }
-
- public void helpTestEmptyGroup(boolean groupBy) throws Exception {
- BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
-
- ElementSymbol col1 = new ElementSymbol("col1"); //$NON-NLS-1$
- col1.setType(Integer.class);
- ElementSymbol bigDecimal = new ElementSymbol("value"); //$NON-NLS-1$
- bigDecimal.setType(DataTypeManager.DefaultDataClasses.BIG_DECIMAL);
-
- // Set up
- GroupingNode node = new GroupingNode(1);
- List outputElements = new ArrayList();
- outputElements.add(new AggregateSymbol("bigSum", "SUM", false, bigDecimal)); //$NON-NLS-1$ //$NON-NLS-2$
- outputElements.add(new AggregateSymbol("bigAvg", "AVG", false, bigDecimal)); //$NON-NLS-1$ //$NON-NLS-2$
- node.setElements(outputElements);
-
- // Set grouping elements to null
- if (groupBy) {
- List groupingElements = new ArrayList();
- groupingElements.add(new ElementSymbol("col1")); //$NON-NLS-1$
- node.setGroupingElements(groupingElements);
- }
- CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
-
- List[] data = new List[] {
- };
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, null })
- };
-
- if (groupBy) {
- expected = new List[] {};
- }
-
- List symbols = new ArrayList();
- symbols.add(col1);
- symbols.add(bigDecimal);
- FakeTupleSource dataSource = new FakeTupleSource(symbols, data);
- helpProcess(mgr, node, context, expected, dataSource, null);
- }
-
- @Test public void testTestEmptyGroupWithoutGroupBy() throws Exception {
- helpTestEmptyGroup(false);
- }
-
- @Test public void testTestEmptyGroupWithGroupBy() throws Exception {
- helpTestEmptyGroup(true);
- }
-
- @Test public void testLookupFunctionMultipleBatches() throws Exception {
- helpTestLookupFunctionInAggregate(3);
- }
-
- @Test public void testDupSort() throws Exception {
- BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
-
- GroupingNode node = getExampleGroupingNode();
- node.setRemoveDuplicates(true);
- CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { null, new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(6), new Integer(2) })
- };
-
- helpProcess(mgr, node, context, expected, null);
- }
-
- private GroupingNode getExampleGroupingNode() {
- GroupingNode node = new GroupingNode(1);
- List outputElements = new ArrayList();
- ElementSymbol col1 = new ElementSymbol("col1"); //$NON-NLS-1$
- col1.setType(Integer.class);
- ElementSymbol col2 = new ElementSymbol("col2"); //$NON-NLS-1$
- col2.setType(Integer.class);
- outputElements.add(col1);
- outputElements.add(new AggregateSymbol("countDist", "COUNT", true, col2)); //$NON-NLS-1$ //$NON-NLS-2$
- node.setElements(outputElements);
-
- List groupingElements = new ArrayList();
- groupingElements.add(col1);
- node.setGroupingElements(groupingElements);
- return node;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,441 @@
+/*
+ * 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 static org.junit.Assert.assertEquals;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+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.common.buffer.impl.BufferManagerImpl;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.query.function.FunctionDescriptor;
+import org.teiid.query.function.aggregate.AggregateFunction;
+import org.teiid.query.processor.FakeDataManager;
+import org.teiid.query.processor.FakeTupleSource;
+import org.teiid.query.processor.ProcessorDataManager;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+
+public class TestGroupingNode {
+
+ public static FakeTupleSource createTupleSource1() {
+ List<ElementSymbol> symbols = new ArrayList<ElementSymbol>();
+ symbols.add(new ElementSymbol("col1")); //$NON-NLS-1$
+ symbols.get(0).setType(DataTypeManager.DefaultDataClasses.INTEGER);
+ symbols.add(new ElementSymbol("col2")); //$NON-NLS-1$
+ symbols.get(1).setType(DataTypeManager.DefaultDataClasses.INTEGER);
+ List[] tuples = new List[] {
+ Arrays.asList(new Object[] { new Integer(5), new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(4), null }),
+ Arrays.asList(new Object[] { null, new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(0), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { null, null }),
+ };
+
+ return new FakeTupleSource(symbols, tuples);
+ }
+
+ private void helpProcess(BufferManager mgr,
+ GroupingNode node,
+ CommandContext context,
+ List[] expected, ProcessorDataManager dataMgr) throws TeiidComponentException,
+ BlockedException,
+ TeiidProcessingException {
+ FakeTupleSource dataSource = createTupleSource1();
+ helpProcess(mgr, node, context, expected, dataSource, dataMgr);
+ }
+
+ private void helpProcess(BufferManager mgr,
+ GroupingNode node,
+ CommandContext context,
+ List[] expected,
+ FakeTupleSource dataSource, ProcessorDataManager dataMgr) throws TeiidComponentException,
+ BlockedException,
+ TeiidProcessingException {
+ RelationalNode dataNode = new FakeRelationalNode(0, dataSource, mgr.getProcessorBatchSize());
+ dataNode.setElements(dataSource.getSchema());
+ node.addChild(dataNode);
+ node.initialize(context, mgr, dataMgr);
+ node.open();
+
+ int currentRow = 1;
+ while(true) {
+ try {
+ TupleBatch batch = node.nextBatch();
+ for(int row = currentRow; row <= batch.getEndRow(); row++) {
+ List tuple = batch.getTuple(row);
+ assertEquals("Rows don't match at " + row, expected[row-1], tuple); //$NON-NLS-1$
+ }
+ currentRow += batch.getRowCount();
+ if(batch.getTerminationFlag()) {
+ break;
+ }
+ } catch (BlockedException e) {
+ //ignore
+ }
+ }
+ assertEquals(expected.length, currentRow -1);
+ }
+
+ // ################################## ACTUAL TESTS ################################
+
+ @Test public void test1() throws Exception {
+ BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
+
+ // Set up
+ GroupingNode node = new GroupingNode(1);
+ List outputElements = new ArrayList();
+ ElementSymbol col1 = new ElementSymbol("col1"); //$NON-NLS-1$
+ col1.setType(Integer.class);
+ ElementSymbol col2 = new ElementSymbol("col2"); //$NON-NLS-1$
+ col2.setType(Integer.class);
+ outputElements.add(col1);
+ outputElements.add(new AggregateSymbol("countAll", "COUNT", false, null)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("count", "COUNT", false, col2)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("countDist", "COUNT", true, col2)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("sum", "SUM", false, col2)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("sumDist", "SUM", true, col2)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("avg", "AVG", false, col2)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("avgDist", "AVG", true, col2)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("min", "MIN", false, col2)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("minDist", "MIN", true, col2)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("max", "MAX", false, col2)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("maxDist", "MAX", true, col2)); //$NON-NLS-1$ //$NON-NLS-2$
+ node.setElements(outputElements);
+
+ List groupingElements = new ArrayList();
+ groupingElements.add(col1);
+ node.setGroupingElements(groupingElements);
+ CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, new Integer(2), new Integer(1), new Integer(1), new Long(3), new Long(3), new Double(3.0), new Double(3.0), new Integer(3), new Integer(3), new Integer(3), new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(0), new Integer(1), new Integer(1), new Integer(1), new Long(4), new Long(4), new Double(4.0), new Double(4.0), new Integer(4), new Integer(4), new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1), new Integer(1), new Integer(1), new Long(2), new Long(2), new Double(2.0), new Double(2.0), new Integer(2), new Integer(2), new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(4), new Integer(4), new Integer(2), new Long(5), new Long(3), new Double(1.25), new Double(1.5), new Integer(1), new Integer(1), new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(1), new Integer(1), new Integer(1), new Long(0), new Long(0), new Double(0.0), new Double(0.0), new Integer(0), new Integer(0), new Integer(0), new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(3), new Integer(2), new Integer(2), new Long(5), new Long(5), new Double(2.5), new Double(2.5), new Integer(2), new Integer(2), new Integer(3), new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(1), new Integer(1), new Integer(1), new Long(3), new Long(3), new Double(3.0), new Double(3.0), new Integer(3), new Integer(3), new Integer(3), new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(2), new Integer(2), new Integer(2), new Long(7), new Long(7), new Double(3.5), new Double(3.5), new Integer(3), new Integer(3), new Integer(4), new Integer(4) })
+ };
+
+ helpProcess(mgr, node, context, expected, null);
+
+ //ensure that the distinct input type is correct
+ AggregateFunction[] functions = node.getFunctions();
+ AggregateFunction countDist = functions[5];
+ SortingFilter dup = (SortingFilter)countDist;
+ assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((ElementSymbol)dup.getElements().get(0)).getType());
+ }
+
+ @Test public void test2() throws Exception {
+ BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
+
+ GroupingNode node = getExampleGroupingNode();
+ CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(2) })
+ };
+
+ helpProcess(mgr, node, context, expected, null);
+ }
+
+ // Same as test2, but uses processor batch size smaller than number of groups
+ @Test public void test3() throws Exception {
+ BufferManagerImpl mgr = BufferManagerFactory.createBufferManager();
+ mgr.setProcessorBatchSize(5);
+
+ GroupingNode node = getExampleGroupingNode();
+ CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(2) })
+ };
+
+ helpProcess(mgr, node, context, expected, null);
+ }
+
+ @Test public void testDefect5769() throws Exception {
+ BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
+
+ ElementSymbol bigDecimal = new ElementSymbol("value"); //$NON-NLS-1$
+ bigDecimal.setType(DataTypeManager.DefaultDataClasses.BIG_DECIMAL);
+
+ // Set up
+ GroupingNode node = new GroupingNode(1);
+ List outputElements = new ArrayList();
+ outputElements.add(new AggregateSymbol("bigSum", "SUM", false, bigDecimal)); //$NON-NLS-1$ //$NON-NLS-2$
+ 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[] {
+ Arrays.asList(new Object[] { new BigDecimal("0.0") }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new BigDecimal("1.0") }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new BigDecimal("2.0") }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new BigDecimal("3.0") }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new BigDecimal("4.0") }) //$NON-NLS-1$
+ };
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new BigDecimal("10.0"), new BigDecimal("2.000000000") }) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ List symbols = new ArrayList();
+ symbols.add(bigDecimal);
+ FakeTupleSource dataSource = new FakeTupleSource(symbols, data);
+ helpProcess(mgr, node, context, expected, dataSource, null);
+ }
+
+ @Test public void testdefect9842() throws Exception {
+ BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
+
+ ElementSymbol col1 = new ElementSymbol("col1"); //$NON-NLS-1$
+ col1.setType(Integer.class);
+ ElementSymbol bigDecimal = new ElementSymbol("value"); //$NON-NLS-1$
+ bigDecimal.setType(DataTypeManager.DefaultDataClasses.BIG_DECIMAL);
+
+ // Set up
+ GroupingNode node = new GroupingNode(1);
+ List outputElements = new ArrayList();
+ outputElements.add(col1);
+ outputElements.add(new AggregateSymbol("bigSum", "SUM", false, bigDecimal)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("bigAvg", "AVG", false, bigDecimal)); //$NON-NLS-1$ //$NON-NLS-2$
+ node.setElements(outputElements);
+
+ // Set grouping elements to null
+ List groupingElements = new ArrayList();
+ groupingElements.add(col1);
+ node.setGroupingElements(groupingElements);
+ CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
+
+ List[] data = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new BigDecimal("0.0") }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(1), new BigDecimal("1.0") }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(2), new BigDecimal("2.0") }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(2), new BigDecimal("3.0") }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { new Integer(2), new BigDecimal("4.0") }) //$NON-NLS-1$
+ };
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new BigDecimal("1.0"), new BigDecimal("0.500000000") }), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList(new Object[] { new Integer(2), new BigDecimal("9.0"), new BigDecimal("3.000000000") }) //$NON-NLS-1$ //$NON-NLS-2$
+ };
+
+ List symbols = new ArrayList();
+ symbols.add(col1);
+ symbols.add(bigDecimal);
+ FakeTupleSource dataSource = new FakeTupleSource(symbols, data);
+ helpProcess(mgr, node, context, expected, dataSource, null);
+ }
+
+ private void helpTestLookupFunctionInAggregate(int batchSize) throws Exception {
+ BufferManagerImpl mgr = BufferManagerFactory.createBufferManager();
+ mgr.setProcessorBatchSize(batchSize);
+
+ // Set up
+ GroupingNode node = new GroupingNode(1);
+ List outputElements = new ArrayList();
+ ElementSymbol col1 = new ElementSymbol("col1"); //$NON-NLS-1$
+ col1.setType(Integer.class);
+ ElementSymbol col2 = new ElementSymbol("col2"); //$NON-NLS-1$
+ 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 = 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);
+
+ outputElements.add(col1);
+ outputElements.add(new AggregateSymbol("count", "COUNT", false, func)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("sum", "SUM", false, func)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("sumDist", "SUM", true, func)); //$NON-NLS-1$ //$NON-NLS-2$
+ node.setElements(outputElements);
+
+ List groupingElements = new ArrayList();
+ groupingElements.add(col1);
+ node.setGroupingElements(groupingElements);
+ CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
+
+ FakeDataManager dataMgr = new FakeDataManager();
+ dataMgr.setThrowBlocked(true);
+ Map valueMap = new HashMap();
+ valueMap.put(new Integer(0), new Integer(1));
+ valueMap.put(new Integer(1), new Integer(2));
+ valueMap.put(new Integer(2), new Integer(3));
+ valueMap.put(new Integer(3), new Integer(4));
+ valueMap.put(new Integer(4), new Integer(5));
+ dataMgr.defineCodeTable("pm1.g1", "e1", "e2", valueMap); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, new Integer(1), new Long(4), new Long(4) }),
+ Arrays.asList(new Object[] { new Integer(0), new Integer(1), new Long(5), new Long(5) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1), new Long(3), new Long(3) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(4), new Long(9), new Long(5) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(1), new Long(1), new Long(1) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(2), new Long(7), new Long(7) }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(1), new Long(4), new Long(4) }),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(2), new Long(9), new Long(9) })
+ };
+
+ helpProcess(mgr, node, context, expected, dataMgr);
+ }
+
+ public void helpTestEmptyGroup(boolean groupBy) throws Exception {
+ BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
+
+ ElementSymbol col1 = new ElementSymbol("col1"); //$NON-NLS-1$
+ col1.setType(Integer.class);
+ ElementSymbol bigDecimal = new ElementSymbol("value"); //$NON-NLS-1$
+ bigDecimal.setType(DataTypeManager.DefaultDataClasses.BIG_DECIMAL);
+
+ // Set up
+ GroupingNode node = new GroupingNode(1);
+ List outputElements = new ArrayList();
+ outputElements.add(new AggregateSymbol("bigSum", "SUM", false, bigDecimal)); //$NON-NLS-1$ //$NON-NLS-2$
+ outputElements.add(new AggregateSymbol("bigAvg", "AVG", false, bigDecimal)); //$NON-NLS-1$ //$NON-NLS-2$
+ node.setElements(outputElements);
+
+ // Set grouping elements to null
+ if (groupBy) {
+ List groupingElements = new ArrayList();
+ groupingElements.add(new ElementSymbol("col1")); //$NON-NLS-1$
+ node.setGroupingElements(groupingElements);
+ }
+ CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
+
+ List[] data = new List[] {
+ };
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, null })
+ };
+
+ if (groupBy) {
+ expected = new List[] {};
+ }
+
+ List symbols = new ArrayList();
+ symbols.add(col1);
+ symbols.add(bigDecimal);
+ FakeTupleSource dataSource = new FakeTupleSource(symbols, data);
+ helpProcess(mgr, node, context, expected, dataSource, null);
+ }
+
+ @Test public void testTestEmptyGroupWithoutGroupBy() throws Exception {
+ helpTestEmptyGroup(false);
+ }
+
+ @Test public void testTestEmptyGroupWithGroupBy() throws Exception {
+ helpTestEmptyGroup(true);
+ }
+
+ @Test public void testLookupFunctionMultipleBatches() throws Exception {
+ helpTestLookupFunctionInAggregate(3);
+ }
+
+ @Test public void testDupSort() throws Exception {
+ BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
+
+ GroupingNode node = getExampleGroupingNode();
+ node.setRemoveDuplicates(true);
+ CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { null, new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(0), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(2) })
+ };
+
+ helpProcess(mgr, node, context, expected, null);
+ }
+
+ private GroupingNode getExampleGroupingNode() {
+ GroupingNode node = new GroupingNode(1);
+ List outputElements = new ArrayList();
+ ElementSymbol col1 = new ElementSymbol("col1"); //$NON-NLS-1$
+ col1.setType(Integer.class);
+ ElementSymbol col2 = new ElementSymbol("col2"); //$NON-NLS-1$
+ col2.setType(Integer.class);
+ outputElements.add(col1);
+ outputElements.add(new AggregateSymbol("countDist", "COUNT", true, col2)); //$NON-NLS-1$ //$NON-NLS-2$
+ node.setElements(outputElements);
+
+ List groupingElements = new ArrayList();
+ groupingElements.add(col1);
+ node.setGroupingElements(groupingElements);
+ return node;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestJoinNode.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/relational/TestJoinNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestJoinNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.processor.relational;
-
-import static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.TupleBatch;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.function.FunctionDescriptor;
-import org.teiid.query.processor.FakeDataManager;
-import org.teiid.query.processor.relational.MergeJoinStrategy.SortOption;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.JoinType;
-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.util.CommandContext;
-
- at SuppressWarnings("unchecked")
-public class TestJoinNode {
- private static final int NO_CRITERIA = 0;
- private static final int EQUAL_CRITERIA = 1;
- private static final int FUNCTION_CRITERIA = 2;
-
- private int criteriaType = EQUAL_CRITERIA;
-
- protected JoinType joinType;
-
- protected List[] leftTuples;
- protected List[] rightTuples;
-
- protected List[] expected;
- private List[] expectedReversed;
-
- protected JoinNode join;
- protected JoinStrategy joinStrategy;
- private RelationalNode leftNode;
- private RelationalNode rightNode;
-
- private FakeDataManager dataMgr;
-
- @Before public void setup() {
- leftTuples = createTuples1();
- rightTuples = createTuples2();
- }
-
- protected List[] createTuples1() {
- return new List[] {
- Arrays.asList(new Object[] { new Integer(5) }),
- Arrays.asList(new Object[] { new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(10) }),
- Arrays.asList(new Object[] { new Integer(11) }),
- Arrays.asList(new Object[] { new Integer(11) })
- };
- }
-
- private List[] createTuples2() {
- return new List[] {
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(4) }),
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(6) })
- };
- }
-
- private List[] createTuples3() {
- return new List[] {
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { new Integer(10) }),
- Arrays.asList(new Object[] { new Integer(10) }),
- Arrays.asList(new Object[] { new Integer(9) }),
- Arrays.asList(new Object[] { new Integer(9) }),
- Arrays.asList(new Object[] { new Integer(9) }),
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(5) }),
- Arrays.asList(new Object[] { new Integer(15) })
- };
- }
-
- private List[] createTuples4() {
- return new List[] {
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(4) }),
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(9) }),
- Arrays.asList(new Object[] { new Integer(5) }),
- Arrays.asList(new Object[] { new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(10) }),
- Arrays.asList(new Object[] { null }),
- Arrays.asList(new Object[] { null })
- };
- }
-
- private List[] createTuples(int startingValue, int count) {
- return createTuples(startingValue, count, false);
- }
-
- private List[] createTuples(int startingValue, int count, boolean addNullAsSecondColumn) {
- ArrayList lists = new ArrayList();
- for (int i=0; i<count; i++) {
- Object[] tuple;
- if (addNullAsSecondColumn) {
- tuple = new Object[] {new Integer(startingValue + i), null };
- } else {
- tuple = new Object[] {new Integer(startingValue + i) };
- }
- lists.add( Arrays.asList(tuple) );
- }
- return (List[]) lists.toArray(new List[] {});
- }
-
- private List[] createResults(int startingValue, int count) {
- return createTuples(startingValue, count, true);
- }
-
- protected void helpCreateJoin() {
- ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
- es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-
- ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
- es2.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-
- List leftElements = new ArrayList();
- leftElements.add(es1);
- leftNode = new FakeRelationalNode(1, leftTuples);
- leftNode.setElements(leftElements);
-
- List rightElements = new ArrayList();
- rightElements.add(es2);
- rightNode = new FakeRelationalNode(2, rightTuples);
- rightNode.setElements(rightElements);
-
- List joinElements = new ArrayList();
- joinElements.add(es1);
- joinElements.add(es2);
-
- join = new JoinNode(3);
- joinStrategy = new NestedLoopJoinStrategy();
- join.setJoinStrategy(joinStrategy);
- join.setElements(joinElements);
- join.setJoinType(joinType);
-
- switch (criteriaType) {
- case NO_CRITERIA :
- break;
-
- case EQUAL_CRITERIA :
- join.setJoinExpressions(Arrays.asList(es1), Arrays.asList(es2));
- joinStrategy = new MergeJoinStrategy(SortOption.SORT, SortOption.SORT, false);
- join.setJoinStrategy(joinStrategy);
- break;
-
- 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$
- func.setFunctionDescriptor(desc);
- func.setType(DataTypeManager.DefaultDataClasses.INTEGER);
- CompareCriteria joinCriteria = new CompareCriteria(es2, CompareCriteria.EQ, func);
- join.setJoinCriteria(joinCriteria);
- break;
- }
- }
-
- public void helpTestJoin() throws TeiidComponentException, TeiidProcessingException {
- for (int batchSize : new int[] {1, 10, leftTuples.length, 100}) {
- helpCreateJoin();
- if (batchSize == 0) {
- continue;
- }
- helpTestJoinDirect(expected, batchSize, 100000);
- List[] temp = leftTuples;
- leftTuples = rightTuples;
- rightTuples = temp;
- helpCreateJoin();
- helpTestJoinDirect(expectedReversed, batchSize, 100000);
- temp = leftTuples;
- leftTuples = rightTuples;
- rightTuples = temp;
- }
- }
-
- public void helpTestJoinDirect(List[] expectedResults, int batchSize, int processingBytes) throws TeiidComponentException, TeiidProcessingException {
- BufferManager mgr = NodeTestUtil.getTestBufferManager(processingBytes, batchSize);
- CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
-
- join.addChild(leftNode);
- join.addChild(rightNode);
-
- leftNode.initialize(context, mgr, dataMgr);
- rightNode.initialize(context, mgr, dataMgr);
- join.initialize(context, mgr, dataMgr);
-
- join.open();
-
- int currentRow = 1;
- while(true) {
- try {
- TupleBatch batch = join.nextBatch();
- for(;currentRow <= batch.getEndRow(); currentRow++) {
- List tuple = batch.getTuple(currentRow);
- assertEquals("Rows don't match at " + currentRow, expectedResults[currentRow-1], tuple); //$NON-NLS-1$
- }
- if(batch.getTerminationFlag()) {
- break;
- }
- } catch(BlockedException e) {
- // ignore and retry
- }
- }
- assertEquals(expectedResults.length, currentRow - 1);
- join.close();
- }
-
- @Test public void testNoRows() throws Exception {
- leftTuples = new List[0];
- rightTuples = new List[0];
- joinType = JoinType.JOIN_INNER;
- expected = new List[0];
- expectedReversed = new List[0];
- helpTestJoin();
- }
-
- @Test public void testInnerJoin() throws Exception {
- joinType = JoinType.JOIN_INNER;
- expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) })
- };
- expectedReversed = expected;
- helpTestJoin();
- }
-
- @Test public void testLeftOuterJoin() throws Exception {
- joinType = JoinType.JOIN_LEFT_OUTER;
- expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(3), null }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(5), null }),
- Arrays.asList(new Object[] { new Integer(10), null }),
- Arrays.asList(new Object[] { new Integer(11), null }),
- Arrays.asList(new Object[] { new Integer(11), null })
- };
- expectedReversed = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(6), null }),
- Arrays.asList(new Object[] { new Integer(7), null }),
- Arrays.asList(new Object[] { new Integer(7), null })
- };
- helpTestJoin();
- }
-
- @Test public void testLeftOuterJoinWithSwap() throws Exception {
- int outerSize = 11;
- leftTuples = createTuples(1,outerSize);
- rightTuples = createTuples(201,outerSize+1);
- joinType = JoinType.JOIN_LEFT_OUTER;
- expected = createResults(1, outerSize);
- expectedReversed = createResults(201, outerSize+1);
- helpTestJoin();
- }
-
- @Test public void testCrossJoin() throws Exception {
- joinType = JoinType.JOIN_CROSS;
- criteriaType = NO_CRITERIA;
- expected = new List[] {
- Arrays.asList(new Object[] { new Integer(5), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(5), null }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(3), null }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(2), null }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(4), null }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(1), null }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(4), null }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(10), null }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(11), null }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(11), null }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(11), new Integer(6) })
- };
- expectedReversed = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(5)}),
- Arrays.asList(new Object[] { new Integer(1), new Integer(3)}),
- Arrays.asList(new Object[] { new Integer(1), new Integer(2)}),
- Arrays.asList(new Object[] { new Integer(1), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(1), new Integer(1)}),
- Arrays.asList(new Object[] { new Integer(1), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(1), new Integer(10)}),
- Arrays.asList(new Object[] { new Integer(1), new Integer(11)}),
- Arrays.asList(new Object[] { new Integer(1), new Integer(11)}),
-
- Arrays.asList(new Object[] { new Integer(4), new Integer(5)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(3)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(2)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(1)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(10)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(11)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(11)}),
-
- Arrays.asList(new Object[] { new Integer(2), new Integer(5)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(3)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(10)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(11)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(11)}),
-
- Arrays.asList(new Object[] { new Integer(2), new Integer(5)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(3)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(1)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(10)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(11)}),
- Arrays.asList(new Object[] { new Integer(2), new Integer(11)}),
-
- Arrays.asList(new Object[] { new Integer(4), new Integer(5)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(3)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(2)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(1)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(10)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(11)}),
- Arrays.asList(new Object[] { new Integer(4), new Integer(11)}),
-
- Arrays.asList(new Object[] { null, new Integer(5)}),
- Arrays.asList(new Object[] { null, new Integer(3)}),
- Arrays.asList(new Object[] { null, new Integer(2)}),
- Arrays.asList(new Object[] { null, new Integer(4)}),
- Arrays.asList(new Object[] { null, new Integer(1)}),
- Arrays.asList(new Object[] { null, new Integer(4)}),
- Arrays.asList(new Object[] { null, new Integer(10)}),
- Arrays.asList(new Object[] { null, new Integer(11)}),
- Arrays.asList(new Object[] { null, new Integer(11)}),
-
- Arrays.asList(new Object[] { new Integer(7), new Integer(5)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(3)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(2)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(1)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(10)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(11)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(11)}),
-
- Arrays.asList(new Object[] { new Integer(7), new Integer(5)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(3)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(2)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(1)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(10)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(11)}),
- Arrays.asList(new Object[] { new Integer(7), new Integer(11)}),
-
- Arrays.asList(new Object[] { new Integer(6), new Integer(5)}),
- Arrays.asList(new Object[] { new Integer(6), new Integer(3)}),
- Arrays.asList(new Object[] { new Integer(6), new Integer(2)}),
- Arrays.asList(new Object[] { new Integer(6), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(6), new Integer(1)}),
- Arrays.asList(new Object[] { new Integer(6), new Integer(4)}),
- Arrays.asList(new Object[] { new Integer(6), new Integer(10)}),
- Arrays.asList(new Object[] { new Integer(6), new Integer(11)}),
- Arrays.asList(new Object[] { new Integer(6), new Integer(11)})
- };
-
- helpTestJoin();
- }
-
- @Test public void testInnerJoinWithLookupFunction() throws Exception {
- criteriaType = FUNCTION_CRITERIA;
- joinType = JoinType.JOIN_INNER;
- expected = new List[] {
- Arrays.asList(new Object[] { new Integer(5), new Integer(6) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(3), new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(7) })
- };
- expectedReversed = new List[] {
- Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(5) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(3) }),
- Arrays.asList(new Object[] { new Integer(4), new Integer(5) })
- };
-
- dataMgr = new FakeDataManager();
- dataMgr.setThrowBlocked(true);
- Map valueMap = new HashMap();
- valueMap.put(new Integer(1), new Integer(2));
- valueMap.put(new Integer(2), new Integer(3));
- valueMap.put(new Integer(3), new Integer(4));
- valueMap.put(new Integer(4), new Integer(5));
- valueMap.put(new Integer(5), new Integer(6));
- valueMap.put(new Integer(10), new Integer(7));
- valueMap.put(new Integer(11), new Integer(8));
- dataMgr.defineCodeTable("pm1.g1", "e1", "e2", valueMap); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- helpTestJoin();
- }
-
- @Test public void testFullOuterJoin() throws Exception {
- this.joinType = JoinType.JOIN_FULL_OUTER;
- this.leftTuples = createTuples3();
- this.rightTuples = createTuples4();
- expected = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(3), null }),
- Arrays.asList(new Object[] { null, new Integer(4) }),
- Arrays.asList(new Object[] { null, new Integer(4) }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(5) }),
- Arrays.asList(new Object[] { null, new Integer(6) }),
- Arrays.asList(new Object[] { null, new Integer(7) }),
- Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
- Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
- Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
- Arrays.asList(new Object[] { new Integer(15), null })
- };
- expectedReversed = new List[] {
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { null, null }),
- Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
- Arrays.asList(new Object[] { null, 3 }),
- Arrays.asList(new Object[] { 4, null }),
- Arrays.asList(new Object[] { 4, null }),
- Arrays.asList(new Object[] { new Integer(5), new Integer(5) }),
- Arrays.asList(new Object[] { 6, null }),
- Arrays.asList(new Object[] { 7, null }),
- Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
- Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
- Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
- Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
- Arrays.asList(new Object[] { null, 15 })
- };
- helpTestJoin();
- }
-
- @Test public void testMergeJoinOptimization() throws Exception {
- helpTestEnhancedSortMergeJoin(99);
- }
-
- private void helpTestEnhancedSortMergeJoin(int batchSize)
- throws TeiidComponentException, TeiidProcessingException {
- this.joinType = JoinType.JOIN_INNER;
- int rows = 100;
- List[] data = new List[rows];
- for(int i=0; i<rows; i++) {
- data[i] = new ArrayList();
- Integer value = new Integer((i*17) % 47);
- data[i].add(value);
- }
- this.leftTuples = data;
- this.rightTuples = createTuples2();
- expected = new List[] {
- Arrays.asList(new Object[] { 4, 4 }),
- Arrays.asList(new Object[] { 4, 4 }),
- Arrays.asList(new Object[] { 7, 7 }),
- Arrays.asList(new Object[] { 7, 7 }),
- Arrays.asList(new Object[] { 2, 2 }),
- Arrays.asList(new Object[] { 2, 2 }),
- Arrays.asList(new Object[] { 6, 6 }),
- Arrays.asList(new Object[] { 1, 1 }),
- Arrays.asList(new Object[] { 4, 4 }),
- Arrays.asList(new Object[] { 4, 4 }),
- Arrays.asList(new Object[] { 7, 7 }),
- Arrays.asList(new Object[] { 7, 7 }),
- Arrays.asList(new Object[] { 2, 2 }),
- Arrays.asList(new Object[] { 2, 2 }),
- Arrays.asList(new Object[] { 6, 6 }),
- Arrays.asList(new Object[] { 1, 1 }),
- Arrays.asList(new Object[] { 4, 4 }),
- Arrays.asList(new Object[] { 4, 4 }),
- };
- helpCreateJoin();
- this.joinStrategy = new EnhancedSortMergeJoinStrategy(SortOption.SORT, SortOption.SORT);
- this.join.setJoinStrategy(joinStrategy);
- helpTestJoinDirect(expected, batchSize, 1);
- }
-
- @Test public void testMergeJoinOptimizationMultiBatch() throws Exception {
- helpTestEnhancedSortMergeJoin(10);
- }
-
- @Test public void testMergeJoinOptimizationNoRows() throws Exception {
- this.joinType = JoinType.JOIN_INNER;
- this.leftTuples = createTuples1();
- this.rightTuples = new List[] {};
- expected = new List[] {};
- helpCreateJoin();
- this.joinStrategy = new EnhancedSortMergeJoinStrategy(SortOption.SORT, SortOption.SORT);
- this.join.setJoinStrategy(joinStrategy);
- helpTestJoinDirect(expected, 100, 1);
- }
-
- @Test public void testMergeJoinOptimizationWithDistinct() throws Exception {
- this.joinType = JoinType.JOIN_INNER;
- int rows = 50;
- List[] data = new List[rows];
- for(int i=0; i<rows; i++) {
- data[i] = new ArrayList();
- Integer value = new Integer((i*17) % 47);
- data[i].add(value);
- }
- this.leftTuples = data;
- this.rightTuples = new List[] {
- Arrays.asList(4),
- Arrays.asList(7),
- Arrays.asList(2),
- Arrays.asList(6),
- Arrays.asList(1),
- Arrays.asList(8),
- };
- expected = new List[] {
- Arrays.asList(new Object[] { 4, 4 }),
- Arrays.asList(new Object[] { 8, 8 }),
- Arrays.asList(new Object[] { 7, 7 }),
- Arrays.asList(new Object[] { 2, 2 }),
- Arrays.asList(new Object[] { 6, 6 }),
- Arrays.asList(new Object[] { 1, 1 }),
- };
- helpCreateJoin();
- this.joinStrategy = new EnhancedSortMergeJoinStrategy(SortOption.SORT, SortOption.SORT);
- this.join.setJoinStrategy(joinStrategy);
- //this.join.setRightDistinct(true);
- helpTestJoinDirect(expected, 40, 1);
- }
-
- @Test public void testMergeJoinOptimizationWithDistinctAlreadySorted() throws Exception {
- this.joinType = JoinType.JOIN_INNER;
- int rows = 50;
- List[] data = new List[rows];
- for(int i=0; i<rows; i++) {
- data[i] = new ArrayList();
- Integer value = new Integer((i*17) % 47);
- data[i].add(value);
- }
- this.leftTuples = data;
- this.rightTuples = new List[] {
- Arrays.asList(1),
- Arrays.asList(2),
- Arrays.asList(4),
- Arrays.asList(6),
- Arrays.asList(7),
- Arrays.asList(8),
- };
- expected = new List[] {
- Arrays.asList(new Object[] { 4, 4 }),
- Arrays.asList(new Object[] { 8, 8 }),
- Arrays.asList(new Object[] { 7, 7 }),
- Arrays.asList(new Object[] { 2, 2 }),
- Arrays.asList(new Object[] { 6, 6 }),
- Arrays.asList(new Object[] { 1, 1 })
- };
- helpCreateJoin();
- this.joinStrategy = new EnhancedSortMergeJoinStrategy(SortOption.SORT, SortOption.ALREADY_SORTED);
- this.join.setJoinStrategy(joinStrategy);
- helpTestJoinDirect(expected, 40, 1);
- }
-
- @Test public void testRepeatedMerge() throws Exception {
- helpTestRepeatedMerge(false);
- }
-
- @Test public void testRepeatedMergeWithDistinct() throws Exception {
- helpTestRepeatedMerge(true);
- }
-
- public void helpTestRepeatedMerge(boolean indexDistinct) throws Exception {
- this.joinType = JoinType.JOIN_INNER;
- int rows = 69;
- List[] data = new List[rows];
- for(int i=0; i<rows; i++) {
- data[i]=Arrays.asList((i*17) % 91);
- }
- if (indexDistinct) {
- data[2] = Arrays.asList(0);
- }
- data[6] = Arrays.asList((Integer)null);
- this.rightTuples = data;
- this.leftTuples = new List[17];
- for (int i = 0; i < this.leftTuples.length; i++) {
- this.leftTuples[i] = Arrays.asList(i);
- }
- if (!indexDistinct) {
- this.leftTuples[1] = Arrays.asList(0);
- }
- this.leftTuples[11] = Arrays.asList((Integer)null);
-
- expected = new List[] {
- Arrays.asList(13, 13),
- Arrays.asList(2, 2),
- Arrays.asList(8, 8),
- Arrays.asList(14, 14),
- Arrays.asList(3, 3),
- Arrays.asList(9, 9),
- Arrays.asList(15, 15),
- Arrays.asList(4, 4),
- Arrays.asList(10, 10),
- Arrays.asList(16, 16),
- Arrays.asList(5, 5),
- Arrays.asList(0, 0),
- Arrays.asList(0, 0),
- };
- helpCreateJoin();
- EnhancedSortMergeJoinStrategy psj = new EnhancedSortMergeJoinStrategy(SortOption.SORT, SortOption.SORT);
- psj.setPreferMemCutoff(1);
- this.joinStrategy = psj;
- this.join.setJoinStrategy(joinStrategy);
- helpTestJoinDirect(expected, 4, 1000);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestJoinNode.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/relational/TestJoinNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestJoinNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestJoinNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,774 @@
+/*
+ * 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 static org.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.TupleBatch;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.query.function.FunctionDescriptor;
+import org.teiid.query.processor.FakeDataManager;
+import org.teiid.query.processor.relational.MergeJoinStrategy.SortOption;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.JoinType;
+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.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+ at SuppressWarnings("unchecked")
+public class TestJoinNode {
+ private static final int NO_CRITERIA = 0;
+ private static final int EQUAL_CRITERIA = 1;
+ private static final int FUNCTION_CRITERIA = 2;
+
+ private int criteriaType = EQUAL_CRITERIA;
+
+ protected JoinType joinType;
+
+ protected List[] leftTuples;
+ protected List[] rightTuples;
+
+ protected List[] expected;
+ private List[] expectedReversed;
+
+ protected JoinNode join;
+ protected JoinStrategy joinStrategy;
+ private RelationalNode leftNode;
+ private RelationalNode rightNode;
+
+ private FakeDataManager dataMgr;
+
+ @Before public void setup() {
+ leftTuples = createTuples1();
+ rightTuples = createTuples2();
+ }
+
+ protected List[] createTuples1() {
+ return new List[] {
+ Arrays.asList(new Object[] { new Integer(5) }),
+ Arrays.asList(new Object[] { new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(10) }),
+ Arrays.asList(new Object[] { new Integer(11) }),
+ Arrays.asList(new Object[] { new Integer(11) })
+ };
+ }
+
+ private List[] createTuples2() {
+ return new List[] {
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(4) }),
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(6) })
+ };
+ }
+
+ private List[] createTuples3() {
+ return new List[] {
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { new Integer(10) }),
+ Arrays.asList(new Object[] { new Integer(10) }),
+ Arrays.asList(new Object[] { new Integer(9) }),
+ Arrays.asList(new Object[] { new Integer(9) }),
+ Arrays.asList(new Object[] { new Integer(9) }),
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(5) }),
+ Arrays.asList(new Object[] { new Integer(15) })
+ };
+ }
+
+ private List[] createTuples4() {
+ return new List[] {
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(4) }),
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(9) }),
+ Arrays.asList(new Object[] { new Integer(5) }),
+ Arrays.asList(new Object[] { new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(10) }),
+ Arrays.asList(new Object[] { null }),
+ Arrays.asList(new Object[] { null })
+ };
+ }
+
+ private List[] createTuples(int startingValue, int count) {
+ return createTuples(startingValue, count, false);
+ }
+
+ private List[] createTuples(int startingValue, int count, boolean addNullAsSecondColumn) {
+ ArrayList lists = new ArrayList();
+ for (int i=0; i<count; i++) {
+ Object[] tuple;
+ if (addNullAsSecondColumn) {
+ tuple = new Object[] {new Integer(startingValue + i), null };
+ } else {
+ tuple = new Object[] {new Integer(startingValue + i) };
+ }
+ lists.add( Arrays.asList(tuple) );
+ }
+ return (List[]) lists.toArray(new List[] {});
+ }
+
+ private List[] createResults(int startingValue, int count) {
+ return createTuples(startingValue, count, true);
+ }
+
+ protected void helpCreateJoin() {
+ ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+
+ ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
+ es2.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+
+ List leftElements = new ArrayList();
+ leftElements.add(es1);
+ leftNode = new FakeRelationalNode(1, leftTuples);
+ leftNode.setElements(leftElements);
+
+ List rightElements = new ArrayList();
+ rightElements.add(es2);
+ rightNode = new FakeRelationalNode(2, rightTuples);
+ rightNode.setElements(rightElements);
+
+ List joinElements = new ArrayList();
+ joinElements.add(es1);
+ joinElements.add(es2);
+
+ join = new JoinNode(3);
+ joinStrategy = new NestedLoopJoinStrategy();
+ join.setJoinStrategy(joinStrategy);
+ join.setElements(joinElements);
+ join.setJoinType(joinType);
+
+ switch (criteriaType) {
+ case NO_CRITERIA :
+ break;
+
+ case EQUAL_CRITERIA :
+ join.setJoinExpressions(Arrays.asList(es1), Arrays.asList(es2));
+ joinStrategy = new MergeJoinStrategy(SortOption.SORT, SortOption.SORT, false);
+ join.setJoinStrategy(joinStrategy);
+ break;
+
+ 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 = 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);
+ join.setJoinCriteria(joinCriteria);
+ break;
+ }
+ }
+
+ public void helpTestJoin() throws TeiidComponentException, TeiidProcessingException {
+ for (int batchSize : new int[] {1, 10, leftTuples.length, 100}) {
+ helpCreateJoin();
+ if (batchSize == 0) {
+ continue;
+ }
+ helpTestJoinDirect(expected, batchSize, 100000);
+ List[] temp = leftTuples;
+ leftTuples = rightTuples;
+ rightTuples = temp;
+ helpCreateJoin();
+ helpTestJoinDirect(expectedReversed, batchSize, 100000);
+ temp = leftTuples;
+ leftTuples = rightTuples;
+ rightTuples = temp;
+ }
+ }
+
+ public void helpTestJoinDirect(List[] expectedResults, int batchSize, int processingBytes) throws TeiidComponentException, TeiidProcessingException {
+ BufferManager mgr = NodeTestUtil.getTestBufferManager(processingBytes, batchSize);
+ CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
+
+ join.addChild(leftNode);
+ join.addChild(rightNode);
+
+ leftNode.initialize(context, mgr, dataMgr);
+ rightNode.initialize(context, mgr, dataMgr);
+ join.initialize(context, mgr, dataMgr);
+
+ join.open();
+
+ int currentRow = 1;
+ while(true) {
+ try {
+ TupleBatch batch = join.nextBatch();
+ for(;currentRow <= batch.getEndRow(); currentRow++) {
+ List tuple = batch.getTuple(currentRow);
+ assertEquals("Rows don't match at " + currentRow, expectedResults[currentRow-1], tuple); //$NON-NLS-1$
+ }
+ if(batch.getTerminationFlag()) {
+ break;
+ }
+ } catch(BlockedException e) {
+ // ignore and retry
+ }
+ }
+ assertEquals(expectedResults.length, currentRow - 1);
+ join.close();
+ }
+
+ @Test public void testNoRows() throws Exception {
+ leftTuples = new List[0];
+ rightTuples = new List[0];
+ joinType = JoinType.JOIN_INNER;
+ expected = new List[0];
+ expectedReversed = new List[0];
+ helpTestJoin();
+ }
+
+ @Test public void testInnerJoin() throws Exception {
+ joinType = JoinType.JOIN_INNER;
+ expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) })
+ };
+ expectedReversed = expected;
+ helpTestJoin();
+ }
+
+ @Test public void testLeftOuterJoin() throws Exception {
+ joinType = JoinType.JOIN_LEFT_OUTER;
+ expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(3), null }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(5), null }),
+ Arrays.asList(new Object[] { new Integer(10), null }),
+ Arrays.asList(new Object[] { new Integer(11), null }),
+ Arrays.asList(new Object[] { new Integer(11), null })
+ };
+ expectedReversed = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(6), null }),
+ Arrays.asList(new Object[] { new Integer(7), null }),
+ Arrays.asList(new Object[] { new Integer(7), null })
+ };
+ helpTestJoin();
+ }
+
+ @Test public void testLeftOuterJoinWithSwap() throws Exception {
+ int outerSize = 11;
+ leftTuples = createTuples(1,outerSize);
+ rightTuples = createTuples(201,outerSize+1);
+ joinType = JoinType.JOIN_LEFT_OUTER;
+ expected = createResults(1, outerSize);
+ expectedReversed = createResults(201, outerSize+1);
+ helpTestJoin();
+ }
+
+ @Test public void testCrossJoin() throws Exception {
+ joinType = JoinType.JOIN_CROSS;
+ criteriaType = NO_CRITERIA;
+ expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(5), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(5), null }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(3), null }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(2), null }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(4), null }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(1), null }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(4), null }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(10), null }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(11), null }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(11), null }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(11), new Integer(6) })
+ };
+ expectedReversed = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(5)}),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(3)}),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2)}),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1)}),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(10)}),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(11)}),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(11)}),
+
+ Arrays.asList(new Object[] { new Integer(4), new Integer(5)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(3)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(2)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(1)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(10)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(11)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(11)}),
+
+ Arrays.asList(new Object[] { new Integer(2), new Integer(5)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(3)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(10)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(11)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(11)}),
+
+ Arrays.asList(new Object[] { new Integer(2), new Integer(5)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(3)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(1)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(10)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(11)}),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(11)}),
+
+ Arrays.asList(new Object[] { new Integer(4), new Integer(5)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(3)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(2)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(1)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(10)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(11)}),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(11)}),
+
+ Arrays.asList(new Object[] { null, new Integer(5)}),
+ Arrays.asList(new Object[] { null, new Integer(3)}),
+ Arrays.asList(new Object[] { null, new Integer(2)}),
+ Arrays.asList(new Object[] { null, new Integer(4)}),
+ Arrays.asList(new Object[] { null, new Integer(1)}),
+ Arrays.asList(new Object[] { null, new Integer(4)}),
+ Arrays.asList(new Object[] { null, new Integer(10)}),
+ Arrays.asList(new Object[] { null, new Integer(11)}),
+ Arrays.asList(new Object[] { null, new Integer(11)}),
+
+ Arrays.asList(new Object[] { new Integer(7), new Integer(5)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(3)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(2)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(1)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(10)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(11)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(11)}),
+
+ Arrays.asList(new Object[] { new Integer(7), new Integer(5)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(3)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(2)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(1)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(10)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(11)}),
+ Arrays.asList(new Object[] { new Integer(7), new Integer(11)}),
+
+ Arrays.asList(new Object[] { new Integer(6), new Integer(5)}),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(3)}),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(2)}),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(1)}),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(4)}),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(10)}),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(11)}),
+ Arrays.asList(new Object[] { new Integer(6), new Integer(11)})
+ };
+
+ helpTestJoin();
+ }
+
+ @Test public void testInnerJoinWithLookupFunction() throws Exception {
+ criteriaType = FUNCTION_CRITERIA;
+ joinType = JoinType.JOIN_INNER;
+ expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(5), new Integer(6) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(3), new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(7) })
+ };
+ expectedReversed = new List[] {
+ Arrays.asList(new Object[] { new Integer(1), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(5) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(3) }),
+ Arrays.asList(new Object[] { new Integer(4), new Integer(5) })
+ };
+
+ dataMgr = new FakeDataManager();
+ dataMgr.setThrowBlocked(true);
+ Map valueMap = new HashMap();
+ valueMap.put(new Integer(1), new Integer(2));
+ valueMap.put(new Integer(2), new Integer(3));
+ valueMap.put(new Integer(3), new Integer(4));
+ valueMap.put(new Integer(4), new Integer(5));
+ valueMap.put(new Integer(5), new Integer(6));
+ valueMap.put(new Integer(10), new Integer(7));
+ valueMap.put(new Integer(11), new Integer(8));
+ dataMgr.defineCodeTable("pm1.g1", "e1", "e2", valueMap); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ helpTestJoin();
+ }
+
+ @Test public void testFullOuterJoin() throws Exception {
+ this.joinType = JoinType.JOIN_FULL_OUTER;
+ this.leftTuples = createTuples3();
+ this.rightTuples = createTuples4();
+ expected = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(3), null }),
+ Arrays.asList(new Object[] { null, new Integer(4) }),
+ Arrays.asList(new Object[] { null, new Integer(4) }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(5) }),
+ Arrays.asList(new Object[] { null, new Integer(6) }),
+ Arrays.asList(new Object[] { null, new Integer(7) }),
+ Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
+ Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
+ Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
+ Arrays.asList(new Object[] { new Integer(15), null })
+ };
+ expectedReversed = new List[] {
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { null, null }),
+ Arrays.asList(new Object[] { new Integer(1), new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { new Integer(2), new Integer(2) }),
+ Arrays.asList(new Object[] { null, 3 }),
+ Arrays.asList(new Object[] { 4, null }),
+ Arrays.asList(new Object[] { 4, null }),
+ Arrays.asList(new Object[] { new Integer(5), new Integer(5) }),
+ Arrays.asList(new Object[] { 6, null }),
+ Arrays.asList(new Object[] { 7, null }),
+ Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
+ Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
+ Arrays.asList(new Object[] { new Integer(9), new Integer(9) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
+ Arrays.asList(new Object[] { new Integer(10), new Integer(10) }),
+ Arrays.asList(new Object[] { null, 15 })
+ };
+ helpTestJoin();
+ }
+
+ @Test public void testMergeJoinOptimization() throws Exception {
+ helpTestEnhancedSortMergeJoin(99);
+ }
+
+ private void helpTestEnhancedSortMergeJoin(int batchSize)
+ throws TeiidComponentException, TeiidProcessingException {
+ this.joinType = JoinType.JOIN_INNER;
+ int rows = 100;
+ List[] data = new List[rows];
+ for(int i=0; i<rows; i++) {
+ data[i] = new ArrayList();
+ Integer value = new Integer((i*17) % 47);
+ data[i].add(value);
+ }
+ this.leftTuples = data;
+ this.rightTuples = createTuples2();
+ expected = new List[] {
+ Arrays.asList(new Object[] { 4, 4 }),
+ Arrays.asList(new Object[] { 4, 4 }),
+ Arrays.asList(new Object[] { 7, 7 }),
+ Arrays.asList(new Object[] { 7, 7 }),
+ Arrays.asList(new Object[] { 2, 2 }),
+ Arrays.asList(new Object[] { 2, 2 }),
+ Arrays.asList(new Object[] { 6, 6 }),
+ Arrays.asList(new Object[] { 1, 1 }),
+ Arrays.asList(new Object[] { 4, 4 }),
+ Arrays.asList(new Object[] { 4, 4 }),
+ Arrays.asList(new Object[] { 7, 7 }),
+ Arrays.asList(new Object[] { 7, 7 }),
+ Arrays.asList(new Object[] { 2, 2 }),
+ Arrays.asList(new Object[] { 2, 2 }),
+ Arrays.asList(new Object[] { 6, 6 }),
+ Arrays.asList(new Object[] { 1, 1 }),
+ Arrays.asList(new Object[] { 4, 4 }),
+ Arrays.asList(new Object[] { 4, 4 }),
+ };
+ helpCreateJoin();
+ this.joinStrategy = new EnhancedSortMergeJoinStrategy(SortOption.SORT, SortOption.SORT);
+ this.join.setJoinStrategy(joinStrategy);
+ helpTestJoinDirect(expected, batchSize, 1);
+ }
+
+ @Test public void testMergeJoinOptimizationMultiBatch() throws Exception {
+ helpTestEnhancedSortMergeJoin(10);
+ }
+
+ @Test public void testMergeJoinOptimizationNoRows() throws Exception {
+ this.joinType = JoinType.JOIN_INNER;
+ this.leftTuples = createTuples1();
+ this.rightTuples = new List[] {};
+ expected = new List[] {};
+ helpCreateJoin();
+ this.joinStrategy = new EnhancedSortMergeJoinStrategy(SortOption.SORT, SortOption.SORT);
+ this.join.setJoinStrategy(joinStrategy);
+ helpTestJoinDirect(expected, 100, 1);
+ }
+
+ @Test public void testMergeJoinOptimizationWithDistinct() throws Exception {
+ this.joinType = JoinType.JOIN_INNER;
+ int rows = 50;
+ List[] data = new List[rows];
+ for(int i=0; i<rows; i++) {
+ data[i] = new ArrayList();
+ Integer value = new Integer((i*17) % 47);
+ data[i].add(value);
+ }
+ this.leftTuples = data;
+ this.rightTuples = new List[] {
+ Arrays.asList(4),
+ Arrays.asList(7),
+ Arrays.asList(2),
+ Arrays.asList(6),
+ Arrays.asList(1),
+ Arrays.asList(8),
+ };
+ expected = new List[] {
+ Arrays.asList(new Object[] { 4, 4 }),
+ Arrays.asList(new Object[] { 8, 8 }),
+ Arrays.asList(new Object[] { 7, 7 }),
+ Arrays.asList(new Object[] { 2, 2 }),
+ Arrays.asList(new Object[] { 6, 6 }),
+ Arrays.asList(new Object[] { 1, 1 }),
+ };
+ helpCreateJoin();
+ this.joinStrategy = new EnhancedSortMergeJoinStrategy(SortOption.SORT, SortOption.SORT);
+ this.join.setJoinStrategy(joinStrategy);
+ //this.join.setRightDistinct(true);
+ helpTestJoinDirect(expected, 40, 1);
+ }
+
+ @Test public void testMergeJoinOptimizationWithDistinctAlreadySorted() throws Exception {
+ this.joinType = JoinType.JOIN_INNER;
+ int rows = 50;
+ List[] data = new List[rows];
+ for(int i=0; i<rows; i++) {
+ data[i] = new ArrayList();
+ Integer value = new Integer((i*17) % 47);
+ data[i].add(value);
+ }
+ this.leftTuples = data;
+ this.rightTuples = new List[] {
+ Arrays.asList(1),
+ Arrays.asList(2),
+ Arrays.asList(4),
+ Arrays.asList(6),
+ Arrays.asList(7),
+ Arrays.asList(8),
+ };
+ expected = new List[] {
+ Arrays.asList(new Object[] { 4, 4 }),
+ Arrays.asList(new Object[] { 8, 8 }),
+ Arrays.asList(new Object[] { 7, 7 }),
+ Arrays.asList(new Object[] { 2, 2 }),
+ Arrays.asList(new Object[] { 6, 6 }),
+ Arrays.asList(new Object[] { 1, 1 })
+ };
+ helpCreateJoin();
+ this.joinStrategy = new EnhancedSortMergeJoinStrategy(SortOption.SORT, SortOption.ALREADY_SORTED);
+ this.join.setJoinStrategy(joinStrategy);
+ helpTestJoinDirect(expected, 40, 1);
+ }
+
+ @Test public void testRepeatedMerge() throws Exception {
+ helpTestRepeatedMerge(false);
+ }
+
+ @Test public void testRepeatedMergeWithDistinct() throws Exception {
+ helpTestRepeatedMerge(true);
+ }
+
+ public void helpTestRepeatedMerge(boolean indexDistinct) throws Exception {
+ this.joinType = JoinType.JOIN_INNER;
+ int rows = 69;
+ List[] data = new List[rows];
+ for(int i=0; i<rows; i++) {
+ data[i]=Arrays.asList((i*17) % 91);
+ }
+ if (indexDistinct) {
+ data[2] = Arrays.asList(0);
+ }
+ data[6] = Arrays.asList((Integer)null);
+ this.rightTuples = data;
+ this.leftTuples = new List[17];
+ for (int i = 0; i < this.leftTuples.length; i++) {
+ this.leftTuples[i] = Arrays.asList(i);
+ }
+ if (!indexDistinct) {
+ this.leftTuples[1] = Arrays.asList(0);
+ }
+ this.leftTuples[11] = Arrays.asList((Integer)null);
+
+ expected = new List[] {
+ Arrays.asList(13, 13),
+ Arrays.asList(2, 2),
+ Arrays.asList(8, 8),
+ Arrays.asList(14, 14),
+ Arrays.asList(3, 3),
+ Arrays.asList(9, 9),
+ Arrays.asList(15, 15),
+ Arrays.asList(4, 4),
+ Arrays.asList(10, 10),
+ Arrays.asList(16, 16),
+ Arrays.asList(5, 5),
+ Arrays.asList(0, 0),
+ Arrays.asList(0, 0),
+ };
+ helpCreateJoin();
+ EnhancedSortMergeJoinStrategy psj = new EnhancedSortMergeJoinStrategy(SortOption.SORT, SortOption.SORT);
+ psj.setPreferMemCutoff(1);
+ this.joinStrategy = psj;
+ this.join.setJoinStrategy(joinStrategy);
+ helpTestJoinDirect(expected, 4, 1000);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestProjectNode.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/relational/TestProjectNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestProjectNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,286 +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 java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-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.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.function.FunctionDescriptor;
-import org.teiid.query.processor.FakeDataManager;
-import org.teiid.query.processor.ProcessorDataManager;
-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.unittest.FakeMetadataFactory;
-import org.teiid.query.util.CommandContext;
-
-
-/**
- */
-public class TestProjectNode extends TestCase {
-
- /**
- * Constructor for TestSortNode.
- * @param arg0
- */
- public TestProjectNode(String arg0) {
- super(arg0);
- }
-
- public ProjectNode helpSetupProject(List elements, List[] data, List childElements, ProcessorDataManager dataMgr) throws TeiidComponentException {
- BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
- CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
-
- FakeRelationalNode dataNode = new FakeRelationalNode(2, data);
- dataNode.setElements(childElements);
- dataNode.initialize(context, mgr, null);
-
- ProjectNode projectNode = new ProjectNode(1);
- projectNode.setSelectSymbols(elements);
- projectNode.setElements(elements);
- projectNode.addChild(dataNode);
- projectNode.initialize(context, mgr, dataMgr);
-
- return projectNode;
- }
-
- public void helpTestProject(List elements, List[] data, List childElements, List[] expected, ProcessorDataManager dataMgr) throws TeiidComponentException, TeiidProcessingException {
- ProjectNode projectNode = helpSetupProject(elements, data, childElements, dataMgr);
-
- projectNode.open();
-
- int currentRow = 1;
- while(true) {
- try {
- TupleBatch batch = projectNode.nextBatch();
- for(int row = currentRow; row <= batch.getEndRow(); row++) {
- assertEquals("Rows don't match at " + row, expected[row-1], batch.getTuple(row)); //$NON-NLS-1$
- }
-
- if(batch.getTerminationFlag()) {
- break;
- }
- currentRow += batch.getRowCount();
- } catch(BlockedException e) {
- // ignore and try again
- }
- }
- }
-
- public void helpTestProjectFails(List elements, List[] data, List childElements, String expectedError) throws TeiidComponentException, TeiidProcessingException {
- ProjectNode projectNode = helpSetupProject(elements, data, childElements, null);
-
- try {
- projectNode.open();
-
- while(true) {
- TupleBatch batch = projectNode.nextBatch();
- if(batch.getTerminationFlag()) {
- break;
- }
- }
-
- fail("Expected error but test succeeded"); //$NON-NLS-1$
- } catch(ExpressionEvaluationException e) {
- //note that this should not be a component exception, which would indicate that something abnormal happened
- assertEquals("Got unexpected exception", expectedError.toUpperCase(), e.getMessage().toUpperCase()); //$NON-NLS-1$
- }
- }
-
- public void testNoProject() throws Exception {
- ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
- es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-
- ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
- es2.setType(DataTypeManager.DefaultDataClasses.STRING);
-
- List elements = new ArrayList();
- elements.add(es1);
- elements.add(es2);
-
- List[] data = new List[0];
-
- List projectElements = new ArrayList();
- projectElements.add(es1);
- projectElements.add(es2);
-
- helpTestProject(elements, data, projectElements, data, null);
-
- }
-
- public void testProjectPassThrough() throws Exception {
- ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
- es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-
- ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
- es2.setType(DataTypeManager.DefaultDataClasses.STRING);
-
- List elements = new ArrayList();
- elements.add(es1);
- elements.add(es2);
-
- List projectElements = new ArrayList();
- projectElements.add(es1);
- projectElements.add(es2);
-
- List[] data = new List[20];
- for(int i=0; i<20; i++) {
- data[i] = new ArrayList();
- data[i].add(new Integer((i*51) % 11));
-
- String str = "" + (i*3); //$NON-NLS-1$
- str = str.substring(0,1);
- data[i].add(str);
- }
-
- helpTestProject(elements, data, projectElements, data, null);
- }
-
- public void testProjectReorder() throws Exception {
- ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
- es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-
- ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
- es2.setType(DataTypeManager.DefaultDataClasses.STRING);
-
- List elements = new ArrayList();
- elements.add(es1);
- elements.add(es2);
-
- List projectElements = new ArrayList();
- projectElements.add(es2);
- projectElements.add(es1);
-
- List[] data = new List[20];
- List[] expected = new List[20];
- for(int i=0; i<20; i++) {
- data[i] = new ArrayList();
- expected[i] = new ArrayList();
-
- data[i].add(new Integer((i*51) % 11));
-
- String str = "" + (i*3); //$NON-NLS-1$
- str = str.substring(0,1);
- data[i].add(str);
-
- expected[i].add(data[i].get(1));
- expected[i].add(data[i].get(0));
- }
-
- helpTestProject(elements, data, projectElements, expected, null);
- }
-
- public void testProjectExpression() throws Exception {
- ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
- es1.setType(DataTypeManager.DefaultDataClasses.STRING);
- List elements = new ArrayList();
- 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$
- func.setFunctionDescriptor(fd);
- func.setType(DataTypeManager.DefaultDataClasses.STRING);
- ExpressionSymbol expr = new ExpressionSymbol("expr", func); //$NON-NLS-1$
- List projectElements = new ArrayList();
- projectElements.add(expr);
-
- List[] data = new List[] {
- Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2" }) }; //$NON-NLS-1$
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "1abc" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2abc" }) }; //$NON-NLS-1$
-
- helpTestProject(projectElements, data, elements, expected, null);
- }
-
- public void testProjectExpressionFunctionFails() throws Exception {
- ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
- es1.setType(DataTypeManager.DefaultDataClasses.STRING);
- List elements = new ArrayList();
- 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$
- func.setFunctionDescriptor(fd);
- func.setType(DataTypeManager.DefaultDataClasses.INTEGER);
- ExpressionSymbol expr = new ExpressionSymbol("expr", func); //$NON-NLS-1$
- List projectElements = new ArrayList();
- projectElements.add(expr);
-
- List[] data = new List[] {
- Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2x" }) }; //$NON-NLS-1$
-
- String expectedMessage = "ERROR CODE:ERR.015.001.0003 MESSAGE:Unable to evaluate convert(e1, integer): ERROR CODE:ERR.015.001.0003 MESSAGE:Error while evaluating function convert"; //$NON-NLS-1$
-
- helpTestProjectFails(projectElements, data, elements, expectedMessage);
- }
-
- public void testProjectWithLookupFunction() throws Exception {
- ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
- es1.setType(DataTypeManager.DefaultDataClasses.STRING);
- List elements = new ArrayList();
- 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$
- func.setFunctionDescriptor(desc);
- func.setType(DataTypeManager.DefaultDataClasses.STRING);
-
- ExpressionSymbol expr = new ExpressionSymbol("expr", func); //$NON-NLS-1$
- List projectElements = new ArrayList();
- projectElements.add(expr);
-
- List[] data = new List[] {
- Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "2" }) }; //$NON-NLS-1$
- List[] expected = new List[] {
- Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
- Arrays.asList(new Object[] { "b" }) }; //$NON-NLS-1$
-
- FakeDataManager dataMgr = new FakeDataManager();
- dataMgr.setThrowBlocked(true);
- Map valueMap = new HashMap();
- valueMap.put("1", "a"); //$NON-NLS-1$ //$NON-NLS-2$
- valueMap.put("2", "b"); //$NON-NLS-1$ //$NON-NLS-2$
- dataMgr.defineCodeTable("pm1.g1", "e1", "e2", valueMap); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- helpTestProject(projectElements, data, elements, expected, dataMgr);
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestProjectNode.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/relational/TestProjectNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestProjectNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestProjectNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,286 @@
+/*
+ * 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.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import junit.framework.TestCase;
+
+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.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.query.function.FunctionDescriptor;
+import org.teiid.query.processor.FakeDataManager;
+import org.teiid.query.processor.ProcessorDataManager;
+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.unittest.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+
+/**
+ */
+public class TestProjectNode extends TestCase {
+
+ /**
+ * Constructor for TestSortNode.
+ * @param arg0
+ */
+ public TestProjectNode(String arg0) {
+ super(arg0);
+ }
+
+ public ProjectNode helpSetupProject(List elements, List[] data, List childElements, ProcessorDataManager dataMgr) throws TeiidComponentException {
+ BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
+ CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
+
+ FakeRelationalNode dataNode = new FakeRelationalNode(2, data);
+ dataNode.setElements(childElements);
+ dataNode.initialize(context, mgr, null);
+
+ ProjectNode projectNode = new ProjectNode(1);
+ projectNode.setSelectSymbols(elements);
+ projectNode.setElements(elements);
+ projectNode.addChild(dataNode);
+ projectNode.initialize(context, mgr, dataMgr);
+
+ return projectNode;
+ }
+
+ public void helpTestProject(List elements, List[] data, List childElements, List[] expected, ProcessorDataManager dataMgr) throws TeiidComponentException, TeiidProcessingException {
+ ProjectNode projectNode = helpSetupProject(elements, data, childElements, dataMgr);
+
+ projectNode.open();
+
+ int currentRow = 1;
+ while(true) {
+ try {
+ TupleBatch batch = projectNode.nextBatch();
+ for(int row = currentRow; row <= batch.getEndRow(); row++) {
+ assertEquals("Rows don't match at " + row, expected[row-1], batch.getTuple(row)); //$NON-NLS-1$
+ }
+
+ if(batch.getTerminationFlag()) {
+ break;
+ }
+ currentRow += batch.getRowCount();
+ } catch(BlockedException e) {
+ // ignore and try again
+ }
+ }
+ }
+
+ public void helpTestProjectFails(List elements, List[] data, List childElements, String expectedError) throws TeiidComponentException, TeiidProcessingException {
+ ProjectNode projectNode = helpSetupProject(elements, data, childElements, null);
+
+ try {
+ projectNode.open();
+
+ while(true) {
+ TupleBatch batch = projectNode.nextBatch();
+ if(batch.getTerminationFlag()) {
+ break;
+ }
+ }
+
+ fail("Expected error but test succeeded"); //$NON-NLS-1$
+ } catch(ExpressionEvaluationException e) {
+ //note that this should not be a component exception, which would indicate that something abnormal happened
+ assertEquals("Got unexpected exception", expectedError.toUpperCase(), e.getMessage().toUpperCase()); //$NON-NLS-1$
+ }
+ }
+
+ public void testNoProject() throws Exception {
+ ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+
+ ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
+ es2.setType(DataTypeManager.DefaultDataClasses.STRING);
+
+ List elements = new ArrayList();
+ elements.add(es1);
+ elements.add(es2);
+
+ List[] data = new List[0];
+
+ List projectElements = new ArrayList();
+ projectElements.add(es1);
+ projectElements.add(es2);
+
+ helpTestProject(elements, data, projectElements, data, null);
+
+ }
+
+ public void testProjectPassThrough() throws Exception {
+ ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+
+ ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
+ es2.setType(DataTypeManager.DefaultDataClasses.STRING);
+
+ List elements = new ArrayList();
+ elements.add(es1);
+ elements.add(es2);
+
+ List projectElements = new ArrayList();
+ projectElements.add(es1);
+ projectElements.add(es2);
+
+ List[] data = new List[20];
+ for(int i=0; i<20; i++) {
+ data[i] = new ArrayList();
+ data[i].add(new Integer((i*51) % 11));
+
+ String str = "" + (i*3); //$NON-NLS-1$
+ str = str.substring(0,1);
+ data[i].add(str);
+ }
+
+ helpTestProject(elements, data, projectElements, data, null);
+ }
+
+ public void testProjectReorder() throws Exception {
+ ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+
+ ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
+ es2.setType(DataTypeManager.DefaultDataClasses.STRING);
+
+ List elements = new ArrayList();
+ elements.add(es1);
+ elements.add(es2);
+
+ List projectElements = new ArrayList();
+ projectElements.add(es2);
+ projectElements.add(es1);
+
+ List[] data = new List[20];
+ List[] expected = new List[20];
+ for(int i=0; i<20; i++) {
+ data[i] = new ArrayList();
+ expected[i] = new ArrayList();
+
+ data[i].add(new Integer((i*51) % 11));
+
+ String str = "" + (i*3); //$NON-NLS-1$
+ str = str.substring(0,1);
+ data[i].add(str);
+
+ expected[i].add(data[i].get(1));
+ expected[i].add(data[i].get(0));
+ }
+
+ helpTestProject(elements, data, projectElements, expected, null);
+ }
+
+ public void testProjectExpression() throws Exception {
+ ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ es1.setType(DataTypeManager.DefaultDataClasses.STRING);
+ List elements = new ArrayList();
+ elements.add(es1);
+
+ Function func = new Function("concat", new Expression[] { es1, new Constant("abc")}); //$NON-NLS-1$ //$NON-NLS-2$
+ 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$
+ List projectElements = new ArrayList();
+ projectElements.add(expr);
+
+ List[] data = new List[] {
+ Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2" }) }; //$NON-NLS-1$
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "1abc" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2abc" }) }; //$NON-NLS-1$
+
+ helpTestProject(projectElements, data, elements, expected, null);
+ }
+
+ public void testProjectExpressionFunctionFails() throws Exception {
+ ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ es1.setType(DataTypeManager.DefaultDataClasses.STRING);
+ List elements = new ArrayList();
+ elements.add(es1);
+
+ Function func = new Function("convert", new Expression[] { es1, new Constant("integer")}); //$NON-NLS-1$ //$NON-NLS-2$
+ 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$
+ List projectElements = new ArrayList();
+ projectElements.add(expr);
+
+ List[] data = new List[] {
+ Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2x" }) }; //$NON-NLS-1$
+
+ String expectedMessage = "ERROR CODE:ERR.015.001.0003 MESSAGE:Unable to evaluate convert(e1, integer): ERROR CODE:ERR.015.001.0003 MESSAGE:Error while evaluating function convert"; //$NON-NLS-1$
+
+ helpTestProjectFails(projectElements, data, elements, expectedMessage);
+ }
+
+ public void testProjectWithLookupFunction() throws Exception {
+ ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ es1.setType(DataTypeManager.DefaultDataClasses.STRING);
+ List elements = new ArrayList();
+ 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 = 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);
+
+ ExpressionSymbol expr = new ExpressionSymbol("expr", func); //$NON-NLS-1$
+ List projectElements = new ArrayList();
+ projectElements.add(expr);
+
+ List[] data = new List[] {
+ Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "2" }) }; //$NON-NLS-1$
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+ Arrays.asList(new Object[] { "b" }) }; //$NON-NLS-1$
+
+ FakeDataManager dataMgr = new FakeDataManager();
+ dataMgr.setThrowBlocked(true);
+ Map valueMap = new HashMap();
+ valueMap.put("1", "a"); //$NON-NLS-1$ //$NON-NLS-2$
+ valueMap.put("2", "b"); //$NON-NLS-1$ //$NON-NLS-2$
+ dataMgr.defineCodeTable("pm1.g1", "e1", "e2", valueMap); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ helpTestProject(projectElements, data, elements, expected, dataMgr);
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestSelectNode.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/relational/TestSelectNode.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestSelectNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,274 +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 static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-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;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.eval.Evaluator;
-import org.teiid.query.function.FunctionDescriptor;
-import org.teiid.query.processor.BatchIterator;
-import org.teiid.query.processor.FakeDataManager;
-import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.processor.QueryProcessor;
-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.Expression;
-import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.util.CommandContext;
-
-public class TestSelectNode {
-
- public void helpTestSelect(List elements, Criteria criteria, List[] data, List childElements, ProcessorDataManager dataMgr, List[] expected) throws TeiidComponentException, TeiidProcessingException {
- helpTestSelect(elements, criteria, childElements, dataMgr, expected, new FakeRelationalNode(2, data));
- }
-
- public void helpTestSelect(List elements, Criteria criteria, List childElements, ProcessorDataManager dataMgr, List[] expected, RelationalNode child) throws TeiidComponentException, TeiidProcessingException {
- SelectNode selectNode = new SelectNode(1);
- helpTestSelect(elements, criteria, childElements, dataMgr, expected, child, selectNode);
- }
-
- private void helpTestSelect(List elements, Criteria criteria, List childElements,
- ProcessorDataManager dataMgr, List[] expected,
- RelationalNode child,
- SelectNode selectNode) throws TeiidComponentException,
- TeiidProcessingException {
- BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
- CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
-
- child.setElements(childElements);
- child.initialize(context, mgr, dataMgr);
- selectNode.setCriteria(criteria);
- selectNode.setElements(elements);
- selectNode.addChild(child);
- selectNode.initialize(context, mgr, dataMgr);
-
- selectNode.open();
-
- BatchIterator iterator = new BatchIterator(selectNode);
-
- for (int i = 0; i < expected.length; i++) {
- while (true) {
- try {
- assertEquals("Rows don't match at " + i, expected[i], iterator.nextTuple()); //$NON-NLS-1$
- break;
- } catch (BlockedException e) {
- continue;
- } catch (QueryProcessor.ExpiredTimeSliceException e) {
- continue;
- }
- }
- }
- assertFalse(iterator.hasNext());
- }
-
- /**
- * Ensures that a final empty batch is reindexed so that the batch iterator works correctly
- */
- @Test public void testEmptyBatchIndexing() throws TeiidComponentException, TeiidProcessingException {
- ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
- es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-
- List elements = new ArrayList();
- elements.add(es1);
-
- CompareCriteria crit = new CompareCriteria(new Constant(0), CompareCriteria.EQ, new Constant(new Integer(1)));
-
- List childElements = new ArrayList();
- childElements.add(es1);
-
- RelationalNode child = new RelationalNode(0) {
- int i = 0;
-
- @Override
- public Object clone() {
- return null;
- }
-
- @Override
- protected TupleBatch nextBatchDirect() throws BlockedException,
- TeiidComponentException, TeiidProcessingException {
- if (i++ == 0) {
- return new TupleBatch(1, new List[] {Arrays.asList(1), Arrays.asList(1)});
- }
- TupleBatch batch = new TupleBatch(3, new List[0] );
- batch.setTerminationFlag(true);
- return batch;
- }
-
- };
-
- helpTestSelect(elements, crit, childElements, null, new List[0], child);
- }
-
- @Test public void testTimeslicing() throws TeiidComponentException, TeiidProcessingException {
- ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
- es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-
- List elements = new ArrayList();
- elements.add(es1);
-
- CompareCriteria crit = new CompareCriteria(es1, CompareCriteria.EQ, new Constant(new Integer(1)));
-
- List[] data = new List[] {
- Arrays.asList(1),
- Arrays.asList(1),
- Arrays.asList(1)
- };
-
- List childElements = new ArrayList();
- childElements.add(es1);
-
- helpTestSelect(elements, crit, childElements, null, data, new FakeRelationalNode(2, data), new SelectNode(3) {
- int i = 0;
-
- @Override
- protected Evaluator getEvaluator(Map elementMap) {
- if (i++ == 1) {
- throw new QueryProcessor.ExpiredTimeSliceException();
- }
- return super.getEvaluator(elementMap);
- }
- });
- }
-
- @Test public void testNoRows() throws TeiidComponentException, TeiidProcessingException {
- ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
- es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-
- ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
- es2.setType(DataTypeManager.DefaultDataClasses.STRING);
-
- List elements = new ArrayList();
- elements.add(es1);
-
- List[] data = new List[0];
-
- CompareCriteria crit = new CompareCriteria(es1, CompareCriteria.EQ, new Constant(new Integer(1)));
-
- List childElements = new ArrayList();
- childElements.add(es1);
- childElements.add(es2);
-
- helpTestSelect(elements, crit, data, childElements, null, data);
-
- }
-
- @Test public void testSimpleSelect() throws TeiidComponentException, TeiidProcessingException {
- ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
- es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-
- ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
- es2.setType(DataTypeManager.DefaultDataClasses.STRING);
-
- List elements = new ArrayList();
- elements.add(es1);
-
- CompareCriteria crit = new CompareCriteria(es1, CompareCriteria.EQ, new Constant(new Integer(1)));
-
- List[] data = new List[20];
- for(int i=0; i<20; i++) {
- data[i] = new ArrayList();
- data[i].add(new Integer((i*51) % 11));
-
- String str = "" + (i*3); //$NON-NLS-1$
- str = str.substring(0,1);
- data[i].add(str);
- }
-
- List childElements = new ArrayList();
- childElements.add(es1);
- childElements.add(es2);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(1) }),
- Arrays.asList(new Object[] { new Integer(1) })
- };
-
- helpTestSelect(elements, crit, data, childElements, null, expected);
-
- }
-
- @Test public void testSelectWithLookup() throws TeiidComponentException, TeiidProcessingException {
- ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
- es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-
- ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
- es2.setType(DataTypeManager.DefaultDataClasses.STRING);
-
- List elements = new ArrayList();
- 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$
- func.setFunctionDescriptor(desc);
- func.setType(DataTypeManager.DefaultDataClasses.INTEGER);
- CompareCriteria crit = new CompareCriteria(func, CompareCriteria.EQ, new Constant(new Integer(1)));
-
- List[] data = new List[20];
- for(int i=0; i<20; i++) {
- data[i] = new ArrayList();
- data[i].add(new Integer((i*51) % 11));
-
- String str = "" + (i*3); //$NON-NLS-1$
- str = str.substring(0,1);
- data[i].add(str);
- }
-
- List childElements = new ArrayList();
- childElements.add(es1);
- childElements.add(es2);
-
- List[] expected = new List[] {
- Arrays.asList(new Object[] { new Integer(0) }),
- Arrays.asList(new Object[] { new Integer(0) })
- };
-
- FakeDataManager dataMgr = new FakeDataManager();
- dataMgr.setThrowBlocked(true);
- Map valueMap = new HashMap();
- valueMap.put(new Integer(0), new Integer(1));
- valueMap.put(new Integer(1), new Integer(2));
- dataMgr.defineCodeTable("pm1.g1", "e1", "e2", valueMap); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- helpTestSelect(elements, crit, data, childElements, dataMgr, expected);
-
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestSelectNode.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/relational/TestSelectNode.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestSelectNode.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/relational/TestSelectNode.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,274 @@
+/*
+ * 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 static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+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;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.query.eval.Evaluator;
+import org.teiid.query.function.FunctionDescriptor;
+import org.teiid.query.processor.BatchIterator;
+import org.teiid.query.processor.FakeDataManager;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.processor.QueryProcessor;
+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.Expression;
+import org.teiid.query.sql.symbol.Function;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+public class TestSelectNode {
+
+ public void helpTestSelect(List elements, Criteria criteria, List[] data, List childElements, ProcessorDataManager dataMgr, List[] expected) throws TeiidComponentException, TeiidProcessingException {
+ helpTestSelect(elements, criteria, childElements, dataMgr, expected, new FakeRelationalNode(2, data));
+ }
+
+ public void helpTestSelect(List elements, Criteria criteria, List childElements, ProcessorDataManager dataMgr, List[] expected, RelationalNode child) throws TeiidComponentException, TeiidProcessingException {
+ SelectNode selectNode = new SelectNode(1);
+ helpTestSelect(elements, criteria, childElements, dataMgr, expected, child, selectNode);
+ }
+
+ private void helpTestSelect(List elements, Criteria criteria, List childElements,
+ ProcessorDataManager dataMgr, List[] expected,
+ RelationalNode child,
+ SelectNode selectNode) throws TeiidComponentException,
+ TeiidProcessingException {
+ BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
+ CommandContext context = new CommandContext("pid", "test", null, null, 1); //$NON-NLS-1$ //$NON-NLS-2$
+
+ child.setElements(childElements);
+ child.initialize(context, mgr, dataMgr);
+ selectNode.setCriteria(criteria);
+ selectNode.setElements(elements);
+ selectNode.addChild(child);
+ selectNode.initialize(context, mgr, dataMgr);
+
+ selectNode.open();
+
+ BatchIterator iterator = new BatchIterator(selectNode);
+
+ for (int i = 0; i < expected.length; i++) {
+ while (true) {
+ try {
+ assertEquals("Rows don't match at " + i, expected[i], iterator.nextTuple()); //$NON-NLS-1$
+ break;
+ } catch (BlockedException e) {
+ continue;
+ } catch (QueryProcessor.ExpiredTimeSliceException e) {
+ continue;
+ }
+ }
+ }
+ assertFalse(iterator.hasNext());
+ }
+
+ /**
+ * Ensures that a final empty batch is reindexed so that the batch iterator works correctly
+ */
+ @Test public void testEmptyBatchIndexing() throws TeiidComponentException, TeiidProcessingException {
+ ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+
+ List elements = new ArrayList();
+ elements.add(es1);
+
+ CompareCriteria crit = new CompareCriteria(new Constant(0), CompareCriteria.EQ, new Constant(new Integer(1)));
+
+ List childElements = new ArrayList();
+ childElements.add(es1);
+
+ RelationalNode child = new RelationalNode(0) {
+ int i = 0;
+
+ @Override
+ public Object clone() {
+ return null;
+ }
+
+ @Override
+ protected TupleBatch nextBatchDirect() throws BlockedException,
+ TeiidComponentException, TeiidProcessingException {
+ if (i++ == 0) {
+ return new TupleBatch(1, new List[] {Arrays.asList(1), Arrays.asList(1)});
+ }
+ TupleBatch batch = new TupleBatch(3, new List[0] );
+ batch.setTerminationFlag(true);
+ return batch;
+ }
+
+ };
+
+ helpTestSelect(elements, crit, childElements, null, new List[0], child);
+ }
+
+ @Test public void testTimeslicing() throws TeiidComponentException, TeiidProcessingException {
+ ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+
+ List elements = new ArrayList();
+ elements.add(es1);
+
+ CompareCriteria crit = new CompareCriteria(es1, CompareCriteria.EQ, new Constant(new Integer(1)));
+
+ List[] data = new List[] {
+ Arrays.asList(1),
+ Arrays.asList(1),
+ Arrays.asList(1)
+ };
+
+ List childElements = new ArrayList();
+ childElements.add(es1);
+
+ helpTestSelect(elements, crit, childElements, null, data, new FakeRelationalNode(2, data), new SelectNode(3) {
+ int i = 0;
+
+ @Override
+ protected Evaluator getEvaluator(Map elementMap) {
+ if (i++ == 1) {
+ throw new QueryProcessor.ExpiredTimeSliceException();
+ }
+ return super.getEvaluator(elementMap);
+ }
+ });
+ }
+
+ @Test public void testNoRows() throws TeiidComponentException, TeiidProcessingException {
+ ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+
+ ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
+ es2.setType(DataTypeManager.DefaultDataClasses.STRING);
+
+ List elements = new ArrayList();
+ elements.add(es1);
+
+ List[] data = new List[0];
+
+ CompareCriteria crit = new CompareCriteria(es1, CompareCriteria.EQ, new Constant(new Integer(1)));
+
+ List childElements = new ArrayList();
+ childElements.add(es1);
+ childElements.add(es2);
+
+ helpTestSelect(elements, crit, data, childElements, null, data);
+
+ }
+
+ @Test public void testSimpleSelect() throws TeiidComponentException, TeiidProcessingException {
+ ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+
+ ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
+ es2.setType(DataTypeManager.DefaultDataClasses.STRING);
+
+ List elements = new ArrayList();
+ elements.add(es1);
+
+ CompareCriteria crit = new CompareCriteria(es1, CompareCriteria.EQ, new Constant(new Integer(1)));
+
+ List[] data = new List[20];
+ for(int i=0; i<20; i++) {
+ data[i] = new ArrayList();
+ data[i].add(new Integer((i*51) % 11));
+
+ String str = "" + (i*3); //$NON-NLS-1$
+ str = str.substring(0,1);
+ data[i].add(str);
+ }
+
+ List childElements = new ArrayList();
+ childElements.add(es1);
+ childElements.add(es2);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(1) }),
+ Arrays.asList(new Object[] { new Integer(1) })
+ };
+
+ helpTestSelect(elements, crit, data, childElements, null, expected);
+
+ }
+
+ @Test public void testSelectWithLookup() throws TeiidComponentException, TeiidProcessingException {
+ ElementSymbol es1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ es1.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+
+ ElementSymbol es2 = new ElementSymbol("e2"); //$NON-NLS-1$
+ es2.setType(DataTypeManager.DefaultDataClasses.STRING);
+
+ List elements = new ArrayList();
+ 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 = 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)));
+
+ List[] data = new List[20];
+ for(int i=0; i<20; i++) {
+ data[i] = new ArrayList();
+ data[i].add(new Integer((i*51) % 11));
+
+ String str = "" + (i*3); //$NON-NLS-1$
+ str = str.substring(0,1);
+ data[i].add(str);
+ }
+
+ List childElements = new ArrayList();
+ childElements.add(es1);
+ childElements.add(es2);
+
+ List[] expected = new List[] {
+ Arrays.asList(new Object[] { new Integer(0) }),
+ Arrays.asList(new Object[] { new Integer(0) })
+ };
+
+ FakeDataManager dataMgr = new FakeDataManager();
+ dataMgr.setThrowBlocked(true);
+ Map valueMap = new HashMap();
+ valueMap.put(new Integer(0), new Integer(1));
+ valueMap.put(new Integer(1), new Integer(2));
+ dataMgr.defineCodeTable("pm1.g1", "e1", "e2", valueMap); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ helpTestSelect(elements, crit, data, childElements, dataMgr, expected);
+
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestInstructions.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/xml/TestInstructions.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestInstructions.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,385 +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.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.teiid.api.exception.query.QueryParserException;
-import org.teiid.api.exception.query.QueryResolverException;
-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.core.types.DataTypeManager;
-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.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;
-import org.teiid.query.sql.lang.Command;
-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.util.CommandContext;
-
-import junit.framework.TestCase;
-
-
-/**
- */
-public class TestInstructions extends TestCase {
-
- public TestInstructions(String name) {
- super(name);
- }
-
- /**
- * Construct some fake metadata. Basic conceptual tree is:
- *
- * stock (physical model)
- * items (physical group)
- * itemNum (string)
- * itemName (string)
- * itemQuantity (integer)
- * xmltest (virtual model)
- * rs (virtual group / result set definition)
- * itemNum (string)
- * itemName (string)
- * itemQuantity (integer)
- */
- public FakeMetadataFacade exampleMetadata() {
- // 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$
-
- // Create physical elements
- List itemElements = FakeMetadataFactory.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$
-
- // Create virtual elements
- List rsElements = FakeMetadataFactory.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);
- }
-
- private Command helpGetCommand(String sql, FakeMetadataFacade metadata) throws TeiidComponentException, TeiidProcessingException {
- // parse
- QueryParser parser = new QueryParser();
- Command command = parser.parseCommand(sql);
-
- QueryResolver.resolveCommand(command, metadata);
- command = QueryRewriter.rewrite(command, metadata, null);
-
- return command;
- }
-
- private Criteria helpGetCriteria(String sql, FakeMetadataFacade metadata) throws QueryParserException, QueryResolverException, TeiidComponentException {
- QueryParser parser = new QueryParser();
- Criteria crit = parser.parseCriteria(sql);
-
- ResolverVisitor.resolveLanguageObject(crit, null, metadata);
-
- return crit;
- }
-
- public void helpProcessInstructions(Program prog, XMLProcessorEnvironment env, String expected) throws Exception {
- env.pushProgram(prog);
- XMLPlan plan = new XMLPlan(env);
- TestProcessor.doProcess(plan, new FakeDataManager(), new List[] {Arrays.asList(expected)}, new CommandContext());
- }
-
- public Program exampleProgram(FakeMetadataFacade metadata, XMLProcessorEnvironment env) 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);
- ProcessorInstruction i2 = new MoveDocInstruction(MoveDocInstruction.DOWN);
- descriptor = NodeDescriptor.createNodeDescriptor("Catalog", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
- ProcessorInstruction i3 = new AddNodeInstruction(descriptor);
- ProcessorInstruction i4 = new MoveDocInstruction(MoveDocInstruction.DOWN);
- descriptor = NodeDescriptor.createNodeDescriptor("Items", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
- ProcessorInstruction i5 = new AddNodeInstruction(descriptor);
- ProcessorInstruction i6 = new MoveDocInstruction(MoveDocInstruction.DOWN);
-
- ResultSetInfo info = new ResultSetInfo("xmltest.rs"); //$NON-NLS-1$
- ProcessorInstruction i7 = new ExecSqlInstruction("xmltest.rs", info); //$NON-NLS-1$
- ProcessorInstruction i8 = new MoveCursorInstruction("xmltest.rs"); //$NON-NLS-1$
-
- WhileInstruction i9 = new WhileInstruction("xmltest.rs"); //$NON-NLS-1$
- descriptor = NodeDescriptor.createNodeDescriptor("Item", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
- ProcessorInstruction i10 = new AddNodeInstruction(descriptor);
- ProcessorInstruction i11 = new MoveDocInstruction(MoveDocInstruction.DOWN);
- descriptor = NodeDescriptor.createNodeDescriptor("ItemID", null, AddNodeInstruction.ATTRIBUTE, null, null, null, false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
- ProcessorInstruction i12 = new AddNodeInstruction(descriptor, new ElementSymbol("xmltest.rs.itemNum")); //$NON-NLS-1$
- descriptor = NodeDescriptor.createNodeDescriptor("Name", null, AddNodeInstruction.ELEMENT, null, null, null, false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
- ProcessorInstruction i13 = new AddNodeInstruction(descriptor, new ElementSymbol("xmltest.rs.itemName"));//$NON-NLS-1$
- descriptor = NodeDescriptor.createNodeDescriptor("Quantity", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
- ProcessorInstruction i14 = new AddNodeInstruction(descriptor, new ElementSymbol("xmltest.rs.itemQuantity"));//$NON-NLS-1$
- ProcessorInstruction i15 = new MoveDocInstruction(MoveDocInstruction.UP);
- ProcessorInstruction i16 = new MoveCursorInstruction("xmltest.rs"); //$NON-NLS-1$
-
- ProcessorInstruction i17 = new MoveDocInstruction(MoveDocInstruction.UP);
- ProcessorInstruction i18 = new MoveDocInstruction(MoveDocInstruction.UP);
- ProcessorInstruction i19 = new MoveDocInstruction(MoveDocInstruction.UP);
-
- ProcessorInstruction i20 = new EndDocumentInstruction();
-
- // Stitch them together
-
- Program program = new Program();
- program.addInstruction(i0);
- program.addInstruction(i1);
- program.addInstruction(i2);
- program.addInstruction(i3);
- program.addInstruction(i4);
- program.addInstruction(i5);
- program.addInstruction(i6);
- program.addInstruction(i7);
- program.addInstruction(i8);
- program.addInstruction(i9);
-
- Program subProgram = new Program();
- i9.setBlockProgram(subProgram);
- subProgram.addInstruction(i10);
- subProgram.addInstruction(i11);
- subProgram.addInstruction(i12);
- subProgram.addInstruction(i13);
- subProgram.addInstruction(i14);
- subProgram.addInstruction(i15);
- subProgram.addInstruction(i16);
-
- program.addInstruction(i17);
- program.addInstruction(i18);
- program.addInstruction(i19);
- program.addInstruction(i20);
-
- //ProgramUtil.printProgram(program);
- return program;
- }
-
- public Program exampleProgram2(Criteria crit, FakeMetadataFacade metadata, XMLProcessorEnvironment env) 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);
- ProcessorInstruction i2 = new MoveDocInstruction(MoveDocInstruction.DOWN);
- descriptor = NodeDescriptor.createNodeDescriptor("Catalog", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
- ProcessorInstruction i3 = new AddNodeInstruction(descriptor);
- ProcessorInstruction i4 = new MoveDocInstruction(MoveDocInstruction.DOWN);
- descriptor = NodeDescriptor.createNodeDescriptor("Items", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
- ProcessorInstruction i5 = new AddNodeInstruction(descriptor);
- ProcessorInstruction i6 = new MoveDocInstruction(MoveDocInstruction.DOWN);
-
- ResultSetInfo info = new ResultSetInfo("xmltest.rs"); //$NON-NLS-1$
- ProcessorInstruction i7 = new ExecSqlInstruction("xmltest.rs", info); //$NON-NLS-1$
- ProcessorInstruction i8 = new MoveCursorInstruction("xmltest.rs"); //$NON-NLS-1$
-
- WhileInstruction i9 = new WhileInstruction("xmltest.rs"); //$NON-NLS-1$
-
- //need to move this up here so it can be referenced by "If" instruction
- ProcessorInstruction i17 = new MoveCursorInstruction("xmltest.rs"); //$NON-NLS-1$
-
- IfInstruction i10 = new IfInstruction( );
- descriptor = NodeDescriptor.createNodeDescriptor("Item", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
- ProcessorInstruction i11 = new AddNodeInstruction(descriptor);
- ProcessorInstruction i12 = new MoveDocInstruction(MoveDocInstruction.DOWN);
- descriptor = NodeDescriptor.createNodeDescriptor("ItemID", null, AddNodeInstruction.ATTRIBUTE, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
- ProcessorInstruction i13 = new AddNodeInstruction(descriptor, new ElementSymbol("xmltest.rs.itemNum"));//$NON-NLS-1$
- descriptor = NodeDescriptor.createNodeDescriptor("Name", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
- ProcessorInstruction i14 = new AddNodeInstruction(descriptor, new ElementSymbol("xmltest.rs.itemName"));//$NON-NLS-1$
- descriptor = NodeDescriptor.createNodeDescriptor("Quantity", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
- ProcessorInstruction i15 = new AddNodeInstruction(descriptor, new ElementSymbol("xmltest.rs.itemQuantity")); //$NON-NLS-1$
- ProcessorInstruction i16 = new MoveDocInstruction(MoveDocInstruction.UP);
-
- ProcessorInstruction i18 = new MoveDocInstruction(MoveDocInstruction.UP);
- ProcessorInstruction i19 = new MoveDocInstruction(MoveDocInstruction.UP);
- ProcessorInstruction i20 = new MoveDocInstruction(MoveDocInstruction.UP);
- ProcessorInstruction i21 = new EndDocumentInstruction();
-
-
- // Stitch them together
-
- Program program = new Program();
- program.addInstruction(i0);
- program.addInstruction(i1);
- program.addInstruction(i2);
- program.addInstruction(i3);
- program.addInstruction(i4);
- program.addInstruction(i5);
- program.addInstruction(i6);
- program.addInstruction(i7);
- program.addInstruction(i8);
- program.addInstruction(i9);
-
- Program whileProgram = new Program();
- i9.setBlockProgram(whileProgram);
- whileProgram.addInstruction(i10);
-
- Program thenProgram = new Program();
- Condition cond = new CriteriaCondition(crit, thenProgram);
- i10.addCondition(cond);
-
- thenProgram.addInstruction(i11);
- thenProgram.addInstruction(i12);
- thenProgram.addInstruction(i13);
- thenProgram.addInstruction(i14);
- thenProgram.addInstruction(i15);
- thenProgram.addInstruction(i16);
-
- whileProgram.addInstruction(i17);
-
- program.addInstruction(i18);
- program.addInstruction(i19);
- program.addInstruction(i20);
- program.addInstruction(i21);
-
- //ProgramUtil.printProgram(program);
- return program;
- }
-
-
- public void testProcess1() throws Exception {
- FakeMetadataFacade metadata = exampleMetadata();
- String resultSetName = "xmltest.rs"; //$NON-NLS-1$
-
- FakeXMLProcessorEnvironment env = new FakeXMLProcessorEnvironment();
- Program program = exampleProgram(metadata, env);
-
- 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();
- 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$
-
- env.addData(resultSetName, schema, new List[] {
- Arrays.asList( new Object[] { "001", "Lamp", new Integer(5) } ), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100) } ), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList( new Object[] { "003", "Goat", new Integer(4) } ) //$NON-NLS-1$ //$NON-NLS-2$
- } );
- helpProcessInstructions(program, env,
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$
- "<Catalogs>\n" + //$NON-NLS-1$
- " <Catalog>\n" + //$NON-NLS-1$
- " <Items>\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\n" + //$NON-NLS-1$
- " <Name>Lamp</Name>\n" + //$NON-NLS-1$
- " <Quantity>5</Quantity>\n" + //$NON-NLS-1$
- " </Item>\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\n" + //$NON-NLS-1$
- " <Name>Screwdriver</Name>\n" + //$NON-NLS-1$
- " <Quantity>100</Quantity>\n" + //$NON-NLS-1$
- " </Item>\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\n" + //$NON-NLS-1$
- " <Name>Goat</Name>\n" + //$NON-NLS-1$
- " <Quantity>4</Quantity>\n" + //$NON-NLS-1$
- " </Item>\n" + //$NON-NLS-1$
- " </Items>\n" + //$NON-NLS-1$
- " </Catalog>\n" + //$NON-NLS-1$
- "</Catalogs>"); //$NON-NLS-1$
- }
-
- public void testProcess2() throws Exception {
- FakeMetadataFacade metadata = exampleMetadata();
-
- String resultSetName = "xmltest.rs"; //$NON-NLS-1$
-
- String sql = "SELECT itemNum, itemName, itemQuantity FROM xmltest.rs"; //$NON-NLS-1$
- QueryCommand command = (QueryCommand) helpGetCommand(sql, metadata);
-
- Criteria crit = helpGetCriteria("xmltest.rs.itemName = 'Screwdriver'", metadata); //$NON-NLS-1$
- FakeXMLProcessorEnvironment env = new FakeXMLProcessorEnvironment();
- Program program = exampleProgram2(crit, metadata, env);
-
- 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);
- env.addData(resultSetName, command.getProjectedSymbols(), new List[] {
- Arrays.asList( new Object[] { "001", "Lamp", new Integer(5) } ), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100) } ), //$NON-NLS-1$ //$NON-NLS-2$
- Arrays.asList( new Object[] { "003", "Goat", new Integer(4) } ) //$NON-NLS-1$ //$NON-NLS-2$
- } );
-
- helpProcessInstructions(program, env,
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$
- "<Catalogs>\n" + //$NON-NLS-1$
- " <Catalog>\n" + //$NON-NLS-1$
- " <Items>\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\n" + //$NON-NLS-1$
- " <Name>Screwdriver</Name>\n" + //$NON-NLS-1$
- " <Quantity>100</Quantity>\n" + //$NON-NLS-1$
- " </Item>\n" + //$NON-NLS-1$
- " </Items>\n" + //$NON-NLS-1$
- " </Catalog>\n" + //$NON-NLS-1$
- "</Catalogs>"); //$NON-NLS-1$
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestInstructions.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/xml/TestInstructions.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestInstructions.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestInstructions.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,363 @@
+/*
+ * 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.ArrayList;
+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;
+import org.teiid.common.buffer.BufferManagerFactory;
+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.resolver.QueryResolver;
+import org.teiid.query.resolver.util.ResolverVisitor;
+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.QueryCommand;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+
+/**
+ */
+ at SuppressWarnings("nls")
+public class TestInstructions extends TestCase {
+
+ public TestInstructions(String name) {
+ super(name);
+ }
+
+ /**
+ * Construct some fake metadata. Basic conceptual tree is:
+ *
+ * stock (physical model)
+ * items (physical group)
+ * itemNum (string)
+ * itemName (string)
+ * itemQuantity (integer)
+ * xmltest (virtual model)
+ * rs (virtual group / result set definition)
+ * itemNum (string)
+ * itemName (string)
+ * itemQuantity (integer)
+ */
+ public QueryMetadataInterface exampleMetadata() {
+ MetadataStore metadataStore = new MetadataStore();
+ // Create models
+ Schema stock = RealMetadataFactory.createPhysicalModel("stock", metadataStore); //$NON-NLS-1$
+ Schema xmltest = RealMetadataFactory.createVirtualModel("xmltest", metadataStore); //$NON-NLS-1$
+
+ // Create physical groups
+ Table items = RealMetadataFactory.createPhysicalGroup("items", stock); //$NON-NLS-1$
+
+ // Create physical elements
+ 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$
+ Table rs = RealMetadataFactory.createVirtualGroup("rs", xmltest, rsQuery); //$NON-NLS-1$
+
+ // Create virtual elements
+ 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 });
+
+ // Create the facade from the store
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "example");
+ }
+
+ private Command helpGetCommand(String sql, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException {
+ // parse
+ QueryParser parser = new QueryParser();
+ Command command = parser.parseCommand(sql);
+
+ QueryResolver.resolveCommand(command, metadata);
+ command = QueryRewriter.rewrite(command, metadata, null);
+
+ return command;
+ }
+
+ private Criteria helpGetCriteria(String sql, QueryMetadataInterface metadata) throws QueryParserException, QueryResolverException, TeiidComponentException {
+ QueryParser parser = new QueryParser();
+ Criteria crit = parser.parseCriteria(sql);
+
+ ResolverVisitor.resolveLanguageObject(crit, null, metadata);
+
+ return crit;
+ }
+
+ public void helpProcessInstructions(Program prog, XMLProcessorEnvironment env, String expected) throws Exception {
+ env.pushProgram(prog);
+ XMLPlan plan = new XMLPlan(env);
+ TestProcessor.doProcess(plan, new FakeDataManager(), new List[] {Arrays.asList(expected)}, new CommandContext());
+ }
+
+ 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$
+ ProcessorInstruction i1 = new AddNodeInstruction(descriptor);
+ ProcessorInstruction i2 = new MoveDocInstruction(MoveDocInstruction.DOWN);
+ descriptor = NodeDescriptor.createNodeDescriptor("Catalog", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
+ ProcessorInstruction i3 = new AddNodeInstruction(descriptor);
+ ProcessorInstruction i4 = new MoveDocInstruction(MoveDocInstruction.DOWN);
+ descriptor = NodeDescriptor.createNodeDescriptor("Items", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
+ ProcessorInstruction i5 = new AddNodeInstruction(descriptor);
+ ProcessorInstruction i6 = new MoveDocInstruction(MoveDocInstruction.DOWN);
+
+ ResultSetInfo info = new ResultSetInfo("xmltest.rs"); //$NON-NLS-1$
+ ProcessorInstruction i7 = new ExecSqlInstruction("xmltest.rs", info); //$NON-NLS-1$
+ ProcessorInstruction i8 = new MoveCursorInstruction("xmltest.rs"); //$NON-NLS-1$
+
+ WhileInstruction i9 = new WhileInstruction("xmltest.rs"); //$NON-NLS-1$
+ descriptor = NodeDescriptor.createNodeDescriptor("Item", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
+ ProcessorInstruction i10 = new AddNodeInstruction(descriptor);
+ ProcessorInstruction i11 = new MoveDocInstruction(MoveDocInstruction.DOWN);
+ descriptor = NodeDescriptor.createNodeDescriptor("ItemID", null, AddNodeInstruction.ATTRIBUTE, null, null, null, false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
+ ProcessorInstruction i12 = new AddNodeInstruction(descriptor, new ElementSymbol("xmltest.rs.itemNum")); //$NON-NLS-1$
+ descriptor = NodeDescriptor.createNodeDescriptor("Name", null, AddNodeInstruction.ELEMENT, null, null, null, false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
+ ProcessorInstruction i13 = new AddNodeInstruction(descriptor, new ElementSymbol("xmltest.rs.itemName"));//$NON-NLS-1$
+ descriptor = NodeDescriptor.createNodeDescriptor("Quantity", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
+ ProcessorInstruction i14 = new AddNodeInstruction(descriptor, new ElementSymbol("xmltest.rs.itemQuantity"));//$NON-NLS-1$
+ ProcessorInstruction i15 = new MoveDocInstruction(MoveDocInstruction.UP);
+ ProcessorInstruction i16 = new MoveCursorInstruction("xmltest.rs"); //$NON-NLS-1$
+
+ ProcessorInstruction i17 = new MoveDocInstruction(MoveDocInstruction.UP);
+ ProcessorInstruction i18 = new MoveDocInstruction(MoveDocInstruction.UP);
+ ProcessorInstruction i19 = new MoveDocInstruction(MoveDocInstruction.UP);
+
+ ProcessorInstruction i20 = new EndDocumentInstruction();
+
+ // Stitch them together
+
+ Program program = new Program();
+ program.addInstruction(i0);
+ program.addInstruction(i1);
+ program.addInstruction(i2);
+ program.addInstruction(i3);
+ program.addInstruction(i4);
+ program.addInstruction(i5);
+ program.addInstruction(i6);
+ program.addInstruction(i7);
+ program.addInstruction(i8);
+ program.addInstruction(i9);
+
+ Program subProgram = new Program();
+ i9.setBlockProgram(subProgram);
+ subProgram.addInstruction(i10);
+ subProgram.addInstruction(i11);
+ subProgram.addInstruction(i12);
+ subProgram.addInstruction(i13);
+ subProgram.addInstruction(i14);
+ subProgram.addInstruction(i15);
+ subProgram.addInstruction(i16);
+
+ program.addInstruction(i17);
+ program.addInstruction(i18);
+ program.addInstruction(i19);
+ program.addInstruction(i20);
+
+ //ProgramUtil.printProgram(program);
+ return program;
+ }
+
+ 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);
+ ProcessorInstruction i2 = new MoveDocInstruction(MoveDocInstruction.DOWN);
+ descriptor = NodeDescriptor.createNodeDescriptor("Catalog", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
+ ProcessorInstruction i3 = new AddNodeInstruction(descriptor);
+ ProcessorInstruction i4 = new MoveDocInstruction(MoveDocInstruction.DOWN);
+ descriptor = NodeDescriptor.createNodeDescriptor("Items", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
+ ProcessorInstruction i5 = new AddNodeInstruction(descriptor);
+ ProcessorInstruction i6 = new MoveDocInstruction(MoveDocInstruction.DOWN);
+
+ ResultSetInfo info = new ResultSetInfo("xmltest.rs"); //$NON-NLS-1$
+ ProcessorInstruction i7 = new ExecSqlInstruction("xmltest.rs", info); //$NON-NLS-1$
+ ProcessorInstruction i8 = new MoveCursorInstruction("xmltest.rs"); //$NON-NLS-1$
+
+ WhileInstruction i9 = new WhileInstruction("xmltest.rs"); //$NON-NLS-1$
+
+ //need to move this up here so it can be referenced by "If" instruction
+ ProcessorInstruction i17 = new MoveCursorInstruction("xmltest.rs"); //$NON-NLS-1$
+
+ IfInstruction i10 = new IfInstruction( );
+ descriptor = NodeDescriptor.createNodeDescriptor("Item", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
+ ProcessorInstruction i11 = new AddNodeInstruction(descriptor);
+ ProcessorInstruction i12 = new MoveDocInstruction(MoveDocInstruction.DOWN);
+ descriptor = NodeDescriptor.createNodeDescriptor("ItemID", null, AddNodeInstruction.ATTRIBUTE, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
+ ProcessorInstruction i13 = new AddNodeInstruction(descriptor, new ElementSymbol("xmltest.rs.itemNum"));//$NON-NLS-1$
+ descriptor = NodeDescriptor.createNodeDescriptor("Name", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
+ ProcessorInstruction i14 = new AddNodeInstruction(descriptor, new ElementSymbol("xmltest.rs.itemName"));//$NON-NLS-1$
+ descriptor = NodeDescriptor.createNodeDescriptor("Quantity", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
+ ProcessorInstruction i15 = new AddNodeInstruction(descriptor, new ElementSymbol("xmltest.rs.itemQuantity")); //$NON-NLS-1$
+ ProcessorInstruction i16 = new MoveDocInstruction(MoveDocInstruction.UP);
+
+ ProcessorInstruction i18 = new MoveDocInstruction(MoveDocInstruction.UP);
+ ProcessorInstruction i19 = new MoveDocInstruction(MoveDocInstruction.UP);
+ ProcessorInstruction i20 = new MoveDocInstruction(MoveDocInstruction.UP);
+ ProcessorInstruction i21 = new EndDocumentInstruction();
+
+
+ // Stitch them together
+
+ Program program = new Program();
+ program.addInstruction(i0);
+ program.addInstruction(i1);
+ program.addInstruction(i2);
+ program.addInstruction(i3);
+ program.addInstruction(i4);
+ program.addInstruction(i5);
+ program.addInstruction(i6);
+ program.addInstruction(i7);
+ program.addInstruction(i8);
+ program.addInstruction(i9);
+
+ Program whileProgram = new Program();
+ i9.setBlockProgram(whileProgram);
+ whileProgram.addInstruction(i10);
+
+ Program thenProgram = new Program();
+ Condition cond = new CriteriaCondition(crit, thenProgram);
+ i10.addCondition(cond);
+
+ thenProgram.addInstruction(i11);
+ thenProgram.addInstruction(i12);
+ thenProgram.addInstruction(i13);
+ thenProgram.addInstruction(i14);
+ thenProgram.addInstruction(i15);
+ thenProgram.addInstruction(i16);
+
+ whileProgram.addInstruction(i17);
+
+ program.addInstruction(i18);
+ program.addInstruction(i19);
+ program.addInstruction(i20);
+ program.addInstruction(i21);
+
+ //ProgramUtil.printProgram(program);
+ return program;
+ }
+
+
+ public void testProcess1() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata();
+ String resultSetName = "xmltest.rs"; //$NON-NLS-1$
+
+ FakeXMLProcessorEnvironment env = new FakeXMLProcessorEnvironment();
+ 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<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$
+
+ env.addData(resultSetName, schema, new List[] {
+ Arrays.asList( new Object[] { "001", "Lamp", new Integer(5) } ), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100) } ), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList( new Object[] { "003", "Goat", new Integer(4) } ) //$NON-NLS-1$ //$NON-NLS-2$
+ } );
+ helpProcessInstructions(program, env,
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$
+ "<Catalogs>\n" + //$NON-NLS-1$
+ " <Catalog>\n" + //$NON-NLS-1$
+ " <Items>\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\n" + //$NON-NLS-1$
+ " <Name>Lamp</Name>\n" + //$NON-NLS-1$
+ " <Quantity>5</Quantity>\n" + //$NON-NLS-1$
+ " </Item>\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\n" + //$NON-NLS-1$
+ " <Name>Screwdriver</Name>\n" + //$NON-NLS-1$
+ " <Quantity>100</Quantity>\n" + //$NON-NLS-1$
+ " </Item>\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\n" + //$NON-NLS-1$
+ " <Name>Goat</Name>\n" + //$NON-NLS-1$
+ " <Quantity>4</Quantity>\n" + //$NON-NLS-1$
+ " </Item>\n" + //$NON-NLS-1$
+ " </Items>\n" + //$NON-NLS-1$
+ " </Catalog>\n" + //$NON-NLS-1$
+ "</Catalogs>"); //$NON-NLS-1$
+ }
+
+ public void testProcess2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata();
+
+ String resultSetName = "xmltest.rs"; //$NON-NLS-1$
+
+ String sql = "SELECT itemNum, itemName, itemQuantity FROM xmltest.rs"; //$NON-NLS-1$
+ QueryCommand command = (QueryCommand) helpGetCommand(sql, metadata);
+
+ Criteria crit = helpGetCriteria("xmltest.rs.itemName = 'Screwdriver'", metadata); //$NON-NLS-1$
+ FakeXMLProcessorEnvironment env = new FakeXMLProcessorEnvironment();
+ Program program = exampleProgram2(crit);
+
+ 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);
+ env.addData(resultSetName, command.getProjectedSymbols(), new List[] {
+ Arrays.asList( new Object[] { "001", "Lamp", new Integer(5) } ), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100) } ), //$NON-NLS-1$ //$NON-NLS-2$
+ Arrays.asList( new Object[] { "003", "Goat", new Integer(4) } ) //$NON-NLS-1$ //$NON-NLS-2$
+ } );
+
+ helpProcessInstructions(program, env,
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$
+ "<Catalogs>\n" + //$NON-NLS-1$
+ " <Catalog>\n" + //$NON-NLS-1$
+ " <Items>\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\n" + //$NON-NLS-1$
+ " <Name>Screwdriver</Name>\n" + //$NON-NLS-1$
+ " <Quantity>100</Quantity>\n" + //$NON-NLS-1$
+ " </Item>\n" + //$NON-NLS-1$
+ " </Items>\n" + //$NON-NLS-1$
+ " </Catalog>\n" + //$NON-NLS-1$
+ "</Catalogs>"); //$NON-NLS-1$
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestSourceNodeGenaratorVisitor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/xml/TestSourceNodeGenaratorVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestSourceNodeGenaratorVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,279 +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.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.List;
-
-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.MappingException;
-import org.teiid.query.mapping.xml.MappingLoader;
-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.optimizer.xml.SourceNodeGenaratorVisitor;
-
-import junit.framework.TestCase;
-
-
-
-/**
- *
- */
-public class TestSourceNodeGenaratorVisitor extends TestCase {
-
- private MappingDocument loadMappingDocument(String xml) throws MappingException {
- MappingLoader reader = new MappingLoader();
-
- byte[] bytes = xml.getBytes();
-
- InputStream istream = new ByteArrayInputStream (bytes);
-
- return reader.loadDocument(istream);
- }
-
- public void testSourceAtRootXML50() throws Exception{
- String xml =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<xmlMapping>\r\n" + //$NON-NLS-1$
- " <mappingNode>\r\n" + //$NON-NLS-1$
- " <name>license</name>\r\n" + //$NON-NLS-1$
- " <source>licenseSource</source>\r\n" + //$NON-NLS-1$
- " <minOccurs>0</minOccurs>\r\n" + //$NON-NLS-1$
- " <maxOccurs>unbounded</maxOccurs>\r\n" + //$NON-NLS-1$
- " <tempGroup>testTempGroup1</tempGroup>\r\n" + //$NON-NLS-1$
- " <tempGroup>testTempGroup2</tempGroup>\r\n" + //$NON-NLS-1$
- " </mappingNode>\r\n" + //$NON-NLS-1$
- "</xmlMapping>\r\n\r\n"; //$NON-NLS-1$
-
- // load the original
- MappingDocument doc = loadMappingDocument(xml);
-
- // now extract the source nodes
- doc = SourceNodeGenaratorVisitor.extractSourceNodes(doc);
-
- // check the staging tables
- MappingBaseNode root = doc.getRootNode();
- assertTrue(root instanceof MappingSourceNode);
- MappingSourceNode source = (MappingSourceNode)root;
- assertEquals("licenseSource", source.getResultName()); //$NON-NLS-1$
-
- List list = source.getStagingTables();
- assertEquals(2, list.size());
-
- assertEquals("testTempGroup1", list.get(0)); //$NON-NLS-1$
- assertEquals("testTempGroup2", list.get(1)); //$NON-NLS-1$
-
-
- MappingBaseNode node = (MappingBaseNode)source.getNodeChildren().get(0);
- assertTrue(node instanceof MappingElement);
- MappingElement element = (MappingElement)node;
-
- // make sure name matches and caridinality of root is reset; as there can be only one root
- assertEquals("license", element.getName()); //$NON-NLS-1$
- assertEquals(1, element.getMinOccurence());
- assertEquals(1, element.getMaxOccurence());
- assertNull(element.getSource());
- }
-
- public void testSourceBelowRootXML50() throws Exception{
- String xml =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<xmlMapping>\r\n" + //$NON-NLS-1$
- " <mappingNode>\r\n" + //$NON-NLS-1$
- " <name>parentNode</name>\r\n" + //$NON-NLS-1$
- " <minOccurs>0</minOccurs>\r\n" + //$NON-NLS-1$
- " <maxOccurs>unbounded</maxOccurs>\r\n" + //$NON-NLS-1$
- " <tempGroup>testTempGroup1</tempGroup>\r\n" + //$NON-NLS-1$
- " <mappingNode>\r\n" + //$NON-NLS-1$
- " <name>childNode</name>\r\n" + //$NON-NLS-1$
- " <source>childNodeSource</source>\r\n" + //$NON-NLS-1$
- " <tempGroup>testTempGroup2</tempGroup>\r\n" + //$NON-NLS-1$
- " </mappingNode>\r\n" + //$NON-NLS-1$
- " </mappingNode>\r\n" + //$NON-NLS-1$
- "</xmlMapping>\r\n\r\n"; //$NON-NLS-1$
-
- // load the original
- MappingDocument doc = loadMappingDocument(xml);
-
- // now extract the source nodes
- doc = SourceNodeGenaratorVisitor.extractSourceNodes(doc);
-
- // check source node
- MappingBaseNode node = doc.getRootNode();
- assertTrue(node instanceof MappingElement);
- MappingElement element = (MappingElement)node;
-
- List list = element.getStagingTables();
- assertEquals(1, list.size());
- assertEquals("testTempGroup1", list.get(0)); //$NON-NLS-1$
-
- // make sure name matches and caridinality of root is reset; as there can be only one root
- assertEquals("parentNode", element.getName()); //$NON-NLS-1$
- assertEquals(1, element.getMinOccurence());
- assertEquals(1, element.getMaxOccurence());
-
- MappingNode node1 = (MappingNode)element.getNodeChildren().get(0);
- assertTrue(node1 instanceof MappingSourceNode);
-
- MappingSourceNode source = (MappingSourceNode)node1;
- assertEquals("childNodeSource", source.getResultName()); //$NON-NLS-1$
-
- list = source.getStagingTables();
- assertEquals(1, list.size());
- assertEquals("testTempGroup2", list.get(0)); //$NON-NLS-1$
-
- // make sure source's child is mapping element and mapping element's source
- // is above source
- node1 = (MappingNode)source.getNodeChildren().get(0);
- assertTrue(node instanceof MappingElement);
- element = (MappingElement)node1;
- assertEquals("childNode", element.getName()); //$NON-NLS-1$
- assertNull(element.getSource());
- }
-
-
- public void testRecursiveNodeXML50() throws Exception{
- String xml =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<xmlMapping>\r\n" + //$NON-NLS-1$
- " <mappingNode>\r\n" + //$NON-NLS-1$
- " <name>parentNode</name>\r\n" + //$NON-NLS-1$
- " <source>parentNodeSource</source>\r\n" + //$NON-NLS-1$
- " <mappingNode>\r\n" + //$NON-NLS-1$
- " <name>childNode</name>\r\n" + //$NON-NLS-1$
- " <mappingNode>\r\n" + //$NON-NLS-1$
- " <nodeType>attribute</nodeType>\r\n" + //$NON-NLS-1$
- " <name>attributename</name>\r\n" + //$NON-NLS-1$
- " <default>ddd</default>\r\n" + //$NON-NLS-1$
- " <fixed>fff</fixed>\r\n" + //$NON-NLS-1$
- " </mappingNode>\r\n" + //$NON-NLS-1$
- " <mappingNode>\r\n" + //$NON-NLS-1$
- " <name>recursivenodename</name>\r\n" + //$NON-NLS-1$
- " <isRecursive>TRUE</isRecursive>\r\n" + //$NON-NLS-1$
- " <recursionLimit>8</recursionLimit>\r\n" + //$NON-NLS-1$
- " <recursionCriteria>rrr</recursionCriteria>\r\n" + //$NON-NLS-1$
- " <recursionRootMappingClass>parentNodeSource</recursionRootMappingClass>\r\n" + //$NON-NLS-1$
- " </mappingNode>\r\n" + //$NON-NLS-1$
- " </mappingNode>\r\n" + //$NON-NLS-1$
- " </mappingNode>\r\n" + //$NON-NLS-1$
- "</xmlMapping>\r\n\r\n"; //$NON-NLS-1$
-
- // load the original
- MappingDocument doc = loadMappingDocument(xml);
-
- // now extract the source nodes
- doc = SourceNodeGenaratorVisitor.extractSourceNodes(doc);
-
- MappingNode node = doc.getRootNode();
- assertTrue(node instanceof MappingSourceNode);
- MappingSourceNode source = (MappingSourceNode)node;
- assertEquals("parentNodeSource", source.getSource()); //$NON-NLS-1$
-
- node = (MappingNode)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);
- assertTrue(node instanceof MappingElement);
- element = (MappingElement)node;
- assertEquals("childNode", element.getName()); //$NON-NLS-1$
-
- List attrs = element.getAttributes();
- assertEquals(1, attrs.size());
- MappingAttribute attribute = (MappingAttribute)attrs.get(0);
- assertEquals("attributename", attribute.getName()); //$NON-NLS-1$
- assertEquals("ddd", attribute.getDefaultValue()); //$NON-NLS-1$
- assertEquals("fff", attribute.getValue()); //$NON-NLS-1$
-
- node = (MappingNode)element.getNodeChildren().get(0);
- assertTrue(node instanceof MappingRecursiveElement);
- MappingRecursiveElement recursive = (MappingRecursiveElement)node;
- assertEquals("recursivenodename", recursive.getName()); //$NON-NLS-1$
- assertEquals(8, recursive.getRecursionLimit());
- assertFalse(recursive.isRootRecursiveNode());
- assertTrue(recursive.isRecursive());
- }
-
- public void testRecursiveElementXML50() throws Exception{
- String xml =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<xmlMapping>\r\n" + //$NON-NLS-1$
- " <mappingNode>\r\n" + //$NON-NLS-1$
- " <name>parentNode</name>\r\n" + //$NON-NLS-1$
- " <source>parentSource</source>\r\n" + //$NON-NLS-1$
- " <mappingNode>"+ //$NON-NLS-1$
- " <name>childNode</name>\r\n" + //$NON-NLS-1$
- " <source>childSource</source>\r\n" + //$NON-NLS-1$
- " <recursionRootMappingClass>parentSource</recursionRootMappingClass>" + //$NON-NLS-1$
- " <isRecursive>true</isRecursive>"+ //$NON-NLS-1$
- " <recursionLimit>6</recursionLimit>" + //$NON-NLS-1$
- " <recursionCriteria>foo</recursionCriteria>" + //$NON-NLS-1$
- " </mappingNode>"+ //$NON-NLS-1$
- " </mappingNode>\r\n" + //$NON-NLS-1$
- "</xmlMapping>\r\n\r\n"; //$NON-NLS-1$
-
- // load the original
- MappingDocument doc = loadMappingDocument(xml);
-
- // now extract the source nodes
- doc = SourceNodeGenaratorVisitor.extractSourceNodes(doc);
-
- MappingNode node = doc.getRootNode();
- assertTrue(node instanceof MappingSourceNode);
-
- // ist source
- MappingSourceNode source = (MappingSourceNode)node;
- assertEquals("parentSource", source.getSource()); //$NON-NLS-1$
-
- // parent element
- node = (MappingNode)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());
-
- // recursive source
- node = (MappingNode)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);
- assertTrue(node instanceof MappingRecursiveElement);
- MappingRecursiveElement relement = (MappingRecursiveElement)node;
-
- assertTrue(relement.isRecursive());
- assertEquals("childNode", relement.getName()); //$NON-NLS-1$
- assertEquals("foo", relement.getCriteria()); //$NON-NLS-1$
- assertEquals(6, relement.getRecursionLimit());
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestSourceNodeGenaratorVisitor.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/xml/TestSourceNodeGenaratorVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestSourceNodeGenaratorVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestSourceNodeGenaratorVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,279 @@
+/*
+ * 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.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.util.List;
+
+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.MappingException;
+import org.teiid.query.mapping.xml.MappingLoader;
+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.optimizer.xml.SourceNodeGenaratorVisitor;
+
+import junit.framework.TestCase;
+
+
+
+/**
+ *
+ */
+public class TestSourceNodeGenaratorVisitor extends TestCase {
+
+ private MappingDocument loadMappingDocument(String xml) throws MappingException {
+ MappingLoader reader = new MappingLoader();
+
+ byte[] bytes = xml.getBytes();
+
+ InputStream istream = new ByteArrayInputStream (bytes);
+
+ return reader.loadDocument(istream);
+ }
+
+ public void testSourceAtRootXML50() throws Exception{
+ String xml =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<xmlMapping>\r\n" + //$NON-NLS-1$
+ " <mappingNode>\r\n" + //$NON-NLS-1$
+ " <name>license</name>\r\n" + //$NON-NLS-1$
+ " <source>licenseSource</source>\r\n" + //$NON-NLS-1$
+ " <minOccurs>0</minOccurs>\r\n" + //$NON-NLS-1$
+ " <maxOccurs>unbounded</maxOccurs>\r\n" + //$NON-NLS-1$
+ " <tempGroup>testTempGroup1</tempGroup>\r\n" + //$NON-NLS-1$
+ " <tempGroup>testTempGroup2</tempGroup>\r\n" + //$NON-NLS-1$
+ " </mappingNode>\r\n" + //$NON-NLS-1$
+ "</xmlMapping>\r\n\r\n"; //$NON-NLS-1$
+
+ // load the original
+ MappingDocument doc = loadMappingDocument(xml);
+
+ // now extract the source nodes
+ doc = SourceNodeGenaratorVisitor.extractSourceNodes(doc);
+
+ // check the staging tables
+ MappingBaseNode root = doc.getRootNode();
+ assertTrue(root instanceof MappingSourceNode);
+ MappingSourceNode source = (MappingSourceNode)root;
+ assertEquals("licenseSource", source.getResultName()); //$NON-NLS-1$
+
+ List<String> list = source.getStagingTables();
+ assertEquals(2, list.size());
+
+ assertEquals("testTempGroup1", list.get(0)); //$NON-NLS-1$
+ assertEquals("testTempGroup2", list.get(1)); //$NON-NLS-1$
+
+
+ MappingBaseNode node = (MappingBaseNode)source.getNodeChildren().get(0);
+ assertTrue(node instanceof MappingElement);
+ MappingElement element = (MappingElement)node;
+
+ // make sure name matches and caridinality of root is reset; as there can be only one root
+ assertEquals("license", element.getName()); //$NON-NLS-1$
+ assertEquals(1, element.getMinOccurence());
+ assertEquals(1, element.getMaxOccurence());
+ assertNull(element.getSource());
+ }
+
+ public void testSourceBelowRootXML50() throws Exception{
+ String xml =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<xmlMapping>\r\n" + //$NON-NLS-1$
+ " <mappingNode>\r\n" + //$NON-NLS-1$
+ " <name>parentNode</name>\r\n" + //$NON-NLS-1$
+ " <minOccurs>0</minOccurs>\r\n" + //$NON-NLS-1$
+ " <maxOccurs>unbounded</maxOccurs>\r\n" + //$NON-NLS-1$
+ " <tempGroup>testTempGroup1</tempGroup>\r\n" + //$NON-NLS-1$
+ " <mappingNode>\r\n" + //$NON-NLS-1$
+ " <name>childNode</name>\r\n" + //$NON-NLS-1$
+ " <source>childNodeSource</source>\r\n" + //$NON-NLS-1$
+ " <tempGroup>testTempGroup2</tempGroup>\r\n" + //$NON-NLS-1$
+ " </mappingNode>\r\n" + //$NON-NLS-1$
+ " </mappingNode>\r\n" + //$NON-NLS-1$
+ "</xmlMapping>\r\n\r\n"; //$NON-NLS-1$
+
+ // load the original
+ MappingDocument doc = loadMappingDocument(xml);
+
+ // now extract the source nodes
+ doc = SourceNodeGenaratorVisitor.extractSourceNodes(doc);
+
+ // check source node
+ MappingBaseNode node = doc.getRootNode();
+ assertTrue(node instanceof MappingElement);
+ MappingElement element = (MappingElement)node;
+
+ List<String> list = element.getStagingTables();
+ assertEquals(1, list.size());
+ assertEquals("testTempGroup1", list.get(0)); //$NON-NLS-1$
+
+ // make sure name matches and caridinality of root is reset; as there can be only one root
+ assertEquals("parentNode", element.getName()); //$NON-NLS-1$
+ assertEquals(1, element.getMinOccurence());
+ assertEquals(1, element.getMaxOccurence());
+
+ MappingNode node1 = element.getNodeChildren().get(0);
+ assertTrue(node1 instanceof MappingSourceNode);
+
+ MappingSourceNode source = (MappingSourceNode)node1;
+ assertEquals("childNodeSource", source.getResultName()); //$NON-NLS-1$
+
+ list = source.getStagingTables();
+ assertEquals(1, list.size());
+ assertEquals("testTempGroup2", list.get(0)); //$NON-NLS-1$
+
+ // make sure source's child is mapping element and mapping element's source
+ // is above source
+ node1 = source.getNodeChildren().get(0);
+ assertTrue(node instanceof MappingElement);
+ element = (MappingElement)node1;
+ assertEquals("childNode", element.getName()); //$NON-NLS-1$
+ assertNull(element.getSource());
+ }
+
+
+ public void testRecursiveNodeXML50() throws Exception{
+ String xml =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<xmlMapping>\r\n" + //$NON-NLS-1$
+ " <mappingNode>\r\n" + //$NON-NLS-1$
+ " <name>parentNode</name>\r\n" + //$NON-NLS-1$
+ " <source>parentNodeSource</source>\r\n" + //$NON-NLS-1$
+ " <mappingNode>\r\n" + //$NON-NLS-1$
+ " <name>childNode</name>\r\n" + //$NON-NLS-1$
+ " <mappingNode>\r\n" + //$NON-NLS-1$
+ " <nodeType>attribute</nodeType>\r\n" + //$NON-NLS-1$
+ " <name>attributename</name>\r\n" + //$NON-NLS-1$
+ " <default>ddd</default>\r\n" + //$NON-NLS-1$
+ " <fixed>fff</fixed>\r\n" + //$NON-NLS-1$
+ " </mappingNode>\r\n" + //$NON-NLS-1$
+ " <mappingNode>\r\n" + //$NON-NLS-1$
+ " <name>recursivenodename</name>\r\n" + //$NON-NLS-1$
+ " <isRecursive>TRUE</isRecursive>\r\n" + //$NON-NLS-1$
+ " <recursionLimit>8</recursionLimit>\r\n" + //$NON-NLS-1$
+ " <recursionCriteria>rrr</recursionCriteria>\r\n" + //$NON-NLS-1$
+ " <recursionRootMappingClass>parentNodeSource</recursionRootMappingClass>\r\n" + //$NON-NLS-1$
+ " </mappingNode>\r\n" + //$NON-NLS-1$
+ " </mappingNode>\r\n" + //$NON-NLS-1$
+ " </mappingNode>\r\n" + //$NON-NLS-1$
+ "</xmlMapping>\r\n\r\n"; //$NON-NLS-1$
+
+ // load the original
+ MappingDocument doc = loadMappingDocument(xml);
+
+ // now extract the source nodes
+ doc = SourceNodeGenaratorVisitor.extractSourceNodes(doc);
+
+ MappingNode node = doc.getRootNode();
+ assertTrue(node instanceof MappingSourceNode);
+ MappingSourceNode source = (MappingSourceNode)node;
+ assertEquals("parentNodeSource", source.getSource()); //$NON-NLS-1$
+
+ 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 = element.getNodeChildren().get(0);
+ assertTrue(node instanceof MappingElement);
+ element = (MappingElement)node;
+ assertEquals("childNode", element.getName()); //$NON-NLS-1$
+
+ List attrs = element.getAttributes();
+ assertEquals(1, attrs.size());
+ MappingAttribute attribute = (MappingAttribute)attrs.get(0);
+ assertEquals("attributename", attribute.getName()); //$NON-NLS-1$
+ assertEquals("ddd", attribute.getDefaultValue()); //$NON-NLS-1$
+ assertEquals("fff", attribute.getValue()); //$NON-NLS-1$
+
+ node = element.getNodeChildren().get(0);
+ assertTrue(node instanceof MappingRecursiveElement);
+ MappingRecursiveElement recursive = (MappingRecursiveElement)node;
+ assertEquals("recursivenodename", recursive.getName()); //$NON-NLS-1$
+ assertEquals(8, recursive.getRecursionLimit());
+ assertFalse(recursive.isRootRecursiveNode());
+ assertTrue(recursive.isRecursive());
+ }
+
+ public void testRecursiveElementXML50() throws Exception{
+ String xml =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<xmlMapping>\r\n" + //$NON-NLS-1$
+ " <mappingNode>\r\n" + //$NON-NLS-1$
+ " <name>parentNode</name>\r\n" + //$NON-NLS-1$
+ " <source>parentSource</source>\r\n" + //$NON-NLS-1$
+ " <mappingNode>"+ //$NON-NLS-1$
+ " <name>childNode</name>\r\n" + //$NON-NLS-1$
+ " <source>childSource</source>\r\n" + //$NON-NLS-1$
+ " <recursionRootMappingClass>parentSource</recursionRootMappingClass>" + //$NON-NLS-1$
+ " <isRecursive>true</isRecursive>"+ //$NON-NLS-1$
+ " <recursionLimit>6</recursionLimit>" + //$NON-NLS-1$
+ " <recursionCriteria>foo</recursionCriteria>" + //$NON-NLS-1$
+ " </mappingNode>"+ //$NON-NLS-1$
+ " </mappingNode>\r\n" + //$NON-NLS-1$
+ "</xmlMapping>\r\n\r\n"; //$NON-NLS-1$
+
+ // load the original
+ MappingDocument doc = loadMappingDocument(xml);
+
+ // now extract the source nodes
+ doc = SourceNodeGenaratorVisitor.extractSourceNodes(doc);
+
+ MappingNode node = doc.getRootNode();
+ assertTrue(node instanceof MappingSourceNode);
+
+ // ist source
+ MappingSourceNode source = (MappingSourceNode)node;
+ assertEquals("parentSource", source.getSource()); //$NON-NLS-1$
+
+ // parent element
+ 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());
+
+ // recursive source
+ node = element.getNodeChildren().get(0);
+ source = (MappingSourceNode)node;
+ assertEquals("childSource", source.getSource()); //$NON-NLS-1$
+ assertEquals("parentSource", source.getAliasResultName()); //$NON-NLS-1$
+
+ node = source.getNodeChildren().get(0);
+ assertTrue(node instanceof MappingRecursiveElement);
+ MappingRecursiveElement relement = (MappingRecursiveElement)node;
+
+ assertTrue(relement.isRecursive());
+ assertEquals("childNode", relement.getName()); //$NON-NLS-1$
+ assertEquals("foo", relement.getCriteria()); //$NON-NLS-1$
+ assertEquals(6, relement.getRecursionLimit());
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLPlanningEnhancements.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/xml/TestXMLPlanningEnhancements.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLPlanningEnhancements.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,551 +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 static org.junit.Assert.*;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-
-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.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.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;
-
-
-public class TestXMLPlanningEnhancements {
-
- private FakeMetadataFacade getMetadata(String query) {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata();
-
- FakeMetadataStore store = metadata.getStore();
-
- 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$
-
- List rsElementsY = FakeMetadataFactory.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$
- 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();
-
- FakeMetadataStore store = metadata.getStore();
-
- 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$
- 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;
- if (!simpleTempSelect) {
- tempQueryJoin = new QueryNode("SELECT stock.orders.* FROM stock.orders"); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- 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$
-
- // 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.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.addBinding("xmltest.suppliers.supplierName"); //$NON-NLS-1$
- }
- FakeMetadataObject rsJoin = FakeMetadataFactory.createVirtualGroup("xmltest.ordersC", xmltest, rsQueryJoin); //$NON-NLS-1$
-
- List tempJoinElements = FakeMetadataFactory.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,
- 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() {
-
- 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$
-
- MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
- MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.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.ordersC"); //$NON-NLS-1$
- order.setMaxOccurrs(-1);
- order.addAttribute(new MappingAttribute("OrderID", "xmltest.ordersC.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
- order.addChildElement(new MappingElement("OrderDate", "xmltest.ordersc.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
- order.addChildElement(new MappingElement("OrderQuantity", "xmltest.ordersC.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
- order.addChildElement(new MappingElement("OrderStatus", "xmltest.ordersC.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
- .setMinOccurrs(0);
- //NESTED STUFF======================================================================
- return doc;
- }
-
- @Test public void testBaseballPlayersDocDefect19541() throws Exception {
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
- FakeDataManager dataMgr = TestXMLProcessor.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$
- "</BaseballPlayers>\r\n\r\n"; //$NON-NLS-1$
-
- TestXMLProcessor.helpTestProcess("select * from xmltest.playersDoc where owner. at ownerid = '1009'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-
- }
-
- @Test public void testNested2WithContextCriteria5c() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
- String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5c.xml"; //$NON-NLS-1$
- String expectedDoc = TestXMLProcessor.readFile(resultFile);
-
- TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 WHERE NOT(SupplierID='52') AND (OrderID='5' OR OrderID='2')", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNested2WithContextCriteria5d() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
- String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5d.xml"; //$NON-NLS-1$
- String expectedDoc = TestXMLProcessor.readFile(resultFile);
-
- TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR context(SupplierID, OrderID)='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNested2WithContextCriteria5d1() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
- String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5d.xml"; //$NON-NLS-1$
- String expectedDoc = TestXMLProcessor.readFile(resultFile);
-
- TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(SupplierID, OrderID)='5' OR OrderID='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNested2WithContextCriteria5e() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
- String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5e.xml"; //$NON-NLS-1$
- String expectedDoc = TestXMLProcessor.readFile(resultFile);
-
- TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR SupplierID='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testXQTChoice_6796() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata2();
- FakeDataManager dataMgr = TestXMLProcessor.exampleXQTDataManager(metadata);
- String resultFile = "TestXMLProcessor-testXQTChoice_6796.xml"; //$NON-NLS-1$
- String expectedDoc = TestXMLProcessor.readFile(resultFile);
-
- TestXMLProcessor.helpTestProcess("SELECT * FROM xqttest.doc4 WHERE root.key.keys.nestedkey = 4", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderByWithChoiceCriteriaElement() throws Exception {
- FakeMetadataFacade 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$
-
- TestXMLProcessor.helpTestProcess("SELECT * FROM xqttest.doc5 order by root.wrapper.key", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testXQTChoice_withContextCriteria() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata2();
- FakeDataManager dataMgr = TestXMLProcessor.exampleXQTDataManager(metadata);
- String resultFile = "TestXMLProcessor-testXQTChoice_withContextCriteria.xml"; //$NON-NLS-1$
- String expectedDoc = TestXMLProcessor.readFile(resultFile);
-
- TestXMLProcessor.helpTestProcess("SELECT * FROM xqttest.doc4 WHERE context(root.key.keys.nestedkey, root.key.keys.nestedkey) = 4", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testXQTChoice_withContextCriteria1() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata2();
- FakeDataManager dataMgr = TestXMLProcessor.exampleXQTDataManager(metadata);
- String resultFile = "TestXMLProcessor-testXQTChoice_withContextCriteria1.xml"; //$NON-NLS-1$
- String expectedDoc = TestXMLProcessor.readFile(resultFile);
-
- TestXMLProcessor.helpTestProcess("SELECT * FROM xqttest.doc4 WHERE context(root.key.keys.nestedkey, root.key.keys.nestedkey) = 4 and context(root.wrapper.key.keys.nestedkey, root.wrapper.key.keys.nestedkey) = 3", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @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$
-
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
- String expectedDoc = TestXMLProcessor.readFile("TestXMLPlanningEnhancements-testMappingClassWithStoredProcedureAndCriteria.xml"); //$NON-NLS-1$
-
- TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc18a where supplierID<56", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @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$
-
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
- String expectedDoc = TestXMLProcessor.readFile("TestXMLPlanningEnhancements-testMappingClassWithStoredProcedureAndCriteria.xml"); //$NON-NLS-1$
-
- TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc18a where supplierID<56", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @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$
-
- 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$
- }
-
- @Test public void testAutoStagingFailsForMappingClassWithProcRelational() throws Exception {
- FakeMetadataFacade metadata = getMetadata("SELECT supplierNum, supplierName, supplierZipCode FROM v1.supplierProc where itemnum = ?"); //$NON-NLS-1$
-
- FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$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$
-
- 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$
- 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);
-
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
- String expectedDoc = TestXMLProcessor.readFile("TestXMLPlanningEnhancements-testMappingClassWithStoredProcedureAndCriteria.xml"); //$NON-NLS-1$
-
- XMLPlan plan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc18a where supplierID<56", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-
- Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
- assertNull(stats.get(ExecStagingTableInstruction.class));
- }
-
- @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$
-
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
-
- String expectedDoc = TestXMLProcessor.readFile("TestXMLPlanningEnhancements-testMappingClassWitSelectDistinctAndCriteria.xml"); //$NON-NLS-1$
-
- TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc18a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * based upon testNestedWithStoredQueryInMappingClass
- *
- * Ensures that correlated references to outer scoped groups can
- * be used as inputs
- */
- @Test public void testMappingClassWithStoredProcedureAndCriteria() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
- String expectedDoc = TestXMLProcessor.readFile("TestXMLPlanningEnhancements-testMappingClassWithStoredProcedureAndCriteria.xml"); //$NON-NLS-1$
-
- TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc18 where supplierID<56", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- public void defer_testXMLQueryWithFalseRootCriteria() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
- String expectedDoc = ""; //$NON-NLS-1$
-
- TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc18 where 1 = 0", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * @see #testNested2WithCriteria2
- */
- @Test public void testAutoStagingByCosting() throws Exception {
- FakeMetadataFacade 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$
-
- suppliers.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10));
- itemSuppliers.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10));
-
- String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
-
- XMLPlan plan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-
- //check for staging; one for staging and for unloading
- Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
- assertEquals(2, ((List)stats.get(ExecStagingTableInstruction.class)).size());
- }
-
- /**
- * @see #testNested2WithCriteria2
- */
- @Test public void testAutoStagingFailsByCosting() throws Exception {
- FakeMetadataFacade 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$
-
- suppliers.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10000));
- itemSuppliers.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10000));
-
- String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
-
- XMLPlan plan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-
- //check for no staging
- Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
- assertNull(stats.get(ExecStagingTableInstruction.class));
- }
-
- @Test public void testAutoStagingFailsByNoCache() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
-
- String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
-
- XMLPlan plan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 OPTION NOCACHE", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-
- //check for no staging
- Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
- assertNull(stats.get(ExecStagingTableInstruction.class));
- }
-
- @Test public void testAutoStagingFailsByNoCacheByGroup() throws Exception {
- FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
-
- String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
-
- XMLPlan plan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 OPTION NOCACHE XMLTEST.SUPPLIERS", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-
- //check for no staging by the mapping class name
- Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
- assertNull(stats.get(ExecStagingTableInstruction.class));
-
- plan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 OPTION NOCACHE XMLTEST.SUPPLIERS", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-
- //check for no staging by the alias mapping class name
- stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
- assertNull(stats.get(ExecStagingTableInstruction.class));
- }
-
- // see the next test with costing information too.
- @Test public void testUseOfStagingCardinalityOnDependentJoinsNoCost() throws Exception {
- FakeMetadataFacade metadata = getTempTableMetadata(false);
- FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
-
- String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
-
- XMLPlan xmlPlan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.docJoin", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- Map stats = XMLProgramUtil.getProgramStats(xmlPlan.getOriginalProgram());
- List list = (List)stats.get(ExecSqlInstruction.class);
-
- ExecSqlInstruction instr = (ExecSqlInstruction)list.get(2);
-
- ProcessorPlan plan = instr.info.getPlan();
-
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 2, // Access
- 0, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin (**We are merge join with out any costing info**)
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- TestOptimizer.checkDependentJoinCount(plan, 0);
- }
-
- @Test public void testUseOfStagingCardinalityOnDependentJoinsWithCost() throws Exception {
- FakeMetadataFacade 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);
-
- 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$
- Map stats = XMLProgramUtil.getProgramStats(xmlPlan.getOriginalProgram());
- List list = (List)stats.get(ExecSqlInstruction.class);
-
- ExecSqlInstruction instr = (ExecSqlInstruction)list.get(2);
-
- ProcessorPlan plan = instr.info.getPlan();
- TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
- 0, // DependentSelect
- 0, // DependentProject
- 0, // DupRemove
- 0, // Grouping
- 0, // Join
- 1, // MergeJoin (**We are merge join with out any costing info**)
- 0, // Null
- 0, // PlanExecution
- 1, // Project
- 0, // Select
- 0, // Sort
- 0 // UnionAll
- });
-
- TestOptimizer.checkDependentJoinCount(plan, 1);
- }
-
- @Test public void testNoRedundentStagingTables() throws Exception {
- FakeMetadataFacade 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$
-
- suppliers.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10));
- orders.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10));
-
- String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-OnlySupplier51.xml"); //$NON-NLS-1$
-
- XMLPlan xmlPlan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.docJoin where context(Supplier, SupplierID) = 51", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- //check for staging; one for staging and for unloading - only two pairs are expected
- Map stats = XMLProgramUtil.getProgramStats(xmlPlan.getOriginalProgram());
- 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$
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLPlanningEnhancements.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/xml/TestXMLPlanningEnhancements.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLPlanningEnhancements.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLPlanningEnhancements.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,522 @@
+/*
+ * 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 static org.junit.Assert.*;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+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.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.RealMetadataFactory;
+
+ at SuppressWarnings("nls")
+public class TestXMLPlanningEnhancements {
+
+ private TransformationMetadata getMetadata(String query) {
+ TransformationMetadata metadata = TestXMLProcessor.exampleMetadata();
+
+ Schema xmltest = metadata.getMetadataStore().getSchemas().get("XMLTEST");
+
+ 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$
+ Table rsQY = RealMetadataFactory.createVirtualGroup("suppliersY", xmltest, rsQueryY); //$NON-NLS-1$
+
+ 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 });
+
+ 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});
+ return metadata;
+ }
+
+ private TransformationMetadata getTempTableMetadata(boolean simpleTempSelect) {
+ TransformationMetadata metadata = TestXMLProcessor.exampleMetadata();
+
+ Schema xmltest = metadata.getMetadataStore().getSchemas().get("XMLTEST");
+
+ 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;
+ if (!simpleTempSelect) {
+ tempQueryJoin = new QueryNode("SELECT stock.orders.* FROM stock.orders"); //$NON-NLS-1$ //$NON-NLS-2$
+ } else {
+ 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$
+ }
+
+ 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 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 docJoin.orders WHERE supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+ rsQueryJoin.addBinding("xmltest.suppliers.supplierName"); //$NON-NLS-1$
+ }
+ Table rsJoin = RealMetadataFactory.createVirtualGroup("ordersC", xmltest, rsQueryJoin); //$NON-NLS-1$
+
+ 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});
+
+ 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});
+ return metadata;
+ }
+
+ private static MappingDocument createXMLPlanNestedJoin() {
+
+ MappingDocument doc = new MappingDocument(true);
+
+ MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$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$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.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.ordersC"); //$NON-NLS-1$
+ order.setMaxOccurrs(-1);
+ order.addAttribute(new MappingAttribute("OrderID", "xmltest.ordersC.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ order.addChildElement(new MappingElement("OrderDate", "xmltest.ordersc.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
+ order.addChildElement(new MappingElement("OrderQuantity", "xmltest.ordersC.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
+ order.addChildElement(new MappingElement("OrderStatus", "xmltest.ordersC.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setMinOccurrs(0);
+ //NESTED STUFF======================================================================
+ return doc;
+ }
+
+ @Test public void testBaseballPlayersDocDefect19541() throws Exception {
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleCase3225();
+ FakeDataManager dataMgr = TestXMLProcessor.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$
+ "</BaseballPlayers>\r\n\r\n"; //$NON-NLS-1$
+
+ TestXMLProcessor.helpTestProcess("select * from xmltest.playersDoc where owner. at ownerid = '1009'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+
+ }
+
+ @Test public void testNested2WithContextCriteria5c() throws Exception {
+ QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+ String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5c.xml"; //$NON-NLS-1$
+ String expectedDoc = TestXMLProcessor.readFile(resultFile);
+
+ TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 WHERE NOT(SupplierID='52') AND (OrderID='5' OR OrderID='2')", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNested2WithContextCriteria5d() throws Exception {
+ QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+ String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5d.xml"; //$NON-NLS-1$
+ String expectedDoc = TestXMLProcessor.readFile(resultFile);
+
+ TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR context(SupplierID, OrderID)='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNested2WithContextCriteria5d1() throws Exception {
+ QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+ String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5d.xml"; //$NON-NLS-1$
+ String expectedDoc = TestXMLProcessor.readFile(resultFile);
+
+ TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(SupplierID, OrderID)='5' OR OrderID='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNested2WithContextCriteria5e() throws Exception {
+ QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+ String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5e.xml"; //$NON-NLS-1$
+ String expectedDoc = TestXMLProcessor.readFile(resultFile);
+
+ TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR SupplierID='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testXQTChoice_6796() throws Exception {
+ QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadata2();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleXQTDataManager(metadata);
+ String resultFile = "TestXMLProcessor-testXQTChoice_6796.xml"; //$NON-NLS-1$
+ String expectedDoc = TestXMLProcessor.readFile(resultFile);
+
+ TestXMLProcessor.helpTestProcess("SELECT * FROM xqttest.doc4 WHERE root.key.keys.nestedkey = 4", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderByWithChoiceCriteriaElement() throws Exception {
+ 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$
+
+ TestXMLProcessor.helpTestProcess("SELECT * FROM xqttest.doc5 order by root.wrapper.key", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testXQTChoice_withContextCriteria() throws Exception {
+ QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadata2();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleXQTDataManager(metadata);
+ String resultFile = "TestXMLProcessor-testXQTChoice_withContextCriteria.xml"; //$NON-NLS-1$
+ String expectedDoc = TestXMLProcessor.readFile(resultFile);
+
+ TestXMLProcessor.helpTestProcess("SELECT * FROM xqttest.doc4 WHERE context(root.key.keys.nestedkey, root.key.keys.nestedkey) = 4", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testXQTChoice_withContextCriteria1() throws Exception {
+ QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadata2();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleXQTDataManager(metadata);
+ String resultFile = "TestXMLProcessor-testXQTChoice_withContextCriteria1.xml"; //$NON-NLS-1$
+ String expectedDoc = TestXMLProcessor.readFile(resultFile);
+
+ TestXMLProcessor.helpTestProcess("SELECT * FROM xqttest.doc4 WHERE context(root.key.keys.nestedkey, root.key.keys.nestedkey) = 4 and context(root.wrapper.key.keys.nestedkey, root.wrapper.key.keys.nestedkey) = 3", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testMappingClassWithInlineViewAndCriteria() throws Exception {
+ 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$
+
+ TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc18a where supplierID<56", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testMappingClassWithUnionAndCriteria() throws Exception {
+ 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$
+
+ TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc18a where supplierID<56", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testMappingClassWithInputSetElementNameConflict() throws Exception {
+ 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$
+ }
+
+ @Test public void testAutoStagingFailsForMappingClassWithProcRelational() throws Exception {
+ TransformationMetadata metadata = getMetadata("SELECT supplierNum, supplierName, supplierZipCode FROM v1.supplierProc where itemnum = ?"); //$NON-NLS-1$
+
+ Schema v1 = RealMetadataFactory.createVirtualModel("v1", metadata.getMetadataStore()); //$NON-NLS-1$
+
+ 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$
+
+ 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$
+ 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$
+
+ XMLPlan plan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc18a where supplierID<56", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+
+ Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
+ assertNull(stats.get(ExecStagingTableInstruction.class));
+ }
+
+ @Test public void testMappingClassWitSelectDistinctAndCriteria() throws Exception {
+ 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);
+
+ String expectedDoc = TestXMLProcessor.readFile("TestXMLPlanningEnhancements-testMappingClassWitSelectDistinctAndCriteria.xml"); //$NON-NLS-1$
+
+ TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc18a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * based upon testNestedWithStoredQueryInMappingClass
+ *
+ * Ensures that correlated references to outer scoped groups can
+ * be used as inputs
+ */
+ @Test public void testMappingClassWithStoredProcedureAndCriteria() throws Exception {
+ QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+ String expectedDoc = TestXMLProcessor.readFile("TestXMLPlanningEnhancements-testMappingClassWithStoredProcedureAndCriteria.xml"); //$NON-NLS-1$
+
+ TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc18 where supplierID<56", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ public void defer_testXMLQueryWithFalseRootCriteria() throws Exception {
+ QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+ String expectedDoc = ""; //$NON-NLS-1$
+
+ TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc18 where 1 = 0", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * @see #testNested2WithCriteria2
+ */
+ @Test public void testAutoStagingByCosting() throws Exception {
+ TransformationMetadata metadata = TestXMLProcessor.exampleMetadata();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+ Table suppliers = metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
+ Table itemSuppliers = metadata.getGroupID("stock.item_supplier"); //$NON-NLS-1$
+
+ suppliers.setCardinality(10);
+ itemSuppliers.setCardinality(10);
+
+ String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
+
+ XMLPlan plan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+
+ //check for staging; one for staging and for unloading
+ Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
+ assertEquals(2, ((List)stats.get(ExecStagingTableInstruction.class)).size());
+ }
+
+ /**
+ * @see #testNested2WithCriteria2
+ */
+ @Test public void testAutoStagingFailsByCosting() throws Exception {
+ TransformationMetadata metadata = TestXMLProcessor.exampleMetadata();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+ Table suppliers = metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
+ Table itemSuppliers = metadata.getGroupID("stock.item_supplier"); //$NON-NLS-1$
+
+ suppliers.setCardinality(10000);
+ itemSuppliers.setCardinality(10000);
+
+ String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
+
+ XMLPlan plan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+
+ //check for no staging
+ Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
+ assertNull(stats.get(ExecStagingTableInstruction.class));
+ }
+
+ @Test public void testAutoStagingFailsByNoCache() throws Exception {
+ QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+
+ String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
+
+ XMLPlan plan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 OPTION NOCACHE", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+
+ //check for no staging
+ Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
+ assertNull(stats.get(ExecStagingTableInstruction.class));
+ }
+
+ @Test public void testAutoStagingFailsByNoCacheByGroup() throws Exception {
+ QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+
+ String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
+
+ XMLPlan plan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 OPTION NOCACHE XMLTEST.SUPPLIERS", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+
+ //check for no staging by the mapping class name
+ Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
+ assertNull(stats.get(ExecStagingTableInstruction.class));
+
+ plan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9 OPTION NOCACHE XMLTEST.SUPPLIERS", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+
+ //check for no staging by the alias mapping class name
+ stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
+ assertNull(stats.get(ExecStagingTableInstruction.class));
+ }
+
+ // see the next test with costing information too.
+ @Test public void testUseOfStagingCardinalityOnDependentJoinsNoCost() throws Exception {
+ QueryMetadataInterface metadata = getTempTableMetadata(false);
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+
+ String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
+
+ XMLPlan xmlPlan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.docJoin", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ Map stats = XMLProgramUtil.getProgramStats(xmlPlan.getOriginalProgram());
+ List list = (List)stats.get(ExecSqlInstruction.class);
+
+ ExecSqlInstruction instr = (ExecSqlInstruction)list.get(2);
+
+ ProcessorPlan plan = instr.info.getPlan();
+
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 2, // Access
+ 0, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin (**We are merge join with out any costing info**)
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ TestOptimizer.checkDependentJoinCount(plan, 0);
+ }
+
+ @Test public void testUseOfStagingCardinalityOnDependentJoinsWithCost() throws Exception {
+ TransformationMetadata metadata = getTempTableMetadata(false);
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+
+ 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$
+ Map stats = XMLProgramUtil.getProgramStats(xmlPlan.getOriginalProgram());
+ List list = (List)stats.get(ExecSqlInstruction.class);
+
+ ExecSqlInstruction instr = (ExecSqlInstruction)list.get(2);
+
+ ProcessorPlan plan = instr.info.getPlan();
+ TestOptimizer.checkNodeTypes(plan, new int[] {
+ 1, // Access
+ 1, // DependentAccess
+ 0, // DependentSelect
+ 0, // DependentProject
+ 0, // DupRemove
+ 0, // Grouping
+ 0, // Join
+ 1, // MergeJoin (**We are merge join with out any costing info**)
+ 0, // Null
+ 0, // PlanExecution
+ 1, // Project
+ 0, // Select
+ 0, // Sort
+ 0 // UnionAll
+ });
+
+ TestOptimizer.checkDependentJoinCount(plan, 1);
+ }
+
+ @Test public void testNoRedundentStagingTables() throws Exception {
+ TransformationMetadata metadata = getTempTableMetadata(true);
+ FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
+
+ Table suppliers = metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
+ Table orders = metadata.getGroupID("stock.orders"); //$NON-NLS-1$
+
+ suppliers.setCardinality(10);
+ orders.setCardinality(10);
+
+ String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-OnlySupplier51.xml"); //$NON-NLS-1$
+
+ XMLPlan xmlPlan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.docJoin where context(Supplier, SupplierID) = 51", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ //check for staging; one for staging and for unloading - only two pairs are expected
+ Map stats = XMLProgramUtil.getProgramStats(xmlPlan.getOriginalProgram());
+ assertEquals(4, ((List)stats.get(ExecStagingTableInstruction.class)).size());
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,11842 +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 static org.junit.Assert.*;
-
-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.client.metadata.ParameterInfo;
-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.core.types.DataTypeManager;
-import org.teiid.core.util.UnitTestUtil;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.mapping.xml.MappingAttribute;
-import org.teiid.query.mapping.xml.MappingChoiceNode;
-import org.teiid.query.mapping.xml.MappingCommentNode;
-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;
-import org.teiid.query.mapping.xml.Namespace;
-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.BasicSourceCapabilities;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.optimizer.xml.TestXMLPlanner;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.BatchCollector;
-import org.teiid.query.processor.FakeDataManager;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.QueryProcessor;
-import org.teiid.query.processor.TestProcessor;
-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.util.CommandContext;
-
-
-/**
- * Tests XML processing, which involves XMLPlanner making a ProcessorPlan
- * (XMLPlan) from a mapping document (tree of MappingNode objects) and
- * metadata, and then that XMLPlan being processed with metadata, a
- * ProcessorDataManager and a QueryProcessor.
- */
- at SuppressWarnings("nls")
-public class TestXMLProcessor {
- private static final boolean DEBUG = false;
-
- /**
- * Construct some fake metadata. Basic conceptual tree is:
- *
- * stock (physical model)
- * items (physical group)
- * itemNum (string)
- * itemName (string)
- * itemQuantity (integer)
- * xmltest (virtual model)
- * rs (virtual group / result set definition)
- * itemNum (string)
- * itemName (string)
- * itemQuantity (integer)
- */
- public static FakeMetadataFacade exampleMetadataCached() {
- return EXAMPLE_CACHED;
- }
-
- private static final FakeMetadataFacade EXAMPLE_CACHED = exampleMetadata();
-
- public static FakeMetadataFacade exampleMetadata() {
- 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", "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,
- 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});
-
-
-
-// ======================================================================================================================
-
- // 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$
-
- // 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$
-
- // 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$
-
-
-// ======================================================================================================================
-
- //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$
-
- //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$
-
-// ======================================================================================================================
-
- //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$
-
- //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$
-
-// ======================================================================================================================
-// Alternate mapping class which selects from stored query
-
- // 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$
-
-// ======================================================================================================================
-// 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$
-
- // 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$
-
- // 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$
-
-// ======================================================================================================================
-// ALTERNATE METADATA B (temp groups)
-
- //temp group selects from root temp group and it has bindings to other mapping classes
- // from 5.5 bindings are not supported in the staging tables. even before we did not supported
- // them in the modeler; but we did in execution; now we remove it as it poses more issues.
- QueryNode tempQuery3b = new QueryNode("SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders2 WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
- 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$
-
- // 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$
-
-
-// ======================================================================================================================
-// ALTERNATE METADATA C (temp group with union)
-
-// //temp group selects from root temp group and it has bindings to other mapping classes
-// QueryNode tempQuery3b = new QueryNode("tempGroup.orders3B", "SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders2 WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?");
-// tempQuery3b.addBinding("xmltest.group.items.itemNum");
-// tempQuery3b.addBinding("xmltest.suppliers.supplierNum");
-// tempQuery3b.addBinding("xmltest.suppliers.supplierName");
-// FakeMetadataObject temp3b = FakeMetadataFactory.createVirtualGroup("tempGroup.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);
-
-// ======================================================================================================================
-
-// ======================================================================================================================
-// ALTERNATE METADATA D (correlated subquery in mapping class)
- // 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$
-
- List rsElements12260 = FakeMetadataFactory.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 });
-
-// ======================================================================================================================
-// ALTERNATE METADATA E (mapping class w/ Union)
- // 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$
-
- List rsElements8373 = FakeMetadataFactory.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$
-
- List rsElements8373a = FakeMetadataFactory.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$
-
- List rsElements8373b = FakeMetadataFactory.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 });
-
-// ======================================================================================================================
-
-
- // 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$
-
- // Create virtual elements
- List rsElements = FakeMetadataFactory.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,
- 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,
- 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,
- 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,
- 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,
- 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,
- 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,
- 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,
- 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,
- 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,
- 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,
- 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,
- new String[] { "rowCount" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.INTEGER});
-
- List rsElementsX = FakeMetadataFactory.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$
- 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$
- 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$
- 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$
- 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$
- 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$
-
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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====================
- boolean useRecursiveCriteria = false;
- 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$
-
- useRecursiveCriteria = true;
- FakeMetadataObject doc13 = FakeMetadataFactory.createVirtualGroup("xmltest.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$
- exceptionOnLimit = true;
- FakeMetadataObject doc15 = FakeMetadataFactory.createVirtualGroup("xmltest.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$
-
- FakeMetadataObject doc17 = FakeMetadataFactory.createVirtualGroup("xmltest.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$
- 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$
-
- 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});
-
- //Test doc w/ update mapping class transformation
- FakeMetadataObject docUpdateTest = FakeMetadataFactory.createVirtualGroup("xmltest.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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
- 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$
-
- // 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,
- 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,
- 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,
- 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 + staging ========================================================
-
- //========================================================
-
- // 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$
- //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$
-
- // 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$
- 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$
- 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$
- 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$
-
- // 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;
- }
-
- public FakeMetadataFacade exampleMetadataNestedWithSibling() {
- 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 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$
-
- // 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 });
-
- //many-to-many join table
- List itemOrderElements = FakeMetadataFactory.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,
- 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 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$
-
- 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$
-
- 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$
-
- // Create virtual elements
- List rsElements1 = FakeMetadataFactory.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,
- 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,
- 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$
- 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;
- }
-
- public static FakeMetadataFacade exampleMetadata2() {
- FakeMetadataStore store = new FakeMetadataStore();
- FakeMetadataFacade facade = new FakeMetadataFacade(store);
-
- // Create models
- FakeMetadataObject xqt = FakeMetadataFactory.createPhysicalModel("xqt"); //$NON-NLS-1$
- FakeMetadataObject xqttest = FakeMetadataFactory.createVirtualModel("xqttest"); //$NON-NLS-1$
-
- // Create physical groups
- FakeMetadataObject xqtGroup = FakeMetadataFactory.createPhysicalGroup("xqt.data", xqt); //$NON-NLS-1$
-
- // Create physical elements
- List xqtData = FakeMetadataFactory.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$
-
- 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$
-
- 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$
-
- 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$
-
- // Create virtual elements
-
- List elemXQTData = FakeMetadataFactory.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,
- 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,
- 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,
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
- 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$
-
-
- 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$
-
- 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$
-
- // Create virtual elements
- List rsElements = FakeMetadataFactory.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,
- 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,
- 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,
- 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,
- 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,
- 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,
- 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,
- 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$
-
- List elemGroupDoc = FakeMetadataFactory.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$
- 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$
- 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;
- }
-
- public static FakeMetadataFacade exampleMetadataSoap1() {
- FakeMetadataStore store = new FakeMetadataStore();
- FakeMetadataFacade facade = new FakeMetadataFacade(store);
-
- // Create models
- FakeMetadataObject taxReport = FakeMetadataFactory.createPhysicalModel("taxReport"); //$NON-NLS-1$
- FakeMetadataObject xmltest = FakeMetadataFactory.createVirtualModel("xmltest"); //$NON-NLS-1$
-
- // Create physical groups
- FakeMetadataObject arrayOfItem = FakeMetadataFactory.createPhysicalGroup("taxReport.TaxIDs", taxReport); //$NON-NLS-1$
-
- // Create physical elements
- List itemElements = FakeMetadataFactory.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$
-
- List rsSoapElements = FakeMetadataFactory.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$
- 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;
- }
-
- private static MappingNode createXQTPlanChoice_6796() {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
- MappingChoiceNode choice = root.addChoiceNode(new MappingChoiceNode(false));
- choice.setSource("xqttest.data7"); //$NON-NLS-1$
- choice.setMaxOccurrs(-1);
- MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode("xqttest.data7.intKey < 10", false)); //$NON-NLS-1$
- MappingElement wrapper1 = crit.addChildElement(new MappingElement("wrapper")); //$NON-NLS-1$
-
- MappingElement key = wrapper1.addChildElement(new MappingElement("key", "xqttest.data7.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement keys = key.addChildElement(new MappingElement("keys")); //$NON-NLS-1$
- keys.setSource("xqttest.data8"); //$NON-NLS-1$
- keys.setMaxOccurrs(-1);
- keys.addChildElement(new MappingElement("nestedkey", "xqttest.data8.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingCriteriaNode wrapper2 = choice.addCriteriaNode(new MappingCriteriaNode(null, true));
-
- key = wrapper2.addChildElement( new MappingElement("key", "xqttest.data7.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-
- keys = key.addChildElement(new MappingElement("keys")); //$NON-NLS-1$
- keys.setSource("xqttest.data8"); //$NON-NLS-1$
- keys.setMaxOccurrs(-1);
- keys.addChildElement(new MappingElement("nestedkey", "xqttest.data8.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-
- return doc;
- }
-
- private static MappingNode createChoiceDefect24651() {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
- MappingChoiceNode choice = root.addChoiceNode(new MappingChoiceNode(false));
- choice.setSource("xqttest.data7"); //$NON-NLS-1$
- choice.setMaxOccurrs(-1);
- MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode("xqttest.data7.intKey < 10", false)); //$NON-NLS-1$
- MappingElement wrapper1 = crit.addChildElement(new MappingElement("wrapper")); //$NON-NLS-1$
-
- MappingElement key = wrapper1.addChildElement(new MappingElement("key", "xqttest.data7.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
- key.setExclude(true);
-
- return doc;
- }
-
- /**
- * Method createXQTPlanRecursive.
- * @return Object
- */
- private static MappingNode createXQTPlanRecursive_5988() {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
-
- MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
- src1.setSource("xqttest.data"); //$NON-NLS-1$
-
- MappingSequenceNode seq1 = new MappingSequenceNode();
- seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
- seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
- src1.addSequenceNode(seq1);
-
- MappingElement src2 = seq1.addChildElement(new MappingElement("srcNested")); //$NON-NLS-1$
- src2.setSource("xqttest.data2"); //$NON-NLS-1$
-
- MappingSequenceNode seq2 = src2.addSequenceNode(new MappingSequenceNode());
- seq2.addChildElement(new MappingElement("key", "xqttest.data2.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
- seq2.addChildElement(new MappingElement("data", "xqttest.data2.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement recursive = seq2.addChildElement(new MappingRecursiveElement("srcNestedRecursive", "xqttest.data2")); //$NON-NLS-1$ //$NON-NLS-2$
- recursive.setSource("xqttest.data3"); //$NON-NLS-1$
-
- MappingElement recursive2 = seq1.addChildElement(new MappingRecursiveElement("srcRecursive", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
- recursive2.setSource("xqttest.data4"); //$NON-NLS-1$
-
- return doc;
- }
-
- /**
- * Method createXQTPlanRecursive.
- * @return Object
- */
- private static MappingNode createXQTPlanRecursive1a_5988() {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
-
- MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
- src1.setSource("xqttest.data"); //$NON-NLS-1$
-
- MappingSequenceNode seq1 = new MappingSequenceNode();
- seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
- seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
- src1.addSequenceNode(seq1);
-
- MappingElement src2 = seq1.addChildElement(new MappingElement("srcNested")); //$NON-NLS-1$
- src2.setSource("xqttest.data2"); //$NON-NLS-1$
-
- MappingSequenceNode seq2 = src2.addSequenceNode(new MappingSequenceNode());
- seq2.addChildElement(new MappingElement("key", "xqttest.data2.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
- seq2.addChildElement(new MappingElement("data", "xqttest.data2.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement recursive = seq2.addChildElement(new MappingRecursiveElement("srcRecursive", "xqttest.data2")); //$NON-NLS-1$ //$NON-NLS-2$
- recursive.setSource("xqttest.data3"); //$NON-NLS-1$
-
- MappingElement recursive2 = seq1.addChildElement(new MappingRecursiveElement("srcRecursive", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
- recursive2.setSource("xqttest.data4"); //$NON-NLS-1$
-
- return doc;
- }
-
- /**
- * Tests a non-recursive nested mapping class within a recursive mapping class, where
- * all nested "anchor" nodes are named "srcNested". Test of defect #5988
- * @return Object
- */
- private static MappingNode createXQTPlanRecursive3_5988() {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
-
- MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
- src1.setSource("xqttest.data"); //$NON-NLS-1$
-
- MappingSequenceNode seq1 = src1.addSequenceNode(new MappingSequenceNode());
- seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
- seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement src2 = seq1.addChildElement(new MappingElement("srcNested")); //$NON-NLS-1$
- src2.setSource("xqttest.data2"); //$NON-NLS-1$
-
- MappingSequenceNode seq2 = src2.addSequenceNode(new MappingSequenceNode());
- seq2.addChildElement(new MappingElement("key", "xqttest.data2.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
- seq2.addChildElement(new MappingElement("data", "xqttest.data2.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement nested = seq1.addChildElement(new MappingRecursiveElement("srcNested", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
- nested.setSource("xqttest.data4"); //$NON-NLS-1$
-
- return doc;
- }
-
-
- private static MappingNode createXQTPlanRecursiveSiblings() {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
-
- MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
- src1.setSource("xqttest.data"); //$NON-NLS-1$
-
- MappingSequenceNode seq1 = src1.addSequenceNode(new MappingSequenceNode());
- seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
- seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement sibiling1 = seq1.addChildElement(new MappingRecursiveElement("srcSibling1", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
- sibiling1.setSource("xqttest.data2"); //$NON-NLS-1$
- sibiling1.setMaxOccurrs(-1);
- MappingElement sibiling2 = seq1.addChildElement(new MappingRecursiveElement("srcSibling2", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
- sibiling2.setSource("xqttest.data2");//$NON-NLS-1$
- sibiling2.setMaxOccurrs(-1);
- return doc;
- }
-
- /**
- * Method createXMLPlanNested.
- * @return MappingNode root of mapping doc
- */
- private static MappingNode createXMLPlanNested() {
-
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = new MappingElement("Catalogs"); //$NON-NLS-1$
- doc.addChildElement(root);
-
- MappingSequenceNode sequence = new MappingSequenceNode();
- MappingElement cats = sequence.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
- MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
- MappingSequenceNode sequence0 = items.addSequenceNode(new MappingSequenceNode());
-
- MappingElement item = sequence0.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- MappingSequenceNode sequence1 = item.addSequenceNode(new MappingSequenceNode());
- sequence1.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-
- //NESTED STUFF======================================================================
- MappingElement nestedWrapper = new MappingElement("Suppliers"); //$NON-NLS-1$
- MappingSequenceNode sequence2 = nestedWrapper.addSequenceNode(new MappingSequenceNode());
-
- MappingElement supplier = sequence2.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$
-
-
- MappingSequenceNode sequence3 = supplier.addSequenceNode(new MappingSequenceNode());
- sequence3.addChildElement(new MappingElement("Name", "xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
- sequence3.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
- //NESTED STUFF======================================================================
-
- sequence1.addChildElement(nestedWrapper);
- root.addSequenceNode(sequence);
- return doc;
- }
-
-
- /**
- * for defect 9929
- */
- static MappingNode createXMLPlanNested(String queryGroup) {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = new MappingElement("Catalogs"); //$NON-NLS-1$
- doc.addChildElement(root);
-
- MappingSequenceNode sequence = new MappingSequenceNode();
- MappingElement cats = sequence.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
- MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
- MappingSequenceNode sequence0 = items.addSequenceNode(new MappingSequenceNode());
-
- MappingElement item = sequence0.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingSequenceNode sequence1 = item.addSequenceNode(new MappingSequenceNode());
- sequence1.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-
- //NESTED STUFF======================================================================
- MappingElement nestedWrapper = new MappingElement("Suppliers"); //$NON-NLS-1$
- MappingSequenceNode sequence2 = nestedWrapper.addSequenceNode(new MappingSequenceNode());
-
- MappingElement supplier = sequence2.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
- supplier.setSource(queryGroup);
- supplier.setMaxOccurrs(-1);
- supplier.addAttribute(new MappingAttribute("SupplierID", queryGroup+".supplierNum"));//$NON-NLS-1$ //$NON-NLS-2$
-
- MappingSequenceNode sequence3 = supplier.addSequenceNode(new MappingSequenceNode());
- sequence3.addChildElement(new MappingElement("Name", queryGroup+".supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
- sequence3.addChildElement(new MappingElement("Zip", queryGroup+".supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
- //NESTED STUFF======================================================================
-
- sequence1.addChildElement(nestedWrapper);
- root.addSequenceNode(sequence);
- return doc;
- }
-
- /**
- * for defect 12260
- */
- private static MappingNode createXMLPlanCorrelatedSubqueryTransform() {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-
- MappingSequenceNode sequence = new MappingSequenceNode();
- MappingElement cats = sequence.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
- MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
- MappingSequenceNode sequence0 = items.addSequenceNode(new MappingSequenceNode());
-
- MappingElement item = sequence0.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.itemsWithNumSuppliers"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.itemsWithNumSuppliers.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingSequenceNode sequence1 = item.addSequenceNode(new MappingSequenceNode());
- sequence1.addChildElement(new MappingElement("Name", "xmltest.group.itemsWithNumSuppliers.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.itemsWithNumSuppliers.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
- sequence1.addChildElement(new MappingElement("numSuppliers", "xmltest.group.itemsWithNumSuppliers.numSuppliers")); //$NON-NLS-1$ //$NON-NLS-2$
-
- root.addSequenceNode(sequence);
- return doc;
- }
-
- private static MappingNode createXMLPlan_9893() {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("Root")); //$NON-NLS-1$
-
- MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());
-
- MappingElement node = seq.addChildElement(new MappingElement("ItemName", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- node.setSource("xmltest.group.items"); //$NON-NLS-1$
- node.setMaxOccurrs(-1);
- node.setMaxOccurrs(MappingNodeConstants.CARDINALITY_UNBOUNDED.intValue());
- return doc;
- }
-
- /**
- * DEFECT 8373
- */
- private static Object createXMLPlan_defect8373() {
-
- 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 items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.items8373"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.items8373.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.items8373.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Quantity", "xmltest.items8373.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-
- return doc;
- }
-
- /**
- * DEFECT 8373
- */
- private static Object createXMLPlan_defect8373a() {
- 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 items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.items8373a"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.setStagingTables(Arrays.asList(new String[] {"xmltest.items8373"})); //$NON-NLS-1$
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.items8373a.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.items8373a.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Quantity", "xmltest.items8373a.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-
- return doc;
- }
-
- /**
- * DEFECT 8373
- */
- private static Object createXMLPlan_defect8373b() {
-
- 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 items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.items8373b"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.setStagingTables(Arrays.asList(new String[] {"xmltest.group.items"})); //$NON-NLS-1$
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.items8373b.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.items8373b.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Quantity", "xmltest.items8373b.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-
- return doc;
- }
-
- private static MappingNode createXMLPlanNested2() {
-
- 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 items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.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======================================================================
- return doc;
- }
-
- /** nested with sibling*/
- private MappingNode createXMLPlanNested2c() {
-
- 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 items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.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 = item.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("Name", "xmltest.orders.orderName")); //$NON-NLS-1$ //$NON-NLS-2$
- order.addChildElement(new MappingElement("Zip", "xmltest.orders.orderZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
- //NESTED STUFF======================================================================
- return doc;
- }
-
-
- private static MappingNode 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$
-
- MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
- MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.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.ordersA"); //$NON-NLS-1$
- order.setMaxOccurrs(-1);
- order.addAttribute(new MappingAttribute("OrderID", "xmltest.ordersA.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
- order.addChildElement(new MappingElement("OrderDate", "xmltest.ordersA.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
- order.addChildElement(new MappingElement("OrderQuantity", "xmltest.ordersA.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
-
- order.addChildElement(new MappingElement("OrderStatus", "xmltest.ordersA.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
- .setMinOccurrs(0);
- //NESTED STUFF======================================================================
- return doc;
- }
-
- // for doc 9b - test temp group w/ bindings
- private static MappingNode createXMLPlanNested2b() {
-
- 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$
-
- MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
- MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.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.ordersB"); //$NON-NLS-1$
-
- order.setStagingTables(Arrays.asList(new String[] {"tempGroup.orders3B"})); //$NON-NLS-1$
- order.addAttribute(new MappingAttribute("OrderID", "xmltest.ordersB.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
- order.addChildElement(new MappingElement("OrderDate", "xmltest.ordersB.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
- order.addChildElement(new MappingElement("OrderQuantity", "xmltest.ordersB.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
-
- order.addChildElement(new MappingElement("OrderStatus", "xmltest.ordersB.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
- .setMinOccurrs(0);
- //NESTED STUFF======================================================================
- return doc;
- }
-
- public static MappingDocument createXMLPlanNestedWithChoice() {
- 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$
- return baseXMLPlanNestedWithLookupChoice("xmltest.orders.orderStatus = 'processing'", critNode); //$NON-NLS-1$
- }
-
- private static MappingNode 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() {
- 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$
- return baseXMLPlanNestedWithLookupChoice("lookup('stock.items', 'itemNum', 'itemName', xmltest.orders.orderStatus) = 'processing'", critNode); //$NON-NLS-1$
- }
-
- private static MappingDocument baseXMLPlanNestedWithLookupChoice(String criteria, MappingCriteriaNode defaultNode) {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-
- MappingSequenceNode seq1 = root.addSequenceNode(new MappingSequenceNode());
- MappingElement cats = seq1.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
- MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingSequenceNode seq2 = items.addSequenceNode(new MappingSequenceNode());
-
- MappingElement item = seq2.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingSequenceNode seq3 = item.addSequenceNode(new MappingSequenceNode());
- seq3.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- seq3.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-
- //NESTED STUFF======================================================================
- MappingElement suppliers = seq3.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
-
- MappingSequenceNode seq4 = suppliers.addSequenceNode(new MappingSequenceNode());
- MappingElement supplier = seq4.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$
-
- MappingSequenceNode seq5 = supplier.addSequenceNode(new MappingSequenceNode());
- seq5.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
- seq5.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement ordersWrapper = seq5.addChildElement(new MappingElement("ProcessingOrders")); //$NON-NLS-1$
-
- MappingChoiceNode choice = ordersWrapper.addChoiceNode(new MappingChoiceNode(false));
- choice.setSource("xmltest.orders"); //$NON-NLS-1$
- choice.setMaxOccurrs(-1);
- MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode(criteria, false));
- MappingElement order = crit.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
- order.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingSequenceNode seq6 = order.addSequenceNode(new MappingSequenceNode());
- seq6.addChildElement(new MappingElement("OrderDate", "xmltest.orders.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
- seq6.addChildElement(new MappingElement("OrderQuantity", "xmltest.orders.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
-
- choice.addCriteriaNode(defaultNode);
- //NESTED STUFF======================================================================
- return doc;
- }
-
-
- private static MappingNode createTestAttributePlan() {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("FixedValueTest")); //$NON-NLS-1$
-
- //sequence
- MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());
-
- MappingElement wrapper = seq.addChildElement(new MappingElement("wrapper")); //$NON-NLS-1$
- wrapper.setSource("xmltest.group.items"); //$NON-NLS-1$
- wrapper.setMaxOccurrs(-1);
- MappingAttribute att = new MappingAttribute("fixedAttr"); //$NON-NLS-1$
- att.setValue("fixed attribute"); //$NON-NLS-1$
- wrapper.addAttribute(att);
-
- //sequence
- MappingSequenceNode seq1 = wrapper.addSequenceNode(new MappingSequenceNode());
- seq1.addChildElement(new MappingElement("key","xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- seq1.addChildElement(new MappingElement("fixed")) //$NON-NLS-1$
- .setValue("fixed value"); //$NON-NLS-1$
-
- return doc;
- }
-
- private static Object createUpdateTestDoc() {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("UpdateTest")); //$NON-NLS-1$
-
- MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());
- seq.setSource("xmltest.updateTest"); //$NON-NLS-1$
- seq.addChildElement(new MappingElement("data", "xmltest.updateTest.rowCount")); //$NON-NLS-1$ //$NON-NLS-2$
- return doc;
- }
-
- private static MappingNode createXMLPlanWithComment(){
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("Root")); //$NON-NLS-1$
-
- root.addCommentNode(new MappingCommentNode("Comment1")); //$NON-NLS-1$
- MappingElement node = root.addChildElement(new MappingElement("Something")); //$NON-NLS-1$
- node.addCommentNode(new MappingCommentNode("Comment2")); //$NON-NLS-1$
- return doc;
- }
-
- public static MappingDocument createXMLMappingBoundingNode() {
- 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$
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMinOccurrs(1);
- item.setMaxOccurrs(2);
-
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName").setNillable(true)); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
- return doc;
- }
-
- public static MappingDocument createXMLMappingNode(boolean format) {
- MappingDocument doc = new MappingDocument(format);
- doc.addChildElement(createXMLPlan1Unformatted(false, 1));
- return doc;
- }
-
- private static MappingNode createXMLPlan2(boolean format, boolean testNillable, int cardinality ) {
- MappingDocument doc = new MappingDocument(format);
- doc.addChildElement(createXMLPlan1Unformatted(testNillable, cardinality));
- return doc;
- }
-
- private static MappingNode createXMLPlanSOAP() {
-
- Namespace namespace = new Namespace("ORG", "http://www.mm.org/dummy"); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("TaxReports", namespace)); //$NON-NLS-1$
-
- root.setNamespaces(new Namespace[] {namespace});
-
- MappingElement report = root.addChildElement(new MappingElement("TaxReport", namespace)); //$NON-NLS-1$
- report.setNamespaces(new Namespace[] {namespace});
-
- Namespace xsiNamespace = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$ //$NON-NLS-2$
- Namespace soapNamespace = new Namespace("SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/"); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement taxIds = report.addChildElement(new MappingElement("ArrayOfTaxID", namespace)); //$NON-NLS-1$
- taxIds.setMinOccurrs(0);
- taxIds.setNamespaces(new Namespace[] {xsiNamespace, soapNamespace});
-
- MappingAttribute xsiType = new MappingAttribute("type", xsiNamespace); //$NON-NLS-1$
- xsiType.setValue(namespace.getPrefix()+":ArrayOfTaxIDType"); //$NON-NLS-1$
- xsiType.setOptional(true);
- taxIds.addAttribute(xsiType);
-
- MappingAttribute arrayType = new MappingAttribute("arrayType", soapNamespace); //$NON-NLS-1$
- arrayType.setValue( namespace.getPrefix()+":TaxIDType[]"); //$NON-NLS-1$
- arrayType.setOptional(true);
- taxIds.addAttribute(arrayType);
-
- MappingElement taxId = taxIds.addChildElement(new MappingElement("TaxID", namespace)); //$NON-NLS-1$
- taxId.setSource("xmltest.group.TaxIDs"); //$NON-NLS-1$
- taxId.setMaxOccurrs(-1);
- MappingAttribute xsiType2 = new MappingAttribute("type", xsiNamespace); //$NON-NLS-1$
- xsiType2.setValue(namespace.getPrefix()+":TaxIDType"); //$NON-NLS-1$
- xsiType2.setOptional(true);
- taxId.addAttribute(xsiType2);
-
- taxId.addChildElement(new MappingElement("ID", "xmltest.group.TaxIDs.ID")); //$NON-NLS-1$ //$NON-NLS-2$
- return doc;
- }
-
-
- private static MappingElement createXMLPlan1Unformatted( boolean testNillable, int cardinality ) {
-
- MappingElement root = new MappingElement("Catalogs");//$NON-NLS-1$
- MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
- items.setNillable(testNillable);
- items.setMinOccurrs(cardinality);
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName").setNillable(true)); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
- return root;
- }
-
- private static MappingNode createXMLPlanDefect13617() {
-
- 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$
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.setMinOccurrs(0);
-
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setMinOccurrs(0);
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
- .setMinOccurrs(0);
-
- return doc;
- }
-
-
- private static MappingNode 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$
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- // ======================================================================
- // CHOICE NODE STUFF
- //choice node, non-visual, so it has no name
- MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode(exception_on_Default));
- choice.setSource("xmltest.group.items"); //$NON-NLS-1$
- choice.setMaxOccurrs(-1);
- if (numChoices >= 1){
- MappingCriteriaNode item = getChoiceChild("Item", "xmltest.group.items.itemName='Lamp'", numDefaultChoice == 1); //$NON-NLS-1$ //$NON-NLS-2$
- choice.addCriteriaNode(item);
- }
- if (numChoices >= 2){
- MappingCriteriaNode item = getChoiceChild("Item2", "xmltest.group.items.itemName='Screwdriver'", numDefaultChoice == 2); //$NON-NLS-1$ //$NON-NLS-2$
- choice.addCriteriaNode(item);
- }
- if (numChoices >= 3){
- MappingCriteriaNode item = getChoiceChild("Item3", "xmltest.group.items.itemName='Goat'", numDefaultChoice == 3); //$NON-NLS-1$ //$NON-NLS-2$
- choice.addCriteriaNode(item);
- }
- if (numDefaultChoice > numChoices){
- MappingCriteriaNode item = getChoiceChild("ItemDefault", null, true); //$NON-NLS-1$
- choice.addCriteriaNode(item);
- }
-
- // ======================================================================
- return doc;
- }
-
- private static MappingCriteriaNode getChoiceChild(String name, String criteria, boolean defalt){
- MappingCriteriaNode crit = new MappingCriteriaNode(criteria, defalt);
-
- MappingElement item = crit.addChildElement(new MappingElement(name));
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setNillable(true);
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
- return crit;
- }
-
- private static MappingDocument createXMLPlanWithDefaults() {
- 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$
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setNillable(true);
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
- .setDefaultValue("1"); //$NON-NLS-1$
-
- return doc;
- }
-
- private static MappingNode createXMLPlanUltraAdvanced() {
-
- 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$
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- //choice node, non-visual, so it has no name
- boolean exceptionOnDefault = false;
- MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode(exceptionOnDefault));
- choice.setSource("xmltest.group.items"); //$NON-NLS-1$
- choice.setMaxOccurrs(-1);
- MappingCriteriaNode crit1 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'okay'", false)); //$NON-NLS-1$
- MappingElement item = crit1.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setNillable(true);
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
- .setDefaultValue("0"); //$NON-NLS-1$
-
- MappingCriteriaNode crit2= choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)); //$NON-NLS-1$
- MappingElement discontinued = crit2.addChildElement(new MappingElement("DiscontinuedItem")); //$NON-NLS-1$
- discontinued.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- discontinued.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setNillable(true);
- discontinued.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
- .setDefaultValue("0"); //$NON-NLS-1$
-
- MappingCriteriaNode crit3 = choice.addCriteriaNode(new MappingCriteriaNode());
- MappingElement unknown = crit3.addChildElement(new MappingElement("StatusUnknown"));//$NON-NLS-1$
- unknown.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- unknown.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setNillable(true);
- unknown.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
- .setDefaultValue("0"); //$NON-NLS-1$
-
- choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)).setExclude(true); //$NON-NLS-1$
- choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)).setExclude(true); //$NON-NLS-1$
-
- return doc;
- }
-
-
-
- private static MappingNode createXMLPlanUltraAdvancedExceptionOnDefault() {
-
- 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$
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- //choice node, non-visual, so it has no name
- boolean exceptionOnDefault = true;
- MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode(exceptionOnDefault));
- choice.setSource("xmltest.group.items"); //$NON-NLS-1$
- choice.setMaxOccurrs(-1);
- MappingCriteriaNode crit1 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'okay'", false)); //$NON-NLS-1$
- MappingElement item = crit1.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setNillable(true);
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
- .setDefaultValue("0"); //$NON-NLS-1$
-
- MappingCriteriaNode crit2 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)); //$NON-NLS-1$
- MappingElement discontinued = crit2.addChildElement(new MappingElement("DiscontinuedItem")); //$NON-NLS-1$
- discontinued.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- discontinued.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setNillable(true);
- discontinued.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
- .setDefaultValue("0"); //$NON-NLS-1$
-
- choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)).setExclude(true); //$NON-NLS-1$
-
- return doc;
- }
-
- //advanced tests of namespace declarations, use and scope; also fixed values
- private static MappingNode createXMLPlanAdvanced() {
- //add to previous example
- MappingDocument doc = createXMLPlanWithDefaults();
- MappingElement root = (MappingElement)doc.getRootNode();
-
- Namespace nameSpaceOne = new Namespace("duh", "http://www.duh.org/duh"); //$NON-NLS-1$ //$NON-NLS-2$
- Namespace nameSpaceTwo = new Namespace("duh2", "http://www.duh2.org/duh2"); //$NON-NLS-1$ //$NON-NLS-2$
- Namespace nameSpaceThree = new Namespace("duh", "http://www.duh.org/duh/duh"); //$NON-NLS-1$ //$NON-NLS-2$
- Namespace nameSpaceFour = new Namespace(MappingNodeConstants.DEFAULT_NAMESPACE_PREFIX, ""); //$NON-NLS-1$
- Namespace nameSpaceFive = new Namespace(MappingNodeConstants.DEFAULT_NAMESPACE_PREFIX, "http://www.default.org/default"); //$NON-NLS-1$
-
- MappingElement fakeChildOfRoot = new MappingElement("Fake", nameSpaceOne); //$NON-NLS-1$
- fakeChildOfRoot.setValue("fixed constant value"); //$NON-NLS-1$
- fakeChildOfRoot.addNamespace(nameSpaceOne);
- fakeChildOfRoot.addNamespace(nameSpaceTwo);
- fakeChildOfRoot.addNamespace(nameSpaceFive);
- root.addChildElement(fakeChildOfRoot);
-
- MappingElement fakeChild2 = fakeChildOfRoot.addChildElement(new MappingElement("FakeChild2", nameSpaceOne)); //$NON-NLS-1$
-
- //add fakeChild2a with default namespace
- MappingElement fakeChild2a = fakeChild2.addChildElement(new MappingElement("FakeChild2a")); //$NON-NLS-1$
- fakeChild2a.setValue("another fixed constant value"); //$NON-NLS-1$
-
- MappingElement fakeChild3 = fakeChildOfRoot.addChildElement(new MappingElement("FakeChild3")); //$NON-NLS-1$
- fakeChild3.addNamespace(nameSpaceThree);
- fakeChild3.addNamespace(nameSpaceFour);
-
- MappingAttribute fakeAtt = new MappingAttribute("FakeAtt", nameSpaceOne); //$NON-NLS-1$
- fakeAtt.setValue("fixed att value"); //$NON-NLS-1$
- fakeChild3.addAttribute(fakeAtt);
-
- return doc;
- }
-
-
- /**
- * Method createXMLPlanNested.
- * @return MappingNode root of mapping doc
- */
- private static MappingNode createXMLPlanMultipleDocs() {
-
- MappingDocument doc = new MappingDocument(true);
-
- MappingElement root = doc.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- root.setSource("xmltest.group.items"); //$NON-NLS-1$
- root.setMaxOccurrs(-1);
- root.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingSequenceNode sequence1 = root.addSequenceNode(new MappingSequenceNode());
- sequence1.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-
- //NESTED STUFF======================================================================
- MappingElement nestedWrapper = sequence1.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
- MappingSequenceNode sequence2 = nestedWrapper.addSequenceNode(new MappingSequenceNode());
-
- MappingElement supplier = sequence2.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$
-
- MappingSequenceNode sequence3 = supplier.addSequenceNode(new MappingSequenceNode());
- sequence3.addChildElement(new MappingElement("Name", "xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
- sequence3.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
- return doc;
- }
-
- private static MappingNode createXMLPlanRecursive(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("OrgHierarchy")); //$NON-NLS-1$
-
- MappingElement ceo = root.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
- ceo.setSource("xmltest.employees"); //$NON-NLS-1$
- ceo.setMinOccurrs(0);
- ceo.setMaxOccurrs(-1);
- ceo.addAttribute(new MappingAttribute("ID", "xmltest.employees.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingSequenceNode sequence = ceo.addSequenceNode(new MappingSequenceNode());
- sequence.addChildElement(new MappingElement("FirstName", "xmltest.employees.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
- sequence.addChildElement(new MappingElement("LastName", "xmltest.employees.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
- MappingElement subordinates = sequence.addChildElement(new MappingElement("Subordinates")); //$NON-NLS-1$
-
- //recursive piece
- MappingRecursiveElement employee = (MappingRecursiveElement)subordinates.addChildElement(new MappingRecursiveElement("Employee", "xmltest.employees")); //$NON-NLS-1$ //$NON-NLS-2$
- employee.setSource("xmltest.employeesRecursive"); //$NON-NLS-1$
- employee.setMinOccurrs(0);
- employee.setMaxOccurrs(-1);
-
- if (useRecursiveCriteria){
- employee.setCriteria("xmltest.employees.employeeNum = '04'"); //$NON-NLS-1$
- }
- employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
- return doc;
- }
-
- /*
- * Recursion root mapping class is anchored at sequence node instead of "Employee" node
- */
- private static MappingNode createXMLPlanRecursiveA(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("OrgHierarchy")); //$NON-NLS-1$
-
- MappingSequenceNode seq0 = root.addSequenceNode(new MappingSequenceNode());
- seq0.setSource("xmltest.employees"); //$NON-NLS-1$
- seq0.setMinOccurrs(0);
- seq0.setMaxOccurrs(-1);
-
- MappingElement ceo = seq0.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
- ceo.addAttribute(new MappingAttribute("ID", "xmltest.employees.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingSequenceNode seq = ceo.addSequenceNode(new MappingSequenceNode());
- seq.addChildElement(new MappingElement("FirstName", "xmltest.employees.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
- seq.addChildElement(new MappingElement("LastName", "xmltest.employees.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
- MappingElement subordinates = seq.addChildElement(new MappingElement("Subordinates")); //$NON-NLS-1$
-
- //recursive piece
- MappingRecursiveElement employee = (MappingRecursiveElement)subordinates.addChildElement(new MappingRecursiveElement("Subordinate", "xmltest.employees")); //$NON-NLS-1$ //$NON-NLS-2$
- employee.setSource("xmltest.employeesRecursive"); //$NON-NLS-1$
- employee.setMinOccurrs(0);
- employee.setMaxOccurrs(-1);
-
- if (useRecursiveCriteria){
- employee.setCriteria("xmltest.employees.employeeNum = '04'"); //$NON-NLS-1$
- }
- employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
- return doc;
- }
-
-
- private static MappingNode createXMLPlanRecursiveStaging(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
-
- MappingDocument doc = new MappingDocument(true);
-
- MappingElement root = doc.addChildElement(new MappingElement("OrgHierarchy")); //$NON-NLS-1$
- root.setStagingTables(Arrays.asList(new String[] {"xmltest.doc19temp"})); //$NON-NLS-1$
-
- MappingElement ceo = root.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
- ceo.setSource("xmltest.employeesDoc19"); //$NON-NLS-1$
- ceo.setMinOccurrs(0);
- ceo.setMaxOccurrs(-1);
- ceo.addAttribute(new MappingAttribute("ID", "xmltest.employeesDoc19.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingSequenceNode seq = ceo.addSequenceNode(new MappingSequenceNode());
- seq.addChildElement(new MappingElement("FirstName", "xmltest.employeesDoc19.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
- seq.addChildElement(new MappingElement("LastName", "xmltest.employeesDoc19.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
- MappingElement subordinates = seq.addChildElement(new MappingElement("Subordinates")); //$NON-NLS-1$
-
- //recursive piece
- MappingRecursiveElement employee = (MappingRecursiveElement)subordinates.addChildElement(new MappingRecursiveElement("Employee", "xmltest.employeesDoc19")); //$NON-NLS-1$ //$NON-NLS-2$
- employee.setSource("xmltest.employeesRecursiveDoc19"); //$NON-NLS-1$
- employee.setMinOccurrs(0);
- employee.setMaxOccurrs(-1);
-
- if (useRecursiveCriteria){
- employee.setCriteria("xmltest.employeesDoc19.employeeNum = '04'"); //$NON-NLS-1$
- }
- employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
-
- return doc;
- }
-
- private static MappingNode createXMLPlanRecursive2(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("Employees")); //$NON-NLS-1$
-
- MappingElement ceo = root.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
- ceo.setSource("xmltest.employees2"); //$NON-NLS-1$
- ceo.setMinOccurrs(0);
- ceo.setMaxOccurrs(-1);
- ceo.addAttribute(new MappingAttribute("ID", "xmltest.employees2.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingSequenceNode seq = ceo.addSequenceNode(new MappingSequenceNode());
- seq.addChildElement(new MappingElement("FirstName", "xmltest.employees2.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
- seq.addChildElement(new MappingElement("LastName", "xmltest.employees2.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
-
- //recursive piece
- MappingRecursiveElement employee = (MappingRecursiveElement)seq.addChildElement(new MappingRecursiveElement("Supervisor", "xmltest.employees2")); //$NON-NLS-1$ //$NON-NLS-2$
- employee.setSource("xmltest.employees2Recursive"); //$NON-NLS-1$
- employee.setMinOccurrs(0);
- employee.setMaxOccurrs(-1);
-
- if (useRecursiveCriteria){
- employee.setCriteria("xmltest.employees2.employeeNum = '04'"); //$NON-NLS-1$
- }
- employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
- return doc;
- }
-
- //this is for testing how "optional" XML elements are included/
- //excluded from the result document
- private static MappingNode createXMLPlan_defect8917() {
-
- Namespace namespace1 = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-
- root.addNamespace(namespace1);
-
- {
- //FRAGMENT 1
- MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setNillable(true);
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- {
- //FRAGMENT 2
- MappingElement cat = root.addChildElement(new MappingElement("OptionalCatalog")); //$NON-NLS-1$
- cat.setMinOccurrs(0);
-
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setNillable(true);
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- {
- //FRAGMENT 3
- MappingElement cat = root.addChildElement(new MappingElement("OptionalCatalog2")); //$NON-NLS-1$
- cat.setMinOccurrs(0);
-
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setNillable(true);
- }
-
- {
- //FRAGMENT 4
- MappingElement cat = root.addChildElement(new MappingElement("OptionalCatalog3")); //$NON-NLS-1$
- cat.setMinOccurrs(0);
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- {
- //FRAGMENT 5
- MappingElement cat = root.addChildElement(new MappingElement("Catalog4")); //$NON-NLS-1$
- MappingElement items = cat.addChildElement(new MappingElement("OptionalItems")); //$NON-NLS-1$
- items.setMinOccurrs(0);
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- {
- //FRAGMENT 6
- MappingElement cat = root.addChildElement(new MappingElement("Catalog5")); //$NON-NLS-1$
- MappingElement items = cat.addChildElement(new MappingElement("OptionalItems")); //$NON-NLS-1$
- items.setMinOccurrs(0);
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.addChildElement(new MappingElement("FixedName")) //$NON-NLS-1$
- .setValue("Nugent"); //$NON-NLS-1$
- }
-
- {
- //FRAGMENT 7
- MappingElement cat = root.addChildElement(new MappingElement("Catalog6")); //$NON-NLS-1$
- MappingElement items = cat.addChildElement(new MappingElement("OptionalItems")); //$NON-NLS-1$
- items.setMinOccurrs(0);
-
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.addChildElement(new MappingElement("EmptyName")); //$NON-NLS-1$
- }
- return doc;
- }
-
- /*
- * Test of identically named nodes
- */
- private static MappingNode createXMLPlan_defect9446() {
- 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$
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
- MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addAttribute(new MappingAttribute("XXXXX", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("XXXXX", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("XXXXX", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
- return doc;
- }
-
- private static MappingNode 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$
-
- MappingDocument doc = new MappingDocument(true);
- MappingElement root = doc.addChildElement(new MappingElement("Catalogs", namespace)); //$NON-NLS-1$
- root.addNamespace(namespace);
-
- MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- MappingElement item = items.addChildElement(new MappingElement("Item", namespace)); //$NON-NLS-1$
- item.setSource("xmltest.group.items"); //$NON-NLS-1$
- item.setMaxOccurrs(-1);
- item.addNamespace(namespace2);
- item.addNamespace(namespace3);
-
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
- return doc;
- }
-
- private static MappingNode createGroupDoc() {
- MappingDocument doc = new MappingDocument(true);
-
- MappingElement root = doc.addChildElement(new MappingElement("group")); //$NON-NLS-1$
- root.setSource("xqttest.group"); //$NON-NLS-1$
- root.setMinOccurrs(0);
- root.setMaxOccurrs(-1);
-
- MappingAttribute attr = new MappingAttribute("pseudoID", "xqttest.group.ID"); //$NON-NLS-1$ //$NON-NLS-2$
- attr.setExclude(true);
- root.addAttribute(attr);
-
- MappingSequenceNode sequence = root.addSequenceNode(new MappingSequenceNode());
- sequence.addChildElement(new MappingElement("ID", "xqttest.group.ID")); //$NON-NLS-1$ //$NON-NLS-2$
- sequence.addChildElement(new MappingElement("code", "xqttest.group.Code")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingElement supervisor = sequence.addChildElement(new MappingElement("supervisor")); //$NON-NLS-1$
- supervisor.setSource("xqttest.supervisor"); //$NON-NLS-1$
- supervisor.setMinOccurrs(0);
- supervisor.setMaxOccurrs(-1);
-
- MappingSequenceNode sequence1 = supervisor.addSequenceNode(new MappingSequenceNode());
- sequence1.addChildElement(new MappingElement("ID", "xqttest.supervisor.ID")); //$NON-NLS-1$ //$NON-NLS-2$
- sequence1.addChildElement(new MappingElement("code", "xqttest.supervisor.Code")); //$NON-NLS-1$ //$NON-NLS-2$
-
- MappingRecursiveElement group1 = (MappingRecursiveElement)sequence1.addChildElement(new MappingRecursiveElement("group", "xqttest.group")); //$NON-NLS-1$ //$NON-NLS-2$
- group1.setSource("xqttest.group1"); //$NON-NLS-1$
- group1.setMinOccurrs(0);
- 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) {
- 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$
- } );
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- public static FakeDataManager exampleDataManager15117(FakeMetadataFacade 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$
- } );
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- /** unusual characters in text */
- public static FakeDataManager exampleDataManager15117a(FakeMetadataFacade 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$
- } );
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- public static FakeDataManager exampleDataManager14905(FakeMetadataFacade 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$
- } );
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- public static FakeDataManager exampleDataManager13617(FakeMetadataFacade 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$
- } );
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- public static FakeDataManager exampleDataManagerNested(FakeMetadataFacade 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$
- } );
-
- 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$
- } );
-
-
- 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$
- } );
-
- 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$
- } );
-
- 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$
- } );
-
-
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- private FakeDataManager exampleDataManagerNestedWithSibling(FakeMetadataFacade 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$
- } );
-
- 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$
- } );
-
-
- 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$
- } );
-
- 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$
- } );
-
- 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$
- } );
-
-
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- /**
- * 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) {
- 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$
- } );
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- public static FakeDataManager exampleDataManagerForSoap1(FakeMetadataFacade 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;
- if (makeEmpty){
- tuples = new List[0];
- } else {
- tuples = new List[] {
- Arrays.asList( new Object[] { "1"} ), //$NON-NLS-1$
- Arrays.asList( new Object[] { "2" } ), //$NON-NLS-1$
- Arrays.asList( new Object[] { "3" } ), //$NON-NLS-1$
- };
- }
-
- dataMgr.registerTuples(
- groupID,
- elementSymbols,
- tuples );
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- /** data has a null value */
- private FakeDataManager exampleDataManager_8917(FakeMetadataFacade 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$
- } );
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- /** data has a NON-EMPTY WHITESPACE string */
- private FakeDataManager exampleDataManager_8917a(FakeMetadataFacade 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$
- } );
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- /** data has an EMPTY STRING */
- private FakeDataManager exampleDataManager_8917b(FakeMetadataFacade 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$
- } );
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- /**
- * Duplicate records in data
- * @param metadata
- * @return FakeDataManager
- */
- private FakeDataManager exampleDataManagerWithDuplicates(FakeMetadataFacade 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", "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;
- }
-
- /**
- *
- * Duplicate records in data to test more than two order by elements at the same depth
- * @param metadata
- * @return FakeDataManager
- */
- private FakeDataManager exampleDataManagerWithDuplicates1(FakeMetadataFacade 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", "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
- */
- private FakeDataManager exampleDataManagerDuJour(FakeMetadataFacade 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$
- 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$
- }
-
- return dataMgr;
- }
-
- public static FakeDataManager exampleXQTDataManager(FakeMetadataFacade 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$
- } );
-
- return dataMgr;
- }
-
- public static Command helpGetCommand(String sql, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException {
- QueryParser parser = new QueryParser();
- Command command = parser.parseCommand(sql);
- QueryResolver.resolveCommand(command, metadata);
- command = QueryRewriter.rewrite(command, metadata, null);
- return command;
- }
-
- static ProcessorPlan helpTestProcess(String sql, String expectedDoc, FakeMetadataFacade 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{
-
- 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{
- Command command = helpGetCommand(sql, metadata);
- AnalysisRecord analysisRecord = new AnalysisRecord(false, DEBUG);
-
- try {
- CommandContext planningContext = new CommandContext(); //this should be the same as the processing context, but that's not easy to do
- planningContext.setMetadata(new TempMetadataAdapter(metadata, new TempMetadataStore()));
- ProcessorPlan plan = QueryOptimizer.optimizePlan(command, metadata, null, capFinder, analysisRecord, planningContext);
-
- if(DEBUG) {
- System.out.println(analysisRecord.getDebugLog());
- }
- List[] expected = new List[expectedDoc.length];
- for (int i = 0; i < expectedDoc.length; i++) {
- expected[i] = Arrays.asList(expectedDoc[i]);
- }
- TestProcessor.helpProcess(plan, planningContext, dataMgr, expected);
- assertNull("Expected failure", expectedException);
- return plan;
- } catch (Exception e) {
- if (expectedException == null) {
- throw e;
- }
- assertTrue(expectedException.isInstance(e));
- } finally {
- if(DEBUG) {
- System.out.println(analysisRecord.getDebugLog());
- }
- }
- return null;
- }
-
- // =============================================================================================
- // T E S T S
- // =============================================================================================
-
- @Test public void test1() 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", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy1() 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=\"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$
- " <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$
- " </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 ORDER BY Catalogs.Catalog.Items.Item.Quantity ASC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy1a() 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=\"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$
- " <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$
- " </Items>\r\n" + //$NON-NLS-1$
- " </Catalog>\r\n" + //$NON-NLS-1$
- "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT \"xml\" FROM xmltest.doc1 ORDER BY Catalogs.Catalog.Items.Item.Quantity ASC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy1b() 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=\"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$
- " <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$
- " </Items>\r\n" + //$NON-NLS-1$
- " </Catalog>\r\n" + //$NON-NLS-1$
- "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT xmltest.doc1.xml FROM xmltest.doc1 ORDER BY Catalogs.Catalog.Items.Item.Quantity ASC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy2() 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=\"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=\"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=\"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 ORDER BY Catalogs.Catalog.Items.Item.Quantity DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy3() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8 ORDER BY Catalogs.Catalog.Items.Item.ItemID DESC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy3a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8 ORDER BY Catalogs.Catalog.Items.Item.ItemID ASC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy4() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(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$
- " </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 ItemID='001' AND Quantity < 60 ORDER BY ItemID", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy5() 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 ORDER BY ItemID", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy6() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9 ORDER BY Catalogs.Catalog.Items.Item.ItemID ASC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, OrderID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- //order by with temp group at the root
- @Test public void testOrderBy7() throws Exception {
- FakeMetadataFacade 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();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9 WHERE Catalogs.Catalog.Items.Item.Quantity < 60 ORDER BY Catalogs.Catalog.Items.Item.ItemID ASC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, OrderID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /*
- @Test public void testOrderBy9() throws Exception {
- FakeMetadataFacade metadata = exampleMetadata();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc = "";
-
- boolean shouldSucceed = false;
- Class expectedException = QueryResolverException.class;
- String shouldFailMsg = "Unable to resolve element: Quantity";
-
- helpTestProcess("SELECT * FROM xmltest.doc9 WHERE Quantity < 60 ORDER BY ItemID ASC, SupplierID ASC, OrderID DESC", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);
- }
- */
-
- @Test public void testOrderBy10() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(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=\"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 Quantity < 60 ORDER BY Name DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy11() throws Exception {
- FakeMetadataFacade 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();
- FakeDataManager dataMgr = exampleDataManagerNested(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=\"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=\"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=\"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 ORDER BY Name DESC, Quantity ASC ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy14() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9 ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy15() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(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=\"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$
- " <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$
- " </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 ORDER BY Name ASC, Quantity DESC ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** test null elements*/
- @Test public void testOrderBy17() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerWithNulls(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 xsi:nil=\"true\"/>\r\n" + //$NON-NLS-1$
- " <Quantity>5</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$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
- " <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 ORDER BY Name ASC, Quantity ASC ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** test duplicate elements*/
- @Test public void testOrderBy18() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerWithDuplicates(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>Goat</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>5</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$
- " <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$
- " </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 ORDER BY Name ASC, Quantity DESC ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** test more than two parallel elements*/
- @Test public void testOrderBy19() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerWithDuplicates1(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>Goat</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\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$
- " <Item ItemID=\"003\">\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$
- " </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 ORDER BY ItemID ASC, Name ASC, Quantity DESC ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy20() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9 WHERE ItemID='002' AND Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderQuantity < 1000 " //$NON-NLS-1$
- + "ORDER BY SupplierID ", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /**
- * Doc nodes that are not mapped to data cannot be used in the
- * ORDER BY clause of an XML doc query
- */
- @Test public void testOrderBy_defect9803() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- try {
- helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='002' AND Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderQuantity < 1000 " //$NON-NLS-1$
- + "ORDER BY Suppliers", //$NON-NLS-1$
- "", metadata, dataMgr); //$NON-NLS-1$
- fail("Should have failed with QueryPlannerException but didn't"); //$NON-NLS-1$
- } catch (QueryPlannerException e) {
- String expectedMsg = "The XML document element [element] name='Suppliers' minOccurs=1 maxOccurs=1 is not mapped to data and cannot be used in the ORDER BY clause: ORDER BY Suppliers"; //$NON-NLS-1$
- assertEquals(expectedMsg, e.getMessage());
- }
- }
-
- //defect 8130
- @Test public void test1CriteriaWithUnmappedElementFails() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- helpTestProcess("SELECT * FROM xmltest.doc1 WHERE Catalog = 'something'", null, metadata, dataMgr, QueryPlannerException.class); //$NON-NLS-1$
- }
-
- //defect 8130
- @Test public void test1CriteriaWithUnmappedElementFails2() throws Exception {
- FakeMetadataFacade 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();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- private static final String EXPECTED_DOC_NESTED_2 =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
-
- private static final String EXPECTED_DOC_NESTED_3 =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
-
- @Test public void testNested2() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc = EXPECTED_DOC_NESTED_2;
- helpTestProcess("SELECT * FROM xmltest.doc9", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * Tests a couple temp groups at the root - B selects from A, and a mapping class
- * selects from B
- */
- @Test public void testNested2aTempGroup() throws Exception {
- FakeMetadataFacade 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();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9a WHERE tempGroup.orders.orderNum = 1", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** defect 13172, CSE Case 1811 */
- @Test public void testNested2aTempGroupCompoundCriteria() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-// " <Orders>\r\n" + //$NON-NLS-1$
-// " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-// " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-// " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-// " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-// " </Order>\r\n" + //$NON-NLS-1$
-// " </Orders>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9a WHERE tempGroup.orders.orderNum = '1' AND tempGroup.orders.orderStatus = 'processing'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** defect 13172, CSE Case 1811 */
- @Test public void testNested2aTempGroupCompoundCriteria1() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-// " <Orders>\r\n" + //$NON-NLS-1$
-// " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-// " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-// " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-// " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-// " </Order>\r\n" + //$NON-NLS-1$
-// " </Orders>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9a WHERE tempGroup.orders.orderNum = 1 AND tempGroup.orders.orderQty = 87", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** defect 13172, CSE Case 1811 */
- @Test public void testNested2aTempGroupCompoundCriteria2() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-// " <Orders/>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9a WHERE tempGroup.orders.orderNum = '1' OR tempGroup.orders.orderStatus = 'processing'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNested2cTempGroup() throws Exception {
- FakeMetadataFacade 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$
- }
-
- /**
- * Tests a temp group C that selects from a root temp group, plus has bindings to
- * some ancestor mapping classes ( we no longer support bindings on staging tables)
- */
- public void defer_testNested2bTempGroup() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc = EXPECTED_DOC_NESTED_2;
- helpTestProcess("SELECT * FROM xmltest.doc9b", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNested2WithCriteria() throws Exception {
-
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9 WHERE ItemID='001'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * <p>This test illustrates how to use the context operator
- * to specify that the result set to limit is the same as the
- * result set which the criteria originates from, when that
- * result set is nested below the top level.
- * Test {@link #testNested2WithCriteria2a} shows a similar
- * query without the context operator.</p>
- *
- * @see #testNested2WithCriteria2a
- */
- @Test public void testNested2WithCriteria2() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers/>\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$
- " <Suppliers/>\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$
-
- XMLPlan plan = (XMLPlan)helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(SupplierID, SupplierID)='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-
- // check the staging base line (unknown cost)
- // one for staging and for unloading
- Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
- assertEquals(2, ((List)stats.get(ExecStagingTableInstruction.class)).size());
- }
-
- /**
- * <p>This test illustrates how to use the context operator
- * to specify that the result set to limit is the same as the
- * result set which the criteria originates from, when that
- * result set is nested below the top level.
- * Test {@link #testNested2WithCriteria2a} shows a similar
- * query without the context operator.</p>
- *
- * <p>defect 9802, trying different ways of qualifying 1st arg
- * to context operator</p>
- *
- * @see #testNested2WithCriteria2a
- */
- @Test public void testNested2WithCriteria2_defect9802() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers/>\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$
- " <Suppliers/>\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.doc9 WHERE context(Supplier.SupplierID, SupplierID)='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * <p>Same as {@link #testNested2WithCriteria2} but with a
- * type conversion on the right expression from integer to string.
- * This demonstrates a function of only constants is executed in
- * an XML criteria.</p>
- * shows a similar
- * @see #testNested2WithCriteria2
- */
- @Test public void testNested2WithCriteria2_function() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers/>\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$
- " <Suppliers/>\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.doc9 WHERE context(SupplierID, SupplierID)=convert(52, string)", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * <p>This tests the unintuitive effects of specifying a user
- * criteria on a node inside a nested mapping class. Here, the
- * "Item" fragment is repeated, but the "Supplier" fragment inside
- * is limited by the criteria.
- * Test {@link #testNested2WithCriteria2} shows how to use
- * the "context" syntax to control what context the criteria
- * is used to restrict.</p>
- *
- * <P>UPDATE: With 3.0 sp1 the default behavior is changed.
- * Now, if "context" syntax is not used, the outer context (anchored
- * at "Item" node) will be limited by default, instead of the one
- * the criteria is actually specified on.</p>
- */
- @Test public void testNested2WithCriteria2a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9 WHERE SupplierID='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
-
- @Test public void testNested2WithContextCriteria() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9 WHERE context(Item, SupplierID)='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNested2WithContextCriteria2() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-// " <OrderStatus/>\r\n" +
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9 WHERE context(Item, OrderID)='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNested2WithContextCriteria3() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers/>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers/>\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.doc9 WHERE context(SupplierID, OrderID)='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- private static final String EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4 =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
-
-
- @Test public void testNested2WithContextCriteria4() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
-
- helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR context(Item, OrderID)='6'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNested2WithContextCriteria4a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
-
- helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR OrderID='6'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNested2WithContextCriteria4b() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
-
- helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR OrderID='6'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- private static final String EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5 =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
-
- @Test public void testNested2WithContextCriteria5() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
-
- helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR context(Item, OrderID)='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNested2WithContextCriteria5a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
-
- helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR context(Item, OrderID)='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNested2WithContextCriteria5b() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
-
- helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR OrderID='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- public static String readFile(String fileName) throws Exception {
- FileInputStream fis = new FileInputStream(UnitTestUtil.getTestDataFile(fileName));
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- int c = 0;
- while ((c = fis.read()) != -1) {
- baos.write(c);
- }
-
- return baos.toString();
- }
-
- @Test public void testNested2WithContextCriteria5Fail() throws Exception {
- FakeMetadataFacade 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$
-
- 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();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\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.doc9 WHERE context(Item, OrderID)='5' AND context(Item, OrderID)='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNested2WithContextCriteria6b() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\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.doc9 WHERE OrderID='5' AND OrderID='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- //WHERE CONTEXT(SupplierID, OrderID)='5' AND context(OrderID, OrderID)='5'
- private static final String EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_7 =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers/>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers/>\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$
-
- @Test public void testNested2WithContextCriteria7() throws Exception {
- FakeMetadataFacade 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();
- 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$
- + "Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderID)='5' AND context(OrderID, OrderID)='5'"; //$NON-NLS-1$
- helpTestProcess(query, expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testNested2WithContextCriteria7c() throws Exception {
- FakeMetadataFacade 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$
- + "Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderID)='6' AND context(OrderID, OrderID)='5'"; //$NON-NLS-1$
- helpTestProcess(query, expectedDoc, metadata, dataMgr);
- }
-
- /**
- * per defect 7333
- */
- @Test public void testNested2WithContextCriteria_7333() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9 WHERE OrderID='4' AND ItemID='003'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * per defect 7333
- */
- @Test public void testNested2WithContextCriteria_7333b() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9 WHERE ItemID='003' AND OrderID='4'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * per defect 7333
- */
- @Test public void testNested2WithContextCriteria_7333c() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\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.doc9 WHERE OrderID='5' AND ItemID='003'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * per defect 7333
- */
- @Test public void testNested2WithContextCriteria_7333d() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\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.doc9 WHERE ItemID='003' AND OrderID='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * Select a single item, and then limit the suppliers based on an order #
- */
- @Test public void testNested2WithContextCriteria8() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9 WHERE ItemID='002' AND Context(Supplier,OrderID)='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNestedWithChoice() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders>\r\n" + //$NON-NLS-1$
- " <OtherOrder OrderID=\"2\"/>\r\n" + //$NON-NLS-1$
- " </ProcessingOrders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders>\r\n" + //$NON-NLS-1$
- " <OtherOrder OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
- " </ProcessingOrders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders>\r\n" + //$NON-NLS-1$
- " <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
- " <OtherOrder OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
- " </ProcessingOrders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders>\r\n" + //$NON-NLS-1$
- " <OtherOrder OrderID=\"3\"/>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </ProcessingOrders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc10", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * Does not use 'context' operator
- */
- @Test public void testNestedWithChoiceAndCriteria2_6796() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders>\r\n" + //$NON-NLS-1$
- " <OtherOrder OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
- " </ProcessingOrders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders>\r\n" + //$NON-NLS-1$
- " <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
- " <OtherOrder OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
- " </ProcessingOrders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc10 where Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * Uses the 'context' operator
- */
- @Test public void testNestedWithChoiceAndCriteria2a_6796() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders>\r\n" + //$NON-NLS-1$
- " <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
- " </ProcessingOrders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc10 where context(Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID, Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID)='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * Does not use 'context' operator
- */
- @Test public void testNestedWithLookupChoice() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders>\r\n" + //$NON-NLS-1$
- " <OtherOrder OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
- " </ProcessingOrders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders>\r\n" + //$NON-NLS-1$
- " <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
- " <OtherOrder OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
- " </ProcessingOrders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc10L where Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void test1Unformatted() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
- "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + //$NON-NLS-1$
- "<Catalog>" + //$NON-NLS-1$
- "<Items>" + //$NON-NLS-1$
- "<Item ItemID=\"001\">" + //$NON-NLS-1$
- "<Name>Lamp</Name>" + //$NON-NLS-1$
- "<Quantity>5</Quantity>" + //$NON-NLS-1$
- "</Item>" + //$NON-NLS-1$
- "<Item ItemID=\"002\">" + //$NON-NLS-1$
- "<Name>Screwdriver</Name>" + //$NON-NLS-1$
- "<Quantity>100</Quantity>" + //$NON-NLS-1$
- "</Item>" + //$NON-NLS-1$
- "<Item ItemID=\"003\">" + //$NON-NLS-1$
- "<Name>Goat</Name>" + //$NON-NLS-1$
- "<Quantity>4</Quantity>" + //$NON-NLS-1$
- "</Item>" + //$NON-NLS-1$
- "</Items>" + //$NON-NLS-1$
- "</Catalog>" + //$NON-NLS-1$
- "</Catalogs>\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc1Unformatted", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
-
- // jhTODO: complete this
-
- @Test public void testChoice_5266a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$\r\n"
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$\r\n" +
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <ProcessingOrders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </ProcessingOrders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc_5266a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
-
- @Test public void test1WithCriteriaShortName() 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=\"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 quantity < 50", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void test1WithCriteriaLongName() 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=\"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 catalogs.catalog.items.item.quantity < 50", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void test2() 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$
- " </Items>\r\n" + //$NON-NLS-1$
- " </Catalog>\r\n" + //$NON-NLS-1$
- "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void test2a() 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.doc2a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void test2b() throws Exception {
- FakeMetadataFacade 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();
- 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$
- " <Item2 ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
- " </Item2>\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.doc2c", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void test2d() 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$
- " <Item2 ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
- " </Item2>\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.doc2d", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void test2e() 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$
- " <Item2 ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
- " </Item2>\r\n" + //$NON-NLS-1$
- " <ItemDefault ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Name>Goat</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>4</Quantity>\r\n" + //$NON-NLS-1$
- " </ItemDefault>\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.doc2e", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testWithNillableNode() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerWithNulls(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 xsi:nil=\"true\"/>\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/>\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", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testWithDefault() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerWithNulls(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 xsi:nil=\"true\"/>\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>1</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.doc3", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testWithNamespaces() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerWithNulls(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 xsi:nil=\"true\"/>\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>1</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$
- " <duh:Fake xmlns:duh=\"http://www.duh.org/duh\" xmlns:duh2=\"http://www.duh2.org/duh2\"\n" + //$NON-NLS-1$
- " xmlns=\"http://www.default.org/default\">fixed constant value<duh:FakeChild2>\r\n" + //$NON-NLS-1$
- " <FakeChild2a>another fixed constant value</FakeChild2a>\r\n" + //$NON-NLS-1$
- " </duh:FakeChild2>\r\n" + //$NON-NLS-1$
- " <FakeChild3 xmlns:duh=\"http://www.duh.org/duh/duh\" duh:FakeAtt=\"fixed att value\"/>\r\n" + //$NON-NLS-1$
- " </duh:Fake>\r\n" + //$NON-NLS-1$
- "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc4", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testWithNewIter3Properties() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerDuJour(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 xsi:nil=\"true\"/>\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>0</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$
- " <DiscontinuedItem ItemID=\"004\">\r\n" + //$NON-NLS-1$
- " <Name>Flux Capacitor</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>2</Quantity>\r\n" + //$NON-NLS-1$
- " </DiscontinuedItem>\r\n" + //$NON-NLS-1$
- " <StatusUnknown ItemID=\"005\">\r\n" + //$NON-NLS-1$
- " <Name>Milkshake</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>88</Quantity>\r\n" + //$NON-NLS-1$
- " </StatusUnknown>\r\n" + //$NON-NLS-1$
- " <DiscontinuedItem ItemID=\"006\">\r\n" + //$NON-NLS-1$
- " <Name>Feta Matrix</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>0</Quantity>\r\n" + //$NON-NLS-1$
- " </DiscontinuedItem>\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.doc5", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testWithNewIter3PropertiesException() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerDuJour(metadata);
-
- Command command = helpGetCommand("SELECT * FROM xmltest.doc6", metadata); //$NON-NLS-1$
- XMLPlan plan = TestXMLPlanner.preparePlan(command, metadata, new DefaultCapabilitiesFinder(), null);
-
- BufferManager bufferMgr = BufferManagerFactory.getStandaloneBufferManager();
- CommandContext context = new CommandContext("pID", null, null, null, 1); //$NON-NLS-1$
- QueryProcessor processor = new QueryProcessor(plan, context, bufferMgr, dataMgr);
- processor.setNonBlocking(true);
- BatchCollector collector = processor.createBatchCollector();
- TeiidComponentException failOnDefaultException = null;
- try{
- collector.collectTuples();
- } catch (TeiidComponentException e){
- failOnDefaultException = e;
- }
-
- assertNotNull("Query processing should have failed on default of choice node.", failOnDefaultException); //$NON-NLS-1$
- }
-
- @Test public void testAttributeBug() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<FixedValueTest>\r\n" + //$NON-NLS-1$
- " <wrapper fixedAttr=\"fixed attribute\">\r\n" + //$NON-NLS-1$
- " <key>001</key>\r\n" + //$NON-NLS-1$
- " <fixed>fixed value</fixed>\r\n" + //$NON-NLS-1$
- " </wrapper>\r\n" + //$NON-NLS-1$
- " <wrapper fixedAttr=\"fixed attribute\">\r\n" + //$NON-NLS-1$
- " <key>002</key>\r\n" + //$NON-NLS-1$
- " <fixed>fixed value</fixed>\r\n" + //$NON-NLS-1$
- " </wrapper>\r\n" + //$NON-NLS-1$
- " <wrapper fixedAttr=\"fixed attribute\">\r\n" + //$NON-NLS-1$
- " <key>003</key>\r\n" + //$NON-NLS-1$
- " <fixed>fixed value</fixed>\r\n" + //$NON-NLS-1$
- " </wrapper>\r\n" + //$NON-NLS-1$
- "</FixedValueTest>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc7", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testMultipleDocs() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- String expectedDoc1 =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- "</Item>\r\n\r\n"; //$NON-NLS-1$
-
- String expectedDoc2 =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- "</Item>\r\n\r\n"; //$NON-NLS-1$
-
- String expectedDoc3 =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- "</Item>\r\n\r\n"; //$NON-NLS-1$
-
-
- helpTestProcess("SELECT * FROM xmltest.doc11", metadata, dataMgr, null, new DefaultCapabilitiesFinder(), expectedDoc1, expectedDoc2, expectedDoc3); //$NON-NLS-1$
- }
-
- @Test public void testRecursive() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<OrgHierarchy>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"01\">\r\n" + //$NON-NLS-1$
- " <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"02\">\r\n" + //$NON-NLS-1$
- " <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"04\">\r\n" + //$NON-NLS-1$
- " <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"06\">\r\n" + //$NON-NLS-1$
- " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Zorn</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"11\">\r\n" + //$NON-NLS-1$
- " <FirstName>Mike</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Patton</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"13\">\r\n" + //$NON-NLS-1$
- " <FirstName>Puffy</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Bordin</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"12\">\r\n" + //$NON-NLS-1$
- " <FirstName>Devin</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Townsend</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"03\">\r\n" + //$NON-NLS-1$
- " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"05\">\r\n" + //$NON-NLS-1$
- " <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"07\">\r\n" + //$NON-NLS-1$
- " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"08\">\r\n" + //$NON-NLS-1$
- " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"09\">\r\n" + //$NON-NLS-1$
- " <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"10\">\r\n" + //$NON-NLS-1$
- " <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- "</OrgHierarchy>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc12", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testRecursiveA() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<OrgHierarchy>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"01\">\r\n" + //$NON-NLS-1$
- " <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Subordinate ID=\"02\">\r\n" + //$NON-NLS-1$
- " <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Subordinate ID=\"04\">\r\n" + //$NON-NLS-1$
- " <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Subordinate ID=\"06\">\r\n" + //$NON-NLS-1$
- " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Zorn</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Subordinate ID=\"11\">\r\n" + //$NON-NLS-1$
- " <FirstName>Mike</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Patton</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Subordinate ID=\"13\">\r\n" + //$NON-NLS-1$
- " <FirstName>Puffy</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Bordin</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Subordinate>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Subordinate>\r\n" + //$NON-NLS-1$
- " <Subordinate ID=\"12\">\r\n" + //$NON-NLS-1$
- " <FirstName>Devin</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Townsend</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Subordinate>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Subordinate>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Subordinate>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Subordinate>\r\n" + //$NON-NLS-1$
- " <Subordinate ID=\"03\">\r\n" + //$NON-NLS-1$
- " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Subordinate ID=\"05\">\r\n" + //$NON-NLS-1$
- " <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Subordinate>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Subordinate>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"07\">\r\n" + //$NON-NLS-1$
- " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Subordinate ID=\"08\">\r\n" + //$NON-NLS-1$
- " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Subordinate ID=\"09\">\r\n" + //$NON-NLS-1$
- " <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Subordinate>\r\n" + //$NON-NLS-1$
- " <Subordinate ID=\"10\">\r\n" + //$NON-NLS-1$
- " <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Subordinate>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Subordinate>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- "</OrgHierarchy>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc12a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * 4/25/05 sbale - This failing test raises a question about recursion
- * termination criteria - should the chunk of document that meets the
- * criteria be included or not? In this test below, it is expected to
- * be included, but is not included in actual results due to recent
- * changes for Booz Allen POC. I could see it going either way.
- *
- * sbale 4/27/05 I have changed expected results as a result of changes for
- * Booz Allen POC. Previously, the recursive fragment of the document that
- * satisfied the recursion termination criteria was included, now it is not.
- * See commented out section below for previous expected results.
- * @throws Exception
- */
- @Test public void testRecursive2() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<OrgHierarchy>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"01\">\r\n" + //$NON-NLS-1$
- " <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"02\">\r\n" + //$NON-NLS-1$
- " <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
-// " <Subordinates>\r\n" + //$NON-NLS-1$
-// " <Employee ID=\"04\">\r\n" + //$NON-NLS-1$
-// " <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
-// " <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
-// " <Subordinates/>\r\n" + //$NON-NLS-1$
-// " </Employee>\r\n" + //$NON-NLS-1$
-// " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"03\">\r\n" + //$NON-NLS-1$
- " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"05\">\r\n" + //$NON-NLS-1$
- " <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"07\">\r\n" + //$NON-NLS-1$
- " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"08\">\r\n" + //$NON-NLS-1$
- " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"09\">\r\n" + //$NON-NLS-1$
- " <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"10\">\r\n" + //$NON-NLS-1$
- " <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- "</OrgHierarchy>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc13", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
- @Test public void testRecursive3() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<OrgHierarchy>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"01\">\r\n" + //$NON-NLS-1$
- " <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"02\">\r\n" + //$NON-NLS-1$
- " <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"04\">\r\n" + //$NON-NLS-1$
- " <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"03\">\r\n" + //$NON-NLS-1$
- " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"05\">\r\n" + //$NON-NLS-1$
- " <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"07\">\r\n" + //$NON-NLS-1$
- " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"08\">\r\n" + //$NON-NLS-1$
- " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"09\">\r\n" + //$NON-NLS-1$
- " <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"10\">\r\n" + //$NON-NLS-1$
- " <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- "</OrgHierarchy>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc14", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testRecursive4Exception() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- helpTestProcess("SELECT * FROM xmltest.doc15", null, metadata, dataMgr, TeiidComponentException.class); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Seems to be failing as a result of changes for defect 12288
- */
- @Test public void testRecursive5() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Employees>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"08\">\r\n" + //$NON-NLS-1$
- " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
- " <Supervisor ID=\"07\">\r\n" + //$NON-NLS-1$
- " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
- " </Supervisor>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"09\">\r\n" + //$NON-NLS-1$
- " <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
- " <Supervisor ID=\"08\">\r\n" + //$NON-NLS-1$
- " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
- " <Supervisor ID=\"07\">\r\n" + //$NON-NLS-1$
- " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
- " </Supervisor>\r\n" + //$NON-NLS-1$
- " </Supervisor>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"10\">\r\n" + //$NON-NLS-1$
- " <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
- " <Supervisor ID=\"08\">\r\n" + //$NON-NLS-1$
- " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
- " <Supervisor ID=\"07\">\r\n" + //$NON-NLS-1$
- " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
- " </Supervisor>\r\n" + //$NON-NLS-1$
- " </Supervisor>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- "</Employees>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc16", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * sbale 4/27/05 I have changed expected results as a result of changes for
- * Booz Allen POC. Previously, the recursive fragment of the document that
- * satisfied the recursion termination criteria was included, now it is not.
- * See commented out section below for previous expected results.
- * @throws Exception
- */
- @Test public void testRecursiveWithStagingTable_defect15607() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<OrgHierarchy>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"01\">\r\n" + //$NON-NLS-1$
- " <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"02\">\r\n" + //$NON-NLS-1$
- " <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
-// " <Subordinates>\r\n" + //$NON-NLS-1$
-// " <Employee ID=\"04\">\r\n" + //$NON-NLS-1$
-// " <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
-// " <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
-// " <Subordinates/>\r\n" + //$NON-NLS-1$
-// " </Employee>\r\n" + //$NON-NLS-1$
-// " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"03\">\r\n" + //$NON-NLS-1$
- " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"05\">\r\n" + //$NON-NLS-1$
- " <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"07\">\r\n" + //$NON-NLS-1$
- " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"08\">\r\n" + //$NON-NLS-1$
- " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"09\">\r\n" + //$NON-NLS-1$
- " <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee ID=\"10\">\r\n" + //$NON-NLS-1$
- " <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
- " <Subordinates/>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Subordinates>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- "</OrgHierarchy>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc19", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * Tests a recursive nested mapping class within a recursive mapping class, where
- * all nested "anchor" nodes are named "srcNestedRecursive". Test of defect #5988
- */
- @Test public void testXQTRecursive_5988() throws Exception {
- FakeMetadataFacade metadata = exampleMetadata2();
- FakeDataManager dataMgr = exampleXQTDataManager(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<recursiveTest>\r\n" + //$NON-NLS-1$
- " <src>\r\n" + //$NON-NLS-1$
- " <key>13</key>\r\n" + //$NON-NLS-1$
- " <data>10</data>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>10</key>\r\n" + //$NON-NLS-1$
- " <data>7</data>\r\n" + //$NON-NLS-1$
- " <srcNestedRecursive>\r\n" + //$NON-NLS-1$
- " <key>7</key>\r\n" + //$NON-NLS-1$
- " <data>4</data>\r\n" + //$NON-NLS-1$
- " <srcNestedRecursive>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcNestedRecursive>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcNestedRecursive>\r\n" + //$NON-NLS-1$
- " </srcNestedRecursive>\r\n" + //$NON-NLS-1$
- " </srcNestedRecursive>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " <srcRecursive>\r\n" + //$NON-NLS-1$
- " <key>10</key>\r\n" + //$NON-NLS-1$
- " <data>7</data>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>7</key>\r\n" + //$NON-NLS-1$
- " <data>4</data>\r\n" + //$NON-NLS-1$
- " <srcNestedRecursive>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcNestedRecursive>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcNestedRecursive>\r\n" + //$NON-NLS-1$
- " </srcNestedRecursive>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " <srcRecursive>\r\n" + //$NON-NLS-1$
- " <key>7</key>\r\n" + //$NON-NLS-1$
- " <data>4</data>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcNestedRecursive>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcNestedRecursive>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " <srcRecursive>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " <srcRecursive>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcRecursive>\r\n" + //$NON-NLS-1$
- " </srcRecursive>\r\n" + //$NON-NLS-1$
- " </srcRecursive>\r\n" + //$NON-NLS-1$
- " </srcRecursive>\r\n" + //$NON-NLS-1$
- " </src>\r\n" + //$NON-NLS-1$
- "</recursiveTest>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xqttest.doc1", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * Tests a non-recursive nested mapping class within a recursive mapping class, where
- * all nested "anchor" nodes are named "srcNested". Test of defect #5988
- */
- public void DEFER_testXQTRecursive1a_5988() throws Exception {
- FakeMetadataFacade metadata = exampleMetadata2();
- FakeDataManager dataMgr = exampleXQTDataManager(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<recursiveTest>\r\n" + //$NON-NLS-1$
- " <src>\r\n" + //$NON-NLS-1$
- " <key>13</key>\r\n" + //$NON-NLS-1$
- " <data>10</data>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>10</key>\r\n" + //$NON-NLS-1$
- " <data>7</data>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>10</key>\r\n" + //$NON-NLS-1$
- " <data>7</data>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>7</key>\r\n" + //$NON-NLS-1$
- " <data>4</data>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>7</key>\r\n" + //$NON-NLS-1$
- " <data>4</data>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " </src>\r\n" + //$NON-NLS-1$
- "</recursiveTest>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xqttest.doc1a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * Tests a non-recursive nested mapping class within a recursive mapping class, where
- * all nested "anchor" nodes are named "srcNested". Test of defect #5988
- */
- @Test public void testXQTRecursive2_5988() throws Exception {
- FakeMetadataFacade metadata = exampleMetadata2();
- FakeDataManager dataMgr = exampleXQTDataManager(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<recursiveTest>\r\n" + //$NON-NLS-1$
- " <src>\r\n" + //$NON-NLS-1$
- " <key>13</key>\r\n" + //$NON-NLS-1$
- " <data>10</data>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>10</key>\r\n" + //$NON-NLS-1$
- " <data>7</data>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>10</key>\r\n" + //$NON-NLS-1$
- " <data>7</data>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>7</key>\r\n" + //$NON-NLS-1$
- " <data>4</data>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>7</key>\r\n" + //$NON-NLS-1$
- " <data>4</data>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " <srcNested>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " </srcNested>\r\n" + //$NON-NLS-1$
- " </src>\r\n" + //$NON-NLS-1$
- "</recursiveTest>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xqttest.doc3", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
-
- /**
- * for defect 5988
- */
- @Test public void testXQTRecursiveSiblings_5988() throws Exception {
- FakeMetadataFacade metadata = exampleMetadata2();
- FakeDataManager dataMgr = exampleXQTDataManager(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<recursiveTest>\r\n" + //$NON-NLS-1$
- " <src>\r\n" + //$NON-NLS-1$
- " <key>13</key>\r\n" + //$NON-NLS-1$
- " <data>10</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>10</key>\r\n" + //$NON-NLS-1$
- " <data>7</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>7</key>\r\n" + //$NON-NLS-1$
- " <data>4</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>7</key>\r\n" + //$NON-NLS-1$
- " <data>4</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>10</key>\r\n" + //$NON-NLS-1$
- " <data>7</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>7</key>\r\n" + //$NON-NLS-1$
- " <data>4</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>7</key>\r\n" + //$NON-NLS-1$
- " <data>4</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>4</key>\r\n" + //$NON-NLS-1$
- " <data>1</data>\r\n" + //$NON-NLS-1$
- " <srcSibling1>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling1>\r\n" + //$NON-NLS-1$
- " <srcSibling2>\r\n" + //$NON-NLS-1$
- " <key>1</key>\r\n" + //$NON-NLS-1$
- " <data>-2</data>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </srcSibling2>\r\n" + //$NON-NLS-1$
- " </src>\r\n" + //$NON-NLS-1$
- "</recursiveTest>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xqttest.doc2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testSelectElement1() 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>\r\n" + //$NON-NLS-1$
- " <Name>Lamp</Name>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Name>Goat</Name>\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 Name FROM xmltest.doc1", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testSelectElement2() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 SupplierID, OrderID, ItemID, OrderQuantity FROM xmltest.doc9 ORDER BY "+ //$NON-NLS-1$
- " Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC," + //$NON-NLS-1$
- " OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** select element in the reverse order of depth*/
- @Test public void testSelectElement3() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 OrderQuantity, SupplierID, ItemID, OrderID FROM xmltest.doc9" + //$NON-NLS-1$
- " ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC," + //$NON-NLS-1$
- " OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** two select elements at the same level*/
- @Test public void testSelectElement4() 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 ItemID, Name, Quantity FROM xmltest.doc1 WHERE ItemID='001' OR " //$NON-NLS-1$
- + " ItemID='002' OR ItemID='003' ORDER BY ItemID", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** defect 9756 */
- @Test public void testSelectElement4_defect9756() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Item ItemID=\"002\"/>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\"/>\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 Catalogs.Catalog.Items.Item. at ItemID FROM xmltest.doc1", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** 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();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 OrderQuantity, SupplierID, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Name, OrderID, ItemID " //$NON-NLS-1$
- + "FROM xmltest.doc9 ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, " //$NON-NLS-1$
- + "OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** check element.* case */
- @Test public void testSelectElement6() 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 Item.* FROM xmltest.doc1 ORDER BY ItemID", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** check element.* case without attribute in order by*/
- @Test public void testSelectElement6a() 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>\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>\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>\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 Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Quantity" //$NON-NLS-1$
- + " FROM xmltest.doc1", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testSelectElement7() 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 Catalogs.Catalog.Items.Item.* FROM xmltest.doc1 ORDER BY ItemID", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testSelectElement8() 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 xmltest.doc1.Catalogs.Catalog.Items.Item.* FROM xmltest.doc1 ORDER BY ItemID", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** SELECT clause has element.*, but the sibling elements should not be included, only subtree should */
- @Test public void testSelectElement9() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 Catalogs.Catalog.Items.Item.Suppliers.Supplier.* FROM xmltest.doc9 " //$NON-NLS-1$
- + "WHERE ItemID='002' AND Context(Supplier,OrderID)='5' ", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testSelectElement9a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 Catalogs.Catalog.Items.Item.Suppliers.Supplier.* FROM xmltest.doc9 " //$NON-NLS-1$
- + "WHERE ItemID='002' AND Context(Supplier,OrderID)='5' AND Context(OrderID, OrderID)='5'", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** check element.* case with criteria and order by clause */
- @Test public void testSelectElement10() 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 Item.* FROM xmltest.doc1 WHERE Quantity <= 100 ORDER BY ItemID", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testSelectElement12() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 Supplier.*, ItemID FROM xmltest.doc9 " //$NON-NLS-1$
- + " WHERE ItemID='002'" //$NON-NLS-1$
- + " ORDER BY SupplierID, OrderID DESC, ItemID", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testSelectElement13() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(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>\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$
- " </Items>\r\n" + //$NON-NLS-1$
- " </Catalog>\r\n" + //$NON-NLS-1$
- "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT Name, Quantity FROM xmltest.doc1 " //$NON-NLS-1$
- + "WHERE ItemID='002'" //$NON-NLS-1$
- + "ORDER BY Name ", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testSelectElement14() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc9 WHERE ItemID='002' AND Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderQuantity < 1000" //$NON-NLS-1$
- + " ORDER By SupplierID ASC, OrderID ", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testSelectElement15() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 Supplier.* FROM xmltest.doc9 " //$NON-NLS-1$
- + " WHERE ItemID='002'" //$NON-NLS-1$
- + " ORDER By SupplierID ", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testSelectElement16() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 Supplier.* FROM xmltest.doc9a " //$NON-NLS-1$
- + " WHERE ItemID='002'" //$NON-NLS-1$
- + " ORDER By SupplierID", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** CSE query 0 */
- @Test public void testSelectElement17() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <Name>KMart</Name>\r\n" + //$NON-NLS-1$
- " <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <Name>Sun</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <Name>Doc</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
- " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
- " <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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.doc9c ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** CSE query 1 */
- @Test public void testSelectElement18() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
- " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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.doc9c WHERE ItemID='002'", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** CSE query 2 */
- @Test public void testSelectElement19() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
- " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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.doc9c WHERE Catalogs.Catalog.Items.Item.Name='Screwdriver'", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
-
- /** CSE query 3 */
- @Test public void testSelectElement20() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 ItemID, Catalogs.Catalog.Items.Item.Quantity, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Zip" + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE Catalogs.Catalog.Items.Item.Name='Screwdriver'", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** CSE query 3a */
- @Test public void testSelectElement20a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order>\r\n" + //$NON-NLS-1$
- " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order>\r\n" + //$NON-NLS-1$
- " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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 ItemID, Catalogs.Catalog.Items.Item.Quantity, Catalogs.Catalog.Items.Item.Orders.Order.Zip" + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE Catalogs.Catalog.Items.Item.Name='Screwdriver'", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** CSE query 4 */
- @Test public void testSelectElement21() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <Name>KMart</Name>\r\n" + //$NON-NLS-1$
- " <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <Name>Sun</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <Name>Doc</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
- " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
- " <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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 * " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE SupplierID > '54' AND context(SupplierID, SupplierID)>'54' ", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** CSE query 4a */
- @Test public void testSelectElement21a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
- " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
- " <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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 * " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE OrderID > '4' AND context(OrderID, OrderID)>'4'", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** CSE query 5 */
- @Test public void testSelectElement22() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 ItemID, Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Zip " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE SupplierID > '4' ", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** CSE query 5a */
- @Test public void testSelectElement22a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <Name>KMart</Name>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <Name>Sun</Name>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <Name>Doc</Name>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
- " <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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 ItemID, Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Orders.Order.Name, OrderID " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE OrderID > '3' ", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** CSE query 6 */
- @Test public void testSelectElement23() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Name>Goat</Name>\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Name, SupplierID " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE OrderID > '4' ", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** CSE query 6a */
- @Test public void testSelectElement23a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\"/>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\"/>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\"/>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"7\"/>\r\n" + //$NON-NLS-1$
- " </Orders>\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 Catalogs.Catalog.Items.Item.ItemID, OrderID " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE SupplierID > '54' ", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** 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();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"7\"/>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\"/>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\"/>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\"/>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
- " </Orders>\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 Catalogs.Catalog.Items.Item.ITEMID, OrderID " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE SupplierID > '54' " + //$NON-NLS-1$
- " ORDER BY ItemID DESC, OrderID DESC", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** 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();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
- " <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
- " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <Name>Doc</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <Name>Sun</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <Name>KMart</Name>\r\n" + //$NON-NLS-1$
- " <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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 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$
- expectedDoc, metadata, dataMgr);
- }
-
- /** test with order by with only necessary sub-mapping classes are queried*/
- @Test public void testSelectElement25() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\"/>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\"/>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\"/>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\"/>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\"/>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\"/>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\"/>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\"/>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 ItemID, SupplierID " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE SupplierID > '54' " + //$NON-NLS-1$
- " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** test element.* with order by with only necessary sub-mapping classes are queried*/
- @Test public void testSelectElement25a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 ItemID, Supplier.* " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE SupplierID > '54' " + //$NON-NLS-1$
- " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** Test element.* with order by with only necessary sub-mapping classes are queried
- * and case_insensitive nodes in the mapping tree
- */
- @Test public void testSelectElement25b() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 ItemID, SUPPLIER.* " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE SupplierID > '54' " + //$NON-NLS-1$
- " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testSelectElement26() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 ItemID, xmltest.doc9c.catalogs.catalog.items.item.suppliers.SUPPLIER.* " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE SupplierID > '54' " + //$NON-NLS-1$
- " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** test special elements: result set name, and name with format of "document.fully.qualified.element"
- * --> refer to Defect9497, this should fail
- */
- @Test public void testSelectElement27() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier/>\r\n" + //$NON-NLS-1$
- " <Supplier/>\r\n" + //$NON-NLS-1$
- " <Supplier/>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 doc9c.catalogs.catalog.items.item.itemID, items.item.name, item.Quantity, supplier " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE doc9c.catalogs.catalog.items.item.suppliers.supplier.SupplierID > '54' AND itemID='002'" + //$NON-NLS-1$
- " ORDER BY doc9c.catalogs.catalog.items.item.ITEMid ", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** test special element, root element */
- @Test public void testSelectElement28() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs/>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT catalogs " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
-
- /*String expectedDoc = "";
- try {
- helpTestProcess("SELECT catalogs " +
- " FROM xmltest.doc9c " +
- " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'",
- expectedDoc, metadata, dataMgr);
- } catch(QueryPlannerException qpe) {
- // ok, as expected
- } */
- }
-
- /** test special element */
- @Test public void testSelectElement28a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog/>\r\n" + //$NON-NLS-1$
- "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
- /*String expectedDoc = "";
- try {
- helpTestProcess("SELECT catalog " +
- " FROM xmltest.doc9c " +
- " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'",
- expectedDoc, metadata, dataMgr, false);
- } catch (QueryPlannerException qpe) {
- // ok, as expected
- } */
-
- helpTestProcess("SELECT catalog " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** test model.document.* */
- @Test public void testSelectElement28b() 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 xmltest.doc1.* " + //$NON-NLS-1$
- "FROM xmltest.doc1 ORDER BY ItemID ", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
-
- }
-
- /** test special element, root element */
- @Test public void testSelectElement29() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs/>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT xmltest.doc9c.catalogs " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
-
- /*String expectedDoc = "";
- try {
- helpTestProcess("SELECT xmltest.doc9c.catalogs " +
- " FROM xmltest.doc9c " +
- " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'",
- expectedDoc, metadata, dataMgr);
- } catch (QueryPlannerException qpe) {
- // ok, as expected
- }*/
-
- }
-
- /** test simple case for two elements in a mapping class */
- @Test public void testSelectElement30() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(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$
- " </Items>\r\n" + //$NON-NLS-1$
- " </Catalog>\r\n" + //$NON-NLS-1$
- "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT item.* FROM xmltest.doc1 WHERE ItemID='001' AND Quantity < 60 ORDER BY ItemID", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** test NullPointerException*/
- @Test public void testDefect_9496_1() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 items.item.ItemID, suppliers.supplier.* " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE item.suppliers.supplier.SupplierID > '54' " + //$NON-NLS-1$
- " ORDER BY ITEMid DESC, items.item.suppliers.supplier.SupplierID DESC", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testDefect_9496_2() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier>\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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 doc9c.Catalogs.catalog.items.item.ItemID, items.item.Suppliers,SuppliER.Name " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE SupplierID > '54' " + //$NON-NLS-1$
- " ORDER BY ItemID DESC", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** test StringIndexOutOfBoundsException */
- @Test public void testDefect_9496_3() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <Name>KMart</Name>\r\n" + //$NON-NLS-1$
- " <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <Name>Sun</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <Name>Doc</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
- " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
- " <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
- " <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\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 item.itemID, items.item.* " + //$NON-NLS-1$
- " FROM xmltest.doc9c " + //$NON-NLS-1$
- " WHERE item.suppliers.supplier.SupplierID > '54' " + //$NON-NLS-1$
- " ORDER BY ITEMid, items.item.suppliers.supplier.SupplierID ", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- /** should fail: because there are other element other than "xml" */
- /*@Test public void testResolver1() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc = "";
-
- boolean shouldSucceed = false;
- Class expectedException = QueryResolverException.class;
- String shouldFailMsg = "If any symbol in SELECT clause is 'xml' or group.'xml' , then no other element is allowed.";
-
- helpTestProcess("SELECT xml, ItemID " +
- " FROM xmltest.doc9c " +
- " WHERE SupplierID > '54' " +
- " ORDER BY ItemID DESC", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);
- }*/
-
- /** should fail: partial qualified element name and "model.document.xml" */
- /*@Test public void testResolver2() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc = "";
-
- boolean shouldSucceed = false;
- Class expectedException = QueryResolverException.class;
- String shouldFailMsg = "If any symbol in SELECT clause is 'xml' or group.'xml' , then no other element is allowed.";
-
- helpTestProcess("SELECT item.ItemID, xmltest.doc9c.xml " +
- " FROM xmltest.doc9c " +
- " WHERE SupplierID > '54' " +
- " ORDER BY ItemID DESC", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);
- }*/
-
- /** should fail: test XMLResolver validatation for model.* */
- /*@Test public void testDefect_9498_1() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc = "";
-
- boolean shouldSucceed = false;
- Class expectedException = QueryResolverException.class;
- String shouldFailMsg = "Unable to resolve element: xmltest";
-
- helpTestProcess("SELECT xmltest.* FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);
- }*/
-
- /** should fail: test XMLResolver validatation for model.document.* */
- /*@Test public void testDefect_9498_2() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc = "";
-
- boolean shouldSucceed = false;
- Class expectedException = QueryResolverException.class;
- String shouldFailMsg = "Unable to resolve element: xmltest.doc9c";
-
- helpTestProcess("SELECT xmltest.doc9c.* FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);
- }*/
-
- /** should fail: test XMLResolver validatation for xml.* */
- /*@Test public void testDefect_9498_3() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc = "";
-
- boolean shouldSucceed = false;
- Class expectedException = QueryResolverException.class;
- String shouldFailMsg = "Unable to resolve element: xml";
-
- helpTestProcess("SELECT xml.* FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);
- }*/
-
- /** Test element.* with order by with only necessary sub-mapping classes are queried
- * and case_insensitive nodes in the mapping tree
- */
- @Test public void testCommentNodeInDoc() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Root><!--Comment1--><Something><!--Comment2--></Something>\r\n" + //$NON-NLS-1$
- "</Root>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc17", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- private static final String EXPECTED_DOC_DEFECT_8917_AND_11789 =
- "<?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 xsi:nil=\"true\"/>\r\n" + //$NON-NLS-1$
- " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " </Items>\r\n" + //$NON-NLS-1$
- " </Catalog>\r\n" + //$NON-NLS-1$
- " <OptionalCatalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Name xsi:nil=\"true\"/>\r\n" + //$NON-NLS-1$
- " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " </Items>\r\n" + //$NON-NLS-1$
- " </OptionalCatalog>\r\n" + //$NON-NLS-1$
- " <OptionalCatalog2>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Name xsi:nil=\"true\"/>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " </Items>\r\n" + //$NON-NLS-1$
- " </OptionalCatalog2>\r\n" + //$NON-NLS-1$
- " <Catalog4/>\r\n" + //$NON-NLS-1$
- " <Catalog5>\r\n" + //$NON-NLS-1$
- " <OptionalItems>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <FixedName>Nugent</FixedName>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " </OptionalItems>\r\n" + //$NON-NLS-1$
- " </Catalog5>\r\n" + //$NON-NLS-1$
- " <Catalog6/>\r\n" + //$NON-NLS-1$
- "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
- @Test public void testDefect8917() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager_8917(metadata);
-
-// helpTestProcess("SELECT * FROM xmltest.doc_8917 WHERE Catalog.Items.Item.ItemID = '001'",
- helpTestProcess("SELECT * FROM xmltest.doc_8917", //$NON-NLS-1$
- EXPECTED_DOC_DEFECT_8917_AND_11789, metadata, dataMgr);
- }
- /*
- * jhTODO
- */
- @Test public void testNillableOptional() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
- "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + //$NON-NLS-1$
- "<Catalog>" + //$NON-NLS-1$
- "<Items xsi:nil=\"true\"/>" + //$NON-NLS-1$
- "</Catalog>" + //$NON-NLS-1$
- "</Catalogs>"; //$NON-NLS-1$
-
- // note: doc1b contains an 'items' element that is nillable = true, and minoccurs = 0
- helpTestProcess("SELECT * FROM xmltest.doc1b WHERE ItemID='9999' ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /*
- * jhTODO
- */
- @Test public void testNillableNonOptional() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
- "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + //$NON-NLS-1$
- "<Catalog>" + //$NON-NLS-1$
- "<Items xsi:nil=\"true\"/>" + //$NON-NLS-1$
- "</Catalog>" + //$NON-NLS-1$
- "</Catalogs>"; //$NON-NLS-1$
-
- // note: doc1c contains an 'items' element that has no nillable set, and minoccurs = 1
- helpTestProcess("SELECT * FROM xmltest.doc1c WHERE ItemID='9999' ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * Related to defect 8917
- * The expected result is slightly different because the data has a
- * NON-empty whitespace string, which will NOT be treated as null
- * see also defect 15117
- */
- @Test public void testDefect11789() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager_8917a(metadata);
-
- String expected =
- "<?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> </Name>\r\n" + //$NON-NLS-1$
- " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " </Items>\r\n" + //$NON-NLS-1$
- " </Catalog>\r\n" + //$NON-NLS-1$
- " <OptionalCatalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Name> </Name>\r\n" + //$NON-NLS-1$
- " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " </Items>\r\n" + //$NON-NLS-1$
- " </OptionalCatalog>\r\n" + //$NON-NLS-1$
- " <OptionalCatalog2>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Name> </Name>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " </Items>\r\n" + //$NON-NLS-1$
- " </OptionalCatalog2>\r\n" + //$NON-NLS-1$
- " <OptionalCatalog3>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Name> </Name>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " </Items>\r\n" + //$NON-NLS-1$
- " </OptionalCatalog3>\r\n" + //$NON-NLS-1$
- " <Catalog4>\r\n" + //$NON-NLS-1$
- " <OptionalItems>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Name> </Name>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " </OptionalItems>\r\n" + //$NON-NLS-1$
- " </Catalog4>\r\n" + //$NON-NLS-1$
- " <Catalog5>\r\n" + //$NON-NLS-1$
- " <OptionalItems>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <FixedName>Nugent</FixedName>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " </OptionalItems>\r\n" + //$NON-NLS-1$
- " </Catalog5>\r\n" + //$NON-NLS-1$
- " <Catalog6/>\r\n" + //$NON-NLS-1$
- "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc_8917", //$NON-NLS-1$
- expected, metadata, dataMgr);
- }
-
- /**
- * Related to defect 8917 - the result should be the same as
- * testDefect8917
- */
- @Test public void testDefect11789b() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager_8917b(metadata);
-
- helpTestProcess("SELECT * FROM xmltest.doc_8917", //$NON-NLS-1$
- EXPECTED_DOC_DEFECT_8917_AND_11789, metadata, dataMgr);
- }
-
- @Test public void testDefect9446() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager_8917(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item XXXXX=\"001\">\r\n" + //$NON-NLS-1$
- " <XXXXX/>\r\n" + //$NON-NLS-1$
- " <XXXXX>5</XXXXX>\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.doc_8917 WHERE Catalog.Items.Item.ItemID = '001'",
- helpTestProcess("SELECT * FROM xmltest.doc_9446", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testDefect9446_2() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager_8917(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\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.doc_9446 WHERE Catalogs.Catalog.Items.Item.XXXXX = '001'", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testDefect_9530() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<mm:Catalogs xmlns:mm=\"http://www.duh.org/duh\">\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <mm:Item xmlns:mm2=\"http://www.duh3.org/duh3\" xmlns:mm=\"http://www.duh2.org/duh2\"\r\n" + //$NON-NLS-1$
- " ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <Name>Lamp</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
- " </mm:Item>\r\n" + //$NON-NLS-1$
- " <mm:Item xmlns:mm2=\"http://www.duh3.org/duh3\" xmlns:mm=\"http://www.duh2.org/duh2\"\r\n" + //$NON-NLS-1$
- " ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
- " </mm:Item>\r\n" + //$NON-NLS-1$
- " <mm:Item xmlns:mm2=\"http://www.duh3.org/duh3\" xmlns:mm=\"http://www.duh2.org/duh2\"\r\n" + //$NON-NLS-1$
- " ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Name>Goat</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>4</Quantity>\r\n" + //$NON-NLS-1$
- " </mm:Item>\r\n" + //$NON-NLS-1$
- " </Items>\r\n" + //$NON-NLS-1$
- " </Catalog>\r\n" + //$NON-NLS-1$
- "</mm:Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc_9530", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testSubqueryInXMLQueryCriteria() 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" +
-// " <Name>Screwdriver</Name>\r\n" +
-// " <Quantity>100</Quantity>\r\n" +
-// " </Item>\r\n" +
-// " <Item ItemID=\"003\">\r\n" +
-// " <Name>Goat</Name>\r\n" +
-// " <Quantity>4</Quantity>\r\n" +
-// " </Item>\r\n" +
- " </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 ItemID IN (SELECT itemNum FROM stock.items WHERE itemNum = '001')", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryInXMLQueryCriteria2() 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" +
-// " <Name>Lamp</Name>\r\n" +
-// " <Quantity>5</Quantity>\r\n" +
-// " </Item>\r\n" +
- " <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 ItemID > ANY (SELECT itemNum FROM stock.items WHERE itemNum IN ('001','002') )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryInXMLQueryCriteria3() 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" +
-// " <Name>Lamp</Name>\r\n" +
-// " <Quantity>5</Quantity>\r\n" +
-// " </Item>\r\n" +
- " <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 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();
- 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" +
-// " <Name>Lamp</Name>\r\n" +
-// " <Quantity>5</Quantity>\r\n" +
-// " </Item>\r\n" +
- " <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 ItemID > ANY (SELECT itemNum FROM stock.items WHERE itemNum IN (SELECT itemNum FROM stock.items WHERE itemNum IN ('001','002') ) )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
-// " <Item ItemID=\"001\">\r\n" +
-// " <Name>Lamp</Name>\r\n" +
-// " <Quantity>5</Quantity>\r\n" +
-// " <Suppliers>\r\n" +
-// " <Supplier SupplierID=\"51\">\r\n" +
-// " <Name>Chucky</Name>\r\n" +
-// " <Zip>11111</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " <Supplier SupplierID=\"52\">\r\n" +
-// " <Name>Biff's Stuff</Name>\r\n" +
-// " <Zip>22222</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " <Supplier SupplierID=\"53\">\r\n" +
-// " <Name>AAAA</Name>\r\n" +
-// " <Zip>33333</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " <Supplier SupplierID=\"56\">\r\n" +
-// " <Name>Microsoft</Name>\r\n" +
-// " <Zip>66666</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " </Suppliers>\r\n" +
-// " </Item>\r\n" +
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8 WHERE ItemID > ANY (SELECT itemNum FROM stock.items WHERE itemNum IN ('001','002') )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass2() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8 WHERE SupplierID > ANY (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('53','54') )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass3() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
-// " <Item ItemID=\"002\">\r\n" +
-// " <Name>Screwdriver</Name>\r\n" +
-// " <Quantity>100</Quantity>\r\n" +
-// " <Suppliers>\r\n" +
-// " <Supplier SupplierID=\"54\">\r\n" +
-// " <Name>Nugent Co.</Name>\r\n" +
-// " <Zip>44444</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " <Supplier SupplierID=\"55\">\r\n" +
-// " <Name>Zeta</Name>\r\n" +
-// " <Zip>55555</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " <Supplier SupplierID=\"56\">\r\n" +
-// " <Name>Microsoft</Name>\r\n" +
-// " <Zip>66666</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " </Suppliers>\r\n" +
-// " </Item>\r\n" +
-// " <Item ItemID=\"003\">\r\n" +
-// " <Name>Goat</Name>\r\n" +
-// " <Quantity>4</Quantity>\r\n" +
-// " <Suppliers>\r\n" +
-// " <Supplier SupplierID=\"56\">\r\n" +
-// " <Name>Microsoft</Name>\r\n" +
-// " <Zip>66666</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " </Suppliers>\r\n" +
-// " </Item>\r\n" +
- " </Items>\r\n" + //$NON-NLS-1$
- " </Catalog>\r\n" + //$NON-NLS-1$
- "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID < ALL (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('52','54') )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass3a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
-// " <Item ItemID=\"002\">\r\n" +
-// " <Name>Screwdriver</Name>\r\n" +
-// " <Quantity>100</Quantity>\r\n" +
-// " <Suppliers>\r\n" +
-// " <Supplier SupplierID=\"54\">\r\n" +
-// " <Name>Nugent Co.</Name>\r\n" +
-// " <Zip>44444</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " <Supplier SupplierID=\"55\">\r\n" +
-// " <Name>Zeta</Name>\r\n" +
-// " <Zip>55555</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " <Supplier SupplierID=\"56\">\r\n" +
-// " <Name>Microsoft</Name>\r\n" +
-// " <Zip>66666</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " </Suppliers>\r\n" +
-// " </Item>\r\n" +
-// " <Item ItemID=\"003\">\r\n" +
-// " <Name>Goat</Name>\r\n" +
-// " <Quantity>4</Quantity>\r\n" +
-// " <Suppliers>\r\n" +
-// " <Supplier SupplierID=\"56\">\r\n" +
-// " <Name>Microsoft</Name>\r\n" +
-// " <Zip>66666</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " </Suppliers>\r\n" +
-// " </Item>\r\n" +
- " </Items>\r\n" + //$NON-NLS-1$
- " </Catalog>\r\n" + //$NON-NLS-1$
- "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID IN (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('52') )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
-
- @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass4() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
-// " <Supplier SupplierID=\"56\">\r\n" +
-// " <Name>Microsoft</Name>\r\n" +
-// " <Zip>66666</Zip>\r\n" +
-// " </Supplier>\r\n" +
- " </Suppliers>\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$
- " <Suppliers/>\r\n" + //$NON-NLS-1$
-// " <Suppliers>\r\n" +
-// " <Supplier SupplierID=\"54\">\r\n" +
-// " <Name>Nugent Co.</Name>\r\n" +
-// " <Zip>44444</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " <Supplier SupplierID=\"55\">\r\n" +
-// " <Name>Zeta</Name>\r\n" +
-// " <Zip>55555</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " <Supplier SupplierID=\"56\">\r\n" +
-// " <Name>Microsoft</Name>\r\n" +
-// " <Zip>66666</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " </Suppliers>\r\n" +
- " </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$
- " <Suppliers/>\r\n" + //$NON-NLS-1$
-// " <Suppliers>\r\n" +
-// " <Supplier SupplierID=\"56\">\r\n" +
-// " <Name>Microsoft</Name>\r\n" +
-// " <Zip>66666</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " </Suppliers>\r\n" +
- " </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.doc8 WHERE context(SupplierID, SupplierID) < SOME (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('52','54') )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testCritNestedMappingClass() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
-// " <Item ItemID=\"002\">\r\n" +
-// " <Name>Screwdriver</Name>\r\n" +
-// " <Quantity>100</Quantity>\r\n" +
-// " <Suppliers>\r\n" +
-// " <Supplier SupplierID=\"54\">\r\n" +
-// " <Name>Nugent Co.</Name>\r\n" +
-// " <Zip>44444</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " <Supplier SupplierID=\"55\">\r\n" +
-// " <Name>Zeta</Name>\r\n" +
-// " <Zip>55555</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " <Supplier SupplierID=\"56\">\r\n" +
-// " <Name>Microsoft</Name>\r\n" +
-// " <Zip>66666</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " </Suppliers>\r\n" +
-// " </Item>\r\n" +
-// " <Item ItemID=\"003\">\r\n" +
-// " <Name>Goat</Name>\r\n" +
-// " <Quantity>4</Quantity>\r\n" +
-// " <Suppliers>\r\n" +
-// " <Supplier SupplierID=\"56\">\r\n" +
-// " <Name>Microsoft</Name>\r\n" +
-// " <Zip>66666</Zip>\r\n" +
-// " </Supplier>\r\n" +
-// " </Suppliers>\r\n" +
-// " </Item>\r\n" +
- " </Items>\r\n" + //$NON-NLS-1$
- " </Catalog>\r\n" + //$NON-NLS-1$
- "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID = '52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testDefect_9893() throws Exception{
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Root>\r\n" + //$NON-NLS-1$
- " <ItemName>Lamp</ItemName>\r\n" + //$NON-NLS-1$
- " <ItemName>Screwdriver</ItemName>\r\n" + //$NON-NLS-1$
- " <ItemName>Goat</ItemName>\r\n" + //$NON-NLS-1$
- "</Root>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.doc9893", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testDefect_9893_2() throws Exception{
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Root>\r\n" + //$NON-NLS-1$
- " <ItemName>Lamp</ItemName>\r\n" + //$NON-NLS-1$
- " <ItemName>Screwdriver</ItemName>\r\n" + //$NON-NLS-1$
- " <ItemName>Goat</ItemName>\r\n" + //$NON-NLS-1$
- "</Root>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT ItemName FROM xmltest.doc9893", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testDefect_9893_3() throws Exception{
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Root>\r\n" + //$NON-NLS-1$
- " <ItemName>Lamp</ItemName>\r\n" + //$NON-NLS-1$
- " <ItemName>Screwdriver</ItemName>\r\n" + //$NON-NLS-1$
- " <ItemName>Goat</ItemName>\r\n" + //$NON-NLS-1$
- "</Root>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT ItemName.* FROM xmltest.doc9893", //$NON-NLS-1$
- expectedDoc, metadata, dataMgr);
- }
-
- @Test public void testDefect_9893_4() throws Exception{
- FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
- FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item/>\r\n" + //$NON-NLS-1$
- " <Item/>\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$
-
- 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();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc18", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** homegenous, simple array elements */
- @Test public void testWithSOAPEncoding1() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataSoap1();
- FakeDataManager dataMgr = exampleDataManagerForSoap1(metadata, false);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<ORG:TaxReports xmlns:ORG=\"http://www.mm.org/dummy\">\r\n" + //$NON-NLS-1$
- " <ORG:TaxReport>\r\n" + //$NON-NLS-1$
- " <ORG:ArrayOfTaxID xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" + //$NON-NLS-1$
- " xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n" + //$NON-NLS-1$
- " xsi:type=\"ORG:ArrayOfTaxIDType\"\r\n" + //$NON-NLS-1$
- " SOAP-ENC:arrayType=\"ORG:TaxIDType[]\">\r\n" + //$NON-NLS-1$
- " <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" + //$NON-NLS-1$
- " <ID>1</ID>\r\n" + //$NON-NLS-1$
- " </ORG:TaxID>\r\n" + //$NON-NLS-1$
- " <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" + //$NON-NLS-1$
- " <ID>2</ID>\r\n" + //$NON-NLS-1$
- " </ORG:TaxID>\r\n" + //$NON-NLS-1$
- " <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" + //$NON-NLS-1$
- " <ID>3</ID>\r\n" + //$NON-NLS-1$
- " </ORG:TaxID>\r\n" + //$NON-NLS-1$
- " </ORG:ArrayOfTaxID>\r\n" + //$NON-NLS-1$
- " </ORG:TaxReport>\r\n" + //$NON-NLS-1$
- "</ORG:TaxReports>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.docSoap", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
-
- /**
- * if no data is contained in the soap elements
- * (e.g. ORG:ArrayOfTaxID) and the schema allows it, eliminate the
- * whole fragment
- */
- @Test public void testWithSOAPEncodingNoRows() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataSoap1();
- FakeDataManager dataMgr = exampleDataManagerForSoap1(metadata, true);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<ORG:TaxReports xmlns:ORG=\"http://www.mm.org/dummy\">\r\n" + //$NON-NLS-1$
- " <ORG:TaxReport/>\r\n" + //$NON-NLS-1$
-// " <ORG:TaxReport>\r\n" +
-// " <ORG:ArrayOfTaxID xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xsi:type=\"ORG:ArrayOfTaxIDType\" SOAP-ENC:arrayType=\"ORG:TaxIDType[]\">\r\n" +
-// " <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" +
-// " <ID>1</ID>\r\n" +
-// " </ORG:TaxID>\r\n" +
-// " <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" +
-// " <ID>2</ID>\r\n" +
-// " </ORG:TaxID>\r\n" +
-// " <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" +
-// " <ID>3</ID>\r\n" +
-// " </ORG:TaxID>\r\n" +
-// " </ORG:ArrayOfTaxID>\r\n" +
-// " </ORG:TaxReport>\r\n" +
- "</ORG:TaxReports>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xmltest.docSoap", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testDefect12260() throws Exception{
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <numSuppliers>4</numSuppliers>\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$
- " <numSuppliers>3</numSuppliers>\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$
- " <numSuppliers>1</numSuppliers>\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$
-
-
- // Set up capabilities to duplicate defect
- BasicSourceCapabilities caps = new BasicSourceCapabilities();
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
- caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
- caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
- caps.setFunctionSupport("convert", true); //$NON-NLS-1$
- CapabilitiesFinder capFinder = new DefaultCapabilitiesFinder(caps);
-
- helpTestProcess("SELECT * FROM xmltest.doc12260", metadata, dataMgr, null, capFinder, expectedDoc); //$NON-NLS-1$
- }
-
- @Test public void testDefect8373() throws Exception{
-
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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/>\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/>\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$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <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/>\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.doc8373", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testDefect8373a() throws Exception{
-
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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/>\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/>\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$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <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/>\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.doc8373a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testDefect8373b() throws Exception{
-
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
-
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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/>\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/>\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$
- " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
- " <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/>\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.doc8373b", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testDefect13617() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager13617(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Name>Lamp</Name>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item>\r\n" + //$NON-NLS-1$
- " <Name>Goat</Name>\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 Item.Name FROM xmltest.doc13617", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testDefect13617a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager13617(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
- " <Name>Screwdriver</Name>\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$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"004\"/>\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 ItemID, Item.Name FROM xmltest.doc13617", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * Tests that non-zero length whitespace string will be treated like
- * normal data
- * @throws Exception
- * @since 4.2
- */
- @Test public void testDefect14905() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager14905(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=\" \">\r\n" + //$NON-NLS-1$
- " <Name> </Name>\r\n" + //$NON-NLS-1$
- " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\" \">\r\n" + //$NON-NLS-1$
- " <Name> </Name>\r\n" + //$NON-NLS-1$
- " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\" \">\r\n" + //$NON-NLS-1$
- " <Name> </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", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testTextUnnormalizedDefect15117() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager15117(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> Screw driver </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", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testTextUnnormalizedDefect15117a() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager15117a(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>\t \n
</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> >Screw< \n driver &</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", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testRecursiveGroupDoc() throws Exception {
-
- FakeMetadataFacade metadata = exampleMetadata2();
- FakeDataManager dataMgr = exampleXQTDataManager(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<group>\r\n" + //$NON-NLS-1$
- " <ID>2</ID>\r\n" + //$NON-NLS-1$
- " <code>-1</code>\r\n" + //$NON-NLS-1$
- " <supervisor>\r\n" + //$NON-NLS-1$
- " <ID>4</ID>\r\n" + //$NON-NLS-1$
- " <code>1</code>\r\n" + //$NON-NLS-1$
- " <group>\r\n" + //$NON-NLS-1$
- " <ID>6</ID>\r\n" + //$NON-NLS-1$
- " <code>3</code>\r\n" + //$NON-NLS-1$
- " <supervisor>\r\n" + //$NON-NLS-1$
- " <ID>8</ID>\r\n" + //$NON-NLS-1$
- " <code>5</code>\r\n" + //$NON-NLS-1$
- " <group>\r\n" + //$NON-NLS-1$
- " <ID>10</ID>\r\n" + //$NON-NLS-1$
- " <code>7</code>\r\n" + //$NON-NLS-1$
- " <supervisor>\r\n" + //$NON-NLS-1$
- " <ID>12</ID>\r\n" + //$NON-NLS-1$
- " <code>9</code>\r\n" + //$NON-NLS-1$
- " </supervisor>\r\n" + //$NON-NLS-1$
- " </group>\r\n" + //$NON-NLS-1$
- " </supervisor>\r\n" + //$NON-NLS-1$
- " </group>\r\n" + //$NON-NLS-1$
- " </supervisor>\r\n" + //$NON-NLS-1$
- "</group>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("SELECT * FROM xqttest.groupDoc WHERE pseudoID = 2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testCase2951MaxRows() throws Exception {
-
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** test rowlimitexception() doesn't throw exception is rowlimit isn't passed */
- @Test public void testDefect19173RowLimitException() throws Exception {
-
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8 WHERE rowlimitexception(supplier) = 4", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** test criteria can be written backwards */
- @Test public void testDefect19173RowLimitExceptionBackwardsCriteria() throws Exception {
-
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8 WHERE 4 = rowlimitexception(supplier)", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testCase2951MaxRows2() throws Exception {
-
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8 WHERE rowlimit(supplier) = 2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** test processing exception is thrown if row limit is passed */
- @Test public void testDefect19173RowLimitException2() throws Exception {
-
- FakeMetadataFacade 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$
- }
-
- /** 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();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8 WHERE rowlimit(supplier) = 2 AND rowlimit(supplierid) = 2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** test processing exception is thrown if row limit is passed */
- @Test public void testDefect19173RowLimitException2a() throws Exception {
-
- FakeMetadataFacade 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$
- }
-
- /** compound criteria */
- @Test public void testCase2951MaxRows3() throws Exception {
-
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8 WHERE ItemID='002' AND rowlimit(supplier) = 2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** compound criteria */
- @Test public void testDefect19173RowLimitException3() throws Exception {
-
- FakeMetadataFacade 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$
- }
-
- @Test public void testCase2951MaxRows4() throws Exception {
-
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8 WHERE rowlimit(supplier) = 2 AND rowlimit(item) = 2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testCase2951AndDefect19173MixTwoFunctions() throws Exception {
-
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8 WHERE rowlimit(supplier) = 2 AND rowlimitException(item) = 6", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /** arg to rowlimit function isn't in the scope of any mapping class */
- @Test public void testCase2951MaxRowsFails() throws Exception {
-
- FakeMetadataFacade 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$
- }
-
- /** two conflicting row limits on the same mapping class */
- @Test public void testCase2951MaxRowsFails2() throws Exception {
-
- FakeMetadataFacade 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$
- }
-
- /** arg to rowlimitexception function isn't in the scope of any mapping class */
- @Test public void testDefect19173RowLimitExceptionFails() throws Exception {
-
- FakeMetadataFacade 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$
- }
-
- /** two conflicting rowlimitexceptions on the same mapping class */
- @Test public void testDefect19173RowLimitExceptionFails2() throws Exception {
-
- FakeMetadataFacade 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$
- }
-
- /** two conflicting rowlimit and rowlimitexceptions on the same mapping class fails planning */
- @Test public void testDefect19173RowLimitAndRowLimitExceptionMixFails2() throws Exception {
-
- FakeMetadataFacade 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$
- }
-
- /** try rowlimit criteria written the reverse way */
- @Test public void testCase2951MaxRows5() throws Exception {
-
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNested(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.doc8 WHERE 2 = rowlimit(supplier)", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
-
- @Test public void testNormalizationCollapse() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNormalization(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 xsi:nil=\"true\"/>\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>0</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$
- " <DiscontinuedItem ItemID=\"004\">\r\n" + //$NON-NLS-1$
- " <Name>Flux Capacitor</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>2</Quantity>\r\n" + //$NON-NLS-1$
- " </DiscontinuedItem>\r\n" + //$NON-NLS-1$
- " <StatusUnknown ItemID=\"005\">\r\n" + //$NON-NLS-1$
- " <Name>Milkshake</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>88</Quantity>\r\n" + //$NON-NLS-1$
- " </StatusUnknown>\r\n" + //$NON-NLS-1$
- " <DiscontinuedItem ItemID=\"006\">\r\n" + //$NON-NLS-1$
- " <Name>Feta Matrix</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>0</Quantity>\r\n" + //$NON-NLS-1$
- " </DiscontinuedItem>\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.normDoc1", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testNormalizationReplace() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNormalization(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 xsi:nil=\"true\"/>\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>0</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$
- " <DiscontinuedItem ItemID=\"004\">\r\n" + //$NON-NLS-1$
- " <Name>Flux Capacitor</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>2</Quantity>\r\n" + //$NON-NLS-1$
- " </DiscontinuedItem>\r\n" + //$NON-NLS-1$
- " <StatusUnknown ItemID=\"005\">\r\n" + //$NON-NLS-1$
- " <Name>Milkshake</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>88</Quantity>\r\n" + //$NON-NLS-1$
- " </StatusUnknown>\r\n" + //$NON-NLS-1$
- " <DiscontinuedItem ItemID=\"006\">\r\n" + //$NON-NLS-1$
- " <Name> Feta Matrix </Name>\r\n" + //$NON-NLS-1$
- " <Quantity>0</Quantity>\r\n" + //$NON-NLS-1$
- " </DiscontinuedItem>\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.normDoc2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
- @Test public void testNormalizationPreserve() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManagerNormalization2(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 xsi:nil=\"true\"/>\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>My Screwdriver</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>0</Quantity>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
- " <Name>My Goat</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>4</Quantity>\r\n" + //$NON-NLS-1$
- " </Item>\r\n" + //$NON-NLS-1$
- " <DiscontinuedItem ItemID=\"004\">\r\n" + //$NON-NLS-1$
- " <Name>My Flux Capacitor</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>2</Quantity>\r\n" + //$NON-NLS-1$
- " </DiscontinuedItem>\r\n" + //$NON-NLS-1$
- " <StatusUnknown ItemID=\"005\">\r\n" + //$NON-NLS-1$
- " <Name>My Milkshake</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>88</Quantity>\r\n" + //$NON-NLS-1$
- " </StatusUnknown>\r\n" + //$NON-NLS-1$
- " <DiscontinuedItem ItemID=\"006\">\r\n" + //$NON-NLS-1$
- " <Name>My Feta Matrix</Name>\r\n" + //$NON-NLS-1$
- " <Quantity>0</Quantity>\r\n" + //$NON-NLS-1$
- " </DiscontinuedItem>\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.normDoc3", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * Deluxe example
- */
- private FakeDataManager exampleDataManagerNormalization(FakeMetadataFacade 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$
- } );
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
- private FakeDataManager exampleDataManagerNormalization2(FakeMetadataFacade 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$
- } );
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- private static MappingNode createXMLPlanNormalization(String normMode) {
-
- 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$
- MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
- //choice node, non-visual, so it has no name
- MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode());
- choice.setSource("xmltest.group.items"); //$NON-NLS-1$
- choice.setMaxOccurrs(-1);
- MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'okay'", false)); //$NON-NLS-1$
- MappingElement item = crit.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
- item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setNormalizeText(normMode)
- .setNillable(true);
- item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
- .setDefaultValue("0"); //$NON-NLS-1$
-
- MappingCriteriaNode crit2 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)); //$NON-NLS-1$
- MappingElement discontinuedItem = crit2.addChildElement(new MappingElement("DiscontinuedItem")); //$NON-NLS-1$
- discontinuedItem.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- discontinuedItem.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setNormalizeText(normMode)
- .setNillable(true);
- discontinuedItem.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
- .setDefaultValue("0"); //$NON-NLS-1$
-
- MappingCriteriaNode crit3 = choice.addCriteriaNode(new MappingCriteriaNode());
- MappingElement unknownItem = crit3.addChildElement(new MappingElement("StatusUnknown")); //$NON-NLS-1$
- unknownItem.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
- unknownItem.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
- .setNormalizeText(normMode)
- .setNillable(true);
- unknownItem.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
- .setDefaultValue("0"); //$NON-NLS-1$
-
- MappingCriteriaNode notIncludedSibling = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)); //$NON-NLS-1$
- notIncludedSibling.setExclude(true);
-
- MappingCriteriaNode notIncludedSibling2 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)); //$NON-NLS-1$
- notIncludedSibling2.setExclude(true);
- return doc;
- }
-
- static FakeDataManager exampleDataManagerCase3225(FakeMetadataFacade 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$
- } );
-
- 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$
- } );
-
-
- 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$
- } );
-
- 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$
- } );
-
- 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$
- } );
-
- } catch(Throwable e) {
- e.printStackTrace();
- fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return dataMgr;
- }
-
- /**
- * Test of doc model w/o criteria, just as a baseline
- * @throws Exception
- */
- @Test public void testCase3225() throws Exception {
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
- FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>2/13/05</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>2</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " <Employees>\r\n" + //$NON-NLS-1$
- " <Employee EmployeeID=\"1001\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
- " <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee EmployeeID=\"1002\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
- " <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Employees>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>3/13/05</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " <Employees/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " <Employees/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " <Employees>\r\n" + //$NON-NLS-1$
- " <Employee EmployeeID=\"1005\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
- " <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Employees>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " <Employees>\r\n" + //$NON-NLS-1$
- " <Employee EmployeeID=\"1003\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
- " <FirstName>David</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Eckstein</LastName>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Employees>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " <Employees/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderDate>5/13/05</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>cancelled</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " <Employees>\r\n" + //$NON-NLS-1$
- " <Employee EmployeeID=\"1008\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
- " <FirstName>Carlos</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Zambrano</LastName>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Employees>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>6/13/05</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>800</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " <Employees>\r\n" + //$NON-NLS-1$
- " <Employee EmployeeID=\"1006\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
- " <FirstName>Corey</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Patterson</LastName>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Employees>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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.itemsdoc", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * For ESpace case 3225 tests, with criteria
- * "... where employee. at supervisorID='1004' and order.orderquantity > 1"
- */
- private static final String CASE_3225_WITH_CRITERIA_EXPECTED_DOC =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>2/13/05</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>2</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " <Employees>\r\n" + //$NON-NLS-1$
- " <Employee EmployeeID=\"1001\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
- " <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " <Employee EmployeeID=\"1002\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
- " <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Employees>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>3/13/05</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " <Employees/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " <Employees/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " <Employees>\r\n" + //$NON-NLS-1$
- " <Employee EmployeeID=\"1005\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
- " <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
- " </Employee>\r\n" + //$NON-NLS-1$
- " </Employees>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
-
- private static String EXPECTED_ORDERED_DOC9A = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\r\n" + //$NON-NLS-1$
- " <Items>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
- " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
- " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
- " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
- " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
- " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
- " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
- " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
- " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
- " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\r\n" + //$NON-NLS-1$
- " </Item>\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$
- " <Suppliers>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
- " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
- " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
- " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
- " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
- " <Orders>\r\n" + //$NON-NLS-1$
- " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
- " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
- " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
- " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
- " </Order>\r\n" + //$NON-NLS-1$
- " </Orders>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
- " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
- " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
- " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
- " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
- " <Orders/>\r\n" + //$NON-NLS-1$
- " </Supplier>\r\n" + //$NON-NLS-1$
- " </Suppliers>\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";
-
- /**
- * Test of query with criteria written one way. This test is paired up
- * with {@link #testCase3225WithCriteriaReversed()}; both tests have the same
- * expected results and are identical queries except their compound criteria are
- * written in reverse order relative to each other. What Alan Tetrault found at
- * ESpace is that this changes actual results, which it shouldn't. The likely
- * culprit is the algorithm to apply criteria to the implied context mapping class.
- * That is, the criteria is on nodes in the scope of two nested mapping classes
- * (the ones for orders and employees), but the implied context mapping class of both
- * of them is the root mapping class (for items).
- *
- * The criteria "@supervisorID='1004'" should limit the returned items to items 001 and 002,
- * the criteria "order.orderquantity > 1" should limit the returned items to 001 and 003, so
- * the combined criteria should limit returned items to item 001.
- * @throws Exception
- */
- @Test public void testCase3225WithCriteria() throws Exception {
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- }
-
- /**
- * Test of query with criteria written the other way. This test is paired up
- * with {@link #testCase3225WithCriteria()}; both tests have the same
- * expected results and are identical queries except their compound criteria are
- * written in reverse order relative to each other. What Alan Tetrault found at
- * ESpace is that this changes actual results, which it shouldn't. The likely
- * culprit is the algorithm to apply criteria to the implied context mapping class.
- * That is, the criteria is on nodes in the scope of two nested mapping classes
- * (the ones for orders and employees), but the implied context mapping class of both
- * of them is the root mapping class (for items).
- *
- * The criteria "@supervisorID='1004'" should limit the returned items to items 001 and 002,
- * the criteria "order.orderquantity > 1" should limit the returned items to 001 and 003, so
- * the combined criteria should limit returned items to item 001.
- * @throws Exception
- */
- @Test public void testCase3225WithCriteriaReversed() throws Exception {
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- }
-
- /**
- * Test the criteria from previous test, plus additional criteria explicitly
- * on the context mapping class (in this case, the root "items" mapping class)
- * to make sure all of the criteria is processed correctly.
- * @throws Exception
- */
- @Test public void testCase3225WithEmptyDocCriteria() throws Exception {
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
- FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
- String expectedDoc =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
- "<Catalogs>\r\n" + //$NON-NLS-1$
- " <Catalog>\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.itemsdoc where order.orderquantity > 1 and employee. at supervisorID='1004' and item. at itemid='002'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- /**
- * This just tests selecting * from the document, nothing fancy
- * @throws Exception
- * @since 4.3
- */
- @Test public void testBaseballPlayersDoc() throws Exception {
-
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- " <Manager ManagerID=\"1007\">\r\n" + //$NON-NLS-1$
- " <FirstName>Dusty</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Baker</LastName>\r\n" + //$NON-NLS-1$
- " <Owner OwnerID=\"1010\">\r\n" + //$NON-NLS-1$
- " <FirstName>Some</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Guy</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=\"1006\">\r\n" + //$NON-NLS-1$
- " <FirstName>Corey</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Patterson</LastName>\r\n" + //$NON-NLS-1$
- " <Manager ManagerID=\"1007\">\r\n" + //$NON-NLS-1$
- " <FirstName>Dusty</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Baker</LastName>\r\n" + //$NON-NLS-1$
- " <Owner OwnerID=\"1010\">\r\n" + //$NON-NLS-1$
- " <FirstName>Some</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Guy</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=\"1008\">\r\n" + //$NON-NLS-1$
- " <FirstName>Carlos</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Zambrano</LastName>\r\n" + //$NON-NLS-1$
- " <Manager ManagerID=\"1007\">\r\n" + //$NON-NLS-1$
- " <FirstName>Dusty</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Baker</LastName>\r\n" + //$NON-NLS-1$
- " <Owner OwnerID=\"1010\">\r\n" + //$NON-NLS-1$
- " <FirstName>Some</FirstName>\r\n" + //$NON-NLS-1$
- " <LastName>Guy</LastName>\r\n" + //$NON-NLS-1$
- " </Owner>\r\n" + //$NON-NLS-1$
- " </Manager>\r\n" + //$NON-NLS-1$
- " </Player>\r\n" + //$NON-NLS-1$
- "</BaseballPlayers>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("select * from xmltest.playersDoc", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-
- }
-
- /**
- * This one seems to work fine - criteria mapping class is
- * managers while implied context mapping class is players.
- * Expected result is same as previous test.
- * @throws Exception
- * @since 4.3
- */
- @Test public void testBaseballPlayersDocCriteria() throws Exception {
-
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
- "</BaseballPlayers>\r\n\r\n"; //$NON-NLS-1$
-
- helpTestProcess("select * from xmltest.playersDoc where manager. at managerid = '1004'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-
- }
-
- /**
- * This also seems to work fine. The context mapping class is the
- * middle one (managers).
- * @throws Exception
- * @since 4.3
- */
- @Test public void testBaseballPlayersDocContextCriteria() throws Exception {
-
- FakeMetadataFacade metadata = FakeMetadataFactory.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$
-
- }
-
- /**
- * Ensures that temp tables are still visible when processing criteria
- */
- @Test public void testProcedureAndXML() 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=\"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("call xmltest.vsp1(1000)", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- }
-
- @Test public void testProcedureAndXML1() throws Exception {
- FakeMetadataFacade metadata = exampleMetadataCached();
- FakeDataManager dataMgr = exampleDataManager(metadata);
- String expectedDoc1 =
- "<?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$
- " </Catalog>\r\n" + //$NON-NLS-1$
- "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
- String expectedDoc2 =
- "<?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=\"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$
- String expectedDoc3 =
- "<?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=\"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 (call xmltest.vsp1(y)) from texttable(unescape('1\n100\n1000') COLUMNS y integer) as x", metadata, dataMgr, null, new DefaultCapabilitiesFinder(), expectedDoc1, expectedDoc2, expectedDoc3); //$NON-NLS-1$
- }
-
- /**
- * When a element with source node is specied, it can be unbouned or bounded. In the case
- * of bounded, but result set is returning more results then it should fail.
- */
- public void defer_testMinMaxOnSourceNode() 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$
-
- try {
- helpTestProcess("SELECT * FROM xmltest.docBounded", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
- fail("should have failed the document restrictions."); //$NON-NLS-1$
- } catch (TeiidProcessingException e) {
- // pass
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,11322 @@
+/*
+ * 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 static org.junit.Assert.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.FileInputStream;
+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;
+import org.teiid.query.mapping.xml.MappingChoiceNode;
+import org.teiid.query.mapping.xml.MappingCommentNode;
+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.MappingNodeConstants;
+import org.teiid.query.mapping.xml.MappingRecursiveElement;
+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.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;
+import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.optimizer.xml.TestXMLPlanner;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.BatchCollector;
+import org.teiid.query.processor.FakeDataManager;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.QueryProcessor;
+import org.teiid.query.processor.TestProcessor;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+
+/**
+ * Tests XML processing, which involves XMLPlanner making a ProcessorPlan
+ * (XMLPlan) from a mapping document (tree of MappingNode objects) and
+ * metadata, and then that XMLPlan being processed with metadata, a
+ * ProcessorDataManager and a QueryProcessor.
+ */
+ at SuppressWarnings("nls")
+public class TestXMLProcessor {
+ 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:
+ *
+ * stock (physical model)
+ * items (physical group)
+ * itemNum (string)
+ * itemName (string)
+ * itemQuantity (integer)
+ * xmltest (virtual model)
+ * rs (virtual group / result set definition)
+ * itemNum (string)
+ * itemName (string)
+ * itemQuantity (integer)
+ */
+ public static TransformationMetadata exampleMetadataCached() {
+ return EXAMPLE_CACHED;
+ }
+
+ private static final TransformationMetadata EXAMPLE_CACHED = exampleMetadata();
+
+ public static TransformationMetadata exampleMetadata() {
+ MetadataStore metadataStore = new MetadataStore();
+
+ // Create models
+ Schema stock = RealMetadataFactory.createPhysicalModel("stock", metadataStore); //$NON-NLS-1$
+ Schema xmltest = RealMetadataFactory.createVirtualModel("xmltest", metadataStore); //$NON-NLS-1$
+
+ // Create physical groups
+ Table items = RealMetadataFactory.createPhysicalGroup("items", stock); //$NON-NLS-1$
+ Table item_supplier = RealMetadataFactory.createPhysicalGroup("item_supplier", 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
+ 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
+ RealMetadataFactory.createElements(item_supplier,
+ new String[] { "itemNum", "supplierNum" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+
+ 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});
+
+ 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});
+
+ 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});
+
+
+
+// ======================================================================================================================
+
+ // 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ Table rs5a = RealMetadataFactory.createVirtualGroup("employees2Recursive", xmltest, rsEmployees2Recursive); //$NON-NLS-1$
+
+// ======================================================================================================================
+// Alternate mapping class which selects from stored query
+
+ // 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$
+ 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$
+ 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$
+ 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$
+ Table rs3a = RealMetadataFactory.createVirtualGroup("ordersA", xmltest, rsQuery3a); //$NON-NLS-1$
+
+// ======================================================================================================================
+// ALTERNATE METADATA B (temp groups)
+
+ //temp group selects from root temp group and it has bindings to other mapping classes
+ // from 5.5 bindings are not supported in the staging tables. even before we did not supported
+ // them in the modeler; but we did in execution; now we remove it as it poses more issues.
+ QueryNode tempQuery3b = new QueryNode("SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders2 WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+ 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$
+ 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$
+ Table rs3b = RealMetadataFactory.createVirtualGroup("ordersB", xmltest, rsQuery3b); //$NON-NLS-1$
+
+
+// ======================================================================================================================
+// ALTERNATE METADATA C (temp group with union)
+
+// //temp group selects from root temp group and it has bindings to other mapping classes
+// QueryNode tempQuery3b = new QueryNode("tempGroup.orders3B", "SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders2 WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?");
+// tempQuery3b.addBinding("xmltest.group.items.itemNum");
+// tempQuery3b.addBinding("xmltest.suppliers.supplierNum");
+// tempQuery3b.addBinding("xmltest.suppliers.supplierName");
+// 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");
+// Table rs3b = RealMetadataFactory.createVirtualGroup("ordersB", xmltest, rs Query3b);
+
+// ======================================================================================================================
+
+// ======================================================================================================================
+// ALTERNATE METADATA D (correlated subquery in mapping class)
+ // 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$
+ Table rs12260 = RealMetadataFactory.createVirtualGroup("group.itemsWithNumSuppliers", xmltest, rsQuery12260); //$NON-NLS-1$
+
+ 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 });
+
+// ======================================================================================================================
+// ALTERNATE METADATA E (mapping class w/ Union)
+ // 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$
+ Table rs8373 = RealMetadataFactory.createVirtualGroup("items8373", xmltest, rsQuery8373); //$NON-NLS-1$
+
+ 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$
+ Table rs8373a = RealMetadataFactory.createVirtualGroup("items8373a", xmltest, rsQuery8373a); //$NON-NLS-1$
+
+ 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$
+ Table rs8373b = RealMetadataFactory.createVirtualGroup("items8373b", xmltest, rsQuery8373b); //$NON-NLS-1$
+
+ 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 });
+
+// ======================================================================================================================
+
+
+ // 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$
+ Table rsUpdate = RealMetadataFactory.createVirtualGroup("updateTest", xmltest, rsUpdateQuery); //$NON-NLS-1$
+
+ // Create virtual elements
+ 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 });
+
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+ RealMetadataFactory.createElements(rsUpdate,
+ new String[] { "rowCount" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.INTEGER});
+
+ 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
+ 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 });
+
+ 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 });
+ 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 });
+
+ 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 });
+
+ 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 });
+ 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$
+
+ 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 });
+ 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});
+ 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 });
+ 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 });
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+
+ 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====================
+ boolean useRecursiveCriteria = false;
+ int recursionlimit = -1;
+ boolean exceptionOnLimit = false;
+
+ RealMetadataFactory.createXmlDocument("doc12", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+ RealMetadataFactory.createXmlDocument("doc12a", xmltest, createXMLPlanRecursiveA(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+
+ useRecursiveCriteria = true;
+ RealMetadataFactory.createXmlDocument("doc13", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+ useRecursiveCriteria = false;
+ recursionlimit = 2;
+ RealMetadataFactory.createXmlDocument("doc14", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+ exceptionOnLimit = true;
+ RealMetadataFactory.createXmlDocument("doc15", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+
+ useRecursiveCriteria = false;
+ recursionlimit = -1;
+ exceptionOnLimit = false;
+ RealMetadataFactory.createXmlDocument("doc16", xmltest, createXMLPlanRecursive2(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+
+ RealMetadataFactory.createXmlDocument("doc17", xmltest, createXMLPlanWithComment()); //$NON-NLS-1$
+
+ 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 });
+
+
+ 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$
+
+ 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
+ RealMetadataFactory.createXmlDocument("docUpdateTest", xmltest, createUpdateTestDoc()); //$NON-NLS-1$
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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});
+
+ 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 ========================================================
+
+ 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$
+ 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$
+ 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$
+ 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});
+
+ // recursive + staging ========================================================
+
+ //========================================================
+
+ // Stored queries
+ 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$
+ 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
+ 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 });
+ 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 });
+
+ 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$
+ 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);
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "example1");
+ }
+
+ public QueryMetadataInterface exampleMetadataNestedWithSibling() {
+ MetadataStore metadataStore = new MetadataStore();
+
+ // Create models
+ Schema stock = RealMetadataFactory.createPhysicalModel("stock", metadataStore); //$NON-NLS-1$
+ Schema xmltest = RealMetadataFactory.createVirtualModel("xmltest", metadataStore); //$NON-NLS-1$
+
+ // Create physical groups
+ 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
+ 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
+ RealMetadataFactory.createElements(item_supplier,
+ new String[] { "itemNum", "supplierNum" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+
+ 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
+ RealMetadataFactory.createElements(item_order,
+ new String[] { "itemNum", "orderNum" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+
+ 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 });
+
+// ======================================================================================================================
+
+ // Create virtual groups
+ QueryNode rsQuery1 = new QueryNode("SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
+ 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$
+ 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$
+ Table rs3= RealMetadataFactory.createVirtualGroup("orders", xmltest, rsQuery3); //$NON-NLS-1$
+
+ // Create virtual elements
+ 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 });
+
+ 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 });
+
+ 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
+ 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});
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "nestedWithSibling");
+ }
+
+ public static TransformationMetadata exampleMetadata2() {
+ MetadataStore metadataStore = new MetadataStore();
+
+ // Create models
+ Schema xqt = RealMetadataFactory.createPhysicalModel("xqt", metadataStore); //$NON-NLS-1$
+ Schema xqttest = RealMetadataFactory.createVirtualModel("xqttest", metadataStore); //$NON-NLS-1$
+
+ // Create physical groups
+ Table xqtGroup = RealMetadataFactory.createPhysicalGroup("data", xqt); //$NON-NLS-1$
+
+ // Create physical elements
+ 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$
+ 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$
+ 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$
+ 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$
+ Table objGroup1 = RealMetadataFactory.createVirtualGroup("group1", xqttest, rsGroup1); //$NON-NLS-1$
+
+ // Create virtual elements
+
+ 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 });
+
+ 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 });
+
+ 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 });
+
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ Table rs8 = RealMetadataFactory.createVirtualGroup("data8", xqttest, rsQuery8); //$NON-NLS-1$
+
+ // Create virtual elements
+ 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 });
+
+ 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 });
+
+ 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 });
+
+ 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 });
+
+ 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 });
+
+ 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 });
+
+ 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 });
+
+ 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 });
+
+
+ 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$
+
+ RealMetadataFactory.createElements(groupDoc, new String[] { "group", "group.pseudoID" /*, etc...*/ }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+ 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});
+
+ RealMetadataFactory.createElements(doc5, new String[] { "root", "root.wrapper.key" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "example2");
+ }
+
+ public static TransformationMetadata exampleMetadataSoap1() {
+ MetadataStore metadataStore = new MetadataStore();
+
+ // Create models
+ Schema taxReport = RealMetadataFactory.createPhysicalModel("taxReport", metadataStore); //$NON-NLS-1$
+ Schema xmltest = RealMetadataFactory.createVirtualModel("xmltest", metadataStore); //$NON-NLS-1$
+
+ // Create physical groups
+ Table arrayOfItem = RealMetadataFactory.createPhysicalGroup("TaxIDs", taxReport); //$NON-NLS-1$
+
+ // Create physical elements
+ 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$
+ Table rsSoap = RealMetadataFactory.createVirtualGroup("group.TaxIDs", xmltest, rsQuerySoap); //$NON-NLS-1$
+
+ RealMetadataFactory.createElements(rsSoap,
+ new String[] { "ID"}, //$NON-NLS-1$
+ new String[] {DataTypeManager.DefaultDataTypes.STRING});
+
+ 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 });
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "soap1");
+ }
+
+ private static MappingDocument createXQTPlanChoice_6796() {
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+ MappingChoiceNode choice = root.addChoiceNode(new MappingChoiceNode(false));
+ choice.setSource("xqttest.data7"); //$NON-NLS-1$
+ choice.setMaxOccurrs(-1);
+ MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode("xqttest.data7.intKey < 10", false)); //$NON-NLS-1$
+ MappingElement wrapper1 = crit.addChildElement(new MappingElement("wrapper")); //$NON-NLS-1$
+
+ MappingElement key = wrapper1.addChildElement(new MappingElement("key", "xqttest.data7.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement keys = key.addChildElement(new MappingElement("keys")); //$NON-NLS-1$
+ keys.setSource("xqttest.data8"); //$NON-NLS-1$
+ keys.setMaxOccurrs(-1);
+ keys.addChildElement(new MappingElement("nestedkey", "xqttest.data8.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingCriteriaNode wrapper2 = choice.addCriteriaNode(new MappingCriteriaNode(null, true));
+
+ key = wrapper2.addChildElement( new MappingElement("key", "xqttest.data7.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ keys = key.addChildElement(new MappingElement("keys")); //$NON-NLS-1$
+ keys.setSource("xqttest.data8"); //$NON-NLS-1$
+ keys.setMaxOccurrs(-1);
+ keys.addChildElement(new MappingElement("nestedkey", "xqttest.data8.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ return doc;
+ }
+
+ private static MappingDocument createChoiceDefect24651() {
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+ MappingChoiceNode choice = root.addChoiceNode(new MappingChoiceNode(false));
+ choice.setSource("xqttest.data7"); //$NON-NLS-1$
+ choice.setMaxOccurrs(-1);
+ MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode("xqttest.data7.intKey < 10", false)); //$NON-NLS-1$
+ MappingElement wrapper1 = crit.addChildElement(new MappingElement("wrapper")); //$NON-NLS-1$
+
+ MappingElement key = wrapper1.addChildElement(new MappingElement("key", "xqttest.data7.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+ key.setExclude(true);
+
+ return doc;
+ }
+
+ /**
+ * Method createXQTPlanRecursive.
+ * @return Object
+ */
+ private static MappingDocument createXQTPlanRecursive_5988() {
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
+
+ MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
+ src1.setSource("xqttest.data"); //$NON-NLS-1$
+
+ MappingSequenceNode seq1 = new MappingSequenceNode();
+ seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ src1.addSequenceNode(seq1);
+
+ MappingElement src2 = seq1.addChildElement(new MappingElement("srcNested")); //$NON-NLS-1$
+ src2.setSource("xqttest.data2"); //$NON-NLS-1$
+
+ MappingSequenceNode seq2 = src2.addSequenceNode(new MappingSequenceNode());
+ seq2.addChildElement(new MappingElement("key", "xqttest.data2.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq2.addChildElement(new MappingElement("data", "xqttest.data2.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement recursive = seq2.addChildElement(new MappingRecursiveElement("srcNestedRecursive", "xqttest.data2")); //$NON-NLS-1$ //$NON-NLS-2$
+ recursive.setSource("xqttest.data3"); //$NON-NLS-1$
+
+ MappingElement recursive2 = seq1.addChildElement(new MappingRecursiveElement("srcRecursive", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
+ recursive2.setSource("xqttest.data4"); //$NON-NLS-1$
+
+ return doc;
+ }
+
+ /**
+ * Method createXQTPlanRecursive.
+ * @return Object
+ */
+ private static MappingDocument createXQTPlanRecursive1a_5988() {
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
+
+ MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
+ src1.setSource("xqttest.data"); //$NON-NLS-1$
+
+ MappingSequenceNode seq1 = new MappingSequenceNode();
+ seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ src1.addSequenceNode(seq1);
+
+ MappingElement src2 = seq1.addChildElement(new MappingElement("srcNested")); //$NON-NLS-1$
+ src2.setSource("xqttest.data2"); //$NON-NLS-1$
+
+ MappingSequenceNode seq2 = src2.addSequenceNode(new MappingSequenceNode());
+ seq2.addChildElement(new MappingElement("key", "xqttest.data2.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq2.addChildElement(new MappingElement("data", "xqttest.data2.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement recursive = seq2.addChildElement(new MappingRecursiveElement("srcRecursive", "xqttest.data2")); //$NON-NLS-1$ //$NON-NLS-2$
+ recursive.setSource("xqttest.data3"); //$NON-NLS-1$
+
+ MappingElement recursive2 = seq1.addChildElement(new MappingRecursiveElement("srcRecursive", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
+ recursive2.setSource("xqttest.data4"); //$NON-NLS-1$
+
+ return doc;
+ }
+
+ /**
+ * Tests a non-recursive nested mapping class within a recursive mapping class, where
+ * all nested "anchor" nodes are named "srcNested". Test of defect #5988
+ * @return Object
+ */
+ private static MappingDocument createXQTPlanRecursive3_5988() {
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
+
+ MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
+ src1.setSource("xqttest.data"); //$NON-NLS-1$
+
+ MappingSequenceNode seq1 = src1.addSequenceNode(new MappingSequenceNode());
+ seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement src2 = seq1.addChildElement(new MappingElement("srcNested")); //$NON-NLS-1$
+ src2.setSource("xqttest.data2"); //$NON-NLS-1$
+
+ MappingSequenceNode seq2 = src2.addSequenceNode(new MappingSequenceNode());
+ seq2.addChildElement(new MappingElement("key", "xqttest.data2.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq2.addChildElement(new MappingElement("data", "xqttest.data2.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement nested = seq1.addChildElement(new MappingRecursiveElement("srcNested", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
+ nested.setSource("xqttest.data4"); //$NON-NLS-1$
+
+ return doc;
+ }
+
+
+ private static MappingDocument createXQTPlanRecursiveSiblings() {
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
+
+ MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
+ src1.setSource("xqttest.data"); //$NON-NLS-1$
+
+ MappingSequenceNode seq1 = src1.addSequenceNode(new MappingSequenceNode());
+ seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement sibiling1 = seq1.addChildElement(new MappingRecursiveElement("srcSibling1", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
+ sibiling1.setSource("xqttest.data2"); //$NON-NLS-1$
+ sibiling1.setMaxOccurrs(-1);
+ MappingElement sibiling2 = seq1.addChildElement(new MappingRecursiveElement("srcSibling2", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
+ sibiling2.setSource("xqttest.data2");//$NON-NLS-1$
+ sibiling2.setMaxOccurrs(-1);
+ return doc;
+ }
+
+ /**
+ * Method createXMLPlanNested.
+ * @return MappingNode root of mapping doc
+ */
+ private static MappingDocument createXMLPlanNested() {
+
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = new MappingElement("Catalogs"); //$NON-NLS-1$
+ doc.addChildElement(root);
+
+ MappingSequenceNode sequence = new MappingSequenceNode();
+ MappingElement cats = sequence.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+ MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+ MappingSequenceNode sequence0 = items.addSequenceNode(new MappingSequenceNode());
+
+ MappingElement item = sequence0.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ MappingSequenceNode sequence1 = item.addSequenceNode(new MappingSequenceNode());
+ sequence1.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ //NESTED STUFF======================================================================
+ MappingElement nestedWrapper = new MappingElement("Suppliers"); //$NON-NLS-1$
+ MappingSequenceNode sequence2 = nestedWrapper.addSequenceNode(new MappingSequenceNode());
+
+ MappingElement supplier = sequence2.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$
+
+
+ MappingSequenceNode sequence3 = supplier.addSequenceNode(new MappingSequenceNode());
+ sequence3.addChildElement(new MappingElement("Name", "xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
+ sequence3.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+ //NESTED STUFF======================================================================
+
+ sequence1.addChildElement(nestedWrapper);
+ root.addSequenceNode(sequence);
+ return doc;
+ }
+
+
+ /**
+ * for defect 9929
+ */
+ static MappingDocument createXMLPlanNested(String queryGroup) {
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = new MappingElement("Catalogs"); //$NON-NLS-1$
+ doc.addChildElement(root);
+
+ MappingSequenceNode sequence = new MappingSequenceNode();
+ MappingElement cats = sequence.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+ MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+ MappingSequenceNode sequence0 = items.addSequenceNode(new MappingSequenceNode());
+
+ MappingElement item = sequence0.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingSequenceNode sequence1 = item.addSequenceNode(new MappingSequenceNode());
+ sequence1.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ //NESTED STUFF======================================================================
+ MappingElement nestedWrapper = new MappingElement("Suppliers"); //$NON-NLS-1$
+ MappingSequenceNode sequence2 = nestedWrapper.addSequenceNode(new MappingSequenceNode());
+
+ MappingElement supplier = sequence2.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
+ supplier.setSource(queryGroup);
+ supplier.setMaxOccurrs(-1);
+ supplier.addAttribute(new MappingAttribute("SupplierID", queryGroup+".supplierNum"));//$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingSequenceNode sequence3 = supplier.addSequenceNode(new MappingSequenceNode());
+ sequence3.addChildElement(new MappingElement("Name", queryGroup+".supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
+ sequence3.addChildElement(new MappingElement("Zip", queryGroup+".supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+ //NESTED STUFF======================================================================
+
+ sequence1.addChildElement(nestedWrapper);
+ root.addSequenceNode(sequence);
+ return doc;
+ }
+
+ /**
+ * for defect 12260
+ */
+ private static MappingDocument createXMLPlanCorrelatedSubqueryTransform() {
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+
+ MappingSequenceNode sequence = new MappingSequenceNode();
+ MappingElement cats = sequence.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+ MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+ MappingSequenceNode sequence0 = items.addSequenceNode(new MappingSequenceNode());
+
+ MappingElement item = sequence0.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.itemsWithNumSuppliers"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.itemsWithNumSuppliers.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingSequenceNode sequence1 = item.addSequenceNode(new MappingSequenceNode());
+ sequence1.addChildElement(new MappingElement("Name", "xmltest.group.itemsWithNumSuppliers.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.itemsWithNumSuppliers.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+ sequence1.addChildElement(new MappingElement("numSuppliers", "xmltest.group.itemsWithNumSuppliers.numSuppliers")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ root.addSequenceNode(sequence);
+ return doc;
+ }
+
+ private static MappingDocument createXMLPlan_9893() {
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("Root")); //$NON-NLS-1$
+
+ MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());
+
+ MappingElement node = seq.addChildElement(new MappingElement("ItemName", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ node.setSource("xmltest.group.items"); //$NON-NLS-1$
+ node.setMaxOccurrs(-1);
+ node.setMaxOccurrs(MappingNodeConstants.CARDINALITY_UNBOUNDED.intValue());
+ return doc;
+ }
+
+ /**
+ * DEFECT 8373
+ */
+ private static MappingDocument createXMLPlan_defect8373() {
+
+ 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 items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.items8373"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.items8373.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.items8373.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Quantity", "xmltest.items8373.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ return doc;
+ }
+
+ /**
+ * DEFECT 8373
+ */
+ private static MappingDocument createXMLPlan_defect8373a() {
+ 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 items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.items8373a"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.setStagingTables(Arrays.asList(new String[] {"xmltest.items8373"})); //$NON-NLS-1$
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.items8373a.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.items8373a.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Quantity", "xmltest.items8373a.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ return doc;
+ }
+
+ /**
+ * DEFECT 8373
+ */
+ private static MappingDocument createXMLPlan_defect8373b() {
+
+ 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 items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.items8373b"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.setStagingTables(Arrays.asList(new String[] {"xmltest.group.items"})); //$NON-NLS-1$
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.items8373b.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.items8373b.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Quantity", "xmltest.items8373b.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ return doc;
+ }
+
+ private static MappingDocument createXMLPlanNested2() {
+
+ 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 items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.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======================================================================
+ return doc;
+ }
+
+ /** nested with sibling*/
+ private MappingDocument createXMLPlanNested2c() {
+
+ 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 items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.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 = item.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("Name", "xmltest.orders.orderName")); //$NON-NLS-1$ //$NON-NLS-2$
+ order.addChildElement(new MappingElement("Zip", "xmltest.orders.orderZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+ //NESTED STUFF======================================================================
+ return doc;
+ }
+
+
+ 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[] {"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$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.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.ordersA"); //$NON-NLS-1$
+ order.setMaxOccurrs(-1);
+ order.addAttribute(new MappingAttribute("OrderID", "xmltest.ordersA.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ order.addChildElement(new MappingElement("OrderDate", "xmltest.ordersA.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
+ order.addChildElement(new MappingElement("OrderQuantity", "xmltest.ordersA.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ order.addChildElement(new MappingElement("OrderStatus", "xmltest.ordersA.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setMinOccurrs(0);
+ //NESTED STUFF======================================================================
+ return doc;
+ }
+
+ // for doc 9b - test temp group w/ bindings
+ private static MappingDocument createXMLPlanNested2b() {
+
+ 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$
+
+ MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+ MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.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.ordersB"); //$NON-NLS-1$
+
+ order.setStagingTables(Arrays.asList(new String[] {"tempGroup.orders3B"})); //$NON-NLS-1$
+ order.addAttribute(new MappingAttribute("OrderID", "xmltest.ordersB.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ order.addChildElement(new MappingElement("OrderDate", "xmltest.ordersB.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
+ order.addChildElement(new MappingElement("OrderQuantity", "xmltest.ordersB.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ order.addChildElement(new MappingElement("OrderStatus", "xmltest.ordersB.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setMinOccurrs(0);
+ //NESTED STUFF======================================================================
+ return doc;
+ }
+
+ public static MappingDocument createXMLPlanNestedWithChoice() {
+ 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$
+ return baseXMLPlanNestedWithLookupChoice("xmltest.orders.orderStatus = 'processing'", critNode); //$NON-NLS-1$
+ }
+
+ 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 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$
+ return baseXMLPlanNestedWithLookupChoice("lookup('stock.items', 'itemNum', 'itemName', xmltest.orders.orderStatus) = 'processing'", critNode); //$NON-NLS-1$
+ }
+
+ private static MappingDocument baseXMLPlanNestedWithLookupChoice(String criteria, MappingCriteriaNode defaultNode) {
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+
+ MappingSequenceNode seq1 = root.addSequenceNode(new MappingSequenceNode());
+ MappingElement cats = seq1.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+ MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingSequenceNode seq2 = items.addSequenceNode(new MappingSequenceNode());
+
+ MappingElement item = seq2.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingSequenceNode seq3 = item.addSequenceNode(new MappingSequenceNode());
+ seq3.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq3.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ //NESTED STUFF======================================================================
+ MappingElement suppliers = seq3.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
+
+ MappingSequenceNode seq4 = suppliers.addSequenceNode(new MappingSequenceNode());
+ MappingElement supplier = seq4.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$
+
+ MappingSequenceNode seq5 = supplier.addSequenceNode(new MappingSequenceNode());
+ seq5.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq5.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement ordersWrapper = seq5.addChildElement(new MappingElement("ProcessingOrders")); //$NON-NLS-1$
+
+ MappingChoiceNode choice = ordersWrapper.addChoiceNode(new MappingChoiceNode(false));
+ choice.setSource("xmltest.orders"); //$NON-NLS-1$
+ choice.setMaxOccurrs(-1);
+ MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode(criteria, false));
+ MappingElement order = crit.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
+ order.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingSequenceNode seq6 = order.addSequenceNode(new MappingSequenceNode());
+ seq6.addChildElement(new MappingElement("OrderDate", "xmltest.orders.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq6.addChildElement(new MappingElement("OrderQuantity", "xmltest.orders.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ choice.addCriteriaNode(defaultNode);
+ //NESTED STUFF======================================================================
+ return doc;
+ }
+
+
+ private static MappingDocument createTestAttributePlan() {
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("FixedValueTest")); //$NON-NLS-1$
+
+ //sequence
+ MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());
+
+ MappingElement wrapper = seq.addChildElement(new MappingElement("wrapper")); //$NON-NLS-1$
+ wrapper.setSource("xmltest.group.items"); //$NON-NLS-1$
+ wrapper.setMaxOccurrs(-1);
+ MappingAttribute att = new MappingAttribute("fixedAttr"); //$NON-NLS-1$
+ att.setValue("fixed attribute"); //$NON-NLS-1$
+ wrapper.addAttribute(att);
+
+ //sequence
+ MappingSequenceNode seq1 = wrapper.addSequenceNode(new MappingSequenceNode());
+ seq1.addChildElement(new MappingElement("key","xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq1.addChildElement(new MappingElement("fixed")) //$NON-NLS-1$
+ .setValue("fixed value"); //$NON-NLS-1$
+
+ return doc;
+ }
+
+ private static MappingDocument createUpdateTestDoc() {
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("UpdateTest")); //$NON-NLS-1$
+
+ MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());
+ seq.setSource("xmltest.updateTest"); //$NON-NLS-1$
+ seq.addChildElement(new MappingElement("data", "xmltest.updateTest.rowCount")); //$NON-NLS-1$ //$NON-NLS-2$
+ return doc;
+ }
+
+ private static MappingDocument createXMLPlanWithComment(){
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("Root")); //$NON-NLS-1$
+
+ root.addCommentNode(new MappingCommentNode("Comment1")); //$NON-NLS-1$
+ MappingElement node = root.addChildElement(new MappingElement("Something")); //$NON-NLS-1$
+ node.addCommentNode(new MappingCommentNode("Comment2")); //$NON-NLS-1$
+ return doc;
+ }
+
+ public static MappingDocument createXMLMappingBoundingNode() {
+ 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$
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMinOccurrs(1);
+ item.setMaxOccurrs(2);
+
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName").setNillable(true)); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+ return doc;
+ }
+
+ public static MappingDocument createXMLMappingNode(boolean format) {
+ MappingDocument doc = new MappingDocument(format);
+ doc.addChildElement(createXMLPlan1Unformatted(false, 1));
+ return doc;
+ }
+
+ private static MappingDocument createXMLPlan2(boolean format, boolean testNillable, int cardinality ) {
+ MappingDocument doc = new MappingDocument(format);
+ doc.addChildElement(createXMLPlan1Unformatted(testNillable, cardinality));
+ return doc;
+ }
+
+ private static MappingDocument createXMLPlanSOAP() {
+
+ Namespace namespace = new Namespace("ORG", "http://www.mm.org/dummy"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("TaxReports", namespace)); //$NON-NLS-1$
+
+ root.setNamespaces(new Namespace[] {namespace});
+
+ MappingElement report = root.addChildElement(new MappingElement("TaxReport", namespace)); //$NON-NLS-1$
+ report.setNamespaces(new Namespace[] {namespace});
+
+ Namespace xsiNamespace = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$ //$NON-NLS-2$
+ Namespace soapNamespace = new Namespace("SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement taxIds = report.addChildElement(new MappingElement("ArrayOfTaxID", namespace)); //$NON-NLS-1$
+ taxIds.setMinOccurrs(0);
+ taxIds.setNamespaces(new Namespace[] {xsiNamespace, soapNamespace});
+
+ MappingAttribute xsiType = new MappingAttribute("type", xsiNamespace); //$NON-NLS-1$
+ xsiType.setValue(namespace.getPrefix()+":ArrayOfTaxIDType"); //$NON-NLS-1$
+ xsiType.setOptional(true);
+ taxIds.addAttribute(xsiType);
+
+ MappingAttribute arrayType = new MappingAttribute("arrayType", soapNamespace); //$NON-NLS-1$
+ arrayType.setValue( namespace.getPrefix()+":TaxIDType[]"); //$NON-NLS-1$
+ arrayType.setOptional(true);
+ taxIds.addAttribute(arrayType);
+
+ MappingElement taxId = taxIds.addChildElement(new MappingElement("TaxID", namespace)); //$NON-NLS-1$
+ taxId.setSource("xmltest.group.TaxIDs"); //$NON-NLS-1$
+ taxId.setMaxOccurrs(-1);
+ MappingAttribute xsiType2 = new MappingAttribute("type", xsiNamespace); //$NON-NLS-1$
+ xsiType2.setValue(namespace.getPrefix()+":TaxIDType"); //$NON-NLS-1$
+ xsiType2.setOptional(true);
+ taxId.addAttribute(xsiType2);
+
+ taxId.addChildElement(new MappingElement("ID", "xmltest.group.TaxIDs.ID")); //$NON-NLS-1$ //$NON-NLS-2$
+ return doc;
+ }
+
+
+ private static MappingElement createXMLPlan1Unformatted( boolean testNillable, int cardinality ) {
+
+ MappingElement root = new MappingElement("Catalogs");//$NON-NLS-1$
+ MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+ items.setNillable(testNillable);
+ items.setMinOccurrs(cardinality);
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName").setNillable(true)); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+ return root;
+ }
+
+ private static MappingDocument createXMLPlanDefect13617() {
+
+ 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$
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.setMinOccurrs(0);
+
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setMinOccurrs(0);
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setMinOccurrs(0);
+
+ return doc;
+ }
+
+
+ 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$
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ // ======================================================================
+ // CHOICE NODE STUFF
+ //choice node, non-visual, so it has no name
+ MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode(exception_on_Default));
+ choice.setSource("xmltest.group.items"); //$NON-NLS-1$
+ choice.setMaxOccurrs(-1);
+ if (numChoices >= 1){
+ MappingCriteriaNode item = getChoiceChild("Item", "xmltest.group.items.itemName='Lamp'", numDefaultChoice == 1); //$NON-NLS-1$ //$NON-NLS-2$
+ choice.addCriteriaNode(item);
+ }
+ if (numChoices >= 2){
+ MappingCriteriaNode item = getChoiceChild("Item2", "xmltest.group.items.itemName='Screwdriver'", numDefaultChoice == 2); //$NON-NLS-1$ //$NON-NLS-2$
+ choice.addCriteriaNode(item);
+ }
+ if (numChoices >= 3){
+ MappingCriteriaNode item = getChoiceChild("Item3", "xmltest.group.items.itemName='Goat'", numDefaultChoice == 3); //$NON-NLS-1$ //$NON-NLS-2$
+ choice.addCriteriaNode(item);
+ }
+ if (numDefaultChoice > numChoices){
+ MappingCriteriaNode item = getChoiceChild("ItemDefault", null, true); //$NON-NLS-1$
+ choice.addCriteriaNode(item);
+ }
+
+ // ======================================================================
+ return doc;
+ }
+
+ private static MappingCriteriaNode getChoiceChild(String name, String criteria, boolean defalt){
+ MappingCriteriaNode crit = new MappingCriteriaNode(criteria, defalt);
+
+ MappingElement item = crit.addChildElement(new MappingElement(name));
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setNillable(true);
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+ return crit;
+ }
+
+ private static MappingDocument createXMLPlanWithDefaults() {
+ 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$
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setNillable(true);
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setDefaultValue("1"); //$NON-NLS-1$
+
+ return doc;
+ }
+
+ private static MappingDocument createXMLPlanUltraAdvanced() {
+
+ 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$
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ //choice node, non-visual, so it has no name
+ boolean exceptionOnDefault = false;
+ MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode(exceptionOnDefault));
+ choice.setSource("xmltest.group.items"); //$NON-NLS-1$
+ choice.setMaxOccurrs(-1);
+ MappingCriteriaNode crit1 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'okay'", false)); //$NON-NLS-1$
+ MappingElement item = crit1.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setNillable(true);
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setDefaultValue("0"); //$NON-NLS-1$
+
+ MappingCriteriaNode crit2= choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)); //$NON-NLS-1$
+ MappingElement discontinued = crit2.addChildElement(new MappingElement("DiscontinuedItem")); //$NON-NLS-1$
+ discontinued.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ discontinued.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setNillable(true);
+ discontinued.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setDefaultValue("0"); //$NON-NLS-1$
+
+ MappingCriteriaNode crit3 = choice.addCriteriaNode(new MappingCriteriaNode());
+ MappingElement unknown = crit3.addChildElement(new MappingElement("StatusUnknown"));//$NON-NLS-1$
+ unknown.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ unknown.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setNillable(true);
+ unknown.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setDefaultValue("0"); //$NON-NLS-1$
+
+ choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)).setExclude(true); //$NON-NLS-1$
+ choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)).setExclude(true); //$NON-NLS-1$
+
+ return doc;
+ }
+
+ private static MappingDocument createXMLPlanUltraAdvancedExceptionOnDefault() {
+
+ 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$
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ //choice node, non-visual, so it has no name
+ boolean exceptionOnDefault = true;
+ MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode(exceptionOnDefault));
+ choice.setSource("xmltest.group.items"); //$NON-NLS-1$
+ choice.setMaxOccurrs(-1);
+ MappingCriteriaNode crit1 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'okay'", false)); //$NON-NLS-1$
+ MappingElement item = crit1.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setNillable(true);
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setDefaultValue("0"); //$NON-NLS-1$
+
+ MappingCriteriaNode crit2 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)); //$NON-NLS-1$
+ MappingElement discontinued = crit2.addChildElement(new MappingElement("DiscontinuedItem")); //$NON-NLS-1$
+ discontinued.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ discontinued.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setNillable(true);
+ discontinued.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setDefaultValue("0"); //$NON-NLS-1$
+
+ choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)).setExclude(true); //$NON-NLS-1$
+
+ return doc;
+ }
+
+ //advanced tests of namespace declarations, use and scope; also fixed values
+ private static MappingDocument createXMLPlanAdvanced() {
+ //add to previous example
+ MappingDocument doc = createXMLPlanWithDefaults();
+ MappingElement root = (MappingElement)doc.getRootNode();
+
+ Namespace nameSpaceOne = new Namespace("duh", "http://www.duh.org/duh"); //$NON-NLS-1$ //$NON-NLS-2$
+ Namespace nameSpaceTwo = new Namespace("duh2", "http://www.duh2.org/duh2"); //$NON-NLS-1$ //$NON-NLS-2$
+ Namespace nameSpaceThree = new Namespace("duh", "http://www.duh.org/duh/duh"); //$NON-NLS-1$ //$NON-NLS-2$
+ Namespace nameSpaceFour = new Namespace(MappingNodeConstants.DEFAULT_NAMESPACE_PREFIX, ""); //$NON-NLS-1$
+ Namespace nameSpaceFive = new Namespace(MappingNodeConstants.DEFAULT_NAMESPACE_PREFIX, "http://www.default.org/default"); //$NON-NLS-1$
+
+ MappingElement fakeChildOfRoot = new MappingElement("Fake", nameSpaceOne); //$NON-NLS-1$
+ fakeChildOfRoot.setValue("fixed constant value"); //$NON-NLS-1$
+ fakeChildOfRoot.addNamespace(nameSpaceOne);
+ fakeChildOfRoot.addNamespace(nameSpaceTwo);
+ fakeChildOfRoot.addNamespace(nameSpaceFive);
+ root.addChildElement(fakeChildOfRoot);
+
+ MappingElement fakeChild2 = fakeChildOfRoot.addChildElement(new MappingElement("FakeChild2", nameSpaceOne)); //$NON-NLS-1$
+
+ //add fakeChild2a with default namespace
+ MappingElement fakeChild2a = fakeChild2.addChildElement(new MappingElement("FakeChild2a")); //$NON-NLS-1$
+ fakeChild2a.setValue("another fixed constant value"); //$NON-NLS-1$
+
+ MappingElement fakeChild3 = fakeChildOfRoot.addChildElement(new MappingElement("FakeChild3")); //$NON-NLS-1$
+ fakeChild3.addNamespace(nameSpaceThree);
+ fakeChild3.addNamespace(nameSpaceFour);
+
+ MappingAttribute fakeAtt = new MappingAttribute("FakeAtt", nameSpaceOne); //$NON-NLS-1$
+ fakeAtt.setValue("fixed att value"); //$NON-NLS-1$
+ fakeChild3.addAttribute(fakeAtt);
+
+ return doc;
+ }
+
+
+ /**
+ * Method createXMLPlanNested.
+ * @return MappingNode root of mapping doc
+ */
+ private static MappingDocument createXMLPlanMultipleDocs() {
+
+ MappingDocument doc = new MappingDocument(true);
+
+ MappingElement root = doc.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ root.setSource("xmltest.group.items"); //$NON-NLS-1$
+ root.setMaxOccurrs(-1);
+ root.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingSequenceNode sequence1 = root.addSequenceNode(new MappingSequenceNode());
+ sequence1.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ //NESTED STUFF======================================================================
+ MappingElement nestedWrapper = sequence1.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
+ MappingSequenceNode sequence2 = nestedWrapper.addSequenceNode(new MappingSequenceNode());
+
+ MappingElement supplier = sequence2.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$
+
+ MappingSequenceNode sequence3 = supplier.addSequenceNode(new MappingSequenceNode());
+ sequence3.addChildElement(new MappingElement("Name", "xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
+ sequence3.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+ return doc;
+ }
+
+ 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$
+
+ MappingElement ceo = root.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
+ ceo.setSource("xmltest.employees"); //$NON-NLS-1$
+ ceo.setMinOccurrs(0);
+ ceo.setMaxOccurrs(-1);
+ ceo.addAttribute(new MappingAttribute("ID", "xmltest.employees.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingSequenceNode sequence = ceo.addSequenceNode(new MappingSequenceNode());
+ sequence.addChildElement(new MappingElement("FirstName", "xmltest.employees.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
+ sequence.addChildElement(new MappingElement("LastName", "xmltest.employees.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
+ MappingElement subordinates = sequence.addChildElement(new MappingElement("Subordinates")); //$NON-NLS-1$
+
+ //recursive piece
+ MappingRecursiveElement employee = (MappingRecursiveElement)subordinates.addChildElement(new MappingRecursiveElement("Employee", "xmltest.employees")); //$NON-NLS-1$ //$NON-NLS-2$
+ employee.setSource("xmltest.employeesRecursive"); //$NON-NLS-1$
+ employee.setMinOccurrs(0);
+ employee.setMaxOccurrs(-1);
+
+ if (useRecursiveCriteria){
+ employee.setCriteria("xmltest.employees.employeeNum = '04'"); //$NON-NLS-1$
+ }
+ employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
+ return doc;
+ }
+
+ /*
+ * Recursion root mapping class is anchored at sequence node instead of "Employee" node
+ */
+ 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$
+
+ MappingSequenceNode seq0 = root.addSequenceNode(new MappingSequenceNode());
+ seq0.setSource("xmltest.employees"); //$NON-NLS-1$
+ seq0.setMinOccurrs(0);
+ seq0.setMaxOccurrs(-1);
+
+ MappingElement ceo = seq0.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
+ ceo.addAttribute(new MappingAttribute("ID", "xmltest.employees.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingSequenceNode seq = ceo.addSequenceNode(new MappingSequenceNode());
+ seq.addChildElement(new MappingElement("FirstName", "xmltest.employees.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq.addChildElement(new MappingElement("LastName", "xmltest.employees.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
+ MappingElement subordinates = seq.addChildElement(new MappingElement("Subordinates")); //$NON-NLS-1$
+
+ //recursive piece
+ MappingRecursiveElement employee = (MappingRecursiveElement)subordinates.addChildElement(new MappingRecursiveElement("Subordinate", "xmltest.employees")); //$NON-NLS-1$ //$NON-NLS-2$
+ employee.setSource("xmltest.employeesRecursive"); //$NON-NLS-1$
+ employee.setMinOccurrs(0);
+ employee.setMaxOccurrs(-1);
+
+ if (useRecursiveCriteria){
+ employee.setCriteria("xmltest.employees.employeeNum = '04'"); //$NON-NLS-1$
+ }
+ employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
+ return doc;
+ }
+
+ private static MappingDocument createXMLPlanRecursiveStaging(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
+
+ MappingDocument doc = new MappingDocument(true);
+
+ MappingElement root = doc.addChildElement(new MappingElement("OrgHierarchy")); //$NON-NLS-1$
+ root.setStagingTables(Arrays.asList(new String[] {"xmltest.doc19temp"})); //$NON-NLS-1$
+
+ MappingElement ceo = root.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
+ ceo.setSource("xmltest.employeesDoc19"); //$NON-NLS-1$
+ ceo.setMinOccurrs(0);
+ ceo.setMaxOccurrs(-1);
+ ceo.addAttribute(new MappingAttribute("ID", "xmltest.employeesDoc19.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingSequenceNode seq = ceo.addSequenceNode(new MappingSequenceNode());
+ seq.addChildElement(new MappingElement("FirstName", "xmltest.employeesDoc19.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq.addChildElement(new MappingElement("LastName", "xmltest.employeesDoc19.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
+ MappingElement subordinates = seq.addChildElement(new MappingElement("Subordinates")); //$NON-NLS-1$
+
+ //recursive piece
+ MappingRecursiveElement employee = (MappingRecursiveElement)subordinates.addChildElement(new MappingRecursiveElement("Employee", "xmltest.employeesDoc19")); //$NON-NLS-1$ //$NON-NLS-2$
+ employee.setSource("xmltest.employeesRecursiveDoc19"); //$NON-NLS-1$
+ employee.setMinOccurrs(0);
+ employee.setMaxOccurrs(-1);
+
+ if (useRecursiveCriteria){
+ employee.setCriteria("xmltest.employeesDoc19.employeeNum = '04'"); //$NON-NLS-1$
+ }
+ employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
+
+ return doc;
+ }
+
+ 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$
+
+ MappingElement ceo = root.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
+ ceo.setSource("xmltest.employees2"); //$NON-NLS-1$
+ ceo.setMinOccurrs(0);
+ ceo.setMaxOccurrs(-1);
+ ceo.addAttribute(new MappingAttribute("ID", "xmltest.employees2.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingSequenceNode seq = ceo.addSequenceNode(new MappingSequenceNode());
+ seq.addChildElement(new MappingElement("FirstName", "xmltest.employees2.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
+ seq.addChildElement(new MappingElement("LastName", "xmltest.employees2.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ //recursive piece
+ MappingRecursiveElement employee = (MappingRecursiveElement)seq.addChildElement(new MappingRecursiveElement("Supervisor", "xmltest.employees2")); //$NON-NLS-1$ //$NON-NLS-2$
+ employee.setSource("xmltest.employees2Recursive"); //$NON-NLS-1$
+ employee.setMinOccurrs(0);
+ employee.setMaxOccurrs(-1);
+
+ if (useRecursiveCriteria){
+ employee.setCriteria("xmltest.employees2.employeeNum = '04'"); //$NON-NLS-1$
+ }
+ employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
+ return doc;
+ }
+
+ //this is for testing how "optional" XML elements are included/
+ //excluded from the result document
+ private static MappingDocument createXMLPlan_defect8917() {
+
+ Namespace namespace1 = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+
+ root.addNamespace(namespace1);
+
+ {
+ //FRAGMENT 1
+ MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setNillable(true);
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ {
+ //FRAGMENT 2
+ MappingElement cat = root.addChildElement(new MappingElement("OptionalCatalog")); //$NON-NLS-1$
+ cat.setMinOccurrs(0);
+
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setNillable(true);
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ {
+ //FRAGMENT 3
+ MappingElement cat = root.addChildElement(new MappingElement("OptionalCatalog2")); //$NON-NLS-1$
+ cat.setMinOccurrs(0);
+
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setNillable(true);
+ }
+
+ {
+ //FRAGMENT 4
+ MappingElement cat = root.addChildElement(new MappingElement("OptionalCatalog3")); //$NON-NLS-1$
+ cat.setMinOccurrs(0);
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ {
+ //FRAGMENT 5
+ MappingElement cat = root.addChildElement(new MappingElement("Catalog4")); //$NON-NLS-1$
+ MappingElement items = cat.addChildElement(new MappingElement("OptionalItems")); //$NON-NLS-1$
+ items.setMinOccurrs(0);
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ {
+ //FRAGMENT 6
+ MappingElement cat = root.addChildElement(new MappingElement("Catalog5")); //$NON-NLS-1$
+ MappingElement items = cat.addChildElement(new MappingElement("OptionalItems")); //$NON-NLS-1$
+ items.setMinOccurrs(0);
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.addChildElement(new MappingElement("FixedName")) //$NON-NLS-1$
+ .setValue("Nugent"); //$NON-NLS-1$
+ }
+
+ {
+ //FRAGMENT 7
+ MappingElement cat = root.addChildElement(new MappingElement("Catalog6")); //$NON-NLS-1$
+ MappingElement items = cat.addChildElement(new MappingElement("OptionalItems")); //$NON-NLS-1$
+ items.setMinOccurrs(0);
+
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.addChildElement(new MappingElement("EmptyName")); //$NON-NLS-1$
+ }
+ return doc;
+ }
+
+ /*
+ * Test of identically named nodes
+ */
+ private static MappingDocument createXMLPlan_defect9446() {
+ 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$
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+ MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addAttribute(new MappingAttribute("XXXXX", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("XXXXX", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("XXXXX", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+ return doc;
+ }
+
+ 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$
+
+ MappingDocument doc = new MappingDocument(true);
+ MappingElement root = doc.addChildElement(new MappingElement("Catalogs", namespace)); //$NON-NLS-1$
+ root.addNamespace(namespace);
+
+ MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ MappingElement item = items.addChildElement(new MappingElement("Item", namespace)); //$NON-NLS-1$
+ item.setSource("xmltest.group.items"); //$NON-NLS-1$
+ item.setMaxOccurrs(-1);
+ item.addNamespace(namespace2);
+ item.addNamespace(namespace3);
+
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+ return doc;
+ }
+
+ private static MappingDocument createGroupDoc() {
+ MappingDocument doc = new MappingDocument(true);
+
+ MappingElement root = doc.addChildElement(new MappingElement("group")); //$NON-NLS-1$
+ root.setSource("xqttest.group"); //$NON-NLS-1$
+ root.setMinOccurrs(0);
+ root.setMaxOccurrs(-1);
+
+ MappingAttribute attr = new MappingAttribute("pseudoID", "xqttest.group.ID"); //$NON-NLS-1$ //$NON-NLS-2$
+ attr.setExclude(true);
+ root.addAttribute(attr);
+
+ MappingSequenceNode sequence = root.addSequenceNode(new MappingSequenceNode());
+ sequence.addChildElement(new MappingElement("ID", "xqttest.group.ID")); //$NON-NLS-1$ //$NON-NLS-2$
+ sequence.addChildElement(new MappingElement("code", "xqttest.group.Code")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingElement supervisor = sequence.addChildElement(new MappingElement("supervisor")); //$NON-NLS-1$
+ supervisor.setSource("xqttest.supervisor"); //$NON-NLS-1$
+ supervisor.setMinOccurrs(0);
+ supervisor.setMaxOccurrs(-1);
+
+ MappingSequenceNode sequence1 = supervisor.addSequenceNode(new MappingSequenceNode());
+ sequence1.addChildElement(new MappingElement("ID", "xqttest.supervisor.ID")); //$NON-NLS-1$ //$NON-NLS-2$
+ sequence1.addChildElement(new MappingElement("code", "xqttest.supervisor.Code")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ MappingRecursiveElement group1 = (MappingRecursiveElement)sequence1.addChildElement(new MappingRecursiveElement("group", "xqttest.group")); //$NON-NLS-1$ //$NON-NLS-2$
+ group1.setSource("xqttest.group1"); //$NON-NLS-1$
+ group1.setMinOccurrs(0);
+ group1.setMaxOccurrs(-1);
+ return doc;
+ }
+
+ public static FakeDataManager exampleDataManager(QueryMetadataInterface metadata) {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ try {
+ dataMgr.registerTuples(
+ 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(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ return dataMgr;
+ }
+
+ public static FakeDataManager exampleDataManager15117(QueryMetadataInterface metadata) {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ try {
+ dataMgr.registerTuples(
+ 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(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ return dataMgr;
+ }
+
+ /** unusual characters in text */
+ public static FakeDataManager exampleDataManager15117a(QueryMetadataInterface metadata) {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ try {
+ dataMgr.registerTuples(
+ 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(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ return dataMgr;
+ }
+
+ public static FakeDataManager exampleDataManager14905(QueryMetadataInterface metadata) {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ try {
+ dataMgr.registerTuples(
+ 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(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ return dataMgr;
+ }
+
+ public static FakeDataManager exampleDataManager13617(QueryMetadataInterface metadata) {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ try {
+ dataMgr.registerTuples(
+ 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(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ return dataMgr;
+ }
+
+ public static FakeDataManager exampleDataManagerNested(QueryMetadataInterface metadata) {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ try {
+ dataMgr.registerTuples(
+ 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(
+ 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(
+ 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(
+ 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(
+ 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(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ return dataMgr;
+ }
+
+ private FakeDataManager exampleDataManagerNestedWithSibling(QueryMetadataInterface metadata) {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ try {
+
+ dataMgr.registerTuples(
+ 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(
+ 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(
+ 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(
+ 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(
+ 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(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ return dataMgr;
+ }
+
+ /**
+ * Returned with some null values in the tuples, to test default/fixed attributes of nodes
+ * as well as nillable nodes
+ */
+ private FakeDataManager exampleDataManagerWithNulls(QueryMetadataInterface metadata) {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ try {
+ 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$
+ } );
+
+ } catch(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ return dataMgr;
+ }
+
+ public static FakeDataManager exampleDataManagerForSoap1(QueryMetadataInterface metadata, boolean makeEmpty) {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ try {
+ List<?>[] tuples = null;
+ if (makeEmpty){
+ tuples = new List[0];
+ } else {
+ tuples = new List[] {
+ Arrays.asList( new Object[] { "1"} ), //$NON-NLS-1$
+ Arrays.asList( new Object[] { "2" } ), //$NON-NLS-1$
+ Arrays.asList( new Object[] { "3" } ), //$NON-NLS-1$
+ };
+ }
+
+ dataMgr.registerTuples(
+ metadata,
+ "taxReport.TaxIDs", tuples );
+
+ } catch(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ return dataMgr;
+ }
+
+ /** data has a null value
+ * @throws TeiidComponentException
+ * @throws QueryResolverException */
+ private FakeDataManager exampleDataManager_8917(QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ 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(QueryMetadataInterface metadata) {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ try {
+ 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$
+ } );
+
+ } catch(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ return dataMgr;
+ }
+
+ /** data has an EMPTY STRING
+ * @throws TeiidComponentException
+ * @throws QueryResolverException */
+ private FakeDataManager exampleDataManager_8917b(QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ 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$
+ } );
+
+ return dataMgr;
+ }
+
+ /**
+ * Duplicate records in data
+ * @param metadata
+ * @return FakeDataManager
+ * @throws TeiidComponentException
+ * @throws QueryResolverException
+ */
+ private FakeDataManager exampleDataManagerWithDuplicates(QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ 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$
+ } );
+
+ return dataMgr;
+ }
+
+ /**
+ *
+ * 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(QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ 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$
+ } );
+
+ return dataMgr;
+ }
+
+ /**
+ * Deluxe example
+ * @throws TeiidComponentException
+ * @throws QueryResolverException
+ */
+ private FakeDataManager exampleDataManagerDuJour(QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ 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(QueryMetadataInterface metadata) throws Exception {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ // Group stock.items
+ dataMgr.registerTuples(
+ 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;
+ }
+
+ public static Command helpGetCommand(String sql, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException {
+ QueryParser parser = new QueryParser();
+ Command command = parser.parseCommand(sql);
+ QueryResolver.resolveCommand(command, metadata);
+ command = QueryRewriter.rewrite(command, metadata, null);
+ return command;
+ }
+
+ 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, QueryMetadataInterface metadata, FakeDataManager dataMgr, Class<?> expectedException) throws Exception{
+
+ return helpTestProcess(sql, metadata, dataMgr, expectedException, new DefaultCapabilitiesFinder(), expectedDoc);
+ }
+
+ 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);
+
+ try {
+ CommandContext planningContext = new CommandContext(); //this should be the same as the processing context, but that's not easy to do
+ planningContext.setMetadata(new TempMetadataAdapter(metadata, new TempMetadataStore()));
+ ProcessorPlan plan = QueryOptimizer.optimizePlan(command, metadata, null, capFinder, analysisRecord, planningContext);
+
+ if(DEBUG) {
+ System.out.println(analysisRecord.getDebugLog());
+ }
+ List<?>[] expected = new List[expectedDoc.length];
+ for (int i = 0; i < expectedDoc.length; i++) {
+ expected[i] = Arrays.asList(expectedDoc[i]);
+ }
+ TestProcessor.helpProcess(plan, planningContext, dataMgr, expected);
+ assertNull("Expected failure", expectedException);
+ return plan;
+ } catch (Exception e) {
+ if (expectedException == null) {
+ throw e;
+ }
+ assertTrue(expectedException.isInstance(e));
+ } finally {
+ if(DEBUG) {
+ System.out.println(analysisRecord.getDebugLog());
+ }
+ }
+ return null;
+ }
+
+ // =============================================================================================
+ // T E S T S
+ // =============================================================================================
+
+ @Test public void test1() throws Exception {
+ QueryMetadataInterface 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", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy1() throws Exception {
+ QueryMetadataInterface 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=\"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$
+ " <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$
+ " </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 ORDER BY Catalogs.Catalog.Items.Item.Quantity ASC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy1a() throws Exception {
+ QueryMetadataInterface 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=\"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$
+ " <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$
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </Catalog>\r\n" + //$NON-NLS-1$
+ "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT \"xml\" FROM xmltest.doc1 ORDER BY Catalogs.Catalog.Items.Item.Quantity ASC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy1b() throws Exception {
+ QueryMetadataInterface 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=\"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$
+ " <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$
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </Catalog>\r\n" + //$NON-NLS-1$
+ "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT xmltest.doc1.xml FROM xmltest.doc1 ORDER BY Catalogs.Catalog.Items.Item.Quantity ASC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy2() throws Exception {
+ QueryMetadataInterface 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=\"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=\"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=\"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 ORDER BY Catalogs.Catalog.Items.Item.Quantity DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy3() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8 ORDER BY Catalogs.Catalog.Items.Item.ItemID DESC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy3a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8 ORDER BY Catalogs.Catalog.Items.Item.ItemID ASC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy4() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(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$
+ " </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 ItemID='001' AND Quantity < 60 ORDER BY ItemID", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy5() throws Exception {
+ QueryMetadataInterface 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 ORDER BY ItemID", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy6() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9 ORDER BY Catalogs.Catalog.Items.Item.ItemID ASC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, OrderID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ //order by with temp group at the root
+ @Test public void testOrderBy7() throws Exception {
+ 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 {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9 WHERE Catalogs.Catalog.Items.Item.Quantity < 60 ORDER BY Catalogs.Catalog.Items.Item.ItemID ASC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, OrderID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /*
+ @Test public void testOrderBy9() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc = "";
+
+ boolean shouldSucceed = false;
+ Class expectedException = QueryResolverException.class;
+ String shouldFailMsg = "Unable to resolve element: Quantity";
+
+ helpTestProcess("SELECT * FROM xmltest.doc9 WHERE Quantity < 60 ORDER BY ItemID ASC, SupplierID ASC, OrderID DESC", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);
+ }
+ */
+
+ @Test public void testOrderBy10() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(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=\"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 Quantity < 60 ORDER BY Name DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy11() throws Exception {
+ 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 {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(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=\"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=\"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=\"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 ORDER BY Name DESC, Quantity ASC ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy14() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9 ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy15() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(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=\"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$
+ " <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$
+ " </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 ORDER BY Name ASC, Quantity DESC ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** test null elements*/
+ @Test public void testOrderBy17() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerWithNulls(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 xsi:nil=\"true\"/>\r\n" + //$NON-NLS-1$
+ " <Quantity>5</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$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
+ " <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 ORDER BY Name ASC, Quantity ASC ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** test duplicate elements*/
+ @Test public void testOrderBy18() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerWithDuplicates(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>Goat</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>5</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$
+ " <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$
+ " </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 ORDER BY Name ASC, Quantity DESC ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** test more than two parallel elements*/
+ @Test public void testOrderBy19() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerWithDuplicates1(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>Goat</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\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$
+ " <Item ItemID=\"003\">\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$
+ " </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 ORDER BY ItemID ASC, Name ASC, Quantity DESC ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy20() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9 WHERE ItemID='002' AND Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderQuantity < 1000 " //$NON-NLS-1$
+ + "ORDER BY SupplierID ", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /**
+ * Doc nodes that are not mapped to data cannot be used in the
+ * ORDER BY clause of an XML doc query
+ */
+ @Test public void testOrderBy_defect9803() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ try {
+ helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='002' AND Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderQuantity < 1000 " //$NON-NLS-1$
+ + "ORDER BY Suppliers", //$NON-NLS-1$
+ "", metadata, dataMgr); //$NON-NLS-1$
+ fail("Should have failed with QueryPlannerException but didn't"); //$NON-NLS-1$
+ } catch (QueryPlannerException e) {
+ String expectedMsg = "The XML document element [element] name='Suppliers' minOccurs=1 maxOccurs=1 is not mapped to data and cannot be used in the ORDER BY clause: ORDER BY Suppliers"; //$NON-NLS-1$
+ assertEquals(expectedMsg, e.getMessage());
+ }
+ }
+
+ //defect 8130
+ @Test public void test1CriteriaWithUnmappedElementFails() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ helpTestProcess("SELECT * FROM xmltest.doc1 WHERE Catalog = 'something'", null, metadata, dataMgr, QueryPlannerException.class); //$NON-NLS-1$
+ }
+
+ //defect 8130
+ @Test public void test1CriteriaWithUnmappedElementFails2() throws Exception {
+ 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 {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ private static final String EXPECTED_DOC_NESTED_2 =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+
+ private static final String EXPECTED_DOC_NESTED_3 =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+
+ @Test public void testNested2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc = EXPECTED_DOC_NESTED_2;
+ helpTestProcess("SELECT * FROM xmltest.doc9", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * Tests a couple temp groups at the root - B selects from A, and a mapping class
+ * selects from B
+ */
+ @Test public void testNested2aTempGroup() throws Exception {
+ 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 {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9a WHERE tempGroup.orders.orderNum = 1", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** defect 13172, CSE Case 1811 */
+ @Test public void testNested2aTempGroupCompoundCriteria() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+// " <Orders>\r\n" + //$NON-NLS-1$
+// " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+// " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+// " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+// " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+// " </Order>\r\n" + //$NON-NLS-1$
+// " </Orders>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9a WHERE tempGroup.orders.orderNum = '1' AND tempGroup.orders.orderStatus = 'processing'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** defect 13172, CSE Case 1811 */
+ @Test public void testNested2aTempGroupCompoundCriteria1() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+// " <Orders>\r\n" + //$NON-NLS-1$
+// " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+// " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+// " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+// " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+// " </Order>\r\n" + //$NON-NLS-1$
+// " </Orders>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9a WHERE tempGroup.orders.orderNum = 1 AND tempGroup.orders.orderQty = 87", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** defect 13172, CSE Case 1811 */
+ @Test public void testNested2aTempGroupCompoundCriteria2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+// " <Orders/>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9a WHERE tempGroup.orders.orderNum = '1' OR tempGroup.orders.orderStatus = 'processing'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNested2cTempGroup() throws Exception {
+ 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$
+ }
+
+ /**
+ * Tests a temp group C that selects from a root temp group, plus has bindings to
+ * some ancestor mapping classes ( we no longer support bindings on staging tables)
+ */
+ public void defer_testNested2bTempGroup() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc = EXPECTED_DOC_NESTED_2;
+ helpTestProcess("SELECT * FROM xmltest.doc9b", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNested2WithCriteria() throws Exception {
+
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9 WHERE ItemID='001'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * <p>This test illustrates how to use the context operator
+ * to specify that the result set to limit is the same as the
+ * result set which the criteria originates from, when that
+ * result set is nested below the top level.
+ * Test {@link #testNested2WithCriteria2a} shows a similar
+ * query without the context operator.</p>
+ *
+ * @see #testNested2WithCriteria2a
+ */
+ @Test public void testNested2WithCriteria2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers/>\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$
+ " <Suppliers/>\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$
+
+ XMLPlan plan = (XMLPlan)helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(SupplierID, SupplierID)='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+
+ // check the staging base line (unknown cost)
+ // one for staging and for unloading
+ Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
+ assertEquals(2, ((List)stats.get(ExecStagingTableInstruction.class)).size());
+ }
+
+ /**
+ * <p>This test illustrates how to use the context operator
+ * to specify that the result set to limit is the same as the
+ * result set which the criteria originates from, when that
+ * result set is nested below the top level.
+ * Test {@link #testNested2WithCriteria2a} shows a similar
+ * query without the context operator.</p>
+ *
+ * <p>defect 9802, trying different ways of qualifying 1st arg
+ * to context operator</p>
+ *
+ * @see #testNested2WithCriteria2a
+ */
+ @Test public void testNested2WithCriteria2_defect9802() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers/>\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$
+ " <Suppliers/>\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.doc9 WHERE context(Supplier.SupplierID, SupplierID)='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * <p>Same as {@link #testNested2WithCriteria2} but with a
+ * type conversion on the right expression from integer to string.
+ * This demonstrates a function of only constants is executed in
+ * an XML criteria.</p>
+ * shows a similar
+ * @see #testNested2WithCriteria2
+ */
+ @Test public void testNested2WithCriteria2_function() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers/>\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$
+ " <Suppliers/>\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.doc9 WHERE context(SupplierID, SupplierID)=convert(52, string)", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * <p>This tests the unintuitive effects of specifying a user
+ * criteria on a node inside a nested mapping class. Here, the
+ * "Item" fragment is repeated, but the "Supplier" fragment inside
+ * is limited by the criteria.
+ * Test {@link #testNested2WithCriteria2} shows how to use
+ * the "context" syntax to control what context the criteria
+ * is used to restrict.</p>
+ *
+ * <P>UPDATE: With 3.0 sp1 the default behavior is changed.
+ * Now, if "context" syntax is not used, the outer context (anchored
+ * at "Item" node) will be limited by default, instead of the one
+ * the criteria is actually specified on.</p>
+ */
+ @Test public void testNested2WithCriteria2a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9 WHERE SupplierID='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+
+ @Test public void testNested2WithContextCriteria() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9 WHERE context(Item, SupplierID)='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNested2WithContextCriteria2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+// " <OrderStatus/>\r\n" +
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9 WHERE context(Item, OrderID)='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNested2WithContextCriteria3() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers/>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers/>\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.doc9 WHERE context(SupplierID, OrderID)='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ private static final String EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4 =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+
+
+ @Test public void testNested2WithContextCriteria4() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
+
+ helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR context(Item, OrderID)='6'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNested2WithContextCriteria4a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
+
+ helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR OrderID='6'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNested2WithContextCriteria4b() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
+
+ helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR OrderID='6'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ private static final String EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5 =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+
+ @Test public void testNested2WithContextCriteria5() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
+
+ helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR context(Item, OrderID)='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNested2WithContextCriteria5a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
+
+ helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR context(Item, OrderID)='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNested2WithContextCriteria5b() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
+
+ helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR OrderID='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ public static String readFile(String fileName) throws Exception {
+ FileInputStream fis = new FileInputStream(UnitTestUtil.getTestDataFile(fileName));
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+
+ int c = 0;
+ while ((c = fis.read()) != -1) {
+ baos.write(c);
+ }
+
+ return baos.toString();
+ }
+
+ @Test public void testNested2WithContextCriteria5Fail() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc = ""; //doesn't matter //$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 {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\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.doc9 WHERE context(Item, OrderID)='5' AND context(Item, OrderID)='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNested2WithContextCriteria6b() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\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.doc9 WHERE OrderID='5' AND OrderID='2'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ //WHERE CONTEXT(SupplierID, OrderID)='5' AND context(OrderID, OrderID)='5'
+ private static final String EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_7 =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers/>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers/>\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$
+
+ @Test public void testNested2WithContextCriteria7() throws Exception {
+ 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 {
+ 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$
+ + "Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderID)='5' AND context(OrderID, OrderID)='5'"; //$NON-NLS-1$
+ helpTestProcess(query, expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testNested2WithContextCriteria7c() throws Exception {
+ 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$
+ + "Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderID)='6' AND context(OrderID, OrderID)='5'"; //$NON-NLS-1$
+ helpTestProcess(query, expectedDoc, metadata, dataMgr);
+ }
+
+ /**
+ * per defect 7333
+ */
+ @Test public void testNested2WithContextCriteria_7333() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9 WHERE OrderID='4' AND ItemID='003'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * per defect 7333
+ */
+ @Test public void testNested2WithContextCriteria_7333b() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9 WHERE ItemID='003' AND OrderID='4'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * per defect 7333
+ */
+ @Test public void testNested2WithContextCriteria_7333c() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\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.doc9 WHERE OrderID='5' AND ItemID='003'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * per defect 7333
+ */
+ @Test public void testNested2WithContextCriteria_7333d() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\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.doc9 WHERE ItemID='003' AND OrderID='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * Select a single item, and then limit the suppliers based on an order #
+ */
+ @Test public void testNested2WithContextCriteria8() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9 WHERE ItemID='002' AND Context(Supplier,OrderID)='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNestedWithChoice() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " <OtherOrder OrderID=\"2\"/>\r\n" + //$NON-NLS-1$
+ " </ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " <OtherOrder OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
+ " </ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
+ " <OtherOrder OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
+ " </ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " <OtherOrder OrderID=\"3\"/>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc10", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * Does not use 'context' operator
+ */
+ @Test public void testNestedWithChoiceAndCriteria2_6796() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " <OtherOrder OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
+ " </ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
+ " <OtherOrder OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
+ " </ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc10 where Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * Uses the 'context' operator
+ */
+ @Test public void testNestedWithChoiceAndCriteria2a_6796() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
+ " </ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc10 where context(Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID, Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID)='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * Does not use 'context' operator
+ */
+ @Test public void testNestedWithLookupChoice() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " <OtherOrder OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
+ " </ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
+ " <OtherOrder OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
+ " </ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc10L where Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID='5'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void test1Unformatted() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
+ "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + //$NON-NLS-1$
+ "<Catalog>" + //$NON-NLS-1$
+ "<Items>" + //$NON-NLS-1$
+ "<Item ItemID=\"001\">" + //$NON-NLS-1$
+ "<Name>Lamp</Name>" + //$NON-NLS-1$
+ "<Quantity>5</Quantity>" + //$NON-NLS-1$
+ "</Item>" + //$NON-NLS-1$
+ "<Item ItemID=\"002\">" + //$NON-NLS-1$
+ "<Name>Screwdriver</Name>" + //$NON-NLS-1$
+ "<Quantity>100</Quantity>" + //$NON-NLS-1$
+ "</Item>" + //$NON-NLS-1$
+ "<Item ItemID=\"003\">" + //$NON-NLS-1$
+ "<Name>Goat</Name>" + //$NON-NLS-1$
+ "<Quantity>4</Quantity>" + //$NON-NLS-1$
+ "</Item>" + //$NON-NLS-1$
+ "</Items>" + //$NON-NLS-1$
+ "</Catalog>" + //$NON-NLS-1$
+ "</Catalogs>\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc1Unformatted", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+
+ // jhTODO: complete this
+
+ @Test public void testChoice_5266a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$\r\n"
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$\r\n" +
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </ProcessingOrders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc_5266a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+
+ @Test public void test1WithCriteriaShortName() throws Exception {
+ QueryMetadataInterface 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=\"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 quantity < 50", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void test1WithCriteriaLongName() throws Exception {
+ QueryMetadataInterface 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=\"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 catalogs.catalog.items.item.quantity < 50", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void test2() throws Exception {
+ QueryMetadataInterface 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$
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </Catalog>\r\n" + //$NON-NLS-1$
+ "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void test2a() throws Exception {
+ QueryMetadataInterface 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.doc2a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void test2b() throws Exception {
+ 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 {
+ QueryMetadataInterface 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$
+ " <Item2 ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
+ " </Item2>\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.doc2c", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void test2d() throws Exception {
+ QueryMetadataInterface 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$
+ " <Item2 ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
+ " </Item2>\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.doc2d", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void test2e() throws Exception {
+ QueryMetadataInterface 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$
+ " <Item2 ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
+ " </Item2>\r\n" + //$NON-NLS-1$
+ " <ItemDefault ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Name>Goat</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>4</Quantity>\r\n" + //$NON-NLS-1$
+ " </ItemDefault>\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.doc2e", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testWithNillableNode() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerWithNulls(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 xsi:nil=\"true\"/>\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/>\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", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testWithDefault() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerWithNulls(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 xsi:nil=\"true\"/>\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>1</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.doc3", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testWithNamespaces() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerWithNulls(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 xsi:nil=\"true\"/>\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>1</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$
+ " <duh:Fake xmlns:duh=\"http://www.duh.org/duh\" xmlns:duh2=\"http://www.duh2.org/duh2\"\n" + //$NON-NLS-1$
+ " xmlns=\"http://www.default.org/default\">fixed constant value<duh:FakeChild2>\r\n" + //$NON-NLS-1$
+ " <FakeChild2a>another fixed constant value</FakeChild2a>\r\n" + //$NON-NLS-1$
+ " </duh:FakeChild2>\r\n" + //$NON-NLS-1$
+ " <FakeChild3 xmlns:duh=\"http://www.duh.org/duh/duh\" duh:FakeAtt=\"fixed att value\"/>\r\n" + //$NON-NLS-1$
+ " </duh:Fake>\r\n" + //$NON-NLS-1$
+ "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc4", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testWithNewIter3Properties() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerDuJour(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 xsi:nil=\"true\"/>\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>0</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$
+ " <DiscontinuedItem ItemID=\"004\">\r\n" + //$NON-NLS-1$
+ " <Name>Flux Capacitor</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>2</Quantity>\r\n" + //$NON-NLS-1$
+ " </DiscontinuedItem>\r\n" + //$NON-NLS-1$
+ " <StatusUnknown ItemID=\"005\">\r\n" + //$NON-NLS-1$
+ " <Name>Milkshake</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>88</Quantity>\r\n" + //$NON-NLS-1$
+ " </StatusUnknown>\r\n" + //$NON-NLS-1$
+ " <DiscontinuedItem ItemID=\"006\">\r\n" + //$NON-NLS-1$
+ " <Name>Feta Matrix</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>0</Quantity>\r\n" + //$NON-NLS-1$
+ " </DiscontinuedItem>\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.doc5", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testWithNewIter3PropertiesException() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerDuJour(metadata);
+
+ Command command = helpGetCommand("SELECT * FROM xmltest.doc6", metadata); //$NON-NLS-1$
+ XMLPlan plan = TestXMLPlanner.preparePlan(command, metadata, new DefaultCapabilitiesFinder(), null);
+
+ BufferManager bufferMgr = BufferManagerFactory.getStandaloneBufferManager();
+ CommandContext context = new CommandContext("pID", null, null, null, 1); //$NON-NLS-1$
+ QueryProcessor processor = new QueryProcessor(plan, context, bufferMgr, dataMgr);
+ processor.setNonBlocking(true);
+ BatchCollector collector = processor.createBatchCollector();
+ TeiidComponentException failOnDefaultException = null;
+ try{
+ collector.collectTuples();
+ } catch (TeiidComponentException e){
+ failOnDefaultException = e;
+ }
+
+ assertNotNull("Query processing should have failed on default of choice node.", failOnDefaultException); //$NON-NLS-1$
+ }
+
+ @Test public void testAttributeBug() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<FixedValueTest>\r\n" + //$NON-NLS-1$
+ " <wrapper fixedAttr=\"fixed attribute\">\r\n" + //$NON-NLS-1$
+ " <key>001</key>\r\n" + //$NON-NLS-1$
+ " <fixed>fixed value</fixed>\r\n" + //$NON-NLS-1$
+ " </wrapper>\r\n" + //$NON-NLS-1$
+ " <wrapper fixedAttr=\"fixed attribute\">\r\n" + //$NON-NLS-1$
+ " <key>002</key>\r\n" + //$NON-NLS-1$
+ " <fixed>fixed value</fixed>\r\n" + //$NON-NLS-1$
+ " </wrapper>\r\n" + //$NON-NLS-1$
+ " <wrapper fixedAttr=\"fixed attribute\">\r\n" + //$NON-NLS-1$
+ " <key>003</key>\r\n" + //$NON-NLS-1$
+ " <fixed>fixed value</fixed>\r\n" + //$NON-NLS-1$
+ " </wrapper>\r\n" + //$NON-NLS-1$
+ "</FixedValueTest>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc7", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testMultipleDocs() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ String expectedDoc1 =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ "</Item>\r\n\r\n"; //$NON-NLS-1$
+
+ String expectedDoc2 =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ "</Item>\r\n\r\n"; //$NON-NLS-1$
+
+ String expectedDoc3 =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ "</Item>\r\n\r\n"; //$NON-NLS-1$
+
+
+ helpTestProcess("SELECT * FROM xmltest.doc11", metadata, dataMgr, null, new DefaultCapabilitiesFinder(), expectedDoc1, expectedDoc2, expectedDoc3); //$NON-NLS-1$
+ }
+
+ @Test public void testRecursive() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<OrgHierarchy>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"01\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"02\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"04\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"06\">\r\n" + //$NON-NLS-1$
+ " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Zorn</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"11\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Mike</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Patton</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"13\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Puffy</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Bordin</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"12\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Devin</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Townsend</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"03\">\r\n" + //$NON-NLS-1$
+ " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"05\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"07\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"08\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"09\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"10\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ "</OrgHierarchy>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc12", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testRecursiveA() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<OrgHierarchy>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"01\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Subordinate ID=\"02\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Subordinate ID=\"04\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Subordinate ID=\"06\">\r\n" + //$NON-NLS-1$
+ " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Zorn</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Subordinate ID=\"11\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Mike</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Patton</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Subordinate ID=\"13\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Puffy</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Bordin</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Subordinate>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Subordinate>\r\n" + //$NON-NLS-1$
+ " <Subordinate ID=\"12\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Devin</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Townsend</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Subordinate>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Subordinate>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Subordinate>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Subordinate>\r\n" + //$NON-NLS-1$
+ " <Subordinate ID=\"03\">\r\n" + //$NON-NLS-1$
+ " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Subordinate ID=\"05\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Subordinate>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Subordinate>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"07\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Subordinate ID=\"08\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Subordinate ID=\"09\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Subordinate>\r\n" + //$NON-NLS-1$
+ " <Subordinate ID=\"10\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Subordinate>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Subordinate>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ "</OrgHierarchy>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc12a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * 4/25/05 sbale - This failing test raises a question about recursion
+ * termination criteria - should the chunk of document that meets the
+ * criteria be included or not? In this test below, it is expected to
+ * be included, but is not included in actual results due to recent
+ * changes for Booz Allen POC. I could see it going either way.
+ *
+ * sbale 4/27/05 I have changed expected results as a result of changes for
+ * Booz Allen POC. Previously, the recursive fragment of the document that
+ * satisfied the recursion termination criteria was included, now it is not.
+ * See commented out section below for previous expected results.
+ * @throws Exception
+ */
+ @Test public void testRecursive2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<OrgHierarchy>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"01\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"02\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+// " <Subordinates>\r\n" + //$NON-NLS-1$
+// " <Employee ID=\"04\">\r\n" + //$NON-NLS-1$
+// " <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
+// " <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
+// " <Subordinates/>\r\n" + //$NON-NLS-1$
+// " </Employee>\r\n" + //$NON-NLS-1$
+// " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"03\">\r\n" + //$NON-NLS-1$
+ " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"05\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"07\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"08\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"09\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"10\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ "</OrgHierarchy>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc13", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+ @Test public void testRecursive3() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<OrgHierarchy>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"01\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"02\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"04\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"03\">\r\n" + //$NON-NLS-1$
+ " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"05\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"07\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"08\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"09\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"10\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ "</OrgHierarchy>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc14", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testRecursive4Exception() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ helpTestProcess("SELECT * FROM xmltest.doc15", null, metadata, dataMgr, TeiidComponentException.class); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Seems to be failing as a result of changes for defect 12288
+ */
+ @Test public void testRecursive5() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Employees>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"08\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+ " <Supervisor ID=\"07\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+ " </Supervisor>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"09\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
+ " <Supervisor ID=\"08\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+ " <Supervisor ID=\"07\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+ " </Supervisor>\r\n" + //$NON-NLS-1$
+ " </Supervisor>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"10\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
+ " <Supervisor ID=\"08\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+ " <Supervisor ID=\"07\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+ " </Supervisor>\r\n" + //$NON-NLS-1$
+ " </Supervisor>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ "</Employees>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc16", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * sbale 4/27/05 I have changed expected results as a result of changes for
+ * Booz Allen POC. Previously, the recursive fragment of the document that
+ * satisfied the recursion termination criteria was included, now it is not.
+ * See commented out section below for previous expected results.
+ * @throws Exception
+ */
+ @Test public void testRecursiveWithStagingTable_defect15607() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<OrgHierarchy>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"01\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"02\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+// " <Subordinates>\r\n" + //$NON-NLS-1$
+// " <Employee ID=\"04\">\r\n" + //$NON-NLS-1$
+// " <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
+// " <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
+// " <Subordinates/>\r\n" + //$NON-NLS-1$
+// " </Employee>\r\n" + //$NON-NLS-1$
+// " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"03\">\r\n" + //$NON-NLS-1$
+ " <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"05\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"07\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"08\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"09\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee ID=\"10\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
+ " <Subordinates/>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Subordinates>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ "</OrgHierarchy>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc19", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * Tests a recursive nested mapping class within a recursive mapping class, where
+ * all nested "anchor" nodes are named "srcNestedRecursive". Test of defect #5988
+ */
+ @Test public void testXQTRecursive_5988() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata2();
+ FakeDataManager dataMgr = exampleXQTDataManager(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<recursiveTest>\r\n" + //$NON-NLS-1$
+ " <src>\r\n" + //$NON-NLS-1$
+ " <key>13</key>\r\n" + //$NON-NLS-1$
+ " <data>10</data>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>10</key>\r\n" + //$NON-NLS-1$
+ " <data>7</data>\r\n" + //$NON-NLS-1$
+ " <srcNestedRecursive>\r\n" + //$NON-NLS-1$
+ " <key>7</key>\r\n" + //$NON-NLS-1$
+ " <data>4</data>\r\n" + //$NON-NLS-1$
+ " <srcNestedRecursive>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcNestedRecursive>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcNestedRecursive>\r\n" + //$NON-NLS-1$
+ " </srcNestedRecursive>\r\n" + //$NON-NLS-1$
+ " </srcNestedRecursive>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " <srcRecursive>\r\n" + //$NON-NLS-1$
+ " <key>10</key>\r\n" + //$NON-NLS-1$
+ " <data>7</data>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>7</key>\r\n" + //$NON-NLS-1$
+ " <data>4</data>\r\n" + //$NON-NLS-1$
+ " <srcNestedRecursive>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcNestedRecursive>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcNestedRecursive>\r\n" + //$NON-NLS-1$
+ " </srcNestedRecursive>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " <srcRecursive>\r\n" + //$NON-NLS-1$
+ " <key>7</key>\r\n" + //$NON-NLS-1$
+ " <data>4</data>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcNestedRecursive>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcNestedRecursive>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " <srcRecursive>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " <srcRecursive>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcRecursive>\r\n" + //$NON-NLS-1$
+ " </srcRecursive>\r\n" + //$NON-NLS-1$
+ " </srcRecursive>\r\n" + //$NON-NLS-1$
+ " </srcRecursive>\r\n" + //$NON-NLS-1$
+ " </src>\r\n" + //$NON-NLS-1$
+ "</recursiveTest>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xqttest.doc1", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * Tests a non-recursive nested mapping class within a recursive mapping class, where
+ * all nested "anchor" nodes are named "srcNested". Test of defect #5988
+ */
+ public void DEFER_testXQTRecursive1a_5988() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata2();
+ FakeDataManager dataMgr = exampleXQTDataManager(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<recursiveTest>\r\n" + //$NON-NLS-1$
+ " <src>\r\n" + //$NON-NLS-1$
+ " <key>13</key>\r\n" + //$NON-NLS-1$
+ " <data>10</data>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>10</key>\r\n" + //$NON-NLS-1$
+ " <data>7</data>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>10</key>\r\n" + //$NON-NLS-1$
+ " <data>7</data>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>7</key>\r\n" + //$NON-NLS-1$
+ " <data>4</data>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>7</key>\r\n" + //$NON-NLS-1$
+ " <data>4</data>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " </src>\r\n" + //$NON-NLS-1$
+ "</recursiveTest>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xqttest.doc1a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * Tests a non-recursive nested mapping class within a recursive mapping class, where
+ * all nested "anchor" nodes are named "srcNested". Test of defect #5988
+ */
+ @Test public void testXQTRecursive2_5988() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata2();
+ FakeDataManager dataMgr = exampleXQTDataManager(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<recursiveTest>\r\n" + //$NON-NLS-1$
+ " <src>\r\n" + //$NON-NLS-1$
+ " <key>13</key>\r\n" + //$NON-NLS-1$
+ " <data>10</data>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>10</key>\r\n" + //$NON-NLS-1$
+ " <data>7</data>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>10</key>\r\n" + //$NON-NLS-1$
+ " <data>7</data>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>7</key>\r\n" + //$NON-NLS-1$
+ " <data>4</data>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>7</key>\r\n" + //$NON-NLS-1$
+ " <data>4</data>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " <srcNested>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " </srcNested>\r\n" + //$NON-NLS-1$
+ " </src>\r\n" + //$NON-NLS-1$
+ "</recursiveTest>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xqttest.doc3", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+
+ /**
+ * for defect 5988
+ */
+ @Test public void testXQTRecursiveSiblings_5988() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata2();
+ FakeDataManager dataMgr = exampleXQTDataManager(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<recursiveTest>\r\n" + //$NON-NLS-1$
+ " <src>\r\n" + //$NON-NLS-1$
+ " <key>13</key>\r\n" + //$NON-NLS-1$
+ " <data>10</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>10</key>\r\n" + //$NON-NLS-1$
+ " <data>7</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>7</key>\r\n" + //$NON-NLS-1$
+ " <data>4</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>7</key>\r\n" + //$NON-NLS-1$
+ " <data>4</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>10</key>\r\n" + //$NON-NLS-1$
+ " <data>7</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>7</key>\r\n" + //$NON-NLS-1$
+ " <data>4</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>7</key>\r\n" + //$NON-NLS-1$
+ " <data>4</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>4</key>\r\n" + //$NON-NLS-1$
+ " <data>1</data>\r\n" + //$NON-NLS-1$
+ " <srcSibling1>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling1>\r\n" + //$NON-NLS-1$
+ " <srcSibling2>\r\n" + //$NON-NLS-1$
+ " <key>1</key>\r\n" + //$NON-NLS-1$
+ " <data>-2</data>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </srcSibling2>\r\n" + //$NON-NLS-1$
+ " </src>\r\n" + //$NON-NLS-1$
+ "</recursiveTest>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xqttest.doc2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testSelectElement1() throws Exception {
+ QueryMetadataInterface 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>\r\n" + //$NON-NLS-1$
+ " <Name>Lamp</Name>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Name>Goat</Name>\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 Name FROM xmltest.doc1", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testSelectElement2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 SupplierID, OrderID, ItemID, OrderQuantity FROM xmltest.doc9 ORDER BY "+ //$NON-NLS-1$
+ " Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC," + //$NON-NLS-1$
+ " OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** select element in the reverse order of depth*/
+ @Test public void testSelectElement3() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 OrderQuantity, SupplierID, ItemID, OrderID FROM xmltest.doc9" + //$NON-NLS-1$
+ " ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC," + //$NON-NLS-1$
+ " OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** two select elements at the same level*/
+ @Test public void testSelectElement4() throws Exception {
+ QueryMetadataInterface 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 ItemID, Name, Quantity FROM xmltest.doc1 WHERE ItemID='001' OR " //$NON-NLS-1$
+ + " ItemID='002' OR ItemID='003' ORDER BY ItemID", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** defect 9756 */
+ @Test public void testSelectElement4_defect9756() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Item ItemID=\"002\"/>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\"/>\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 Catalogs.Catalog.Items.Item. at ItemID FROM xmltest.doc1", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** 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 {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 OrderQuantity, SupplierID, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Name, OrderID, ItemID " //$NON-NLS-1$
+ + "FROM xmltest.doc9 ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, " //$NON-NLS-1$
+ + "OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** check element.* case */
+ @Test public void testSelectElement6() throws Exception {
+ QueryMetadataInterface 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 Item.* FROM xmltest.doc1 ORDER BY ItemID", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** check element.* case without attribute in order by*/
+ @Test public void testSelectElement6a() throws Exception {
+ QueryMetadataInterface 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>\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>\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>\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 Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Quantity" //$NON-NLS-1$
+ + " FROM xmltest.doc1", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testSelectElement7() throws Exception {
+ QueryMetadataInterface 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 Catalogs.Catalog.Items.Item.* FROM xmltest.doc1 ORDER BY ItemID", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testSelectElement8() throws Exception {
+ QueryMetadataInterface 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 xmltest.doc1.Catalogs.Catalog.Items.Item.* FROM xmltest.doc1 ORDER BY ItemID", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** SELECT clause has element.*, but the sibling elements should not be included, only subtree should */
+ @Test public void testSelectElement9() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 Catalogs.Catalog.Items.Item.Suppliers.Supplier.* FROM xmltest.doc9 " //$NON-NLS-1$
+ + "WHERE ItemID='002' AND Context(Supplier,OrderID)='5' ", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testSelectElement9a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 Catalogs.Catalog.Items.Item.Suppliers.Supplier.* FROM xmltest.doc9 " //$NON-NLS-1$
+ + "WHERE ItemID='002' AND Context(Supplier,OrderID)='5' AND Context(OrderID, OrderID)='5'", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** check element.* case with criteria and order by clause */
+ @Test public void testSelectElement10() throws Exception {
+ QueryMetadataInterface 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 Item.* FROM xmltest.doc1 WHERE Quantity <= 100 ORDER BY ItemID", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testSelectElement12() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 Supplier.*, ItemID FROM xmltest.doc9 " //$NON-NLS-1$
+ + " WHERE ItemID='002'" //$NON-NLS-1$
+ + " ORDER BY SupplierID, OrderID DESC, ItemID", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testSelectElement13() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(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>\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$
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </Catalog>\r\n" + //$NON-NLS-1$
+ "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT Name, Quantity FROM xmltest.doc1 " //$NON-NLS-1$
+ + "WHERE ItemID='002'" //$NON-NLS-1$
+ + "ORDER BY Name ", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testSelectElement14() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc9 WHERE ItemID='002' AND Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderQuantity < 1000" //$NON-NLS-1$
+ + " ORDER By SupplierID ASC, OrderID ", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testSelectElement15() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 Supplier.* FROM xmltest.doc9 " //$NON-NLS-1$
+ + " WHERE ItemID='002'" //$NON-NLS-1$
+ + " ORDER By SupplierID ", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testSelectElement16() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 Supplier.* FROM xmltest.doc9a " //$NON-NLS-1$
+ + " WHERE ItemID='002'" //$NON-NLS-1$
+ + " ORDER By SupplierID", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** CSE query 0 */
+ @Test public void testSelectElement17() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <Name>KMart</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <Name>Sun</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <Name>Doc</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
+ " <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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.doc9c ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** CSE query 1 */
+ @Test public void testSelectElement18() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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.doc9c WHERE ItemID='002'", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** CSE query 2 */
+ @Test public void testSelectElement19() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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.doc9c WHERE Catalogs.Catalog.Items.Item.Name='Screwdriver'", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+
+ /** CSE query 3 */
+ @Test public void testSelectElement20() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 ItemID, Catalogs.Catalog.Items.Item.Quantity, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Zip" + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE Catalogs.Catalog.Items.Item.Name='Screwdriver'", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** CSE query 3a */
+ @Test public void testSelectElement20a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order>\r\n" + //$NON-NLS-1$
+ " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order>\r\n" + //$NON-NLS-1$
+ " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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 ItemID, Catalogs.Catalog.Items.Item.Quantity, Catalogs.Catalog.Items.Item.Orders.Order.Zip" + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE Catalogs.Catalog.Items.Item.Name='Screwdriver'", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** CSE query 4 */
+ @Test public void testSelectElement21() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <Name>KMart</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <Name>Sun</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <Name>Doc</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
+ " <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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 * " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE SupplierID > '54' AND context(SupplierID, SupplierID)>'54' ", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** CSE query 4a */
+ @Test public void testSelectElement21a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
+ " <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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 * " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE OrderID > '4' AND context(OrderID, OrderID)>'4'", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** CSE query 5 */
+ @Test public void testSelectElement22() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 ItemID, Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Zip " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE SupplierID > '4' ", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** CSE query 5a */
+ @Test public void testSelectElement22a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <Name>KMart</Name>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <Name>Sun</Name>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <Name>Doc</Name>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
+ " <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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 ItemID, Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Orders.Order.Name, OrderID " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE OrderID > '3' ", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** CSE query 6 */
+ @Test public void testSelectElement23() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Name>Goat</Name>\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Name, SupplierID " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE OrderID > '4' ", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** CSE query 6a */
+ @Test public void testSelectElement23a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\"/>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\"/>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\"/>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"7\"/>\r\n" + //$NON-NLS-1$
+ " </Orders>\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 Catalogs.Catalog.Items.Item.ItemID, OrderID " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE SupplierID > '54' ", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** test with order by and the element in the criteria is not in the select elements*/
+ @Test public void testSelectElement24() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"7\"/>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\"/>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\"/>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\"/>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
+ " </Orders>\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 Catalogs.Catalog.Items.Item.ITEMID, OrderID " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE SupplierID > '54' " + //$NON-NLS-1$
+ " ORDER BY ItemID DESC, OrderID DESC", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** test element.* with order by and the element in the criteria is not in the select elements*/
+ @Test public void testSelectElement24a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
+ " <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <Name>Doc</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <Name>Sun</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <Name>KMart</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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 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$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** test with order by with only necessary sub-mapping classes are queried*/
+ @Test public void testSelectElement25() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\"/>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\"/>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\"/>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\"/>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\"/>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\"/>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\"/>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\"/>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 ItemID, SupplierID " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE SupplierID > '54' " + //$NON-NLS-1$
+ " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** test element.* with order by with only necessary sub-mapping classes are queried*/
+ @Test public void testSelectElement25a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 ItemID, Supplier.* " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE SupplierID > '54' " + //$NON-NLS-1$
+ " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** Test element.* with order by with only necessary sub-mapping classes are queried
+ * and case_insensitive nodes in the mapping tree
+ */
+ @Test public void testSelectElement25b() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 ItemID, SUPPLIER.* " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE SupplierID > '54' " + //$NON-NLS-1$
+ " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testSelectElement26() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 ItemID, xmltest.doc9c.catalogs.catalog.items.item.suppliers.SUPPLIER.* " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE SupplierID > '54' " + //$NON-NLS-1$
+ " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** test special elements: result set name, and name with format of "document.fully.qualified.element"
+ * --> refer to Defect9497, this should fail
+ */
+ @Test public void testSelectElement27() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier/>\r\n" + //$NON-NLS-1$
+ " <Supplier/>\r\n" + //$NON-NLS-1$
+ " <Supplier/>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 doc9c.catalogs.catalog.items.item.itemID, items.item.name, item.Quantity, supplier " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE doc9c.catalogs.catalog.items.item.suppliers.supplier.SupplierID > '54' AND itemID='002'" + //$NON-NLS-1$
+ " ORDER BY doc9c.catalogs.catalog.items.item.ITEMid ", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** test special element, root element */
+ @Test public void testSelectElement28() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs/>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT catalogs " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+
+ /*String expectedDoc = "";
+ try {
+ helpTestProcess("SELECT catalogs " +
+ " FROM xmltest.doc9c " +
+ " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'",
+ expectedDoc, metadata, dataMgr);
+ } catch(QueryPlannerException qpe) {
+ // ok, as expected
+ } */
+ }
+
+ /** test special element */
+ @Test public void testSelectElement28a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog/>\r\n" + //$NON-NLS-1$
+ "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+ /*String expectedDoc = "";
+ try {
+ helpTestProcess("SELECT catalog " +
+ " FROM xmltest.doc9c " +
+ " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'",
+ expectedDoc, metadata, dataMgr, false);
+ } catch (QueryPlannerException qpe) {
+ // ok, as expected
+ } */
+
+ helpTestProcess("SELECT catalog " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** test model.document.* */
+ @Test public void testSelectElement28b() throws Exception {
+ QueryMetadataInterface 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 xmltest.doc1.* " + //$NON-NLS-1$
+ "FROM xmltest.doc1 ORDER BY ItemID ", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+
+ }
+
+ /** test special element, root element */
+ @Test public void testSelectElement29() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs/>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT xmltest.doc9c.catalogs " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+
+ /*String expectedDoc = "";
+ try {
+ helpTestProcess("SELECT xmltest.doc9c.catalogs " +
+ " FROM xmltest.doc9c " +
+ " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'",
+ expectedDoc, metadata, dataMgr);
+ } catch (QueryPlannerException qpe) {
+ // ok, as expected
+ }*/
+
+ }
+
+ /** test simple case for two elements in a mapping class */
+ @Test public void testSelectElement30() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(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$
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </Catalog>\r\n" + //$NON-NLS-1$
+ "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT item.* FROM xmltest.doc1 WHERE ItemID='001' AND Quantity < 60 ORDER BY ItemID", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** test NullPointerException*/
+ @Test public void testDefect_9496_1() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 items.item.ItemID, suppliers.supplier.* " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE item.suppliers.supplier.SupplierID > '54' " + //$NON-NLS-1$
+ " ORDER BY ITEMid DESC, items.item.suppliers.supplier.SupplierID DESC", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testDefect_9496_2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier>\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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 doc9c.Catalogs.catalog.items.item.ItemID, items.item.Suppliers,SuppliER.Name " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE SupplierID > '54' " + //$NON-NLS-1$
+ " ORDER BY ItemID DESC", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** test StringIndexOutOfBoundsException */
+ @Test public void testDefect_9496_3() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <Name>KMart</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <Name>Sun</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <Name>Doc</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
+ " <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\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 item.itemID, items.item.* " + //$NON-NLS-1$
+ " FROM xmltest.doc9c " + //$NON-NLS-1$
+ " WHERE item.suppliers.supplier.SupplierID > '54' " + //$NON-NLS-1$
+ " ORDER BY ITEMid, items.item.suppliers.supplier.SupplierID ", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ /** should fail: because there are other element other than "xml" */
+ /*@Test public void testResolver1() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc = "";
+
+ boolean shouldSucceed = false;
+ Class expectedException = QueryResolverException.class;
+ String shouldFailMsg = "If any symbol in SELECT clause is 'xml' or group.'xml' , then no other element is allowed.";
+
+ helpTestProcess("SELECT xml, ItemID " +
+ " FROM xmltest.doc9c " +
+ " WHERE SupplierID > '54' " +
+ " ORDER BY ItemID DESC", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);
+ }*/
+
+ /** should fail: partial qualified element name and "model.document.xml" */
+ /*@Test public void testResolver2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc = "";
+
+ boolean shouldSucceed = false;
+ Class expectedException = QueryResolverException.class;
+ String shouldFailMsg = "If any symbol in SELECT clause is 'xml' or group.'xml' , then no other element is allowed.";
+
+ helpTestProcess("SELECT item.ItemID, xmltest.doc9c.xml " +
+ " FROM xmltest.doc9c " +
+ " WHERE SupplierID > '54' " +
+ " ORDER BY ItemID DESC", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);
+ }*/
+
+ /** should fail: test XMLResolver validatation for model.* */
+ /*@Test public void testDefect_9498_1() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc = "";
+
+ boolean shouldSucceed = false;
+ Class expectedException = QueryResolverException.class;
+ String shouldFailMsg = "Unable to resolve element: xmltest";
+
+ helpTestProcess("SELECT xmltest.* FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);
+ }*/
+
+ /** should fail: test XMLResolver validatation for model.document.* */
+ /*@Test public void testDefect_9498_2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc = "";
+
+ boolean shouldSucceed = false;
+ Class expectedException = QueryResolverException.class;
+ String shouldFailMsg = "Unable to resolve element: xmltest.doc9c";
+
+ helpTestProcess("SELECT xmltest.doc9c.* FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);
+ }*/
+
+ /** should fail: test XMLResolver validatation for xml.* */
+ /*@Test public void testDefect_9498_3() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc = "";
+
+ boolean shouldSucceed = false;
+ Class expectedException = QueryResolverException.class;
+ String shouldFailMsg = "Unable to resolve element: xml";
+
+ helpTestProcess("SELECT xml.* FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);
+ }*/
+
+ /** Test element.* with order by with only necessary sub-mapping classes are queried
+ * and case_insensitive nodes in the mapping tree
+ */
+ @Test public void testCommentNodeInDoc() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Root><!--Comment1--><Something><!--Comment2--></Something>\r\n" + //$NON-NLS-1$
+ "</Root>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc17", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ private static final String EXPECTED_DOC_DEFECT_8917_AND_11789 =
+ "<?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 xsi:nil=\"true\"/>\r\n" + //$NON-NLS-1$
+ " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </Catalog>\r\n" + //$NON-NLS-1$
+ " <OptionalCatalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Name xsi:nil=\"true\"/>\r\n" + //$NON-NLS-1$
+ " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </OptionalCatalog>\r\n" + //$NON-NLS-1$
+ " <OptionalCatalog2>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Name xsi:nil=\"true\"/>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </OptionalCatalog2>\r\n" + //$NON-NLS-1$
+ " <Catalog4/>\r\n" + //$NON-NLS-1$
+ " <Catalog5>\r\n" + //$NON-NLS-1$
+ " <OptionalItems>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <FixedName>Nugent</FixedName>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " </OptionalItems>\r\n" + //$NON-NLS-1$
+ " </Catalog5>\r\n" + //$NON-NLS-1$
+ " <Catalog6/>\r\n" + //$NON-NLS-1$
+ "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+ @Test public void testDefect8917() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager_8917(metadata);
+
+// helpTestProcess("SELECT * FROM xmltest.doc_8917 WHERE Catalog.Items.Item.ItemID = '001'",
+ helpTestProcess("SELECT * FROM xmltest.doc_8917", //$NON-NLS-1$
+ EXPECTED_DOC_DEFECT_8917_AND_11789, metadata, dataMgr);
+ }
+ /*
+ * jhTODO
+ */
+ @Test public void testNillableOptional() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
+ "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + //$NON-NLS-1$
+ "<Catalog>" + //$NON-NLS-1$
+ "<Items xsi:nil=\"true\"/>" + //$NON-NLS-1$
+ "</Catalog>" + //$NON-NLS-1$
+ "</Catalogs>"; //$NON-NLS-1$
+
+ // note: doc1b contains an 'items' element that is nillable = true, and minoccurs = 0
+ helpTestProcess("SELECT * FROM xmltest.doc1b WHERE ItemID='9999' ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /*
+ * jhTODO
+ */
+ @Test public void testNillableNonOptional() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + //$NON-NLS-1$
+ "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + //$NON-NLS-1$
+ "<Catalog>" + //$NON-NLS-1$
+ "<Items xsi:nil=\"true\"/>" + //$NON-NLS-1$
+ "</Catalog>" + //$NON-NLS-1$
+ "</Catalogs>"; //$NON-NLS-1$
+
+ // note: doc1c contains an 'items' element that has no nillable set, and minoccurs = 1
+ helpTestProcess("SELECT * FROM xmltest.doc1c WHERE ItemID='9999' ", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * Related to defect 8917
+ * The expected result is slightly different because the data has a
+ * NON-empty whitespace string, which will NOT be treated as null
+ * see also defect 15117
+ */
+ @Test public void testDefect11789() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager_8917a(metadata);
+
+ String expected =
+ "<?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> </Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </Catalog>\r\n" + //$NON-NLS-1$
+ " <OptionalCatalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Name> </Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </OptionalCatalog>\r\n" + //$NON-NLS-1$
+ " <OptionalCatalog2>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Name> </Name>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </OptionalCatalog2>\r\n" + //$NON-NLS-1$
+ " <OptionalCatalog3>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Name> </Name>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </OptionalCatalog3>\r\n" + //$NON-NLS-1$
+ " <Catalog4>\r\n" + //$NON-NLS-1$
+ " <OptionalItems>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Name> </Name>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " </OptionalItems>\r\n" + //$NON-NLS-1$
+ " </Catalog4>\r\n" + //$NON-NLS-1$
+ " <Catalog5>\r\n" + //$NON-NLS-1$
+ " <OptionalItems>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <FixedName>Nugent</FixedName>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " </OptionalItems>\r\n" + //$NON-NLS-1$
+ " </Catalog5>\r\n" + //$NON-NLS-1$
+ " <Catalog6/>\r\n" + //$NON-NLS-1$
+ "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc_8917", //$NON-NLS-1$
+ expected, metadata, dataMgr);
+ }
+
+ /**
+ * Related to defect 8917 - the result should be the same as
+ * testDefect8917
+ */
+ @Test public void testDefect11789b() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager_8917b(metadata);
+
+ helpTestProcess("SELECT * FROM xmltest.doc_8917", //$NON-NLS-1$
+ EXPECTED_DOC_DEFECT_8917_AND_11789, metadata, dataMgr);
+ }
+
+ @Test public void testDefect9446() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager_8917(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item XXXXX=\"001\">\r\n" + //$NON-NLS-1$
+ " <XXXXX/>\r\n" + //$NON-NLS-1$
+ " <XXXXX>5</XXXXX>\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.doc_8917 WHERE Catalog.Items.Item.ItemID = '001'",
+ helpTestProcess("SELECT * FROM xmltest.doc_9446", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testDefect9446_2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager_8917(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\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.doc_9446 WHERE Catalogs.Catalog.Items.Item.XXXXX = '001'", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testDefect_9530() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<mm:Catalogs xmlns:mm=\"http://www.duh.org/duh\">\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <mm:Item xmlns:mm2=\"http://www.duh3.org/duh3\" xmlns:mm=\"http://www.duh2.org/duh2\"\r\n" + //$NON-NLS-1$
+ " ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <Name>Lamp</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+ " </mm:Item>\r\n" + //$NON-NLS-1$
+ " <mm:Item xmlns:mm2=\"http://www.duh3.org/duh3\" xmlns:mm=\"http://www.duh2.org/duh2\"\r\n" + //$NON-NLS-1$
+ " ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
+ " </mm:Item>\r\n" + //$NON-NLS-1$
+ " <mm:Item xmlns:mm2=\"http://www.duh3.org/duh3\" xmlns:mm=\"http://www.duh2.org/duh2\"\r\n" + //$NON-NLS-1$
+ " ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Name>Goat</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>4</Quantity>\r\n" + //$NON-NLS-1$
+ " </mm:Item>\r\n" + //$NON-NLS-1$
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </Catalog>\r\n" + //$NON-NLS-1$
+ "</mm:Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc_9530", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testSubqueryInXMLQueryCriteria() throws Exception {
+ QueryMetadataInterface 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" +
+// " <Name>Screwdriver</Name>\r\n" +
+// " <Quantity>100</Quantity>\r\n" +
+// " </Item>\r\n" +
+// " <Item ItemID=\"003\">\r\n" +
+// " <Name>Goat</Name>\r\n" +
+// " <Quantity>4</Quantity>\r\n" +
+// " </Item>\r\n" +
+ " </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 ItemID IN (SELECT itemNum FROM stock.items WHERE itemNum = '001')", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryInXMLQueryCriteria2() throws Exception {
+ QueryMetadataInterface 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" +
+// " <Name>Lamp</Name>\r\n" +
+// " <Quantity>5</Quantity>\r\n" +
+// " </Item>\r\n" +
+ " <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 ItemID > ANY (SELECT itemNum FROM stock.items WHERE itemNum IN ('001','002') )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryInXMLQueryCriteria3() throws Exception {
+ QueryMetadataInterface 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" +
+// " <Name>Lamp</Name>\r\n" +
+// " <Quantity>5</Quantity>\r\n" +
+// " </Item>\r\n" +
+ " <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 NOT (ItemID IN (SELECT itemNum FROM stock.items WHERE itemNum = '001') )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ public void XXXtestSubqueryInXMLQueryCriteria4() throws Exception {
+ QueryMetadataInterface 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 {
+ QueryMetadataInterface 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" +
+// " <Name>Lamp</Name>\r\n" +
+// " <Quantity>5</Quantity>\r\n" +
+// " </Item>\r\n" +
+ " <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 ItemID > ANY (SELECT itemNum FROM stock.items WHERE itemNum IN (SELECT itemNum FROM stock.items WHERE itemNum IN ('001','002') ) )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+// " <Item ItemID=\"001\">\r\n" +
+// " <Name>Lamp</Name>\r\n" +
+// " <Quantity>5</Quantity>\r\n" +
+// " <Suppliers>\r\n" +
+// " <Supplier SupplierID=\"51\">\r\n" +
+// " <Name>Chucky</Name>\r\n" +
+// " <Zip>11111</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " <Supplier SupplierID=\"52\">\r\n" +
+// " <Name>Biff's Stuff</Name>\r\n" +
+// " <Zip>22222</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " <Supplier SupplierID=\"53\">\r\n" +
+// " <Name>AAAA</Name>\r\n" +
+// " <Zip>33333</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " <Supplier SupplierID=\"56\">\r\n" +
+// " <Name>Microsoft</Name>\r\n" +
+// " <Zip>66666</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " </Suppliers>\r\n" +
+// " </Item>\r\n" +
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8 WHERE ItemID > ANY (SELECT itemNum FROM stock.items WHERE itemNum IN ('001','002') )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8 WHERE SupplierID > ANY (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('53','54') )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass3() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+// " <Item ItemID=\"002\">\r\n" +
+// " <Name>Screwdriver</Name>\r\n" +
+// " <Quantity>100</Quantity>\r\n" +
+// " <Suppliers>\r\n" +
+// " <Supplier SupplierID=\"54\">\r\n" +
+// " <Name>Nugent Co.</Name>\r\n" +
+// " <Zip>44444</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " <Supplier SupplierID=\"55\">\r\n" +
+// " <Name>Zeta</Name>\r\n" +
+// " <Zip>55555</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " <Supplier SupplierID=\"56\">\r\n" +
+// " <Name>Microsoft</Name>\r\n" +
+// " <Zip>66666</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " </Suppliers>\r\n" +
+// " </Item>\r\n" +
+// " <Item ItemID=\"003\">\r\n" +
+// " <Name>Goat</Name>\r\n" +
+// " <Quantity>4</Quantity>\r\n" +
+// " <Suppliers>\r\n" +
+// " <Supplier SupplierID=\"56\">\r\n" +
+// " <Name>Microsoft</Name>\r\n" +
+// " <Zip>66666</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " </Suppliers>\r\n" +
+// " </Item>\r\n" +
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </Catalog>\r\n" + //$NON-NLS-1$
+ "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID < ALL (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('52','54') )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass3a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+// " <Item ItemID=\"002\">\r\n" +
+// " <Name>Screwdriver</Name>\r\n" +
+// " <Quantity>100</Quantity>\r\n" +
+// " <Suppliers>\r\n" +
+// " <Supplier SupplierID=\"54\">\r\n" +
+// " <Name>Nugent Co.</Name>\r\n" +
+// " <Zip>44444</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " <Supplier SupplierID=\"55\">\r\n" +
+// " <Name>Zeta</Name>\r\n" +
+// " <Zip>55555</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " <Supplier SupplierID=\"56\">\r\n" +
+// " <Name>Microsoft</Name>\r\n" +
+// " <Zip>66666</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " </Suppliers>\r\n" +
+// " </Item>\r\n" +
+// " <Item ItemID=\"003\">\r\n" +
+// " <Name>Goat</Name>\r\n" +
+// " <Quantity>4</Quantity>\r\n" +
+// " <Suppliers>\r\n" +
+// " <Supplier SupplierID=\"56\">\r\n" +
+// " <Name>Microsoft</Name>\r\n" +
+// " <Zip>66666</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " </Suppliers>\r\n" +
+// " </Item>\r\n" +
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </Catalog>\r\n" + //$NON-NLS-1$
+ "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID IN (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('52') )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+
+ @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass4() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+// " <Supplier SupplierID=\"56\">\r\n" +
+// " <Name>Microsoft</Name>\r\n" +
+// " <Zip>66666</Zip>\r\n" +
+// " </Supplier>\r\n" +
+ " </Suppliers>\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$
+ " <Suppliers/>\r\n" + //$NON-NLS-1$
+// " <Suppliers>\r\n" +
+// " <Supplier SupplierID=\"54\">\r\n" +
+// " <Name>Nugent Co.</Name>\r\n" +
+// " <Zip>44444</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " <Supplier SupplierID=\"55\">\r\n" +
+// " <Name>Zeta</Name>\r\n" +
+// " <Zip>55555</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " <Supplier SupplierID=\"56\">\r\n" +
+// " <Name>Microsoft</Name>\r\n" +
+// " <Zip>66666</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " </Suppliers>\r\n" +
+ " </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$
+ " <Suppliers/>\r\n" + //$NON-NLS-1$
+// " <Suppliers>\r\n" +
+// " <Supplier SupplierID=\"56\">\r\n" +
+// " <Name>Microsoft</Name>\r\n" +
+// " <Zip>66666</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " </Suppliers>\r\n" +
+ " </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.doc8 WHERE context(SupplierID, SupplierID) < SOME (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('52','54') )", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testCritNestedMappingClass() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+// " <Item ItemID=\"002\">\r\n" +
+// " <Name>Screwdriver</Name>\r\n" +
+// " <Quantity>100</Quantity>\r\n" +
+// " <Suppliers>\r\n" +
+// " <Supplier SupplierID=\"54\">\r\n" +
+// " <Name>Nugent Co.</Name>\r\n" +
+// " <Zip>44444</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " <Supplier SupplierID=\"55\">\r\n" +
+// " <Name>Zeta</Name>\r\n" +
+// " <Zip>55555</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " <Supplier SupplierID=\"56\">\r\n" +
+// " <Name>Microsoft</Name>\r\n" +
+// " <Zip>66666</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " </Suppliers>\r\n" +
+// " </Item>\r\n" +
+// " <Item ItemID=\"003\">\r\n" +
+// " <Name>Goat</Name>\r\n" +
+// " <Quantity>4</Quantity>\r\n" +
+// " <Suppliers>\r\n" +
+// " <Supplier SupplierID=\"56\">\r\n" +
+// " <Name>Microsoft</Name>\r\n" +
+// " <Zip>66666</Zip>\r\n" +
+// " </Supplier>\r\n" +
+// " </Suppliers>\r\n" +
+// " </Item>\r\n" +
+ " </Items>\r\n" + //$NON-NLS-1$
+ " </Catalog>\r\n" + //$NON-NLS-1$
+ "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID = '52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testDefect_9893() throws Exception{
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Root>\r\n" + //$NON-NLS-1$
+ " <ItemName>Lamp</ItemName>\r\n" + //$NON-NLS-1$
+ " <ItemName>Screwdriver</ItemName>\r\n" + //$NON-NLS-1$
+ " <ItemName>Goat</ItemName>\r\n" + //$NON-NLS-1$
+ "</Root>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.doc9893", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testDefect_9893_2() throws Exception{
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Root>\r\n" + //$NON-NLS-1$
+ " <ItemName>Lamp</ItemName>\r\n" + //$NON-NLS-1$
+ " <ItemName>Screwdriver</ItemName>\r\n" + //$NON-NLS-1$
+ " <ItemName>Goat</ItemName>\r\n" + //$NON-NLS-1$
+ "</Root>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT ItemName FROM xmltest.doc9893", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testDefect_9893_3() throws Exception{
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Root>\r\n" + //$NON-NLS-1$
+ " <ItemName>Lamp</ItemName>\r\n" + //$NON-NLS-1$
+ " <ItemName>Screwdriver</ItemName>\r\n" + //$NON-NLS-1$
+ " <ItemName>Goat</ItemName>\r\n" + //$NON-NLS-1$
+ "</Root>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT ItemName.* FROM xmltest.doc9893", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr);
+ }
+
+ @Test public void testDefect_9893_4() throws Exception{
+ QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
+ FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item/>\r\n" + //$NON-NLS-1$
+ " <Item/>\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 Item FROM xmltest.doc9c", //$NON-NLS-1$
+ expectedDoc, metadata, dataMgr, null);
+ }
+
+ @Test public void testNestedWithStoredQueryInMappingClass() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc18", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** homegenous, simple array elements */
+ @Test public void testWithSOAPEncoding1() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataSoap1();
+ FakeDataManager dataMgr = exampleDataManagerForSoap1(metadata, false);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<ORG:TaxReports xmlns:ORG=\"http://www.mm.org/dummy\">\r\n" + //$NON-NLS-1$
+ " <ORG:TaxReport>\r\n" + //$NON-NLS-1$
+ " <ORG:ArrayOfTaxID xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" + //$NON-NLS-1$
+ " xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n" + //$NON-NLS-1$
+ " xsi:type=\"ORG:ArrayOfTaxIDType\"\r\n" + //$NON-NLS-1$
+ " SOAP-ENC:arrayType=\"ORG:TaxIDType[]\">\r\n" + //$NON-NLS-1$
+ " <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" + //$NON-NLS-1$
+ " <ID>1</ID>\r\n" + //$NON-NLS-1$
+ " </ORG:TaxID>\r\n" + //$NON-NLS-1$
+ " <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" + //$NON-NLS-1$
+ " <ID>2</ID>\r\n" + //$NON-NLS-1$
+ " </ORG:TaxID>\r\n" + //$NON-NLS-1$
+ " <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" + //$NON-NLS-1$
+ " <ID>3</ID>\r\n" + //$NON-NLS-1$
+ " </ORG:TaxID>\r\n" + //$NON-NLS-1$
+ " </ORG:ArrayOfTaxID>\r\n" + //$NON-NLS-1$
+ " </ORG:TaxReport>\r\n" + //$NON-NLS-1$
+ "</ORG:TaxReports>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.docSoap", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+
+ /**
+ * if no data is contained in the soap elements
+ * (e.g. ORG:ArrayOfTaxID) and the schema allows it, eliminate the
+ * whole fragment
+ */
+ @Test public void testWithSOAPEncodingNoRows() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataSoap1();
+ FakeDataManager dataMgr = exampleDataManagerForSoap1(metadata, true);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<ORG:TaxReports xmlns:ORG=\"http://www.mm.org/dummy\">\r\n" + //$NON-NLS-1$
+ " <ORG:TaxReport/>\r\n" + //$NON-NLS-1$
+// " <ORG:TaxReport>\r\n" +
+// " <ORG:ArrayOfTaxID xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xsi:type=\"ORG:ArrayOfTaxIDType\" SOAP-ENC:arrayType=\"ORG:TaxIDType[]\">\r\n" +
+// " <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" +
+// " <ID>1</ID>\r\n" +
+// " </ORG:TaxID>\r\n" +
+// " <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" +
+// " <ID>2</ID>\r\n" +
+// " </ORG:TaxID>\r\n" +
+// " <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" +
+// " <ID>3</ID>\r\n" +
+// " </ORG:TaxID>\r\n" +
+// " </ORG:ArrayOfTaxID>\r\n" +
+// " </ORG:TaxReport>\r\n" +
+ "</ORG:TaxReports>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xmltest.docSoap", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testDefect12260() throws Exception{
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <numSuppliers>4</numSuppliers>\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$
+ " <numSuppliers>3</numSuppliers>\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$
+ " <numSuppliers>1</numSuppliers>\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$
+
+
+ // Set up capabilities to duplicate defect
+ BasicSourceCapabilities caps = new BasicSourceCapabilities();
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+ caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+ caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+ caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+ CapabilitiesFinder capFinder = new DefaultCapabilitiesFinder(caps);
+
+ helpTestProcess("SELECT * FROM xmltest.doc12260", metadata, dataMgr, null, capFinder, expectedDoc); //$NON-NLS-1$
+ }
+
+ @Test public void testDefect8373() throws Exception{
+
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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/>\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/>\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$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <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/>\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.doc8373", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testDefect8373a() throws Exception{
+
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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/>\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/>\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$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <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/>\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.doc8373a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testDefect8373b() throws Exception{
+
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
+
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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/>\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/>\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$
+ " <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+ " <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/>\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.doc8373b", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testDefect13617() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager13617(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Name>Lamp</Name>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item>\r\n" + //$NON-NLS-1$
+ " <Name>Goat</Name>\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 Item.Name FROM xmltest.doc13617", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testDefect13617a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager13617(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+ " <Name>Screwdriver</Name>\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$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"004\"/>\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 ItemID, Item.Name FROM xmltest.doc13617", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * Tests that non-zero length whitespace string will be treated like
+ * normal data
+ * @throws Exception
+ * @since 4.2
+ */
+ @Test public void testDefect14905() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager14905(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=\" \">\r\n" + //$NON-NLS-1$
+ " <Name> </Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\" \">\r\n" + //$NON-NLS-1$
+ " <Name> </Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\" \">\r\n" + //$NON-NLS-1$
+ " <Name> </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", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testTextUnnormalizedDefect15117() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager15117(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> Screw driver </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", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testTextUnnormalizedDefect15117a() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager15117a(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>\t \n
</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> >Screw< \n driver &</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", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testRecursiveGroupDoc() throws Exception {
+
+ QueryMetadataInterface metadata = exampleMetadata2();
+ FakeDataManager dataMgr = exampleXQTDataManager(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<group>\r\n" + //$NON-NLS-1$
+ " <ID>2</ID>\r\n" + //$NON-NLS-1$
+ " <code>-1</code>\r\n" + //$NON-NLS-1$
+ " <supervisor>\r\n" + //$NON-NLS-1$
+ " <ID>4</ID>\r\n" + //$NON-NLS-1$
+ " <code>1</code>\r\n" + //$NON-NLS-1$
+ " <group>\r\n" + //$NON-NLS-1$
+ " <ID>6</ID>\r\n" + //$NON-NLS-1$
+ " <code>3</code>\r\n" + //$NON-NLS-1$
+ " <supervisor>\r\n" + //$NON-NLS-1$
+ " <ID>8</ID>\r\n" + //$NON-NLS-1$
+ " <code>5</code>\r\n" + //$NON-NLS-1$
+ " <group>\r\n" + //$NON-NLS-1$
+ " <ID>10</ID>\r\n" + //$NON-NLS-1$
+ " <code>7</code>\r\n" + //$NON-NLS-1$
+ " <supervisor>\r\n" + //$NON-NLS-1$
+ " <ID>12</ID>\r\n" + //$NON-NLS-1$
+ " <code>9</code>\r\n" + //$NON-NLS-1$
+ " </supervisor>\r\n" + //$NON-NLS-1$
+ " </group>\r\n" + //$NON-NLS-1$
+ " </supervisor>\r\n" + //$NON-NLS-1$
+ " </group>\r\n" + //$NON-NLS-1$
+ " </supervisor>\r\n" + //$NON-NLS-1$
+ "</group>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("SELECT * FROM xqttest.groupDoc WHERE pseudoID = 2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testCase2951MaxRows() throws Exception {
+
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** test rowlimitexception() doesn't throw exception is rowlimit isn't passed */
+ @Test public void testDefect19173RowLimitException() throws Exception {
+
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8 WHERE rowlimitexception(supplier) = 4", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** test criteria can be written backwards */
+ @Test public void testDefect19173RowLimitExceptionBackwardsCriteria() throws Exception {
+
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8 WHERE 4 = rowlimitexception(supplier)", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testCase2951MaxRows2() throws Exception {
+
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8 WHERE rowlimit(supplier) = 2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** test processing exception is thrown if row limit is passed */
+ @Test public void testDefect19173RowLimitException2() throws Exception {
+
+ 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$
+ }
+
+ /** 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 {
+
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8 WHERE rowlimit(supplier) = 2 AND rowlimit(supplierid) = 2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** test processing exception is thrown if row limit is passed */
+ @Test public void testDefect19173RowLimitException2a() throws Exception {
+
+ 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$
+ }
+
+ /** compound criteria */
+ @Test public void testCase2951MaxRows3() throws Exception {
+
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8 WHERE ItemID='002' AND rowlimit(supplier) = 2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** compound criteria */
+ @Test public void testDefect19173RowLimitException3() throws Exception {
+
+ 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$
+ }
+
+ @Test public void testCase2951MaxRows4() throws Exception {
+
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8 WHERE rowlimit(supplier) = 2 AND rowlimit(item) = 2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testCase2951AndDefect19173MixTwoFunctions() throws Exception {
+
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8 WHERE rowlimit(supplier) = 2 AND rowlimitException(item) = 6", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /** arg to rowlimit function isn't in the scope of any mapping class */
+ @Test public void testCase2951MaxRowsFails() throws Exception {
+
+ 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$
+ }
+
+ /** two conflicting row limits on the same mapping class */
+ @Test public void testCase2951MaxRowsFails2() throws Exception {
+
+ 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$
+ }
+
+ /** arg to rowlimitexception function isn't in the scope of any mapping class */
+ @Test public void testDefect19173RowLimitExceptionFails() throws Exception {
+
+ 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$
+ }
+
+ /** two conflicting rowlimitexceptions on the same mapping class */
+ @Test public void testDefect19173RowLimitExceptionFails2() throws Exception {
+
+ 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$
+ }
+
+ /** two conflicting rowlimit and rowlimitexceptions on the same mapping class fails planning */
+ @Test public void testDefect19173RowLimitAndRowLimitExceptionMixFails2() throws Exception {
+
+ 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$
+ }
+
+ /** try rowlimit criteria written the reverse way */
+ @Test public void testCase2951MaxRows5() throws Exception {
+
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.doc8 WHERE 2 = rowlimit(supplier)", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+
+ @Test public void testNormalizationCollapse() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNormalization(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 xsi:nil=\"true\"/>\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>0</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$
+ " <DiscontinuedItem ItemID=\"004\">\r\n" + //$NON-NLS-1$
+ " <Name>Flux Capacitor</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>2</Quantity>\r\n" + //$NON-NLS-1$
+ " </DiscontinuedItem>\r\n" + //$NON-NLS-1$
+ " <StatusUnknown ItemID=\"005\">\r\n" + //$NON-NLS-1$
+ " <Name>Milkshake</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>88</Quantity>\r\n" + //$NON-NLS-1$
+ " </StatusUnknown>\r\n" + //$NON-NLS-1$
+ " <DiscontinuedItem ItemID=\"006\">\r\n" + //$NON-NLS-1$
+ " <Name>Feta Matrix</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>0</Quantity>\r\n" + //$NON-NLS-1$
+ " </DiscontinuedItem>\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.normDoc1", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testNormalizationReplace() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNormalization(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 xsi:nil=\"true\"/>\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>0</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$
+ " <DiscontinuedItem ItemID=\"004\">\r\n" + //$NON-NLS-1$
+ " <Name>Flux Capacitor</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>2</Quantity>\r\n" + //$NON-NLS-1$
+ " </DiscontinuedItem>\r\n" + //$NON-NLS-1$
+ " <StatusUnknown ItemID=\"005\">\r\n" + //$NON-NLS-1$
+ " <Name>Milkshake</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>88</Quantity>\r\n" + //$NON-NLS-1$
+ " </StatusUnknown>\r\n" + //$NON-NLS-1$
+ " <DiscontinuedItem ItemID=\"006\">\r\n" + //$NON-NLS-1$
+ " <Name> Feta Matrix </Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>0</Quantity>\r\n" + //$NON-NLS-1$
+ " </DiscontinuedItem>\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.normDoc2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+ @Test public void testNormalizationPreserve() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManagerNormalization2(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 xsi:nil=\"true\"/>\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>My Screwdriver</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>0</Quantity>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+ " <Name>My Goat</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>4</Quantity>\r\n" + //$NON-NLS-1$
+ " </Item>\r\n" + //$NON-NLS-1$
+ " <DiscontinuedItem ItemID=\"004\">\r\n" + //$NON-NLS-1$
+ " <Name>My Flux Capacitor</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>2</Quantity>\r\n" + //$NON-NLS-1$
+ " </DiscontinuedItem>\r\n" + //$NON-NLS-1$
+ " <StatusUnknown ItemID=\"005\">\r\n" + //$NON-NLS-1$
+ " <Name>My Milkshake</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>88</Quantity>\r\n" + //$NON-NLS-1$
+ " </StatusUnknown>\r\n" + //$NON-NLS-1$
+ " <DiscontinuedItem ItemID=\"006\">\r\n" + //$NON-NLS-1$
+ " <Name>My Feta Matrix</Name>\r\n" + //$NON-NLS-1$
+ " <Quantity>0</Quantity>\r\n" + //$NON-NLS-1$
+ " </DiscontinuedItem>\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.normDoc3", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * Deluxe example
+ */
+ private FakeDataManager exampleDataManagerNormalization(QueryMetadataInterface metadata) {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ try {
+ 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", " \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(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ return dataMgr;
+ }
+ private FakeDataManager exampleDataManagerNormalization2(QueryMetadataInterface metadata) {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ try {
+ 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", "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(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ return dataMgr;
+ }
+
+ private static MappingDocument createXMLPlanNormalization(String normMode) {
+
+ 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$
+ MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+ //choice node, non-visual, so it has no name
+ MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode());
+ choice.setSource("xmltest.group.items"); //$NON-NLS-1$
+ choice.setMaxOccurrs(-1);
+ MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'okay'", false)); //$NON-NLS-1$
+ MappingElement item = crit.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+ item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setNormalizeText(normMode)
+ .setNillable(true);
+ item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setDefaultValue("0"); //$NON-NLS-1$
+
+ MappingCriteriaNode crit2 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)); //$NON-NLS-1$
+ MappingElement discontinuedItem = crit2.addChildElement(new MappingElement("DiscontinuedItem")); //$NON-NLS-1$
+ discontinuedItem.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ discontinuedItem.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setNormalizeText(normMode)
+ .setNillable(true);
+ discontinuedItem.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setDefaultValue("0"); //$NON-NLS-1$
+
+ MappingCriteriaNode crit3 = choice.addCriteriaNode(new MappingCriteriaNode());
+ MappingElement unknownItem = crit3.addChildElement(new MappingElement("StatusUnknown")); //$NON-NLS-1$
+ unknownItem.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+ unknownItem.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setNormalizeText(normMode)
+ .setNillable(true);
+ unknownItem.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+ .setDefaultValue("0"); //$NON-NLS-1$
+
+ MappingCriteriaNode notIncludedSibling = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)); //$NON-NLS-1$
+ notIncludedSibling.setExclude(true);
+
+ MappingCriteriaNode notIncludedSibling2 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)); //$NON-NLS-1$
+ notIncludedSibling2.setExclude(true);
+ return doc;
+ }
+
+ static FakeDataManager exampleDataManagerCase3225(QueryMetadataInterface metadata) {
+ FakeDataManager dataMgr = new FakeDataManager();
+
+ try {
+ dataMgr.registerTuples(
+ 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(
+ 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(
+ 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(
+ 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(
+ 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(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ return dataMgr;
+ }
+
+ /**
+ * Test of doc model w/o criteria, just as a baseline
+ * @throws Exception
+ */
+ @Test public void testCase3225() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleCase3225();
+ FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>2/13/05</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>2</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " <Employees>\r\n" + //$NON-NLS-1$
+ " <Employee EmployeeID=\"1001\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee EmployeeID=\"1002\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Employees>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>3/13/05</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " <Employees/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " <Employees/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " <Employees>\r\n" + //$NON-NLS-1$
+ " <Employee EmployeeID=\"1005\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Employees>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " <Employees>\r\n" + //$NON-NLS-1$
+ " <Employee EmployeeID=\"1003\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
+ " <FirstName>David</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Eckstein</LastName>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Employees>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " <Employees/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>5/13/05</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>cancelled</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " <Employees>\r\n" + //$NON-NLS-1$
+ " <Employee EmployeeID=\"1008\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Carlos</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Zambrano</LastName>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Employees>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>6/13/05</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>800</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " <Employees>\r\n" + //$NON-NLS-1$
+ " <Employee EmployeeID=\"1006\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Corey</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Patterson</LastName>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Employees>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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.itemsdoc", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * For ESpace case 3225 tests, with criteria
+ * "... where employee. at supervisorID='1004' and order.orderquantity > 1"
+ */
+ private static final String CASE_3225_WITH_CRITERIA_EXPECTED_DOC =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>2/13/05</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>2</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " <Employees>\r\n" + //$NON-NLS-1$
+ " <Employee EmployeeID=\"1001\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " <Employee EmployeeID=\"1002\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Employees>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>3/13/05</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " <Employees/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " <Employees/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " <Employees>\r\n" + //$NON-NLS-1$
+ " <Employee EmployeeID=\"1005\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
+ " </Employee>\r\n" + //$NON-NLS-1$
+ " </Employees>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+
+ private static String EXPECTED_ORDERED_DOC9A = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\r\n" + //$NON-NLS-1$
+ " <Items>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+ " <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+ " <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\r\n" + //$NON-NLS-1$
+ " </Item>\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$
+ " <Suppliers>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+ " <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+ " <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders>\r\n" + //$NON-NLS-1$
+ " <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+ " <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+ " <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+ " <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+ " </Order>\r\n" + //$NON-NLS-1$
+ " </Orders>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+ " <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+ " <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+ " <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+ " <Orders/>\r\n" + //$NON-NLS-1$
+ " </Supplier>\r\n" + //$NON-NLS-1$
+ " </Suppliers>\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";
+
+ /**
+ * Test of query with criteria written one way. This test is paired up
+ * with {@link #testCase3225WithCriteriaReversed()}; both tests have the same
+ * expected results and are identical queries except their compound criteria are
+ * written in reverse order relative to each other. What Alan Tetrault found at
+ * ESpace is that this changes actual results, which it shouldn't. The likely
+ * culprit is the algorithm to apply criteria to the implied context mapping class.
+ * That is, the criteria is on nodes in the scope of two nested mapping classes
+ * (the ones for orders and employees), but the implied context mapping class of both
+ * of them is the root mapping class (for items).
+ *
+ * The criteria "@supervisorID='1004'" should limit the returned items to items 001 and 002,
+ * the criteria "order.orderquantity > 1" should limit the returned items to 001 and 003, so
+ * the combined criteria should limit returned items to item 001.
+ * @throws Exception
+ */
+ @Test public void testCase3225WithCriteria() throws Exception {
+ 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$
+ }
+
+ /**
+ * Test of query with criteria written the other way. This test is paired up
+ * with {@link #testCase3225WithCriteria()}; both tests have the same
+ * expected results and are identical queries except their compound criteria are
+ * written in reverse order relative to each other. What Alan Tetrault found at
+ * ESpace is that this changes actual results, which it shouldn't. The likely
+ * culprit is the algorithm to apply criteria to the implied context mapping class.
+ * That is, the criteria is on nodes in the scope of two nested mapping classes
+ * (the ones for orders and employees), but the implied context mapping class of both
+ * of them is the root mapping class (for items).
+ *
+ * The criteria "@supervisorID='1004'" should limit the returned items to items 001 and 002,
+ * the criteria "order.orderquantity > 1" should limit the returned items to 001 and 003, so
+ * the combined criteria should limit returned items to item 001.
+ * @throws Exception
+ */
+ @Test public void testCase3225WithCriteriaReversed() throws Exception {
+ 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$
+ }
+
+ /**
+ * Test the criteria from previous test, plus additional criteria explicitly
+ * on the context mapping class (in this case, the root "items" mapping class)
+ * to make sure all of the criteria is processed correctly.
+ * @throws Exception
+ */
+ @Test public void testCase3225WithEmptyDocCriteria() throws Exception {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleCase3225();
+ FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
+ String expectedDoc =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+ "<Catalogs>\r\n" + //$NON-NLS-1$
+ " <Catalog>\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.itemsdoc where order.orderquantity > 1 and employee. at supervisorID='1004' and item. at itemid='002'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ /**
+ * This just tests selecting * from the document, nothing fancy
+ * @throws Exception
+ * @since 4.3
+ */
+ @Test public void testBaseballPlayersDoc() throws Exception {
+
+ 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$
+ " <Manager ManagerID=\"1007\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Dusty</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Baker</LastName>\r\n" + //$NON-NLS-1$
+ " <Owner OwnerID=\"1010\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Some</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Guy</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=\"1006\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Corey</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Patterson</LastName>\r\n" + //$NON-NLS-1$
+ " <Manager ManagerID=\"1007\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Dusty</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Baker</LastName>\r\n" + //$NON-NLS-1$
+ " <Owner OwnerID=\"1010\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Some</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Guy</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=\"1008\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Carlos</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Zambrano</LastName>\r\n" + //$NON-NLS-1$
+ " <Manager ManagerID=\"1007\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Dusty</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Baker</LastName>\r\n" + //$NON-NLS-1$
+ " <Owner OwnerID=\"1010\">\r\n" + //$NON-NLS-1$
+ " <FirstName>Some</FirstName>\r\n" + //$NON-NLS-1$
+ " <LastName>Guy</LastName>\r\n" + //$NON-NLS-1$
+ " </Owner>\r\n" + //$NON-NLS-1$
+ " </Manager>\r\n" + //$NON-NLS-1$
+ " </Player>\r\n" + //$NON-NLS-1$
+ "</BaseballPlayers>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("select * from xmltest.playersDoc", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+
+ }
+
+ /**
+ * This one seems to work fine - criteria mapping class is
+ * managers while implied context mapping class is players.
+ * Expected result is same as previous test.
+ * @throws Exception
+ * @since 4.3
+ */
+ @Test public void testBaseballPlayersDocCriteria() throws Exception {
+
+ 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$
+ "</BaseballPlayers>\r\n\r\n"; //$NON-NLS-1$
+
+ helpTestProcess("select * from xmltest.playersDoc where manager. at managerid = '1004'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+
+ }
+
+ /**
+ * This also seems to work fine. The context mapping class is the
+ * middle one (managers).
+ * @throws Exception
+ * @since 4.3
+ */
+ @Test public void testBaseballPlayersDocContextCriteria() throws Exception {
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleCase3225();
+ FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
+
+ 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 {
+ QueryMetadataInterface 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=\"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("call xmltest.vsp1(1000)", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ }
+
+ @Test public void testProcedureAndXML1() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadataCached();
+ FakeDataManager dataMgr = exampleDataManager(metadata);
+ String expectedDoc1 =
+ "<?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$
+ " </Catalog>\r\n" + //$NON-NLS-1$
+ "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+ String expectedDoc2 =
+ "<?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=\"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$
+ String expectedDoc3 =
+ "<?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=\"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 (call xmltest.vsp1(y)) from texttable(unescape('1\n100\n1000') COLUMNS y integer) as x", metadata, dataMgr, null, new DefaultCapabilitiesFinder(), expectedDoc1, expectedDoc2, expectedDoc3); //$NON-NLS-1$
+ }
+
+ /**
+ * When a element with source node is specied, it can be unbouned or bounded. In the case
+ * of bounded, but result set is returning more results then it should fail.
+ */
+ public void defer_testMinMaxOnSourceNode() throws Exception {
+ QueryMetadataInterface 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$
+
+ try {
+ helpTestProcess("SELECT * FROM xmltest.docBounded", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+ fail("should have failed the document restrictions."); //$NON-NLS-1$
+ } catch (TeiidProcessingException e) {
+ // pass
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestFunctionResolving.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/resolver/TestFunctionResolving.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestFunctionResolving.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,159 +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.resolver;
-
-import static org.junit.Assert.*;
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryParserException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.resolver.util.ResolverVisitor;
-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.sql.symbol.Reference;
-import org.teiid.query.sql.symbol.XMLSerialize;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
-
-public class TestFunctionResolving {
-
- @Test public void testResolveBadConvert() throws Exception {
- 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());
- 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$
- }
- }
-
- @Test public void testResolvesClosestType() throws Exception {
- ElementSymbol e1 = new ElementSymbol("pm1.g1.e1"); //$NON-NLS-1$
- //dummy resolve to a byte
- e1.setType(DataTypeManager.DefaultDataClasses.BYTE);
- e1.setMetadataID(new Object());
- Function function = new Function("abs", new Expression[] {e1}); //$NON-NLS-1$
-
- ResolverVisitor.resolveLanguageObject(function, FakeMetadataFactory.example1Cached());
-
- assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, function.getType());
- }
-
- @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());
-
- assertEquals(DataTypeManager.DefaultDataClasses.BOOLEAN, function.getType());
- assertEquals(DataTypeManager.DefaultDataClasses.BOOLEAN, function.getArgs()[0].getType());
- }
-
- @Test public void testResolveAmbiguousFunction() throws Exception {
- Function function = new Function("LCASE", new Expression[] {new Reference(0)}); //$NON-NLS-1$
-
- try {
- ResolverVisitor.resolveLanguageObject(function, FakeMetadataFactory.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$
- }
- }
-
- @Test public void testResolveCoalesce() throws Exception {
- String sql = "coalesce('', '')"; //$NON-NLS-1$
- helpResolveFunction(sql);
- }
-
- @Test public void testResolveCoalesce1() throws Exception {
- String sql = "coalesce('', '', '')"; //$NON-NLS-1$
- helpResolveFunction(sql);
- }
-
- /**
- * Should resolve using varags logic
- */
- @Test public void testResolveCoalesce1a() throws Exception {
- String sql = "coalesce('', '', '', '')"; //$NON-NLS-1$
- helpResolveFunction(sql);
- }
-
- /**
- * Should resolve as 1 is implicitly convertable to string
- */
- @Test public void testResolveCoalesce2() throws Exception {
- String sql = "coalesce('', 1, '', '')"; //$NON-NLS-1$
- helpResolveFunction(sql);
- }
-
- @Test public void testResolveCoalesce3() throws Exception {
- String sql = "coalesce('', 1, null, '')"; //$NON-NLS-1$
- helpResolveFunction(sql);
- }
-
- @Test public void testResolveCoalesce4() throws Exception {
- String sql = "coalesce({d'2009-03-11'}, 1)"; //$NON-NLS-1$
- helpResolveFunction(sql);
- }
-
- private Function helpResolveFunction(String sql) throws QueryParserException,
- QueryResolverException, TeiidComponentException {
- Function func = (Function)getExpression(sql);
- assertEquals(DataTypeManager.DefaultDataClasses.STRING, func.getType());
- return func;
- }
-
- public static Expression getExpression(String sql) throws QueryParserException,
- TeiidComponentException, QueryResolverException {
- Expression func = QueryParser.getQueryParser().parseExpression(sql);
- ResolverVisitor.resolveLanguageObject(func, FakeMetadataFactory.example1Cached());
- return func;
- }
-
- /**
- * e1 is of type string, so 1 should be converted to string
- * @throws Exception
- */
- @Test public void testLookupTypeConversion() throws Exception {
- String sql = "lookup('pm1.g1', 'e2', 'e1', 1)"; //$NON-NLS-1$
- Function f = (Function)getExpression(sql);
- assertEquals(DataTypeManager.DefaultDataClasses.STRING, f.getArg(3).getType());
- }
-
- @Test public void testXMLSerialize() throws Exception {
- String sql = "xmlserialize(DOCUMENT '<a/>' as clob)"; //$NON-NLS-1$
- XMLSerialize xs = (XMLSerialize)getExpression(sql);
- assertEquals(DataTypeManager.DefaultDataClasses.CLOB, xs.getType());
- }
-
- @Test(expected=QueryResolverException.class) public void testXMLSerialize_1() throws Exception {
- String sql = "xmlserialize(DOCUMENT 1 as clob)"; //$NON-NLS-1$
- XMLSerialize xs = (XMLSerialize)getExpression(sql);
- assertEquals(DataTypeManager.DefaultDataClasses.CLOB, xs.getType());
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestFunctionResolving.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/resolver/TestFunctionResolving.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestFunctionResolving.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestFunctionResolving.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,159 @@
+/*
+ * 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.resolver;
+
+import static org.junit.Assert.*;
+import org.junit.Test;
+import org.teiid.api.exception.query.QueryParserException;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.resolver.util.ResolverVisitor;
+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.sql.symbol.Reference;
+import org.teiid.query.sql.symbol.XMLSerialize;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+
+public class TestFunctionResolving {
+
+ @Test public void testResolveBadConvert() throws Exception {
+ Function function = new Function("convert", new Expression[] {new Constant(new Character('a')), new Constant(DataTypeManager.DefaultDataTypes.DATE)}); //$NON-NLS-1$
+
+ try {
+ 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$
+ }
+ }
+
+ @Test public void testResolvesClosestType() throws Exception {
+ ElementSymbol e1 = new ElementSymbol("pm1.g1.e1"); //$NON-NLS-1$
+ //dummy resolve to a byte
+ e1.setType(DataTypeManager.DefaultDataClasses.BYTE);
+ e1.setMetadataID(new Object());
+ Function function = new Function("abs", new Expression[] {e1}); //$NON-NLS-1$
+
+ ResolverVisitor.resolveLanguageObject(function, RealMetadataFactory.example1Cached());
+
+ assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, function.getType());
+ }
+
+ @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, RealMetadataFactory.example1Cached());
+
+ assertEquals(DataTypeManager.DefaultDataClasses.BOOLEAN, function.getType());
+ assertEquals(DataTypeManager.DefaultDataClasses.BOOLEAN, function.getArgs()[0].getType());
+ }
+
+ @Test public void testResolveAmbiguousFunction() throws Exception {
+ Function function = new Function("LCASE", new Expression[] {new Reference(0)}); //$NON-NLS-1$
+
+ try {
+ 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$
+ }
+ }
+
+ @Test public void testResolveCoalesce() throws Exception {
+ String sql = "coalesce('', '')"; //$NON-NLS-1$
+ helpResolveFunction(sql);
+ }
+
+ @Test public void testResolveCoalesce1() throws Exception {
+ String sql = "coalesce('', '', '')"; //$NON-NLS-1$
+ helpResolveFunction(sql);
+ }
+
+ /**
+ * Should resolve using varags logic
+ */
+ @Test public void testResolveCoalesce1a() throws Exception {
+ String sql = "coalesce('', '', '', '')"; //$NON-NLS-1$
+ helpResolveFunction(sql);
+ }
+
+ /**
+ * Should resolve as 1 is implicitly convertable to string
+ */
+ @Test public void testResolveCoalesce2() throws Exception {
+ String sql = "coalesce('', 1, '', '')"; //$NON-NLS-1$
+ helpResolveFunction(sql);
+ }
+
+ @Test public void testResolveCoalesce3() throws Exception {
+ String sql = "coalesce('', 1, null, '')"; //$NON-NLS-1$
+ helpResolveFunction(sql);
+ }
+
+ @Test public void testResolveCoalesce4() throws Exception {
+ String sql = "coalesce({d'2009-03-11'}, 1)"; //$NON-NLS-1$
+ helpResolveFunction(sql);
+ }
+
+ private Function helpResolveFunction(String sql) throws QueryParserException,
+ QueryResolverException, TeiidComponentException {
+ Function func = (Function)getExpression(sql);
+ assertEquals(DataTypeManager.DefaultDataClasses.STRING, func.getType());
+ return func;
+ }
+
+ public static Expression getExpression(String sql) throws QueryParserException,
+ TeiidComponentException, QueryResolverException {
+ Expression func = QueryParser.getQueryParser().parseExpression(sql);
+ ResolverVisitor.resolveLanguageObject(func, RealMetadataFactory.example1Cached());
+ return func;
+ }
+
+ /**
+ * e1 is of type string, so 1 should be converted to string
+ * @throws Exception
+ */
+ @Test public void testLookupTypeConversion() throws Exception {
+ String sql = "lookup('pm1.g1', 'e2', 'e1', 1)"; //$NON-NLS-1$
+ Function f = (Function)getExpression(sql);
+ assertEquals(DataTypeManager.DefaultDataClasses.STRING, f.getArg(3).getType());
+ }
+
+ @Test public void testXMLSerialize() throws Exception {
+ String sql = "xmlserialize(DOCUMENT '<a/>' as clob)"; //$NON-NLS-1$
+ XMLSerialize xs = (XMLSerialize)getExpression(sql);
+ assertEquals(DataTypeManager.DefaultDataClasses.CLOB, xs.getType());
+ }
+
+ @Test(expected=QueryResolverException.class) public void testXMLSerialize_1() throws Exception {
+ String sql = "xmlserialize(DOCUMENT 1 as clob)"; //$NON-NLS-1$
+ XMLSerialize xs = (XMLSerialize)getExpression(sql);
+ assertEquals(DataTypeManager.DefaultDataClasses.CLOB, xs.getType());
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestProcedureResolving.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/resolver/TestProcedureResolving.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestProcedureResolving.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1584 +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.resolver;
-
-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.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.metadata.TempMetadataStore;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.sql.ProcedureReservedWords;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.ProcedureContainer;
-import org.teiid.query.sql.proc.AssignmentStatement;
-import org.teiid.query.sql.proc.Block;
-import org.teiid.query.sql.proc.CommandStatement;
-import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
-import org.teiid.query.sql.proc.LoopStatement;
-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.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;
-
-
-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) {
- helpFailUpdateProcedure(procedure, userUpdateStr, procedureType, null);
- }
-
- private void helpFailUpdateProcedure(String procedure, String userUpdateStr, String procedureType, String msg) {
- // resolve
- try {
- helpResolveUpdateProcedure(procedure, userUpdateStr, procedureType);
- fail("Expected a QueryResolverException but got none."); //$NON-NLS-1$
- } catch(QueryResolverException ex) {
- if (msg != null) {
- assertEquals(msg, ex.getMessage());
- }
- } catch (TeiidComponentException e) {
- throw new RuntimeException(e);
- } catch (QueryParserException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Test public void testDefect13029_CorrectlySetUpdateProcedureTempGroupIDs() throws Exception {
- StringBuffer proc = new StringBuffer("CREATE VIRTUAL PROCEDURE") //$NON-NLS-1$
- .append("\nBEGIN") //$NON-NLS-1$
- .append("\nDECLARE string var1;") //$NON-NLS-1$
- .append("\nvar1 = '';") //$NON-NLS-1$
- .append("\n LOOP ON (SELECT pm1.g1.e1 FROM pm1.g1) AS loopCursor") //$NON-NLS-1$
- .append("\n BEGIN") //$NON-NLS-1$
- .append("\n LOOP ON (SELECT pm1.g2.e1 FROM pm1.g2 WHERE loopCursor.e1 = pm1.g2.e1) AS loopCursor2") //$NON-NLS-1$
- .append("\n BEGIN") //$NON-NLS-1$
- .append("\n var1 = CONCAT(var1, CONCAT(' ', loopCursor2.e1));") //$NON-NLS-1$
- .append("\n END") //$NON-NLS-1$
- .append("\n END") //$NON-NLS-1$
- .append("\nEND"); //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- Command command = helpResolveUpdateProcedure(proc.toString(), userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE);
- Map tempIDs = command.getTemporaryMetadata();
- assertNotNull(tempIDs);
- assertNull(tempIDs.get("LOOPCURSOR")); //$NON-NLS-1$
- assertNull(tempIDs.get("LOOPCURSOR2")); //$NON-NLS-1$
-
- Command subCommand = CommandCollectorVisitor.getCommands(command).get(0);
- tempIDs = subCommand.getTemporaryMetadata();
- assertNotNull(tempIDs);
- assertNull(tempIDs.get("LOOPCURSOR")); //$NON-NLS-1$
- assertNull(tempIDs.get("LOOPCURSOR2")); //$NON-NLS-1$
-
- subCommand = CommandCollectorVisitor.getCommands(command).get(1);
- tempIDs = subCommand.getTemporaryMetadata();
- assertNotNull(tempIDs);
- assertNotNull(tempIDs.get("LOOPCURSOR")); //$NON-NLS-1$
- 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);
- return resolveProcedure(userUpdateStr, metadata);
- }
-
- private CreateUpdateProcedureCommand resolveProcedure(String userUpdateStr,
- QueryMetadataInterface metadata) throws QueryParserException,
- QueryResolverException, TeiidComponentException,
- QueryMetadataException {
- ProcedureContainer userCommand = (ProcedureContainer)QueryParser.getQueryParser().parseCommand(userUpdateStr);
- QueryResolver.resolveCommand(userCommand, metadata);
- metadata = new TempMetadataAdapter(metadata, new TempMetadataStore(userCommand.getTemporaryMetadata()));
- return (CreateUpdateProcedureCommand)QueryResolver.expandCommand(userCommand, metadata, null);
- }
-
- private void helpResolveException(String userUpdateStr, QueryMetadataInterface metadata, String msg) throws QueryParserException, TeiidComponentException {
- try {
- helpResolve(userUpdateStr, metadata);
- } catch (QueryResolverException e) {
- assertEquals(msg, e.getMessage());
- }
- }
-
- private CreateUpdateProcedureCommand helpResolve(String userUpdateStr, QueryMetadataInterface metadata) throws QueryParserException, QueryResolverException, TeiidComponentException {
- return resolveProcedure(userUpdateStr, metadata);
- }
-
- /**
- * 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$
-
- CommandStatement cs = (CommandStatement)command.getBlock().getStatements().get(1);
-
- Insert insert = (Insert)cs.getCommand();
-
- assertEquals(DataTypeManager.DefaultDataClasses.SHORT, ((Expression)insert.getValues().get(1)).getType());
- }
-
- @Test public void testProcedureScoping() throws Exception {
- StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
- .append("\nBEGIN") //$NON-NLS-1$
- //note that this declare takes presedense over the proc INPUTS.e1 and CHANGING.e1 variables
- .append("\n declare integer e1 = 1;") //$NON-NLS-1$
- .append("\n e1 = e1;") //$NON-NLS-1$
- .append("\n LOOP ON (SELECT pm1.g1.e1 FROM pm1.g1) AS loopCursor") //$NON-NLS-1$
- .append("\n BEGIN") //$NON-NLS-1$
- //inside the scope of the loop, an unqualified e1 should resolve to the loop variable group
- .append("\n variables.e1 = convert(e1, integer);") //$NON-NLS-1$
- .append("\n END") //$NON-NLS-1$
- .append("\nEND"); //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- CreateUpdateProcedureCommand command = helpResolveUpdateProcedure(proc.toString(), userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- 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());
-
- Block inner = ((LoopStatement)block.getStatements().get(2)).getBlock();
-
- assStmt = (AssignmentStatement)inner.getStatements().get(0);
-
- ElementSymbol value = ElementCollectorVisitor.getElements(assStmt.getValue(), false).iterator().next();
-
- assertEquals("LOOPCURSOR", value.getGroupSymbol().getCanonicalName()); //$NON-NLS-1$
- }
-
- // variable resolution, variable used in if statement, variable compared against
- // different datatype element
- @Test public void testCreateUpdateProcedure4() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE boolean var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 =1);\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // variable resolution, variable used in if statement, invalid operation on variable
- @Test public void testCreateUpdateProcedure5() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE boolean var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = var1 + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 whwre var1 = var1+var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // variable resolution, variables declared in different blocks local variables
- // should not override
- @Test public void testCreateUpdateProcedure6() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 =1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE boolean var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where var1 = pm1.g1.e3;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- 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$
- }
-
- // variable resolution, variables declared in different blocks local variables
- // inner block using outer block variables
- @Test public void testCreateUpdateProcedure7() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 =1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE boolean var2;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where var1 = pm1.g1.e1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // variable resolution, variables declared in different blocks local variables
- // outer block cannot use inner block variables
- @Test public void testCreateUpdateProcedure8() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 =1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var2;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where var1 = pm1.g1.e1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "var2 = 1\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // variable resolution, variables declared in different blocks local variables
- // should override, outer block variables still valid afetr inner block is declared
- @Test public void testCreateUpdateProcedure9() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 =1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE boolean var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where var1 = pm1.g1.e3;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = var1 +1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // special variable ROWS_UPDATED resolution
- @Test public void testCreateUpdateProcedure10() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // special variable ROWS_UPDATED used with declared variable
- @Test public void testCreateUpdateProcedure11() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // special variable INPUT used with declared variable
- @Test public void testCreateUpdateProcedure12() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // special variable CHANGING used with declared variable
- @Test public void testCreateUpdateProcedure14() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // special variable CHANGING and INPUT used in compound criteria
- @Test public void testCreateUpdateProcedure15() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(CHANGING.e1='false' and INPUTS.e1=1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // special variable CHANGING and INPUT used in compound criteria, with declared variables
- @Test public void testCreateUpdateProcedure16() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(CHANGING.e4 ='true' and INPUTS.e2=1 or var1 < 30)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // special variable CHANGING compared against integer no implicit conversion available
- @Test public void testCreateUpdateProcedure17() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "if(CHANGING.e4 = {d'2000-01-01'})\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- 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$
- }
-
- // virtual group elements used in procedure(HAS CRITERIA)
- @Test public void testCreateUpdateProcedure18() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where HAS CRITERIA ON (vm1.g1.e1, vm1.g1.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // virtual group elements used in procedure in if statement(HAS CRITERIA)
- @Test public void testCreateUpdateProcedure19() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(HAS CRITERIA ON (vm1.g1.e1, vm1.g1.e1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where HAS CRITERIA ON (vm1.g1.e1, vm1.g1.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // virtual group elements used in procedure(TRANSLATE CRITERIA)
- @Test public void testCreateUpdateProcedure20() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // virtual group elements used in procedure(TRANSLATE CRITERIA)
- @Test public void testCreateUpdateProcedure21() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // using undefined variable should fail
- @Test public void testCreateUpdateProcedure22() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-// procedure = procedure + "DECLARE integer var1;\n";
- procedure = procedure + "var3 = var2+var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var2 = Select pm1.g1.e2 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // using undefined variable declared is of invalid datatype
- @Test public void testCreateUpdateProcedure23() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE struct var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // using declare variable that has parts
- @Test public void testCreateUpdateProcedure24() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var2.var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // using declare variable is qualified
- @Test public void testCreateUpdateProcedure26() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer VARIABLES.var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // using declare variable is qualified but has more parts
- @Test public void testCreateUpdateProcedure27() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer VARIABLES.var1.var2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // using a variable that has not been declared in an assignment stmt
- @Test public void testCreateUpdateProcedure28() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // using a variable that has not been declared in an assignment stmt
- @Test public void testCreateUpdateProcedure29() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = 1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // using invalid function in assignment expr
- @Test public void testCreateUpdateProcedure30() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Declare integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = 'x' + ROWS_UPDATED;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // using invalid function in assignment expr
- @Test public void testCreateUpdateProcedure31() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Declare integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = 'x' + ROWS_UPDATED;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // using a variable being used inside a subcomand
- @Test public void testCreateUpdateProcedure32() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Declare integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select var1 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // variable resolution, variables declared in different blocks local variables
- // should override, outer block variables still valid afetr inner block is declared
- // fails as variable being compared against incorrect type
- @Test public void testCreateUpdateProcedure33() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 =1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE timestamp var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where var1 = pm1.g1.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = var1 +1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // physical elements used on criteria of the if statement
- @Test public void testCreateUpdateProcedure34() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(pm1.g1.e2 =1 and var1=1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- 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$
- }
-
- // virtual elements used on criteria of the if statement
- @Test public void testCreateUpdateProcedure35() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(HAS CRITERIA ON (vm1.g1.e1) and var1=1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // physical elements used on criteria of the if statement
- @Test public void testCreateUpdateProcedure36() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(pm1.g1.e2 =1 and var1=1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // TranslateCriteria on criteria of the if statement
- @Test public void testCreateUpdateProcedure37() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(TRANSLATE CRITERIA ON (vm1.g1.e1) WITH (vm1.g1.e1 = 1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // validating Translate CRITERIA, elements on it should be virtual group elements
- // but can use variables
- @Test public void testCreateUpdateProcedure38() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (pm1.g1.e2 = var1);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // physical elements used on criteria of the if statement
- @Test public void testCreateUpdateProcedure39() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(pm1.g1.e2 =1 and var1=1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // TranslateCriteria on criteria of the if statement
- @Test public void testCreateUpdateProcedure40() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(TRANSLATE CRITERIA ON (e1) WITH (g1.e1 = 1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // TranslateCriteria on criteria of the if statement
- @Test public void testCreateUpdateProcedure41() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(HAS CRITERIA ON (e1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE CRITERIA ON (e1) WITH (g1.e1 = 1);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // TranslateCriteria on criteria of the if statement
- @Test public void testCreateUpdateProcedure42() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(HAS CRITERIA ON (e1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE CRITERIA ON (e1) WITH (g1.e1 = 1);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // TranslateCriteria on criteria of the if statement
- @Test public void testCreateUpdateProcedure43() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE CRITERIA ON (e1) WITH (g1.e1 = 1);\n"; //$NON-NLS-1$
-// procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n";
-// 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);
-
- Command procCommand = QueryParser.getQueryParser().parseCommand(procedure);
- GroupSymbol virtualGroup = new GroupSymbol("vm1.g1"); //$NON-NLS-1$
- virtualGroup.setMetadataID(metadata.getGroupID("vm1.g1")); //$NON-NLS-1$
- QueryResolver.resolveCommand(procCommand, virtualGroup, Command.TYPE_UPDATE, metadata);
- }
-
- // special variable CHANGING compared against integer no implicit conversion available
- @Test public void testCreateUpdateProcedure44() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "if(INPUTS.e1 = 10)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "INSERT into vm1.g1 (e1) values('x')"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
- }
-
- // special variable CHANGING compared against integer no implicit conversion available
- @Test public void testCreateUpdateProcedure45() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "if(INPUTS.e1 = 10)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- Command procCommand = QueryParser.getQueryParser().parseCommand(procedure);
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.INSERT_PROCEDURE, procedure);
-
- GroupSymbol virtualGroup = new GroupSymbol("vm1.g1"); //$NON-NLS-1$
- virtualGroup.setMetadataID(metadata.getGroupID("vm1.g1")); //$NON-NLS-1$
-
- QueryResolver.resolveCommand(procCommand, virtualGroup, Command.TYPE_INSERT, metadata);
- }
-
- // special variable CHANGING compared against integer no implicit conversion available
- @Test public void testCreateUpdateProcedure46() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- Command procCommand = QueryParser.getQueryParser().parseCommand(procedure);
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- GroupSymbol virtualGroup = new GroupSymbol("vm1.g1"); //$NON-NLS-1$
- virtualGroup.setMetadataID(metadata.getGroupID("vm1.g1")); //$NON-NLS-1$
-
- QueryResolver.resolveCommand(procCommand, virtualGroup, Command.TYPE_UPDATE, metadata);
- }
-
- // TranslateCriteria on criteria of the if statement
- @Test public void testCreateUpdateProcedure47() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(HAS CRITERIA ON (e1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE CRITERIA ON (e1) WITH (vm1.g1.e1 = pm1.g1.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // validating Translate CRITERIA, elements(left elements on on it should be virtual group elements
- @Test public void testCreateUpdateProcedure48() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, INPUTS.e2 = 2);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // resolving Translate CRITERIA, right element should be present on the command
- @Test public void testCreateUpdateProcedure49() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = pm1.g2.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // resolving criteria selector(on HAS CRITERIA), elements on it should be virtual group elements
- @Test public void testCreateUpdateProcedure50() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(HAS CRITERIA ON (vm1.g1.E1, vm1.g1.e1, INPUTS.e1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // resolving Translate CRITERIA, right side expression in the translate criteria should be elements on the command
- @Test public void testCreateUpdateProcedure51() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1=1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e2 = var1+vm1.g1.e2, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // validating Translate CRITERIA, elements on it should be virtual group elements
- // but can use variables, gut left exprs should always be virtual elements
- @Test public void testCreateUpdateProcedure52() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (var1 = vm1.g1.e2, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // resolving AssignmentStatement, variable type and assigned type
- // do not match and no implicit conversion available
- @Test public void testCreateUpdateProcedure53() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = INPUTS.e4;"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // resolving AssignmentStatement, variable type and assigned type
- // do not match, but implicit conversion available
- @Test public void testCreateUpdateProcedure54() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE string var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = 1+1;"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // resolving AssignmentStatement, variable type and assigned type
- // do not match, but implicit conversion available
- @Test public void testCreateUpdateProcedure55() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE string var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = 1+ROWS_UPDATED;"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testDefect14912_CreateUpdateProcedure57_FunctionWithElementParamInAssignmentStatement() {
- // Tests that the function params are resolved before the function for assignment statements
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE string var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = badFunction(badElement);"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- 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$
- }
-
- // addresses Cases 4624. Before change to UpdateProcedureResolver,
- // this case failed with assertion exception.
- @Test public void testCase4624() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "VARIABLES.ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE boolean var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = {b'false'};\n"; //$NON-NLS-1$
- procedure = procedure + "IF(var1 = {b 'true'})\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT Rack_ID, RACK_MDT_TYPE INTO #racks FROM Bert_MAP.BERT3.RACK;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- 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$
- }
-
- // addresses Cases 5474.
- @Test public void testCase5474() throws Exception {
- String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer VARIABLES.NLEVELS;\n"; //$NON-NLS-1$
- 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());
- }
-
- @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 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$
-
- TestResolver.helpResolve(procedure, FakeMetadataFactory.example1Cached());
- }
-
- // Address Issue 174519.
- // Expected result is resolver failure, but with different error.
- @Test public void testIssue174519() 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 + "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$
- }
-
- /*@Test public void testCommandUpdatingCountFromLastStatement() throws Exception {
- String procedure = "CREATE VIRTUAL PROCEDURE \n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "declare integer x = convert(pm1.sq1.in, integer) + 5;\n"; //$NON-NLS-1$
- procedure = procedure + "insert into pm1.g1 values (null, null, null, null);"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- QueryMetadataInterface metadata = exampleStoredProcedure(procedure);
- Command command = helpResolve(helpParse("exec pm1.sq1(1)"), metadata, null); //$NON-NLS-1$
-
- assertEquals(1, command.updatingModelCount(new TempMetadataAdapter(metadata, new TempMetadataStore())));
- }*/
-
- //baseline test to ensure that a declare assignment cannot contain the declared variable
- @Test public void testDeclareStatement() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer VARIABLES.var1 = VARIABLES.var1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testDynamicIntoInProc() throws Exception {
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- StringBuffer procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
- .append("BEGIN\n") //$NON-NLS-1$
- .append("execute string 'SELECT e1, e2, e3, e4 FROM pm1.g2' as e1 string, e2 string, e3 string, e4 string INTO #myTempTable;\n") //$NON-NLS-1$
- .append("select e1 from #myTempTable;\n") //$NON-NLS-1$
- .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
- .append("END\n"); //$NON-NLS-1$
- helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testDynamicStatement() throws Exception {
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- StringBuffer procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
- .append("BEGIN\n") //$NON-NLS-1$
- .append("execute string 'SELECT e1, e2, e3, e4 FROM pm1.g2';\n") //$NON-NLS-1$
- .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
- .append("END\n"); //$NON-NLS-1$
- helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testDynamicStatementType() {
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- StringBuffer procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
- .append("BEGIN\n") //$NON-NLS-1$
- .append("DECLARE object VARIABLES.X = null;\n") //$NON-NLS-1$
- .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);
- }
-
- // variable resolution
- @Test public void testCreateUpdateProcedure1() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 1, pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1=1"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // variable resolution, variable used in if statement
- @Test public void testCreateUpdateProcedure3() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 =1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testSelectIntoInProc() throws Exception {
- StringBuffer procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
- .append("BEGIN\n") //$NON-NLS-1$
- .append("SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2;\n") //$NON-NLS-1$
- .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
- .append("END\n"); //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
- .append("BEGIN\n") //$NON-NLS-1$
- .append("SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g2;\n") //$NON-NLS-1$
- .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
- .append("END\n"); //$NON-NLS-1$
- helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testSelectIntoInProcNoFrom() throws Exception {
- StringBuffer procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
- .append("BEGIN\n") //$NON-NLS-1$
- .append("SELECT 'a', 19, {b'true'}, 13.999 INTO pm1.g1;\n") //$NON-NLS-1$
- .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
- .append("END\n"); //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
- .append("BEGIN\n") //$NON-NLS-1$
- .append("SELECT 'a', 19, {b'true'}, 13.999 INTO #myTempTable;\n") //$NON-NLS-1$
- .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
- .append("END\n"); //$NON-NLS-1$
- helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- /*@Test public void testCommandUpdating3() throws Exception{
- StringBuffer procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
- .append("BEGIN\n") //$NON-NLS-1$
- .append("INSERT INTO pm1.g1 (e1) VALUES (INPUTS.e1);\n") //$NON-NLS-1$
- .append("ROWS_UPDATED = INSERT INTO pm1.g2 (e1) VALUES (INPUTS.e1);\n") //$NON-NLS-1$
- .append("END\n"); //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- Command command = helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- assertEquals(2, command.updatingModelCount(metadata));
- }*/
-
- /*@Test public void testCommandUpdatingCount6() throws Exception{
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "if(INPUTS.e1 = 10)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "INSERT INTO pm1.g1 (e2) VALUES (INPUTS.e2);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "INSERT into vm1.g1 (e1) values('x')"; //$NON-NLS-1$
-
- Command command = helpResolveUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
- assertEquals(2, command.updatingModelCount(metadata));
- }*/
-
- // variable declared is of special type ROWS_RETURNED
- @Test public void testDeclareRowsUpdated() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer rows_updated;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- 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$
- }
-
- // validating INPUT element assigned
- @Test public void testAssignInput() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "INPUTS.e1 = Select pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // validating CHANGING element assigned
- @Test public void testAssignChanging() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "CHANGING.e1 = Select pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailUpdateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // variables cannot be used among insert elements
- @Test public void testVariableInInsert() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Insert into pm1.g1 (pm1.g1.e2, var1) values (1, 2);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- 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$
- }
-
- // variables cannot be used among insert elements
- @Test public void testVariableInInsert2() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Insert into pm1.g1 (pm1.g1.e2, INPUTS.x) values (1, 2);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- 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$
- }
-
- //should resolve first to the table's column
- @Test public void testVariableInInsert3() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer e2;\n"; //$NON-NLS-1$
- procedure = procedure + "Insert into pm1.g1 (e2) values (1);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testAmbigousInput() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "select e1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- 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$
- }
-
- @Test public void testLoopRedefinition() {
- StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
- .append("\nBEGIN") //$NON-NLS-1$
- .append("\n declare string var1;") //$NON-NLS-1$
- .append("\n LOOP ON (SELECT pm1.g1.e1 FROM pm1.g1) AS loopCursor") //$NON-NLS-1$
- .append("\n BEGIN") //$NON-NLS-1$
- .append("\n LOOP ON (SELECT pm1.g2.e1 FROM pm1.g2 WHERE loopCursor.e1 = pm1.g2.e1) AS loopCursor") //$NON-NLS-1$
- .append("\n BEGIN") //$NON-NLS-1$
- .append("\n var1 = CONCAT(var1, CONCAT(' ', loopCursor.e1));") //$NON-NLS-1$
- .append("\n END") //$NON-NLS-1$
- .append("\n END") //$NON-NLS-1$
- .append("\n END"); //$NON-NLS-1$
-
- 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$
- }
-
- @Test public void testTempGroupElementShouldNotBeResolable() {
- StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
- .append("\nBEGIN") //$NON-NLS-1$
- .append("\n select 1 as a into #temp;") //$NON-NLS-1$
- .append("\n select #temp.a from pm1.g1;") //$NON-NLS-1$
- .append("\nEND"); //$NON-NLS-1$
-
- 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$
- }
-
- @Test public void testTempGroupElementShouldNotBeResolable1() {
- StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
- .append("\nBEGIN") //$NON-NLS-1$
- .append("\n select 1 as a into #temp;") //$NON-NLS-1$
- .append("\n insert into #temp (a) values (#temp.a);") //$NON-NLS-1$
- .append("\nEND"); //$NON-NLS-1$
-
- 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$
- }
-
- @Test public void testProcedureCreate() throws Exception {
- StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
- .append("\nBEGIN") //$NON-NLS-1$
- .append("\n create local temporary table t1 (e1 string);") //$NON-NLS-1$
- .append("\n select e1 from t1;") //$NON-NLS-1$
- .append("\n create local temporary table t1 (e1 string, e2 integer);") //$NON-NLS-1$
- .append("\n select e2 from t1;") //$NON-NLS-1$
- .append("\nEND"); //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(proc.toString(), userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- /**
- * it is not ok to redefine the loopCursor
- */
- @Test public void testProcedureCreate1() {
- StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
- .append("\nBEGIN") //$NON-NLS-1$
- .append("\n LOOP ON (SELECT pm1.g1.e1 FROM pm1.g1) AS loopCursor") //$NON-NLS-1$
- .append("\n BEGIN") //$NON-NLS-1$
- .append("\n create local temporary table loopCursor (e1 string);") //$NON-NLS-1$
- .append("\nEND") //$NON-NLS-1$
- .append("\nEND"); //$NON-NLS-1$
-
- 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$
- }
-
- @Test public void testProcedureCreateDrop() {
- StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
- .append("\nBEGIN") //$NON-NLS-1$
- .append("\n drop table t1;") //$NON-NLS-1$
- .append("\n create local temporary table t1 (e1 string);") //$NON-NLS-1$
- .append("\nEND"); //$NON-NLS-1$
-
- 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$
- }
-
- @Test public void testProcedureCreateDrop1() throws Exception {
- StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
- .append("\nBEGIN") //$NON-NLS-1$
- .append("\n create local temporary table t1 (e1 string);") //$NON-NLS-1$
- .append("\n drop table t1;") //$NON-NLS-1$
- .append("\nEND"); //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(proc.toString(), userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testCreateAfterImplicitTempTable() throws Exception {
- StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
- .append("\nBEGIN") //$NON-NLS-1$
- .append("\n select e1 into #temp from pm1.g1;") //$NON-NLS-1$
- .append("\n create local temporary table #temp (e1 string);") //$NON-NLS-1$
- .append("\nEND"); //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(proc.toString(), userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testInsertAfterCreate() throws Exception {
- StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
- .append("\nBEGIN") //$NON-NLS-1$
- .append("\n create local temporary table #temp (e1 string, e2 string);") //$NON-NLS-1$
- .append("\n insert into #temp (e1) values ('a');") //$NON-NLS-1$
- .append("\nEND"); //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(proc.toString(), userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- /**
- * delete procedures should not reference input or changing vars.
- */
- @Test public void testDefect16451() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure += "BEGIN\n"; //$NON-NLS-1$
- procedure += "Select pm1.g1.e2 from pm1.g1 where e1 = INPUTS.e1;\n"; //$NON-NLS-1$
- procedure += "ROWS_UPDATED = 0;"; //$NON-NLS-1$
- procedure += "END\n"; //$NON-NLS-1$
-
- 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$
- }
-
- @Test public void testInvalidVirtualProcedure3() throws Exception {
- helpResolveException("EXEC pm1.vsp18()", FakeMetadataFactory.example1Cached(), "Group does not exist: temptable"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // variable resolution, variable compared against
- // different datatype element for which there is no implicit transformation)
- @Test public void testCreateUpdateProcedure2() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure += "BEGIN\n"; //$NON-NLS-1$
- procedure += "DECLARE boolean var1;\n"; //$NON-NLS-1$
- procedure += "ROWS_UPDATED = UPDATE pm1.g1 SET pm1.g1.e4 = convert(var1, string), pm1.g1.e1 = var1;\n"; //$NON-NLS-1$
- procedure += "END\n"; //$NON-NLS-1$
-
- 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$
- }
-
- // special variable INPUT compared against invalid type
- @Test public void testInvalidInputInUpdate() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure += "BEGIN\n"; //$NON-NLS-1$
- procedure += "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure += "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure += "ROWS_UPDATED = UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = INPUTS.e1;\n"; //$NON-NLS-1$
- procedure += "END\n"; //$NON-NLS-1$
-
- 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$
- }
-
- @Test public void testVirtualProcedure() throws Exception {
- helpResolve("EXEC pm1.vsp1()", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
- }
-
- @Test public void testVirtualProcedure2() throws Exception {
- helpResolve("EXEC pm1.vsp14()", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
- }
-
- @Test public void testVirtualProcedurePartialParameterReference() throws Exception {
- helpResolve("EXEC pm1.vsp58(5)", FakeMetadataFactory.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$
- }
-
- @Test public void testVirtualProcedureWithOrderBy() throws Exception {
- helpResolve("EXEC pm1.vsp29()", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
- }
-
- @Test public void testVirtualProcedureWithTempTableAndOrderBy() throws Exception {
- helpResolve("EXEC pm1.vsp33()", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
- }
-
- @Test public void testVirtualProcedureWithConstAndOrderBy() throws Exception {
- helpResolve("EXEC pm1.vsp34()", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
- }
-
- @Test public void testVirtualProcedureWithNoFromAndOrderBy() throws Exception {
- helpResolve("EXEC pm1.vsp28()", FakeMetadataFactory.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$
- }
-
- @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$
- }
-
- @Test public void testVariableResolutionWithIntervening() throws Exception {
- StringBuffer proc = new StringBuffer("CREATE VIRTUAL PROCEDURE") //$NON-NLS-1$
- .append("\nBEGIN") //$NON-NLS-1$
- .append("\n declare string x;") //$NON-NLS-1$
- .append("\n x = '1';") //$NON-NLS-1$
- .append("\n declare string y;") //$NON-NLS-1$
- .append("\n y = '1';") //$NON-NLS-1$
- .append("\nEND"); //$NON-NLS-1$
-
- TestResolver.helpResolve(proc.toString(), FakeMetadataFactory.example1Cached());
- }
-
- @Test public void testVDBQualified() throws Exception {
- helpResolve("EXEC myvdb.pm1.vsp29()", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestProcedureResolving.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/resolver/TestProcedureResolving.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestProcedureResolving.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestProcedureResolving.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1550 @@
+/*
+ * 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.resolver;
+
+import static org.junit.Assert.*;
+
+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.core.TeiidComponentException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.Table;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.sql.ProcedureReservedWords;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.ProcedureContainer;
+import org.teiid.query.sql.proc.AssignmentStatement;
+import org.teiid.query.sql.proc.Block;
+import org.teiid.query.sql.proc.CommandStatement;
+import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
+import org.teiid.query.sql.proc.LoopStatement;
+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.visitor.CommandCollectorVisitor;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+public class TestProcedureResolving {
+
+ private void helpFailUpdateProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType) {
+ helpFailUpdateProcedure(procedure, userUpdateStr, procedureType, null);
+ }
+
+ private void helpFailUpdateProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType, String msg) {
+ // resolve
+ try {
+ helpResolveUpdateProcedure(procedure, userUpdateStr, procedureType);
+ fail("Expected a QueryResolverException but got none."); //$NON-NLS-1$
+ } catch(QueryResolverException ex) {
+ if (msg != null) {
+ assertEquals(msg, ex.getMessage());
+ }
+ } catch (TeiidComponentException e) {
+ throw new RuntimeException(e);
+ } catch (QueryParserException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Test public void testDefect13029_CorrectlySetUpdateProcedureTempGroupIDs() throws Exception {
+ StringBuffer proc = new StringBuffer("CREATE VIRTUAL PROCEDURE") //$NON-NLS-1$
+ .append("\nBEGIN") //$NON-NLS-1$
+ .append("\nDECLARE string var1;") //$NON-NLS-1$
+ .append("\nvar1 = '';") //$NON-NLS-1$
+ .append("\n LOOP ON (SELECT pm1.g1.e1 FROM pm1.g1) AS loopCursor") //$NON-NLS-1$
+ .append("\n BEGIN") //$NON-NLS-1$
+ .append("\n LOOP ON (SELECT pm1.g2.e1 FROM pm1.g2 WHERE loopCursor.e1 = pm1.g2.e1) AS loopCursor2") //$NON-NLS-1$
+ .append("\n BEGIN") //$NON-NLS-1$
+ .append("\n var1 = CONCAT(var1, CONCAT(' ', loopCursor2.e1));") //$NON-NLS-1$
+ .append("\n END") //$NON-NLS-1$
+ .append("\n END") //$NON-NLS-1$
+ .append("\nEND"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ Command command = helpResolveUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE);
+ Map tempIDs = command.getTemporaryMetadata();
+ assertNotNull(tempIDs);
+ assertNull(tempIDs.get("LOOPCURSOR")); //$NON-NLS-1$
+ assertNull(tempIDs.get("LOOPCURSOR2")); //$NON-NLS-1$
+
+ Command subCommand = CommandCollectorVisitor.getCommands(command).get(0);
+ tempIDs = subCommand.getTemporaryMetadata();
+ assertNotNull(tempIDs);
+ assertNull(tempIDs.get("LOOPCURSOR")); //$NON-NLS-1$
+ assertNull(tempIDs.get("LOOPCURSOR2")); //$NON-NLS-1$
+
+ subCommand = CommandCollectorVisitor.getCommands(command).get(1);
+ tempIDs = subCommand.getTemporaryMetadata();
+ assertNotNull(tempIDs);
+ assertNotNull(tempIDs.get("LOOPCURSOR")); //$NON-NLS-1$
+ assertNull(tempIDs.get("LOOPCURSOR2")); //$NON-NLS-1$
+ }
+
+ private CreateUpdateProcedureCommand helpResolveUpdateProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType) throws QueryParserException, QueryResolverException, TeiidComponentException {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(procedureType, procedure);
+ return resolveProcedure(userUpdateStr, metadata);
+ }
+
+ private CreateUpdateProcedureCommand resolveProcedure(String userUpdateStr,
+ QueryMetadataInterface metadata) throws QueryParserException,
+ QueryResolverException, TeiidComponentException,
+ QueryMetadataException {
+ ProcedureContainer userCommand = (ProcedureContainer)QueryParser.getQueryParser().parseCommand(userUpdateStr);
+ QueryResolver.resolveCommand(userCommand, metadata);
+ metadata = new TempMetadataAdapter(metadata, new TempMetadataStore(userCommand.getTemporaryMetadata()));
+ return (CreateUpdateProcedureCommand)QueryResolver.expandCommand(userCommand, metadata, null);
+ }
+
+ private void helpResolveException(String userUpdateStr, QueryMetadataInterface metadata, String msg) throws QueryParserException, TeiidComponentException {
+ try {
+ helpResolve(userUpdateStr, metadata);
+ fail();
+ } catch (QueryResolverException e) {
+ assertEquals(msg, e.getMessage());
+ }
+ }
+
+ private CreateUpdateProcedureCommand helpResolve(String userUpdateStr, QueryMetadataInterface metadata) throws QueryParserException, QueryResolverException, TeiidComponentException {
+ return resolveProcedure(userUpdateStr, metadata);
+ }
+
+ /**
+ * Constants will now auto resolve if they are consistently representable in the target type
+ */
+ @Test public void testDefect23257() throws Exception{
+ CreateUpdateProcedureCommand command = helpResolve("EXEC pm6.vsp59()", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+
+ CommandStatement cs = (CommandStatement)command.getBlock().getStatements().get(1);
+
+ Insert insert = (Insert)cs.getCommand();
+
+ assertEquals(DataTypeManager.DefaultDataClasses.SHORT, ((Expression)insert.getValues().get(1)).getType());
+ }
+
+ @Test public void testProcedureScoping() throws Exception {
+ StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
+ .append("\nBEGIN") //$NON-NLS-1$
+ //note that this declare takes presedense over the proc INPUTS.e1 and CHANGING.e1 variables
+ .append("\n declare integer e1 = 1;") //$NON-NLS-1$
+ .append("\n e1 = e1;") //$NON-NLS-1$
+ .append("\n LOOP ON (SELECT pm1.g1.e1 FROM pm1.g1) AS loopCursor") //$NON-NLS-1$
+ .append("\n BEGIN") //$NON-NLS-1$
+ //inside the scope of the loop, an unqualified e1 should resolve to the loop variable group
+ .append("\n variables.e1 = convert(e1, integer);") //$NON-NLS-1$
+ .append("\n END") //$NON-NLS-1$
+ .append("\nEND"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ CreateUpdateProcedureCommand command = helpResolveUpdateProcedure(proc.toString(), userUpdateStr,
+ 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());
+
+ Block inner = ((LoopStatement)block.getStatements().get(2)).getBlock();
+
+ assStmt = (AssignmentStatement)inner.getStatements().get(0);
+
+ ElementSymbol value = ElementCollectorVisitor.getElements(assStmt.getValue(), false).iterator().next();
+
+ assertEquals("LOOPCURSOR", value.getGroupSymbol().getCanonicalName()); //$NON-NLS-1$
+ }
+
+ // variable resolution, variable used in if statement, variable compared against
+ // different datatype element
+ @Test public void testCreateUpdateProcedure4() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE boolean var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 =1);\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // variable resolution, variable used in if statement, invalid operation on variable
+ @Test public void testCreateUpdateProcedure5() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE boolean var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = var1 + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 whwre var1 = var1+var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // variable resolution, variables declared in different blocks local variables
+ // should not override
+ @Test public void testCreateUpdateProcedure6() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 =1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE boolean var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where var1 = pm1.g1.e3;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE, "Variable var1 was previously declared."); //$NON-NLS-1$
+ }
+
+ // variable resolution, variables declared in different blocks local variables
+ // inner block using outer block variables
+ @Test public void testCreateUpdateProcedure7() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 =1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE boolean var2;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where var1 = pm1.g1.e1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // variable resolution, variables declared in different blocks local variables
+ // outer block cannot use inner block variables
+ @Test public void testCreateUpdateProcedure8() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 =1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var2;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where var1 = pm1.g1.e1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "var2 = 1\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // variable resolution, variables declared in different blocks local variables
+ // should override, outer block variables still valid afetr inner block is declared
+ @Test public void testCreateUpdateProcedure9() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 =1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE boolean var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where var1 = pm1.g1.e3;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = var1 +1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // special variable ROWS_UPDATED resolution
+ @Test public void testCreateUpdateProcedure10() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = ROWS_UPDATED + var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // special variable ROWS_UPDATED used with declared variable
+ @Test public void testCreateUpdateProcedure11() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // special variable INPUT used with declared variable
+ @Test public void testCreateUpdateProcedure12() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // special variable CHANGING used with declared variable
+ @Test public void testCreateUpdateProcedure14() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // special variable CHANGING and INPUT used in compound criteria
+ @Test public void testCreateUpdateProcedure15() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(CHANGING.e1='false' and INPUTS.e1=1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // special variable CHANGING and INPUT used in compound criteria, with declared variables
+ @Test public void testCreateUpdateProcedure16() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(CHANGING.e4 ='true' and INPUTS.e2=1 or var1 < 30)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // special variable CHANGING compared against integer no implicit conversion available
+ @Test public void testCreateUpdateProcedure17() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "if(CHANGING.e4 = {d'2000-01-01'})\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ 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)
+ @Test public void testCreateUpdateProcedure18() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where HAS CRITERIA ON (vm1.g1.e1, vm1.g1.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // virtual group elements used in procedure in if statement(HAS CRITERIA)
+ @Test public void testCreateUpdateProcedure19() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(HAS CRITERIA ON (vm1.g1.e1, vm1.g1.e1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where HAS CRITERIA ON (vm1.g1.e1, vm1.g1.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // virtual group elements used in procedure(TRANSLATE CRITERIA)
+ @Test public void testCreateUpdateProcedure20() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // virtual group elements used in procedure(TRANSLATE CRITERIA)
+ @Test public void testCreateUpdateProcedure21() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e2 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // using undefined variable should fail
+ @Test public void testCreateUpdateProcedure22() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+// procedure = procedure + "DECLARE integer var1;\n";
+ procedure = procedure + "var3 = var2+var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var2 = Select pm1.g1.e2 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // using undefined variable declared is of invalid datatype
+ @Test public void testCreateUpdateProcedure23() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE struct var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 'x', pm1.g1.e2 = INPUTS.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // using declare variable that has parts
+ @Test public void testCreateUpdateProcedure24() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var2.var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // using declare variable is qualified
+ @Test public void testCreateUpdateProcedure26() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer VARIABLES.var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // using declare variable is qualified but has more parts
+ @Test public void testCreateUpdateProcedure27() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer VARIABLES.var1.var2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // using a variable that has not been declared in an assignment stmt
+ @Test public void testCreateUpdateProcedure28() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // using a variable that has not been declared in an assignment stmt
+ @Test public void testCreateUpdateProcedure29() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = 1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // using invalid function in assignment expr
+ @Test public void testCreateUpdateProcedure30() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Declare integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = 'x' + ROWS_UPDATED;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // using invalid function in assignment expr
+ @Test public void testCreateUpdateProcedure31() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Declare integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = 'x' + ROWS_UPDATED;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // using a variable being used inside a subcomand
+ @Test public void testCreateUpdateProcedure32() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Declare integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select var1 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // variable resolution, variables declared in different blocks local variables
+ // should override, outer block variables still valid afetr inner block is declared
+ // fails as variable being compared against incorrect type
+ @Test public void testCreateUpdateProcedure33() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 =1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE timestamp var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where var1 = pm1.g1.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = var1 +1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // physical elements used on criteria of the if statement
+ @Test public void testCreateUpdateProcedure34() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(pm1.g1.e2 =1 and var1=1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ 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
+ @Test public void testCreateUpdateProcedure35() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(HAS CRITERIA ON (vm1.g1.e1) and var1=1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // physical elements used on criteria of the if statement
+ @Test public void testCreateUpdateProcedure36() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(pm1.g1.e2 =1 and var1=1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // TranslateCriteria on criteria of the if statement
+ @Test public void testCreateUpdateProcedure37() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(TRANSLATE CRITERIA ON (vm1.g1.e1) WITH (vm1.g1.e1 = 1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // validating Translate CRITERIA, elements on it should be virtual group elements
+ // but can use variables
+ @Test public void testCreateUpdateProcedure38() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (pm1.g1.e2 = var1);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // physical elements used on criteria of the if statement
+ @Test public void testCreateUpdateProcedure39() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(pm1.g1.e2 =1 and var1=1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // TranslateCriteria on criteria of the if statement
+ @Test public void testCreateUpdateProcedure40() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(TRANSLATE CRITERIA ON (e1) WITH (g1.e1 = 1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // TranslateCriteria on criteria of the if statement
+ @Test public void testCreateUpdateProcedure41() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(HAS CRITERIA ON (e1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE CRITERIA ON (e1) WITH (g1.e1 = 1);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // TranslateCriteria on criteria of the if statement
+ @Test public void testCreateUpdateProcedure42() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(HAS CRITERIA ON (e1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE CRITERIA ON (e1) WITH (g1.e1 = 1);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // TranslateCriteria on criteria of the if statement
+ @Test public void testCreateUpdateProcedure43() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE CRITERIA ON (e1) WITH (g1.e1 = 1);\n"; //$NON-NLS-1$
+// procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n";
+// 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 = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
+
+ Command procCommand = QueryParser.getQueryParser().parseCommand(procedure);
+ GroupSymbol virtualGroup = new GroupSymbol("vm1.g1"); //$NON-NLS-1$
+ virtualGroup.setMetadataID(metadata.getGroupID("vm1.g1")); //$NON-NLS-1$
+ QueryResolver.resolveCommand(procCommand, virtualGroup, Command.TYPE_UPDATE, metadata);
+ }
+
+ // special variable CHANGING compared against integer no implicit conversion available
+ @Test public void testCreateUpdateProcedure44() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "if(INPUTS.e1 = 10)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "INSERT into vm1.g1 (e1) values('x')"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.INSERT);
+ }
+
+ // special variable CHANGING compared against integer no implicit conversion available
+ @Test public void testCreateUpdateProcedure45() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "if(INPUTS.e1 = 10)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ Command procCommand = QueryParser.getQueryParser().parseCommand(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$
+
+ QueryResolver.resolveCommand(procCommand, virtualGroup, Command.TYPE_INSERT, metadata);
+ }
+
+ // special variable CHANGING compared against integer no implicit conversion available
+ @Test public void testCreateUpdateProcedure46() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ Command procCommand = QueryParser.getQueryParser().parseCommand(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$
+
+ QueryResolver.resolveCommand(procCommand, virtualGroup, Command.TYPE_UPDATE, metadata);
+ }
+
+ // TranslateCriteria on criteria of the if statement
+ @Test public void testCreateUpdateProcedure47() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(HAS CRITERIA ON (e1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE CRITERIA ON (e1) WITH (vm1.g1.e1 = pm1.g1.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // validating Translate CRITERIA, elements(left elements on on it should be virtual group elements
+ @Test public void testCreateUpdateProcedure48() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, INPUTS.e2 = 2);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // resolving Translate CRITERIA, right element should be present on the command
+ @Test public void testCreateUpdateProcedure49() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = pm1.g2.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // resolving criteria selector(on HAS CRITERIA), elements on it should be virtual group elements
+ @Test public void testCreateUpdateProcedure50() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(HAS CRITERIA ON (vm1.g1.E1, vm1.g1.e1, INPUTS.e1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // resolving Translate CRITERIA, right side expression in the translate criteria should be elements on the command
+ @Test public void testCreateUpdateProcedure51() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1=1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e2 = var1+vm1.g1.e2, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // validating Translate CRITERIA, elements on it should be virtual group elements
+ // but can use variables, gut left exprs should always be virtual elements
+ @Test public void testCreateUpdateProcedure52() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (var1 = vm1.g1.e2, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // resolving AssignmentStatement, variable type and assigned type
+ // do not match and no implicit conversion available
+ @Test public void testCreateUpdateProcedure53() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = INPUTS.e4;"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // resolving AssignmentStatement, variable type and assigned type
+ // do not match, but implicit conversion available
+ @Test public void testCreateUpdateProcedure54() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE string var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = 1+1;"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // resolving AssignmentStatement, variable type and assigned type
+ // do not match, but implicit conversion available
+ @Test public void testCreateUpdateProcedure55() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE string var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = 1+ROWS_UPDATED;"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testDefect14912_CreateUpdateProcedure57_FunctionWithElementParamInAssignmentStatement() {
+ // Tests that the function params are resolved before the function for assignment statements
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE string var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = badFunction(badElement);"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userCommand = "UPDATE vm1.g1 SET e1='x'"; //$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,
+ // this case failed with assertion exception.
+ @Test public void testCase4624() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "VARIABLES.ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE boolean var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = {b'false'};\n"; //$NON-NLS-1$
+ procedure = procedure + "IF(var1 = {b 'true'})\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT Rack_ID, RACK_MDT_TYPE INTO #racks FROM Bert_MAP.BERT3.RACK;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userCommand = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userCommand, Table.TriggerEvent.UPDATE, "Group does not exist: Bert_MAP.BERT3.RACK"); //$NON-NLS-1$
+ }
+
+ // addresses Cases 5474.
+ @Test public void testCase5474() throws Exception {
+ String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer VARIABLES.NLEVELS;\n"; //$NON-NLS-1$
+ 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, RealMetadataFactory.example1Cached());
+ }
+
+ @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 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$
+
+ TestResolver.helpResolve(procedure, RealMetadataFactory.example1Cached());
+ }
+
+ /*@Test public void testCommandUpdatingCountFromLastStatement() throws Exception {
+ String procedure = "CREATE VIRTUAL PROCEDURE \n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "declare integer x = convert(pm1.sq1.in, integer) + 5;\n"; //$NON-NLS-1$
+ procedure = procedure + "insert into pm1.g1 values (null, null, null, null);"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = exampleStoredProcedure(procedure);
+ Command command = helpResolve(helpParse("exec pm1.sq1(1)"), metadata, null); //$NON-NLS-1$
+
+ assertEquals(1, command.updatingModelCount(new TempMetadataAdapter(metadata, new TempMetadataStore())));
+ }*/
+
+ //baseline test to ensure that a declare assignment cannot contain the declared variable
+ @Test public void testDeclareStatement() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer VARIABLES.var1 = VARIABLES.var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr, Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testDynamicIntoInProc() throws Exception {
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ StringBuffer procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
+ .append("BEGIN\n") //$NON-NLS-1$
+ .append("execute string 'SELECT e1, e2, e3, e4 FROM pm1.g2' as e1 string, e2 string, e3 string, e4 string INTO #myTempTable;\n") //$NON-NLS-1$
+ .append("select e1 from #myTempTable;\n") //$NON-NLS-1$
+ .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
+ .append("END\n"); //$NON-NLS-1$
+ helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testDynamicStatement() throws Exception {
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ StringBuffer procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
+ .append("BEGIN\n") //$NON-NLS-1$
+ .append("execute string 'SELECT e1, e2, e3, e4 FROM pm1.g2';\n") //$NON-NLS-1$
+ .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
+ .append("END\n"); //$NON-NLS-1$
+ helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testDynamicStatementType() {
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ StringBuffer procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
+ .append("BEGIN\n") //$NON-NLS-1$
+ .append("DECLARE object VARIABLES.X = null;\n") //$NON-NLS-1$
+ .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, Table.TriggerEvent.UPDATE);
+ }
+
+ // variable resolution
+ @Test public void testCreateUpdateProcedure1() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = 1, pm1.g1.e2 = var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1=1"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // variable resolution, variable used in if statement
+ @Test public void testCreateUpdateProcedure3() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 =1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testSelectIntoInProc() throws Exception {
+ StringBuffer procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
+ .append("BEGIN\n") //$NON-NLS-1$
+ .append("SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2;\n") //$NON-NLS-1$
+ .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
+ .append("END\n"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+
+ procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
+ .append("BEGIN\n") //$NON-NLS-1$
+ .append("SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g2;\n") //$NON-NLS-1$
+ .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
+ .append("END\n"); //$NON-NLS-1$
+ helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testSelectIntoInProcNoFrom() throws Exception {
+ StringBuffer procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
+ .append("BEGIN\n") //$NON-NLS-1$
+ .append("SELECT 'a', 19, {b'true'}, 13.999 INTO pm1.g1;\n") //$NON-NLS-1$
+ .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
+ .append("END\n"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+
+ procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
+ .append("BEGIN\n") //$NON-NLS-1$
+ .append("SELECT 'a', 19, {b'true'}, 13.999 INTO #myTempTable;\n") //$NON-NLS-1$
+ .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
+ .append("END\n"); //$NON-NLS-1$
+ helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ /*@Test public void testCommandUpdating3() throws Exception{
+ StringBuffer procedure = new StringBuffer("CREATE PROCEDURE ") //$NON-NLS-1$
+ .append("BEGIN\n") //$NON-NLS-1$
+ .append("INSERT INTO pm1.g1 (e1) VALUES (INPUTS.e1);\n") //$NON-NLS-1$
+ .append("ROWS_UPDATED = INSERT INTO pm1.g2 (e1) VALUES (INPUTS.e1);\n") //$NON-NLS-1$
+ .append("END\n"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ Command command = helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ assertEquals(2, command.updatingModelCount(metadata));
+ }*/
+
+ /*@Test public void testCommandUpdatingCount6() throws Exception{
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "if(INPUTS.e1 = 10)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "INSERT INTO pm1.g1 (e2) VALUES (INPUTS.e2);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "INSERT into vm1.g1 (e1) values('x')"; //$NON-NLS-1$
+
+ Command command = helpResolveUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.INSERT);
+ assertEquals(2, command.updatingModelCount(metadata));
+ }*/
+
+ // variable declared is of special type ROWS_RETURNED
+ @Test public void testDeclareRowsUpdated() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer rows_updated;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE, "Variable rows_updated was previously declared."); //$NON-NLS-1$
+ }
+
+ // validating INPUT element assigned
+ @Test public void testAssignInput() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "INPUTS.e1 = Select pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // validating CHANGING element assigned
+ @Test public void testAssignChanging() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "CHANGING.e1 = Select pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // variables cannot be used among insert elements
+ @Test public void testVariableInInsert() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Insert into pm1.g1 (pm1.g1.e2, var1) values (1, 2);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userQuery,
+ 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
+ @Test public void testVariableInInsert2() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Insert into pm1.g1 (pm1.g1.e2, INPUTS.x) values (1, 2);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userQuery,
+ 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
+ @Test public void testVariableInInsert3() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "Insert into pm1.g1 (e2) values (1);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testAmbigousInput() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "select e1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE, "Element \"e1\" is ambiguous, it exists in two or more groups."); //$NON-NLS-1$
+ }
+
+ @Test public void testLoopRedefinition() {
+ StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
+ .append("\nBEGIN") //$NON-NLS-1$
+ .append("\n declare string var1;") //$NON-NLS-1$
+ .append("\n LOOP ON (SELECT pm1.g1.e1 FROM pm1.g1) AS loopCursor") //$NON-NLS-1$
+ .append("\n BEGIN") //$NON-NLS-1$
+ .append("\n LOOP ON (SELECT pm1.g2.e1 FROM pm1.g2 WHERE loopCursor.e1 = pm1.g2.e1) AS loopCursor") //$NON-NLS-1$
+ .append("\n BEGIN") //$NON-NLS-1$
+ .append("\n var1 = CONCAT(var1, CONCAT(' ', loopCursor.e1));") //$NON-NLS-1$
+ .append("\n END") //$NON-NLS-1$
+ .append("\n END") //$NON-NLS-1$
+ .append("\n END"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(proc.toString(), userUpdateStr,
+ Table.TriggerEvent.UPDATE, "Nested Loop can not use the same cursor name as that of its parent."); //$NON-NLS-1$
+ }
+
+ @Test public void testTempGroupElementShouldNotBeResolable() {
+ StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
+ .append("\nBEGIN") //$NON-NLS-1$
+ .append("\n select 1 as a into #temp;") //$NON-NLS-1$
+ .append("\n select #temp.a from pm1.g1;") //$NON-NLS-1$
+ .append("\nEND"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(proc.toString(), userUpdateStr,
+ Table.TriggerEvent.UPDATE, "Symbol #temp.a is specified with an unknown group context"); //$NON-NLS-1$
+ }
+
+ @Test public void testTempGroupElementShouldNotBeResolable1() {
+ StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
+ .append("\nBEGIN") //$NON-NLS-1$
+ .append("\n select 1 as a into #temp;") //$NON-NLS-1$
+ .append("\n insert into #temp (a) values (#temp.a);") //$NON-NLS-1$
+ .append("\nEND"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(proc.toString(), userUpdateStr,
+ Table.TriggerEvent.UPDATE, "Symbol #temp.a is specified with an unknown group context"); //$NON-NLS-1$
+ }
+
+ @Test public void testProcedureCreate() throws Exception {
+ StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
+ .append("\nBEGIN") //$NON-NLS-1$
+ .append("\n create local temporary table t1 (e1 string);") //$NON-NLS-1$
+ .append("\n select e1 from t1;") //$NON-NLS-1$
+ .append("\n create local temporary table t1 (e1 string, e2 integer);") //$NON-NLS-1$
+ .append("\n select e2 from t1;") //$NON-NLS-1$
+ .append("\nEND"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE);
+ }
+
+ /**
+ * it is not ok to redefine the loopCursor
+ */
+ @Test public void testProcedureCreate1() {
+ StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
+ .append("\nBEGIN") //$NON-NLS-1$
+ .append("\n LOOP ON (SELECT pm1.g1.e1 FROM pm1.g1) AS loopCursor") //$NON-NLS-1$
+ .append("\n BEGIN") //$NON-NLS-1$
+ .append("\n create local temporary table loopCursor (e1 string);") //$NON-NLS-1$
+ .append("\nEND") //$NON-NLS-1$
+ .append("\nEND"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$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() {
+ StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
+ .append("\nBEGIN") //$NON-NLS-1$
+ .append("\n drop table t1;") //$NON-NLS-1$
+ .append("\n create local temporary table t1 (e1 string);") //$NON-NLS-1$
+ .append("\nEND"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE, "Group does not exist: t1"); //$NON-NLS-1$
+ }
+
+ @Test public void testProcedureCreateDrop1() throws Exception {
+ StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
+ .append("\nBEGIN") //$NON-NLS-1$
+ .append("\n create local temporary table t1 (e1 string);") //$NON-NLS-1$
+ .append("\n drop table t1;") //$NON-NLS-1$
+ .append("\nEND"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testCreateAfterImplicitTempTable() throws Exception {
+ StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
+ .append("\nBEGIN") //$NON-NLS-1$
+ .append("\n select e1 into #temp from pm1.g1;") //$NON-NLS-1$
+ .append("\n create local temporary table #temp (e1 string);") //$NON-NLS-1$
+ .append("\nEND"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testInsertAfterCreate() throws Exception {
+ StringBuffer proc = new StringBuffer("CREATE PROCEDURE") //$NON-NLS-1$
+ .append("\nBEGIN") //$NON-NLS-1$
+ .append("\n create local temporary table #temp (e1 string, e2 string);") //$NON-NLS-1$
+ .append("\n insert into #temp (e1) values ('a');") //$NON-NLS-1$
+ .append("\nEND"); //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE);
+ }
+
+ /**
+ * delete procedures should not reference input or changing vars.
+ */
+ @Test public void testDefect16451() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure += "BEGIN\n"; //$NON-NLS-1$
+ procedure += "Select pm1.g1.e2 from pm1.g1 where e1 = INPUTS.e1;\n"; //$NON-NLS-1$
+ procedure += "ROWS_UPDATED = 0;"; //$NON-NLS-1$
+ procedure += "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "delete from vm1.g1 where e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ 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()", RealMetadataFactory.example1Cached(), "Group does not exist: temptable"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // variable resolution, variable compared against
+ // different datatype element for which there is no implicit transformation)
+ @Test public void testCreateUpdateProcedure2() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure += "BEGIN\n"; //$NON-NLS-1$
+ procedure += "DECLARE boolean var1;\n"; //$NON-NLS-1$
+ procedure += "ROWS_UPDATED = UPDATE pm1.g1 SET pm1.g1.e4 = convert(var1, string), pm1.g1.e1 = var1;\n"; //$NON-NLS-1$
+ procedure += "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1=1"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ 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
+ @Test public void testInvalidInputInUpdate() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure += "BEGIN\n"; //$NON-NLS-1$
+ procedure += "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure += "Select pm1.g1.e2, INPUTS.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure += "ROWS_UPDATED = UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = INPUTS.e1;\n"; //$NON-NLS-1$
+ procedure += "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailUpdateProcedure(procedure, userUpdateStr,
+ 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()", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testVirtualProcedure2() throws Exception {
+ helpResolve("EXEC pm1.vsp14()", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testVirtualProcedurePartialParameterReference() throws Exception {
+ helpResolve("EXEC pm1.vsp58(5)", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ //cursor starts with "#" Defect14924
+ @Test public void testVirtualProcedureInvalid1() throws Exception {
+ 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()", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testVirtualProcedureWithTempTableAndOrderBy() throws Exception {
+ helpResolve("EXEC pm1.vsp33()", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testVirtualProcedureWithConstAndOrderBy() throws Exception {
+ helpResolve("EXEC pm1.vsp34()", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testVirtualProcedureWithNoFromAndOrderBy() throws Exception {
+ helpResolve("EXEC pm1.vsp28()", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testInvalidVirtualProcedure2() throws Exception {
+ 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()", 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 {
+ StringBuffer proc = new StringBuffer("CREATE VIRTUAL PROCEDURE") //$NON-NLS-1$
+ .append("\nBEGIN") //$NON-NLS-1$
+ .append("\n declare string x;") //$NON-NLS-1$
+ .append("\n x = '1';") //$NON-NLS-1$
+ .append("\n declare string y;") //$NON-NLS-1$
+ .append("\n y = '1';") //$NON-NLS-1$
+ .append("\nEND"); //$NON-NLS-1$
+
+ TestResolver.helpResolve(proc.toString(), RealMetadataFactory.example1Cached());
+ }
+
+ @Test public void testVDBQualified() throws Exception {
+ helpResolve("EXEC example1.pm1.vsp29()", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestResolver.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/resolver/TestResolver.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestResolver.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,2992 +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.resolver;
-
-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.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Before;
-import org.junit.Ignore;
-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.TeiidException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.function.FunctionDescriptor;
-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.TempMetadataID;
-import org.teiid.query.metadata.TempMetadataStore;
-import org.teiid.query.optimizer.FakeFunctionMetadataSource;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.ProcedureReservedWords;
-import org.teiid.query.sql.lang.BatchedUpdateCommand;
-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.From;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.OrderBy;
-import org.teiid.query.sql.lang.ProcedureContainer;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.SubqueryFromClause;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.navigator.DeepPreOrderNavigator;
-import org.teiid.query.sql.proc.CommandStatement;
-import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
-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.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;
-
- at SuppressWarnings("nls")
-public class TestResolver {
-
- private FakeMetadataFacade metadata;
-
- @Before public void setUp() {
- metadata = FakeMetadataFactory.example1Cached();
- }
-
- // ################################## TEST HELPERS ################################
-
- static Command helpParse(String sql) {
- try {
- return QueryParser.getQueryParser().parseCommand(sql);
- } catch(TeiidException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Helps resolve command, then check that the actual resolved Elements variables are the same as
- * the expected variable names. The variableNames param will be empty unless the subquery
- * is a correlated subquery.
- * @param sql Command to parse and resolve
- * @param variableNames expected element symbol variable names, in order
- * @return parsed and resolved Query
- */
- private Command helpResolveSubquery(String sql, String[] variableNames){
- Query query = (Query)helpResolve(sql);
- Collection<ElementSymbol> variables = getVariables(query);
-
- assertTrue("Expected variables size " + variableNames.length + " but was " + variables.size(), //$NON-NLS-1$ //$NON-NLS-2$
- variables.size() == variableNames.length);
- Iterator variablesIter = variables.iterator();
- for (int i=0; variablesIter.hasNext(); i++) {
- ElementSymbol variable = (ElementSymbol)variablesIter.next();
- assertTrue("Expected variable name " + variableNames[i] + " but was " + variable.getName(), //$NON-NLS-1$ //$NON-NLS-2$
- variable.getName().equalsIgnoreCase(variableNames[i]));
- }
-
- if (variableNames.length == 0){
- //There should be no TempMetadataIDs
- Collection symbols = CheckNoTempMetadataIDsVisitor.checkSymbols(query);
- assertTrue("Expected no symbols with temp metadataIDs, but got " + symbols, symbols.isEmpty()); //$NON-NLS-1$
- }
-
- return query;
- }
-
- public static Collection<ElementSymbol> getVariables(LanguageObject languageObject) {
- Collection<ElementSymbol> variables = ElementCollectorVisitor.getElements(languageObject, false, true);
- for (Iterator<ElementSymbol> iterator = variables.iterator(); iterator.hasNext();) {
- ElementSymbol elementSymbol = iterator.next();
- if (!elementSymbol.isExternalReference()) {
- iterator.remove();
- }
- }
- return variables;
- }
-
- public static Command helpResolve(String sql, QueryMetadataInterface queryMetadata){
- return helpResolve(helpParse(sql), queryMetadata);
- }
-
- private Command helpResolve(String sql) {
- return helpResolve(helpParse(sql));
- }
-
- private Command helpResolve(Command command) {
- return helpResolve(command, this.metadata);
- }
-
- static Command helpResolve(Command command, QueryMetadataInterface queryMetadataInterface) {
- // resolve
- try {
- QueryResolver.resolveCommand(command, queryMetadataInterface);
- } catch(TeiidException e) {
- throw new RuntimeException(e);
- }
-
- CheckSymbolsAreResolvedVisitor vis = new CheckSymbolsAreResolvedVisitor();
- DeepPreOrderNavigator.doVisit(command, vis);
- Collection unresolvedSymbols = vis.getUnresolvedSymbols();
- assertTrue("Found unresolved symbols: " + unresolvedSymbols, unresolvedSymbols.isEmpty()); //$NON-NLS-1$
- return command;
- }
-
- /**
- * Expect a QueryResolverException (not any other kind of Throwable)
- */
- private void helpResolveFails(Command command) {
- // resolve
- QueryResolverException exception = null;
- try {
- QueryResolver.resolveCommand(command, metadata);
- } catch(QueryResolverException e) {
- exception = e;
- } catch(TeiidException e) {
- fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
- assertNotNull("Expected a QueryResolverException but got none.", exception); //$NON-NLS-1$
- }
-
- private Criteria helpResolveCriteria(String sql) {
- Criteria criteria = null;
-
- // parse
- try {
- criteria = QueryParser.getQueryParser().parseCriteria(sql);
-
- } catch(TeiidException e) {
- fail("Exception during parsing (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // resolve
- try {
- QueryResolver.resolveCriteria(criteria, metadata);
- } catch(TeiidException e) {
- e.printStackTrace();
- fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- CheckSymbolsAreResolvedVisitor vis = new CheckSymbolsAreResolvedVisitor();
- DeepPreOrderNavigator.doVisit(criteria, vis);
- Collection unresolvedSymbols = vis.getUnresolvedSymbols();
- assertTrue("Found unresolved symbols: " + unresolvedSymbols, unresolvedSymbols.isEmpty()); //$NON-NLS-1$
- return criteria;
- }
-
- public static Command helpResolveWithBindings(String sql, QueryMetadataInterface metadata, List bindings) throws QueryResolverException, TeiidComponentException {
-
- // parse
- Command command = helpParse(sql);
-
- QueryNode qn = new QueryNode(sql);
- qn.setBindings(bindings);
- // resolve
- QueryResolver.resolveWithBindingMetadata(command, metadata, qn, true);
-
- CheckSymbolsAreResolvedVisitor vis = new CheckSymbolsAreResolvedVisitor();
- DeepPreOrderNavigator.doVisit(command, vis);
-
- Collection unresolvedSymbols = vis.getUnresolvedSymbols();
- assertTrue("Found unresolved symbols: " + unresolvedSymbols, unresolvedSymbols.isEmpty()); //$NON-NLS-1$
- return command;
- }
-
- static void helpResolveException(String sql, QueryMetadataInterface queryMetadata){
- helpResolveException(sql, queryMetadata, null);
- }
-
- static void helpResolveException(String sql, QueryMetadataInterface queryMetadata, String expectedExceptionMessage){
-
- // parse
- Command command = helpParse(sql);
-
- // resolve
- try {
- QueryResolver.resolveCommand(command, queryMetadata);
- fail("Expected exception for resolving " + sql); //$NON-NLS-1$
- } catch(QueryResolverException e) {
- if(expectedExceptionMessage != null){
- assertEquals(expectedExceptionMessage, e.getMessage());
- }
- } catch(TeiidComponentException e) {
- throw new RuntimeException(e);
- }
- }
-
- private void helpResolveException(String sql, String expectedExceptionMessage) {
- TestResolver.helpResolveException(sql, this.metadata, expectedExceptionMessage);
- }
-
- private void helpResolveException(String sql) {
- TestResolver.helpResolveException(sql, this.metadata);
- }
-
- private void helpCheckFrom(Query query, String[] groupIDs) {
- From from = query.getFrom();
- List 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$
- }
- }
-
- private void helpCheckSelect(Query query, String[] elementNames) {
- Select select = query.getSelect();
- List elements = select.getSymbols();
- 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);
- 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();
- 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);
- 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$
- }
- }
-
- private void helpTestIsXMLQuery(String sql, boolean isXML) throws QueryResolverException, QueryMetadataException, TeiidComponentException {
- // parse
- Query query = (Query) helpParse(sql);
-
- // check whether it's xml
- boolean actual = QueryResolver.isXMLQuery(query, metadata);
- assertEquals("Wrong answer for isXMLQuery", isXML, actual); //$NON-NLS-1$
- }
-
- /**
- * Helper method to resolve an exec aka stored procedure, then check that the
- * expected parameter expressions are the same as actual parameter expressions.
- * @param sql
- * @param expectedParameterExpressions
- * @since 4.3
- */
- private StoredProcedure helpResolveExec(String sql, Object[] expectedParameterExpressions) {
-
- StoredProcedure proc = (StoredProcedure)helpResolve(sql);
-
- List params = proc.getParameters();
-
- // Remove all but IN and IN/OUT params
- Iterator paramIter = params.iterator();
- while (paramIter.hasNext()) {
- final SPParameter param = (SPParameter)paramIter.next();
- if (param.getParameterType() != ParameterInfo.IN && param.getParameterType() != ParameterInfo.INOUT) {
- paramIter.remove();
- }
- }
-
- // Check remaining params against expected expressions
- assertEquals(expectedParameterExpressions.length, params.size());
- for (int i=0; i<expectedParameterExpressions.length; i++) {
- SPParameter param = (SPParameter)params.get(i);
- if (expectedParameterExpressions[i] == null) {
- assertNull(param.getExpression());
- } else {
- assertEquals(expectedParameterExpressions[i], param.getExpression());
- }
- }
-
- return proc;
- }
-
-
- // ################################## ACTUAL TESTS ################################
-
-
- @Test public void testElementSymbolForms() {
- String sql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 AS a, e4 AS b FROM pm1.g1"; //$NON-NLS-1$
- Query resolvedQuery = (Query) helpResolve(sql);
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "pm1.g1.e2", "a", "b" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- 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$
- assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
- }
-
- @Test public void testElementSymbolFormsWithAliasedGroup() {
- String sql = "SELECT x.e1, e2, x.e3 AS a, e4 AS b FROM pm1.g1 AS x"; //$NON-NLS-1$
- Query resolvedQuery = (Query) helpResolve(sql);
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "x.e1", "x.e2", "a", "b" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- 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$
- assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
- }
-
- @Test public void testGroupWithVDB() {
- String sql = "SELECT e1 FROM myvdb.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$
- 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();
- 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();
- 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();
- 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();
- 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();
- 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();
- 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();
- String sql = "SELECT e1 FROM g4"; //$NON-NLS-1$
- Query resolvedQuery = (Query) helpResolve(sql);
- helpCheckFrom(resolvedQuery, new String[] { "pm2.g4" }); //$NON-NLS-1$
- }
-
- @Test public void testPartiallyQualifiedGroup8() {
- metadata = FakeMetadataFactory.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();
- 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();
- 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$
- }
-
- /** defect 12536 */
- @Test public void testPartiallyQualifiedElement2() {
- metadata = FakeMetadataFactory.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$
- }
-
- /** defect 12536 */
- @Test public void testPartiallyQualifiedElement3() {
- metadata = FakeMetadataFactory.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$
- }
-
- /** defect 12536 */
- @Test public void testPartiallyQualifiedElement4() {
- metadata = FakeMetadataFactory.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$
- 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();
- 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();
- 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();
- helpResolveException("SELECT e1 FROM cat3.g1"); //$NON-NLS-1$
- }
-
- @Test public void testFailPartiallyQualifiedGroup2() {
- metadata = FakeMetadataFactory.example3();
- helpResolveException("SELECT e1 FROM g1"); //$NON-NLS-1$
- }
-
- @Test public void testFailPartiallyQualifiedGroup3() {
- metadata = FakeMetadataFactory.example3();
- helpResolveException("SELECT e1 FROM g2"); //$NON-NLS-1$
- }
-
- @Test public void testFailPartiallyQualifiedGroup4() {
- metadata = FakeMetadataFactory.example3();
- helpResolveException("SELECT e1 FROM g3"); //$NON-NLS-1$
- }
-
- @Test public void testFailPartiallyQualifiedGroup5() {
- metadata = FakeMetadataFactory.example3();
- helpResolveException("SELECT e1 FROM g5"); //$NON-NLS-1$
- }
-
- @Test public void testFailPartiallyQualifiedElement1() {
- metadata = FakeMetadataFactory.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();
- helpResolveException("SELECT g1.e1 FROM pm1.cat1.cat2.cat3.g1, pm2.cat3.g1"); //$NON-NLS-1$
- }
-
- @Test public void testFailPartiallyQualifiedElement3() {
- metadata = FakeMetadataFactory.example3();
- helpResolveException("SELECT cat3.g1.e1 FROM pm2.cat2.g2, pm1.cat2.g3"); //$NON-NLS-1$
- }
-
- @Test public void testFailPartiallyQualifiedElement4() {
- metadata = FakeMetadataFactory.example3();
- helpResolveException("SELECT cat3.g1.e1 FROM pm2.cat2.g2"); //$NON-NLS-1$
- }
-
- @Test public void testFailPartiallyQualifiedElement5() {
- metadata = FakeMetadataFactory.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$
- Query resolvedQuery = (Query) helpResolve(sql);
- helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getSelect(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
- assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
- }
-
- @Test public void testAliasedElementWithVDB() {
- Query resolvedQuery = (Query) helpResolve("SELECT myvdb.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$
- new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @Test public void testSelectExpressions() {
- Query resolvedQuery = (Query) helpResolve("SELECT e1, concat(e1, 's'), concat(e1, 's') as c FROM pm1.g1"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "expr", "c" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- helpCheckElements(resolvedQuery.getSelect(),
- new String[] { "pm1.g1.e1", "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- new String[] { "pm1.g1.e1", "pm1.g1.e1", "pm1.g1.e1" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testSelectCountStar() {
- Query resolvedQuery = (Query) helpResolve("SELECT count(*) FROM pm1.g1"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "count" }); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getSelect(), new String[] { }, new String[] { } );
- }
-
- @Test public void testMultipleIdenticalElements() {
- Query resolvedQuery = (Query) helpResolve("SELECT e1, e1 FROM pm1.g1"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
- helpCheckElements(resolvedQuery.getSelect(),
- new String[] { "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testMultipleIdenticalElements2() {
- Query resolvedQuery = (Query) helpResolve("SELECT e1, pm1.g1.e1 FROM pm1.g1"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
- helpCheckElements(resolvedQuery.getSelect(),
- new String[] { "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testMultipleIdenticalElements3() {
- Query resolvedQuery = (Query) helpResolve("SELECT e1, e1 as x FROM pm1.g1"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "x" }); //$NON-NLS-1$ //$NON-NLS-2$
- helpCheckElements(resolvedQuery.getSelect(),
- new String[] { "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testDifferentElementsSameName() {
- Query resolvedQuery = (Query) helpResolve("SELECT e1 as x, e2 as x FROM pm1.g2"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g2" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "x", "x" }); //$NON-NLS-1$ //$NON-NLS-2$
- helpCheckElements(resolvedQuery.getSelect(),
- new String[] { "pm1.g2.e1", "pm1.g2.e2" }, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { "pm1.g2.e1", "pm1.g2.e2" }); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testDifferentConstantsSameName() {
- Query resolvedQuery = (Query) helpResolve("SELECT 1 as x, 2 as x FROM pm1.g2"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g2" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "x", "x" }); //$NON-NLS-1$ //$NON-NLS-2$
- helpCheckElements(resolvedQuery.getSelect(),
- new String[] { },
- new String[] { });
- }
-
- @Test public void testFailSameGroupsWithSameNames() {
- helpResolveException("SELECT * FROM pm1.g1 as x, pm1.g1 as x"); //$NON-NLS-1$
- }
-
- @Test public void testFailDifferentGroupsWithSameNames() {
- helpResolveException("SELECT * FROM pm1.g1 as x, pm1.g2 as x"); //$NON-NLS-1$
- }
-
- @Test public void testFailAmbiguousElement() {
- helpResolveException("SELECT e1 FROM pm1.g1, pm1.g2"); //$NON-NLS-1$
- }
-
- @Test public void testFailAmbiguousElementAliasedGroup() {
- helpResolveException("SELECT e1 FROM pm1.g1 as x, pm1.g1"); //$NON-NLS-1$
- }
-
- @Test public void testFailFullyQualifiedElementUnknownGroup() {
- helpResolveException("SELECT pm1.g1.e1 FROM pm1.g2"); //$NON-NLS-1$
- }
-
- @Test public void testFailUnknownGroup() {
- helpResolveException("SELECT x.e1 FROM x"); //$NON-NLS-1$
- }
-
- @Test public void testFailUnknownElement() {
- helpResolveException("SELECT x FROM pm1.g1"); //$NON-NLS-1$
- }
-
- @Test public void testFailFunctionOfAggregatesInSelect() {
- helpResolveException("SELECT (SUM(e0) * COUNT(e0)) FROM test.group GROUP BY e0"); //$NON-NLS-1$
- }
-
- /*
- * per defect 4404
- */
- @Test public void testFailGroupNotReferencedByAlias() {
- helpResolveException("SELECT pm1.g1.x FROM pm1.g1 as H"); //$NON-NLS-1$
- }
-
- /*
- * per defect 4404 - this one reproduced the defect,
- * then succeeded after the fix
- */
- @Test public void testFailGroupNotReferencedByAliasSelectAll() {
- helpResolveException("SELECT pm1.g1.* FROM pm1.g1 as H"); //$NON-NLS-1$
- }
-
- @Test public void testComplicatedQuery() {
- Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e2 as y, pm1.g1.E3 as z, CONVERT(pm1.g1.e1, integer) * 1000 as w FROM pm1.g1 WHERE e1 <> 'x'"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "y", "z", "w" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- helpCheckElements(resolvedQuery,
- new String[] { "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- new String[] { "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e1" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testJoinQuery() {
- Query resolvedQuery = (Query) helpResolve("SELECT pm3.g1.e2, pm3.g2.e2 FROM pm3.g1, pm3.g2 WHERE pm3.g1.e2=pm3.g2.e2"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "pm3.g1", "pm3.g2" }); //$NON-NLS-1$ //$NON-NLS-2$
- helpCheckSelect(resolvedQuery, new String[] { "pm3.g1.e2", "pm3.g2.e2" }); //$NON-NLS-1$ //$NON-NLS-2$
- helpCheckElements(resolvedQuery,
- new String[] { "pm3.g1.e2", "pm3.g2.e2", "pm3.g1.e2", "pm3.g2.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- new String[] { "pm3.g1.e2", "pm3.g2.e2", "pm3.g1.e2", "pm3.g2.e2" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- @Test public void testHavingRequiringConvertOnAggregate1() {
- helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING MAX(e2) > 1.2"); //$NON-NLS-1$
- }
-
- @Test public void testHavingRequiringConvertOnAggregate2() {
- helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING MIN(e2) > 1.2"); //$NON-NLS-1$
- }
-
- @Test public void testHavingRequiringConvertOnAggregate3() {
- helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING 1.2 > MAX(e2)"); //$NON-NLS-1$
- }
-
- @Test public void testHavingRequiringConvertOnAggregate4() {
- helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING 1.2 > MIN(e2)"); //$NON-NLS-1$
- }
-
- @Test public void testHavingWithAggsOfDifferentTypes() {
- helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING MIN(e1) = MIN(e2)"); //$NON-NLS-1$
- }
-
- @Test public void testCaseInGroupBy() {
- String sql = "SELECT SUM(e2) FROM pm1.g1 GROUP BY CASE WHEN e2 = 0 THEN 1 ELSE 2 END"; //$NON-NLS-1$
- Command command = helpResolve(sql);
- assertEquals(sql, command.toString());
-
- helpCheckElements(command, new String[] {"pm1.g1.e2", "pm1.g1.e2"}, new String[] {"pm1.g1.e2", "pm1.g1.e2"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$
- }
-
- @Test public void testFunctionInGroupBy() {
- String sql = "SELECT SUM(e2) FROM pm1.g1 GROUP BY (e2 + 1)"; //$NON-NLS-1$
- Command command = helpResolve(sql);
- assertEquals(sql, command.toString());
-
- helpCheckElements(command, new String[] {"pm1.g1.e2", "pm1.g1.e2"}, new String[] {"pm1.g1.e2", "pm1.g1.e2"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$
- }
-
- @Test public void testUnknownFunction() {
- helpResolveException("SELECT abc(e1) FROM pm1.g1", "Error Code:ERR.015.008.0039 Message:The function 'abc(e1)' is an unknown form. Check that the function name and number of arguments is correct."); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testConversionNotPossible() {
- helpResolveException("SELECT dayofmonth('2002-01-01') FROM pm1.g1", "Error Code:ERR.015.008.0040 Message:The function 'dayofmonth('2002-01-01')' is a valid function form, but the arguments do not match a known type signature and cannot be converted using implicit type conversions."); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testResolveParameters() throws Exception {
- List bindings = new ArrayList();
- bindings.add("pm1.g2.e1"); //$NON-NLS-1$
- bindings.add("pm1.g2.e2"); //$NON-NLS-1$
-
- Query resolvedQuery = (Query) helpResolveWithBindings("SELECT pm1.g1.e1, ? FROM pm1.g1 WHERE pm1.g1.e1 = ?", metadata, bindings); //$NON-NLS-1$
-
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "expr" }); //$NON-NLS-1$ //$NON-NLS-2$
- helpCheckElements(resolvedQuery.getCriteria(),
- new String[] { "pm1.g1.e1", "pm1.g2.e2" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1", "pm1.g2.e2" } ); //$NON-NLS-1$
-
- }
-
- @Test public void testResolveParametersInsert() throws Exception {
- List<String> bindings = Arrays.asList("pm1.g2.e1"); //$NON-NLS-1$
-
- helpResolveWithBindings("INSERT INTO pm1.g1 (e1) VALUES (?)", metadata, bindings); //$NON-NLS-1$
- }
-
- @Test public void testResolveParametersExec() throws Exception {
- List<String> bindings = Arrays.asList("pm1.g2.e1"); //$NON-NLS-1$
-
- Query resolvedQuery = (Query)helpResolveWithBindings("SELECT * FROM (exec pm1.sq2(?)) as a", metadata, bindings); //$NON-NLS-1$
- StoredProcedure sp = (StoredProcedure)((SubqueryFromClause)resolvedQuery.getFrom().getClauses().get(0)).getCommand();
- assertEquals(String.class, sp.getInputParameters().get(0).getExpression().getType());
- }
-
- @Test public void testResolveParametersExecNamed() throws Exception {
- List<String> bindings = Arrays.asList("pm1.g2.e1 as x"); //$NON-NLS-1$
-
- helpResolveWithBindings("SELECT * FROM (exec pm1.sq2(input.x)) as a", metadata, bindings); //$NON-NLS-1$
- }
-
- @Test public void testUseNonExistentAlias() {
- helpResolveException("SELECT portfoliob.e1 FROM ((pm1.g1 AS portfoliob JOIN pm1.g2 AS portidentb ON portfoliob.e1 = portidentb.e1) RIGHT OUTER JOIN pm1.g3 AS identifiersb ON portidentb.e1 = 'ISIN' and portidentb.e2 = identifiersb.e2) RIGHT OUTER JOIN pm1.g1 AS issuesb ON a.identifiersb.e1 = issuesb.e1"); //$NON-NLS-1$
- }
-
- @Test public void testCriteria1() {
- CompareCriteria expected = new CompareCriteria();
- ElementSymbol es = new ElementSymbol("pm1.g1.e1"); //$NON-NLS-1$
- GroupSymbol gs = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
- es.setGroupSymbol(gs);
- expected.setLeftExpression(es);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(new Constant("abc")); //$NON-NLS-1$
-
- Criteria actual = helpResolveCriteria("pm1.g1.e1 = 'abc'"); //$NON-NLS-1$
-
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- @Test public void testSubquery1() {
- Query resolvedQuery = (Query) helpResolve("SELECT e1 FROM pm1.g1, (SELECT pm1.g2.e1 AS x FROM pm1.g2) AS y WHERE e1 = x"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g1", "y" }); //$NON-NLS-1$ //$NON-NLS-2$
- helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getSelect(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
-
- }
-
- @Test public void testStoredQuery1() {
- StoredProcedure proc = (StoredProcedure) helpResolve("EXEC pm1.sq2('abc')"); //$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$
-
- // 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 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$
- }
-
- /**
- * per defect 8211 - Input params do not have to be numbered sequentially in metadata. For example,
- * the first input param can be #1 and the second input param can be #3. (This occurs in
- * QueryBuilder's metadata where the return param happens to be created in between the two
- * input params and is numbered #2, but is not loaded into QueryBuilder's runtime env).
- * When the user's query is parsed and resolved, the placeholder
- * input params are numbered #1 and #2. This test tests that this disparity in ordering should not
- * be a problem as long as RELATIVE ordering is in synch.
- */
- @Test public void testStoredQueryParamOrdering_8211() {
- 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$
-
- // Check resolved parameters
- SPParameter param1 = (SPParameter) 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$
- }
-
- 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$
- assertEquals("Did not get expected type for param", type, param.getClassType()); //$NON-NLS-1$
- assertEquals("Did not get expected type for param", expr, param.getExpression()); //$NON-NLS-1$
- }
-
- @Test public void testStoredSubQuery1() {
- Query resolvedQuery = (Query) helpResolve("select x.e1 from (EXEC pm1.sq1()) as x"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "x.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testStoredSubQuery2() {
- Query resolvedQuery = (Query) helpResolve("select x.e1 from (EXEC pm1.sq3('abc', 5)) as x"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "x.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testStoredSubQuery3() {
- Query resolvedQuery = (Query) helpResolve("select * from (EXEC pm1.sq2('abc')) as x"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
-
- List elements = (List) ElementCollectorVisitor.getElements(resolvedQuery.getSelect(), false);
-
- ElementSymbol elem1 = (ElementSymbol)elements.get(0);
- assertEquals("Did not get expected element", "x.e1", elem1.getName() ); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("Did not get expected type", DataTypeManager.DefaultDataClasses.STRING, elem1.getType()); //$NON-NLS-1$
-
- ElementSymbol elem2 = (ElementSymbol)elements.get(1);
- assertEquals("Did not get expected element", "x.e2", elem2.getName() ); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("Did not get expected type", DataTypeManager.DefaultDataClasses.INTEGER, elem2.getType()); //$NON-NLS-1$
- }
-
- @Test public void testStoredQueryTransformationWithVariable4() throws Exception {
- Command command = QueryParser.getQueryParser().parseCommand("EXEC pm1.sq2(pm1.sq2.in)"); //$NON-NLS-1$
-
- // resolve
- try {
- // Construct command metadata
- GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
- ArrayList sqParams = new ArrayList();
- ElementSymbol in = new ElementSymbol("pm1.sq5.in1"); //$NON-NLS-1$
- in.setType(DataTypeManager.DefaultDataClasses.STRING);
- sqParams.add(in);
- Map externalMetadata = new HashMap();
- externalMetadata.put(sqGroup, sqParams);
-
- QueryResolver.resolveCommand(command, metadata);
-
- fail("Expected exception on invalid variable pm1.sq2.in"); //$NON-NLS-1$
- } catch(QueryResolverException e) {
- assertEquals("Symbol pm1.sq2.\"in\" is specified with an unknown group context", e.getMessage()); //$NON-NLS-1$
- }
- }
-
- @Test public void testExec1() {
- helpResolve("EXEC pm1.sq2('xyz')"); //$NON-NLS-1$
- }
-
- @Test public void testExec2() {
- // implicity convert 5 to proper type
- helpResolve("EXEC pm1.sq2(5)"); //$NON-NLS-1$
- }
-
- @Test public void testExecNamedParam() {
- Object[] expectedParameterExpressions = new Object[] {new Constant("xyz")};//$NON-NLS-1$
- helpResolveExec("EXEC pm1.sq2(\"in\" = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
- }
-
- @Test public void testExecNamedParamDup() {
- helpResolveException("EXEC pm1.sq2(\"in\" = 'xyz', \"in\" = 'xyz1')");//$NON-NLS-1$
- }
-
- /** Should get exception because param name is wrong. */
- @Test public void testExecWrongParamName() {
- helpResolveException("EXEC pm1.sq2(in1 = 'xyz')");//$NON-NLS-1$
- }
-
- @Test public void testExecNamedParams() {
- Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(new Integer(5))};//$NON-NLS-1$
- helpResolveExec("EXEC pm1.sq3(\"in\" = 'xyz', in2 = 5)", expectedParameterExpressions);//$NON-NLS-1$
- }
-
- /** try entering params out of order */
- @Test public void testExecNamedParamsReversed() {
- Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(new Integer(5))};//$NON-NLS-1$
- helpResolveExec("EXEC pm1.sq3(in2 = 5, \"in\" = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
- }
-
- /** test omitting an optional parameter */
- @Test public void testExecNamedParamsOptionalParam() {
- Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(null), new Constant("something")};//$NON-NLS-1$ //$NON-NLS-2$
- helpResolveExec("EXEC pm1.sq3b(\"in\" = 'xyz', in3 = 'something')", expectedParameterExpressions);//$NON-NLS-1$
- }
-
- /** test omitting a required parameter that has a default value */
- @Test public void testExecNamedParamsOmitRequiredParamWithDefaultValue() {
- Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(new Integer(666)), new Constant("YYZ")};//$NON-NLS-1$ //$NON-NLS-2$
- StoredProcedure sp = helpResolveExec("EXEC pm1.sq3b(\"in\" = 'xyz', in2 = 666)", expectedParameterExpressions);//$NON-NLS-1$
- assertEquals("EXEC pm1.sq3b(\"in\" => 'xyz', in2 => 666)", sp.toString());
- }
-
- @Test public void testExecNamedParamsOptionalParamWithDefaults() {
- Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
- //override the default value for the first parameter
- expectedParameterExpressions[0] = new Constant("xyz"); //$NON-NLS-1$
- helpResolveExec("EXEC pm1.sqDefaults(inString = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
- }
-
- @Test public void testExecNamedParamsOptionalParamWithDefaultsCaseInsensitive() {
- Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
- //override the default value for the first parameter
- expectedParameterExpressions[0] = new Constant("xyz"); //$NON-NLS-1$
- helpResolveExec("EXEC pm1.sqDefaults(iNsTrInG = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
- }
-
- /** try just a few named parameters, in no particular order */
- @Test public void testExecNamedParamsOptionalParamWithDefaults2() {
- Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
- //override the proper default values in expected results
- expectedParameterExpressions[3] = new Constant(Boolean.FALSE);
- expectedParameterExpressions[9] = new Constant(new Integer(666));
- helpResolveExec("EXEC pm1.sqDefaults(ininteger = 666, inboolean={b'false'})", expectedParameterExpressions);//$NON-NLS-1$
- }
-
- /**
- * Try entering in no actual parameters, rely entirely on defaults.
- * This also tests the default value transformation code in ExecResolver.
- */
- @Test public void testExecNamedParamsOptionalParamWithAllDefaults() {
- Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
- helpResolveExec("EXEC pm1.sqDefaults()", expectedParameterExpressions);//$NON-NLS-1$
- }
-
- /**
- * Retrieve the Object array of expected default values for the stored procedure
- * "pm1.sqDefaults" in FakeMetadataFactory.example1().
- * @return
- * @since 4.3
- */
- private Object[] helpGetStoredProcDefaultValues() {
-
- // This needs to match what's in FakeMetadataFactory.example1 for this stored proc
- return new Object[] {
- new Constant("x"), //$NON-NLS-1$
- new Constant(new BigDecimal("13.0")),//$NON-NLS-1$
- new Constant(new BigInteger("13")),//$NON-NLS-1$
- new Constant(Boolean.TRUE),
- new Constant(new Byte("1")),//$NON-NLS-1$
- new Constant(new Character('q')),
- new Constant(Date.valueOf("2003-03-20")),//$NON-NLS-1$
- new Constant(new Double(13.0)),
- new Constant(new Float(13.0)),
- new Constant(new Integer(13)),
- new Constant(new Long(13)),
- new Constant(new Short((short)13)),
- new Constant(Timestamp.valueOf("2003-03-20 21:26:00.000000")),//$NON-NLS-1$
- new Constant(Time.valueOf("21:26:00")),//$NON-NLS-1$
- };
- }
-
- /** Should get exception because there are two required params */
- @Test public void testExceptionNotSupplyingRequiredParam() {
- helpResolveException("EXEC pm1.sq3(in2 = 5)");//$NON-NLS-1$
- }
-
- /** Should get exception because the default value in metadata is bad for input param */
- @Test public void testExceptionBadDefaultValue() {
- helpResolveException("EXEC pm1.sqBadDefault()");//$NON-NLS-1$
- }
-
- @Test public void testExecWithForcedConvertOfStringToCorrectType() {
- // force conversion of '5' to proper type (integer)
- helpResolve("EXEC pm1.sq3('x', '5')"); //$NON-NLS-1$
- }
-
- /**
- * True/false are consistently representable by integers
- */
- @Test public void testExecBadType() {
- helpResolve("EXEC pm1.sq3('xyz', {b'true'})"); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryInUnion() {
- String sql = "SELECT IntKey, FloatNum FROM BQT1.MediumA WHERE (IntKey >= 0) AND (IntKey < 15) " + //$NON-NLS-1$
- "UNION ALL " + //$NON-NLS-1$
- "SELECT BQT2.SmallB.IntKey, y.FloatNum " + //$NON-NLS-1$
- "FROM BQT2.SmallB INNER JOIN " + //$NON-NLS-1$
- "(SELECT IntKey, FloatNum FROM BQT1.MediumA ) AS y ON BQT2.SmallB.IntKey = y.IntKey " + //$NON-NLS-1$
- "WHERE (y.IntKey >= 10) AND (y.IntKey < 30) " + //$NON-NLS-1$
- "ORDER BY IntKey, FloatNum"; //$NON-NLS-1$
-
- helpResolve(sql, FakeMetadataFactory.exampleBQTCached());
- }
-
- @Test public void testSubQueryINClause1(){
- //select e1 from pm1.g1 where e2 in (select e2 from pm4.g1)
-
- //sub command
- Select innerSelect = new Select();
- ElementSymbol e2inner = new ElementSymbol("e2"); //$NON-NLS-1$
- innerSelect.addSymbol(e2inner);
- From innerFrom = new From();
- GroupSymbol pm4g1 = new GroupSymbol("pm4.g1"); //$NON-NLS-1$
- innerFrom.addGroup(pm4g1);
- Query innerQuery = new Query();
- innerQuery.setSelect(innerSelect);
- innerQuery.setFrom(innerFrom);
-
- //outer command
- Select outerSelect = new Select();
- ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
- outerSelect.addSymbol(e1);
- From outerFrom = new From();
- GroupSymbol pm1g1 = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
- outerFrom.addGroup(pm1g1);
- ElementSymbol e2outer = new ElementSymbol("e2"); //$NON-NLS-1$
- SubquerySetCriteria crit = new SubquerySetCriteria(e2outer, innerQuery);
- Query outerQuery = new Query();
- outerQuery.setSelect(outerSelect);
- outerQuery.setFrom(outerFrom);
- outerQuery.setCriteria(crit);
-
- //test
- helpResolve(outerQuery);
-
- helpCheckFrom(outerQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckFrom(innerQuery, new String[] { "pm4.g1" }); //$NON-NLS-1$
- helpCheckSelect(outerQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- helpCheckSelect(innerQuery, new String[] { "pm4.g1.e2" }); //$NON-NLS-1$
- helpCheckElements(outerQuery.getSelect(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
- helpCheckElements(innerQuery.getSelect(),
- new String[] { "pm4.g1.e2" }, //$NON-NLS-1$
- new String[] { "pm4.g1.e2" } ); //$NON-NLS-1$
-
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm4.g1)"; //$NON-NLS-1$
- assertEquals("Resolved string form was incorrect ", sql, outerQuery.toString()); //$NON-NLS-1$
- }
-
- /**
- * An implicit type conversion needs to be inserted because the
- * project symbol of the subquery is not the same type as the expression in
- * the SubquerySetCriteria object
- */
- @Test public void testSubQueryINClauseImplicitConversion(){
- //select e1 from pm1.g1 where e2 in (select e1 from pm4.g1)
-
- //sub command
- Select innerSelect = new Select();
- ElementSymbol e1inner = new ElementSymbol("e1"); //$NON-NLS-1$
- innerSelect.addSymbol(e1inner);
- From innerFrom = new From();
- GroupSymbol pm4g1 = new GroupSymbol("pm4.g1"); //$NON-NLS-1$
- innerFrom.addGroup(pm4g1);
- Query innerQuery = new Query();
- innerQuery.setSelect(innerSelect);
- innerQuery.setFrom(innerFrom);
-
- //outer command
- Select outerSelect = new Select();
- ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
- outerSelect.addSymbol(e1);
- From outerFrom = new From();
- GroupSymbol pm1g1 = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
- outerFrom.addGroup(pm1g1);
- ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
- SubquerySetCriteria crit = new SubquerySetCriteria(e2, innerQuery);
- Query outerQuery = new Query();
- outerQuery.setSelect(outerSelect);
- outerQuery.setFrom(outerFrom);
- outerQuery.setCriteria(crit);
-
- //test
- helpResolve(outerQuery);
-
- helpCheckFrom(outerQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckFrom(innerQuery, new String[] { "pm4.g1" }); //$NON-NLS-1$
- helpCheckSelect(outerQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- helpCheckSelect(innerQuery, new String[] { "pm4.g1.e1" }); //$NON-NLS-1$
- helpCheckElements(outerQuery.getSelect(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
- helpCheckElements(innerQuery.getSelect(),
- new String[] { "pm4.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm4.g1.e1" } ); //$NON-NLS-1$
-
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e1 FROM pm4.g1)"; //$NON-NLS-1$
- assertEquals("Resolved string form was incorrect ", sql, outerQuery.toString()); //$NON-NLS-1$
-
- //make sure there is a convert function wrapping the criteria left expression
- Collection functions = FunctionCollectorVisitor.getFunctions(outerQuery, true);
- assertTrue(functions.size() == 1);
- Function function = (Function)functions.iterator().next();
- assertTrue(function.getName().equals(FunctionLibrary.CONVERT));
- Expression[] args = function.getArgs();
- assertSame(e2, args[0]);
- assertTrue(args[1] instanceof Constant);
- }
-
- /**
- * Tests that resolving fails if there is no implicit conversion between the
- * type of the expression of the SubquerySetCriteria and the type of the
- * projected symbol of the subquery.
- */
- @Test public void testSubQueryINClauseNoConversionFails(){
- //select e1 from pm1.g1 where e1 in (select e2 from pm4.g1)
-
- //sub command
- Select innerSelect = new Select();
- ElementSymbol e2inner = new ElementSymbol("e2"); //$NON-NLS-1$
- innerSelect.addSymbol(e2inner);
- From innerFrom = new From();
- GroupSymbol pm4g1 = new GroupSymbol("pm4.g1"); //$NON-NLS-1$
- innerFrom.addGroup(pm4g1);
- Query innerQuery = new Query();
- innerQuery.setSelect(innerSelect);
- innerQuery.setFrom(innerFrom);
-
- //outer command
- Select outerSelect = new Select();
- ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
- outerSelect.addSymbol(e1);
- From outerFrom = new From();
- GroupSymbol pm1g1 = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
- outerFrom.addGroup(pm1g1);
- SubquerySetCriteria crit = new SubquerySetCriteria(e1, innerQuery);
- Query outerQuery = new Query();
- outerQuery.setSelect(outerSelect);
- outerQuery.setFrom(outerFrom);
- outerQuery.setCriteria(crit);
-
- //test
- this.helpResolveFails(outerQuery);
- }
-
- @Test public void testSubQueryINClauseTooManyColumns(){
- String sql = "select e1 from pm1.g1 where e1 in (select e1, e2 from pm4.g1)"; //$NON-NLS-1$
-
- //test
- this.helpResolveException(sql);
- }
-
- @Test public void testStoredQueryInFROMSubquery() {
- String sql = "select X.e1 from (EXEC pm1.sq3('abc', 123)) as X"; //$NON-NLS-1$
-
- helpResolve(sql);
- }
-
- @Test public void testStoredQueryInINSubquery() throws Exception {
- String sql = "select * from pm1.g1 where e1 in (EXEC pm1.sqsp1())"; //$NON-NLS-1$
-
- helpResolve(sql);
- }
-
- @Test public void testIsXMLQuery1() throws Exception {
- helpTestIsXMLQuery("SELECT * FROM pm1.g1", false); //$NON-NLS-1$
- }
-
- @Test public void testIsXMLQuery2() throws Exception {
- helpTestIsXMLQuery("SELECT * FROM xmltest.doc1", true); //$NON-NLS-1$
- }
-
- /**
- * Must be able to resolve XML query if short doc name
- * is used (assuming short doc name isn't ambiguous in a
- * VDB). Defect 11479.
- */
- @Test public void testIsXMLQuery3() throws Exception {
- helpTestIsXMLQuery("SELECT * FROM doc1", true); //$NON-NLS-1$
- }
-
- @Test public void testIsXMLQueryFail1() throws Exception {
- helpTestIsXMLQuery("SELECT * FROM xmltest.doc1, xmltest.doc2", false); //$NON-NLS-1$
- }
-
- @Test public void testIsXMLQueryFail2() throws Exception {
- helpTestIsXMLQuery("SELECT * FROM xmltest.doc1, pm1.g1", false); //$NON-NLS-1$
- }
-
- @Test public void testIsXMLQueryFail3() throws Exception {
- helpTestIsXMLQuery("SELECT * FROM pm1.g1, xmltest.doc1", false); //$NON-NLS-1$
- }
-
- /**
- * "docA" is ambiguous as there exist two documents called
- * xmlTest2.docA and xmlTest3.docA. Defect 11479.
- */
- @Test public void testIsXMLQueryFail4() throws Exception {
- Query query = (Query) helpParse("SELECT * FROM docA"); //$NON-NLS-1$
-
- try {
- QueryResolver.isXMLQuery(query, metadata);
- fail("expected exception"); //$NON-NLS-1$
- } catch (QueryResolverException e) {
- assertEquals("Group specified is ambiguous, resubmit the query by fully qualifying the group name: docA", e.getMessage()); //$NON-NLS-1$
- }
- }
-
- @Test public void testStringConversion1() {
- // Expected left expression
- ElementSymbol e1 = new ElementSymbol("pm3.g1.e2"); //$NON-NLS-1$
- e1.setType(DataTypeManager.DefaultDataClasses.DATE);
-
- // Expected right expression
- Class srcType = DataTypeManager.DefaultDataClasses.STRING;
- String tgtTypeName = DataTypeManager.DefaultDataTypes.DATE;
- Expression expression = new Constant("2003-02-27"); //$NON-NLS-1$
-
- FunctionLibrary library = FakeMetadataFactory.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) });
- conversion.setType(DataTypeManager.getDataTypeClass(tgtTypeName));
- conversion.setFunctionDescriptor(fd);
- conversion.makeImplicit();
-
- // Expected criteria
- CompareCriteria expected = new CompareCriteria();
- expected.setLeftExpression(e1);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(conversion);
-
- // Resolve the query and check against expected objects
- CompareCriteria actual = (CompareCriteria) helpResolveCriteria("pm3.g1.e2='2003-02-27'"); //$NON-NLS-1$
-
- //if (! actual.getLeftExpression().equals(expected.getLeftExpression())) {
- // fail("left exprs not equal");
- //} else if (!actual.getRightExpression().equals(expected.getRightExpression())) {
- // fail("right not equal");
- //}
-
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- @Test public void testStringConversion2() {
- // Expected left expression
- ElementSymbol e1 = new ElementSymbol("pm3.g1.e2"); //$NON-NLS-1$
- e1.setType(DataTypeManager.DefaultDataClasses.DATE);
-
- // Expected right expression
- Class srcType = DataTypeManager.DefaultDataClasses.STRING;
- String tgtTypeName = DataTypeManager.DefaultDataTypes.DATE;
- Expression expression = new Constant("2003-02-27"); //$NON-NLS-1$
-
- FunctionLibrary library = FakeMetadataFactory.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) });
- conversion.setType(DataTypeManager.getDataTypeClass(tgtTypeName));
- conversion.setFunctionDescriptor(fd);
- conversion.makeImplicit();
-
- // Expected criteria
- CompareCriteria expected = new CompareCriteria();
- expected.setLeftExpression(conversion);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(e1);
-
- // Resolve the query and check against expected objects
- CompareCriteria actual = (CompareCriteria) helpResolveCriteria("'2003-02-27'=pm3.g1.e2"); //$NON-NLS-1$
-
- //if (! actual.getLeftExpression().equals(expected.getLeftExpression())) {
- // fail("Left expressions not equal");
- //} else if (!actual.getRightExpression().equals(expected.getRightExpression())) {
- // fail("Right expressions not equal");
- //}
-
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- // special test for both sides are String
- @Test public void testStringConversion3() {
- // Expected left expression
- ElementSymbol e1 = new ElementSymbol("pm3.g1.e1"); //$NON-NLS-1$
- e1.setType(DataTypeManager.DefaultDataClasses.STRING);
-
- // Expected right expression
- Constant e2 = new Constant("2003-02-27"); //$NON-NLS-1$
-
- // Expected criteria
- CompareCriteria expected = new CompareCriteria();
- expected.setLeftExpression(e1);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(e2);
-
- // Resolve the query and check against expected objects
- CompareCriteria actual = (CompareCriteria) helpResolveCriteria("pm3.g1.e1='2003-02-27'"); //$NON-NLS-1$
-
- //if (! actual.getLeftExpression().equals(expected.getLeftExpression())) {
- // System.out.println("left exprs not equal");
- //} else if (!actual.getRightExpression().equals(expected.getRightExpression())) {
- // System.out.println("right exprs not equal");
- //}
-
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- @Test public void testDateToTimestampConversion_defect9747() {
- // Expected left expression
- ElementSymbol e1 = new ElementSymbol("pm3.g1.e4"); //$NON-NLS-1$
- e1.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
-
- // Expected right expression
- Constant e2 = new Constant(TimestampUtil.createDate(96, 0, 31), DataTypeManager.DefaultDataClasses.DATE);
- Function f1 = new Function("convert", new Expression[] { e2, new Constant(DataTypeManager.DefaultDataTypes.TIMESTAMP)}); //$NON-NLS-1$
- f1.makeImplicit();
-
- // Expected criteria
- CompareCriteria expected = new CompareCriteria();
- expected.setLeftExpression(e1);
- expected.setOperator(CompareCriteria.GT);
- expected.setRightExpression(f1);
-
- // Resolve the query and check against expected objects
- CompareCriteria actual = (CompareCriteria) helpResolveCriteria("pm3.g1.e4 > {d '1996-01-31'}"); //$NON-NLS-1$
-
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- @Test public void testFailedConversion_defect9725() throws Exception{
- helpResolveException("select * from pm3.g1 where pm3.g1.e4 > {b 'true'}", "Error Code:ERR.015.008.0027 Message:The expressions in this criteria are being compared but are of differing types (timestamp and boolean) and no implicit conversion is available: pm3.g1.e4 > TRUE"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testLookupFunction() {
- String sql = "SELECT lookup('pm1.g1', 'e1', 'e2', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
- Query resolvedQuery = (Query) helpResolve(sql);
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "x", "y" }); //$NON-NLS-1$ //$NON-NLS-2$
- helpCheckElements(resolvedQuery.getSelect(),
- new String[] { "PM1.G1.E2", "PM1.G1.E3" }, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { "PM1.G1.E2", "PM1.G1.E3" } ); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
-
- List projSymbols = resolvedQuery.getSelect().getProjectedSymbols();
- assertEquals("Wrong number of projected symbols", 2, projSymbols.size()); //$NON-NLS-1$
- assertEquals("Wrong type for first symbol", String.class, ((SingleElementSymbol)projSymbols.get(0)).getType()); //$NON-NLS-1$
- assertEquals("Wrong type for second symbol", Double.class, ((SingleElementSymbol)projSymbols.get(1)).getType()); //$NON-NLS-1$
- }
-
- @Test public void testLookupFunctionFailBadElement() {
- String sql = "SELECT lookup('nosuch', 'elementhere', 'e2', e2) AS x FROM pm1.g1"; //$NON-NLS-1$
- helpResolveException(sql);
- }
-
- @Test public void testLookupFunctionFailNotConstantArg1() {
- String sql = "SELECT lookup(e1, 'e1', 'e2', e2) AS x FROM pm1.g1"; //$NON-NLS-1$
- helpResolveException(sql);
- }
-
- @Test public void testLookupFunctionFailNotConstantArg2() {
- String sql = "SELECT lookup('pm1.g1', e1, 'e2', e2) AS x FROM pm1.g1"; //$NON-NLS-1$
- helpResolveException(sql);
- }
-
- @Test public void testLookupFunctionFailNotConstantArg3() {
- String sql = "SELECT lookup('pm1.g1', 'e1', e1, e2) AS x FROM pm1.g1"; //$NON-NLS-1$
- helpResolveException(sql);
- }
-
- @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());
- }
-
- @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());
- }
-
- @Test public void testLookupFunctionFailBadKeyElement() throws Exception {
- String sql = "SELECT lookup('pm1.g1', 'e1', 'x', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
- Command command = QueryParser.getQueryParser().parseCommand(sql);
- try {
- QueryResolver.resolveCommand(command, metadata);
- fail("exception expected"); //$NON-NLS-1$
- } catch (QueryResolverException e) {
-
- }
- }
-
- @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);
-
- 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
- @Test public void testSetCriteriaCastFromExpression_9657() {
- // parse
- Criteria expected = null;
- Criteria actual = null;
- try {
- actual = QueryParser.getQueryParser().parseCriteria("bqt1.smalla.shortvalue IN (1, 2)"); //$NON-NLS-1$
- expected = QueryParser.getQueryParser().parseCriteria("convert(bqt1.smalla.shortvalue, integer) IN (1, 2)"); //$NON-NLS-1$
-
- } catch(TeiidException e) {
- fail("Exception during parsing (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // resolve
- try {
- QueryResolver.resolveCriteria(expected, FakeMetadataFactory.exampleBQTCached());
- QueryResolver.resolveCriteria(actual, FakeMetadataFactory.exampleBQTCached());
- } catch(TeiidException e) {
- fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // Tweak expected to hide convert function - this is expected
- ((Function) ((SetCriteria)expected).getExpression()).makeImplicit();
-
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- /** select e1 from pm1.g1 where e2 BETWEEN 1000 AND 2000 */
- @Test public void testBetween1(){
- String sql = "select e1 from pm1.g1 where e2 BETWEEN 1000 AND 2000"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- /** select e1 from pm1.g1 where e2 NOT BETWEEN 1000 AND 2000 */
- @Test public void testBetween2(){
- String sql = "select e1 from pm1.g1 where e2 NOT BETWEEN 1000 AND 2000"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- /** select e2 from pm1.g1 where e4 BETWEEN 1000 AND e2 */
- @Test public void testBetween3(){
- String sql = "select e2 from pm1.g1 where e4 BETWEEN 1000 AND e2"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- /** select e2 from pm1.g1 where e2 BETWEEN 1000 AND e4 */
- @Test public void testBetween4(){
- String sql = "select e2 from pm1.g1 where e2 BETWEEN 1000 AND e4"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- /** select e1 from pm1.g1 where 1000 BETWEEN e1 AND e2 */
- @Test public void testBetween5(){
- String sql = "select e1 from pm1.g1 where 1000 BETWEEN e1 AND e2"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- /** select e1 from pm1.g1 where 1000 BETWEEN e2 AND e1 */
- @Test public void testBetween6(){
- String sql = "select e1 from pm1.g1 where 1000 BETWEEN e2 AND e1"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- /** select e1 from pm3.g1 where e2 BETWEEN e3 AND e4 */
- @Test public void testBetween7(){
- String sql = "select e1 from pm3.g1 where e2 BETWEEN e3 AND e4"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- /** select pm3.g1.e1 from pm3.g1, pm3.g2 where pm3.g1.e4 BETWEEN pm3.g1.e2 AND pm3.g2.e2 */
- @Test public void testBetween8(){
- String sql = "select pm3.g1.e1 from pm3.g1, pm3.g2 where pm3.g1.e4 BETWEEN pm3.g1.e2 AND pm3.g2.e2"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- /** select e1 from pm1.g1 where e2 = any (select e2 from pm4.g1) */
- @Test public void testCompareSubQuery1(){
-
- String sql = "select e1 from pm1.g1 where e2 = any (select e2 from pm4.g1)"; //$NON-NLS-1$
- Query outerQuery = (Query) this.helpResolveSubquery(sql, new String[0]);
-
- helpCheckFrom(outerQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckSelect(outerQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- helpCheckElements(outerQuery.getSelect(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
-// helpCheckFrom(innerQuery, new String[] { "pm4.g1" });
-// helpCheckSelect(innerQuery, new String[] { "pm4.g1.e2" });
-// helpCheckElements(innerQuery.getSelect(),
-// new String[] { "pm4.g1.e2" },
-// new String[] { "pm4.g1.e2" } );
-
- String sqlActual = "SELECT e1 FROM pm1.g1 WHERE e2 = ANY (SELECT e2 FROM pm4.g1)"; //$NON-NLS-1$
- assertEquals("Resolved string form was incorrect ", sqlActual, outerQuery.toString()); //$NON-NLS-1$
- }
-
- /** select e1 from pm1.g1 where e2 = all (select e2 from pm4.g1) */
- @Test public void testCompareSubQuery2(){
- String sql = "select e1 from pm1.g1 where e2 = all (select e2 from pm4.g1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- /** select e1 from pm1.g1 where e2 < (select e2 from pm4.g1 where e1 = '3') */
- @Test public void testCompareSubQuery3(){
- String sql = "select e1 from pm1.g1 where e2 < (select e2 from pm4.g1 where e1 = '3')"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- /** select e1 from pm1.g1 where e2 < (select e2 from pm4.g1 where e1 = '3') */
- @Test public void testCompareSubQueryImplicitConversion(){
- String sql = "select e1 from pm1.g1 where e1 < (select e2 from pm4.g1 where e1 = '3')"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- @Test public void testExistsSubQuery(){
- String sql = "select e1 from pm1.g1 where exists (select e2 from pm4.g1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- @Test public void testExistsSubQuery2(){
- String sql = "select e1 from pm1.g1 where exists (select e1, e2 from pm4.g1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- @Test public void testScalarSubQueryInSelect(){
- String sql = "select e1, (select e2 from pm4.g1 where e1 = '3') from pm1.g1"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- @Test public void testScalarSubQueryInSelect2(){
- String sql = "select (select e2 from pm4.g1 where e1 = '3'), e1 from pm1.g1"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- @Test public void testScalarSubQueryInSelectWithAlias(){
- String sql = "select e1, (select e2 from pm4.g1 where e1 = '3') as X from pm1.g1"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- @Test public void testSelectWithNoFrom() {
- String sql = "SELECT 5"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @Test public void testSelectWithNoFrom_Alias() {
- String sql = "SELECT 5 AS INTKEY"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @Test public void testSelectWithNoFrom_Alias_OrderBy() {
- String sql = "SELECT 5 AS INTKEY ORDER BY INTKEY"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @Test public void testSubqueryCorrelatedInCriteria(){
- String sql = "select e2 from pm1.g1 where e2 = all (select e2 from pm4.g1 where pm1.g1.e1 = pm4.g1.e1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"pm1.g1.e1"}); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryCorrelatedInCriteria2(){
- String sql = "select e1 from pm1.g1 where e2 = all (select e2 from pm4.g1 where pm1.g1.e1 = e1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"pm1.g1.e1"}); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryCorrelatedInCriteria3(){
- String sql = "select e1 from pm1.g1 X where e2 = all (select e2 from pm4.g1 where X.e1 = pm4.g1.e1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryCorrelatedInCriteria4(){
- String sql = "select e2 from pm1.g1 X where e2 in (select e2 from pm1.g1 Y where X.e1 = Y.e1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryCorrelatedInCriteria5(){
- String sql = "select e1 from pm1.g1 X where e2 = all (select e2 from pm1.g1 Y where X.e1 = e1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
- }
-
- /* 'e5' is only in pm4.g2 */
- @Test public void testSubqueryCorrelatedInCriteria6(){
- String sql = "select e1 from pm4.g2 where e2 = some (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
- }
-
- /* 'e5' is only in pm4.g2 */
- @Test public void testSubqueryCorrelatedInCriteria7(){
- String sql = "select e1 from pm4.g2 where exists (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryCorrelatedInHaving(){
- String sql = "select e1, e2 from pm4.g2 group by e2 having e2 in (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryCorrelatedInHaving2(){
- String sql = "select e1, e2 from pm4.g2 group by e2 having e2 <= all (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
- }
-
- /* 'e5' is only in pm4.g2 */
- @Test public void testSubqueryCorrelatedInSelect(){
- String sql = "select e1, (select e2 from pm4.g1 where e5 = e1) from pm4.g2"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryCorrelatedInSelect2(){
- String sql = "select e1, (select e2 from pm4.g1 where pm4.g2.e5 = e1) from pm4.g2"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryCorrelatedInSelect3(){
- String sql = "select e1, (select e2 from pm4.g1 Y where X.e5 = Y.e1) from pm4.g2 X"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"X.e5"}); //$NON-NLS-1$
- }
-
- /* 'e5' is only in pm4.g2 */
- @Test public void testNestedCorrelatedSubqueries(){
- String sql = "select e1, (select e2 from pm1.g1 where e2 = all (select e2 from pm4.g1 where e5 = e1)) from pm4.g2"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
- }
-
- /**
- * 'e5' is in pm4.g2, so it will be resolved to the group aliased as 'Y'
- */
- @Test public void testNestedCorrelatedSubqueries2(){
- String sql = "select e1, (select e2 from pm4.g2 Y where e2 = all (select e2 from pm4.g1 where e5 = e1)) from pm4.g2 X"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"Y.e5"}); //$NON-NLS-1$
- }
-
- /**
- * 'e5' is in pm4.g2; it will be resolved to the group aliased as 'X'
- */
- @Test public void testNestedCorrelatedSubqueries3(){
- String sql = "select e1, (select e2 from pm4.g2 Y where e2 = all (select e2 from pm4.g1 where X.e5 = e1)) from pm4.g2 X"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"X.e5"}); //$NON-NLS-1$
- }
-
- /**
- * 'e5' is in X and Y
- */
- @Test public void testNestedCorrelatedSubqueries4(){
- String sql = "select X.e2 from pm4.g2 Y, pm4.g2 X where X.e2 = all (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
- helpResolveException(sql, metadata, "Element \"e5\" is ambiguous, it exists in two or more groups."); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryCorrelatedInCriteriaVirtualLayer(){
- String sql = "select e2 from vm1.g1 where e2 = all (select e2 from vm1.g2 where vm1.g1.e1 = vm1.g2.e1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"vm1.g1.e1"}); //$NON-NLS-1$
- }
-
- @Test public void testSubqueryCorrelatedInCriteriaVirtualLayer2(){
- String sql = "select e2 from vm1.g1 X where e2 = all (select e2 from vm1.g2 where X.e1 = vm1.g2.e1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
- }
-
- /**
- * Although this query makes no sense, the "e1" in the nested criteria is
- * NOT a correlated reference
- */
- @Test public void testSubqueryNonCorrelatedInCriteria(){
- String sql = "select e2 from pm1.g1 where e2 = all (select e2 from pm4.g1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- /**
- * Although this query makes no sense, the "e1" in the nested criteria is
- * NOT a correlated reference
- */
- @Test public void testSubqueryNonCorrelatedInCriteria2(){
- String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1 WHERE e1 IN (SELECT e1 FROM pm1.g1))"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- /**
- * Although this query makes no sense, the "e1" in the nested criteria is
- * NOT a correlated reference
- */
- @Test public void testSubqueryNonCorrelatedInCriteria3(){
- String sql = "SELECT e2 FROM pm2.g1 WHERE e1 IN (SELECT e1 FROM pm1.g1)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- /**
- * The group pm1.g1 in the FROM clause of the subquery should resolve to the
- * group in metadata, not the temporary child metadata group defined by the
- * outer query.
- */
- @Test public void testSubquery_defect10090(){
- String sql = "select pm1.g1.e1 from pm1.g1 where pm1.g1.e2 in (select pm1.g1.e2 from pm1.g1 where pm1.g1.e4 = 2.0)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- /**
- * Workaround is to alias group in FROM of outer query (aliasing subquery group doesn't work)
- */
- @Test public void testSubquery_defect10090Workaround(){
- String sql = "select X.e1 from pm1.g1 X where X.e2 in (select pm1.g1.e2 from pm1.g1 where pm1.g1.e4 = 2.0)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- @Test public void testSubquery2_defect10090(){
- String sql = "select pm1.g1.e1 from pm1.g1 where pm1.g1.e2 in (select X.e2 from pm1.g1 X where X.e4 = 2.0)"; //$NON-NLS-1$
- this.helpResolveSubquery(sql, new String[0]);
- }
-
- /** test jdbc USER method */
- @Test public void testUser() {
- //String sql = "select intkey from SmallA where user() = 'bqt2'";
-
- // Expected left expression
- FunctionLibrary library = FakeMetadataFactory.SFM.getSystemFunctionLibrary();
- FunctionDescriptor fd = library.findFunction(FunctionLibrary.USER, new Class[] { });
- Function user = new Function(fd.getName(), new Expression[] {});
- user.setFunctionDescriptor(fd);
-
- // Expected criteria
- CompareCriteria expected = new CompareCriteria();
- // Expected right expression
- Expression e1 = new Constant("bqt2", String.class); //$NON-NLS-1$
- // Expected left expression
- expected.setLeftExpression(user);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(e1);
-
- // Resolve the query and check against expected objects
- CompareCriteria actual = (CompareCriteria) helpResolveCriteria("user()='bqt2'"); //$NON-NLS-1$
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- @Test public void testCaseExpression1() {
- String sql = "SELECT e1, CASE e2 WHEN 0 THEN 20 WHEN 1 THEN 21 WHEN 2 THEN 500 END AS testElement FROM pm1.g1" //$NON-NLS-1$
- +" WHERE e1 = CASE WHEN e2 = 0 THEN 'a' WHEN e2 = 1 THEN 'b' ELSE 'c' END"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
-
- @Test public void testCaseExpression2() {
- // nested case expressions
- String sql = "SELECT CASE e2" + //$NON-NLS-1$
- " WHEN 0 THEN CASE e1 " + //$NON-NLS-1$
- " WHEN 'a' THEN 100" + //$NON-NLS-1$
- " WHEN 'b' THEN 200 " + //$NON-NLS-1$
- " ELSE 1000 " + //$NON-NLS-1$
- " END" + //$NON-NLS-1$
- " WHEN 1 THEN 21" + //$NON-NLS-1$
- " WHEN (CASE WHEN e1 = 'z' THEN 2 WHEN e1 = 'y' THEN 100 ELSE 3 END) THEN 500" + //$NON-NLS-1$
- " END AS testElement FROM pm1.g1"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @Test public void testCaseExpressionWithNestedFunction() {
- String sql = "SELECT CASE WHEN e2 < 0 THEN abs(CASE WHEN e2 < 0 THEN -1 ELSE e2 END)" + //$NON-NLS-1$
- " ELSE e2 END FROM pm1.g1"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @Test public void testFunctionWithNestedCaseExpression() {
- String sql = "SELECT abs(CASE e1 WHEN 'testString1' THEN -13" + //$NON-NLS-1$
- " WHEN 'testString2' THEN -5" + //$NON-NLS-1$
- " ELSE abs(e2)" + //$NON-NLS-1$
- " END) AS absVal FROM pm1.g1"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @Test public void testDefect10809(){
- String sql = "select * from LOB_TESTING_ONE where CLOB_COLUMN LIKE '%fff%'"; //$NON-NLS-1$
- helpResolve(helpParse(sql), FakeMetadataFactory.exampleBQTCached());
- }
-
- @Test public void testNonAutoConversionOfLiteralIntegerToShort() throws Exception {
- // parse
- Query command = (Query) QueryParser.getQueryParser().parseCommand("SELECT intkey FROM bqt1.smalla WHERE shortvalue = 5"); //$NON-NLS-1$
-
- // resolve
- QueryResolver.resolveCommand(command, FakeMetadataFactory.exampleBQTCached());
-
- // Check whether an implicit conversion was added on the correct side
- CompareCriteria crit = (CompareCriteria) command.getCriteria();
-
- assertEquals(DataTypeManager.DefaultDataClasses.SHORT, crit.getRightExpression().getType());
- assertEquals("Sql is incorrect after resolving", "SELECT intkey FROM bqt1.smalla WHERE shortvalue = 5", command.toString()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testNonAutoConversionOfLiteralIntegerToShort2() throws Exception {
- // parse
- Query command = (Query) QueryParser.getQueryParser().parseCommand("SELECT intkey FROM bqt1.smalla WHERE 5 = shortvalue"); //$NON-NLS-1$
-
- // resolve
- QueryResolver.resolveCommand(command, FakeMetadataFactory.exampleBQTCached());
-
- // Check whether an implicit conversion was added on the correct side
- CompareCriteria crit = (CompareCriteria) command.getCriteria();
-
- assertEquals(DataTypeManager.DefaultDataClasses.SHORT, crit.getLeftExpression().getType());
- assertEquals("Sql is incorrect after resolving", "SELECT intkey FROM bqt1.smalla WHERE 5 = shortvalue", command.toString()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testAliasedOrderBy() {
- Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1 as y FROM pm1.g1 ORDER BY y"); //$NON-NLS-1$
- helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
- helpCheckSelect(resolvedQuery, new String[] { "y" }); //$NON-NLS-1$
- }
-
- @Test public void testUnaliasedOrderBySucceeds() {
- helpResolve("SELECT pm1.g1.e1 a, pm1.g1.e1 b FROM pm1.g1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
- }
-
- @Test public void testUnaliasedOrderBySucceeds1() {
- helpResolve("SELECT pm1.g1.e1 a FROM pm1.g1 group by pm1.g1.e1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
- }
-
- @Test public void testUnaliasedOrderByFails() {
- helpResolveException("SELECT pm1.g1.e1 e2 FROM pm1.g1 group by pm1.g1.e1 ORDER BY pm1.g1.e2"); //$NON-NLS-1$
- }
-
- @Test public void testUnaliasedOrderByFails1() {
- helpResolveException("SELECT pm1.g1.e1 e2 FROM pm1.g1 group by pm1.g1.e1 ORDER BY pm1.g1.e2 + 1"); //$NON-NLS-1$
- }
-
- /**
- * the group g1 is not known to the order by clause of a union
- */
- @Test public void testUnionOrderByFail() {
- helpResolveException("SELECT pm1.g1.e1 FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY g1.e1", "ORDER BY expression 'g1.e1' cannot be used with a set query."); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testUnionOrderByFail1() {
- helpResolveException("SELECT pm1.g1.e1 FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY pm1.g1.e1", "ORDER BY expression 'pm1.g1.e1' cannot be used with a set query."); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testOrderByPartiallyQualified() {
- helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY g1.e1"); //$NON-NLS-1$
- }
-
- /**
- * the group g1 is not known to the order by clause of a union
- */
- @Test public void testUnionOrderBy() {
- helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY e1"); //$NON-NLS-1$
- }
-
- /**
- * Test for defect 12087 - Insert with implicit conversion from integer to short
- */
- @Test public void testImplConversionBetweenIntAndShort() throws Exception {
- Insert command = (Insert)QueryParser.getQueryParser().parseCommand("Insert into pm5.g3(e2) Values(100)"); //$NON-NLS-1$
- QueryResolver.resolveCommand(command, metadata);
- assertTrue(((Expression)command.getValues().get(0)).getType() == DataTypeManager.DefaultDataClasses.SHORT);
- }
-
- public static FakeMetadataFacade example_12968() {
- // Create models
- FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("myModel"); //$NON-NLS-1$
- FakeMetadataObject pm2 = FakeMetadataFactory.createPhysicalModel("myModel2"); //$NON-NLS-1$
-
- FakeMetadataObject pm1g1 = FakeMetadataFactory.createPhysicalGroup("myModel.myTable", pm1); //$NON-NLS-1$
- FakeMetadataObject pm2g1 = FakeMetadataFactory.createPhysicalGroup("myModel2.mySchema.myTable2", pm2); //$NON-NLS-1$
-
- List pm1g1e = FakeMetadataFactory.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,
- 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);
- }
-
- @Test public void testDefect12968_union() {
- helpResolve(
- helpParse("SELECT myModel.myTable.myColumn AS myColumn from myModel.myTable UNION " + //$NON-NLS-1$
- "SELECT convert(null, string) AS myColumn From myModel2.mySchema.myTable2"), //$NON-NLS-1$
- example_12968());
- }
-
-
- @Test public void testUnionQueryWithNull() throws Exception{
- helpResolve("SELECT NULL, e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
- helpResolve("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT NULL, e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
- helpResolve("SELECT e1, NULL FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
- helpResolve("SELECT e1, NULL FROM pm1.g2 UNION ALL SELECT e1, NULL FROM pm1.g3"); //$NON-NLS-1$
- helpResolve("SELECT e1, NULL as e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
- helpResolve("SELECT e1, NULL as e2 FROM pm1.g1 UNION ALL SELECT e1, e3 FROM pm1.g2"); //$NON-NLS-1$
- }
-
- @Test public void testUnionQueryWithDiffTypes() throws Exception{
- helpResolve("SELECT e1, e3 FROM pm1.g1 UNION ALL SELECT e2, e3 FROM pm1.g2"); //$NON-NLS-1$
- helpResolve("SELECT e1, e3 FROM pm1.g1 UNION ALL SELECT e2, e3 FROM pm1.g2 UNION ALL SELECT NULL, e3 FROM pm1.g2"); //$NON-NLS-1$
- helpResolve("SELECT e1, e3 FROM pm1.g1 UNION ALL SELECT e3, e3 FROM pm1.g2 UNION ALL SELECT NULL, e3 FROM pm1.g2"); //$NON-NLS-1$
- helpResolve("SELECT e1, e2 FROM pm1.g3 UNION ALL SELECT MAX(e4), e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2"); //$NON-NLS-1$
- helpResolve("SELECT e1, e4 FROM pm1.g1 UNION ALL SELECT e2, e3 FROM pm1.g2"); //$NON-NLS-1$
- helpResolve("SELECT e4, e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2"); //$NON-NLS-1$
- helpResolve("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT e3, e4 FROM pm1.g2"); //$NON-NLS-1$
- helpResolve("SELECT e4, e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g2"); //$NON-NLS-1$
- helpResolve("SELECT e4, e2 FROM pm1.g1 UNION ALL SELECT e1, e2 FROM pm1.g2"); //$NON-NLS-1$
- helpResolve("SELECT MAX(e4), e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2"); //$NON-NLS-1$
- //chooses a common type
- helpResolve("select e2 from pm3.g1 union select e3 from pm3.g1 union select e4 from pm3.g1"); //$NON-NLS-1$
- }
-
- @Test public void testUnionQueryWithDiffTypesFails() throws Exception{
- helpResolveException("SELECT e1 FROM pm1.g1 UNION (SELECT e2 FROM pm1.g2 UNION SELECT e2 from pm1.g1 order by e2)", "The Expression e2 used in a nested UNION ORDER BY clause cannot be implicitly converted from type integer to type string."); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testNestedUnionQueryWithNull() throws Exception{
- SetQuery command = (SetQuery)helpResolve("SELECT e2, e3 FROM pm1.g1 UNION (SELECT null, e3 FROM pm1.g2 UNION SELECT null, e3 from pm1.g1)"); //$NON-NLS-1$
-
- assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(0)).getType());
- }
-
- @Test public void testUnionQueryClone() throws Exception{
- SetQuery command = (SetQuery)helpResolve("SELECT e2, e3 FROM pm1.g1 UNION SELECT e3, e2 from pm1.g1"); //$NON-NLS-1$
-
- assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(1)).getType());
-
- command = (SetQuery)command.clone();
-
- assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(1)).getType());
- }
-
- @Test public void testSelectIntoNoFrom() {
- helpResolve("SELECT 'a', 19, {b'true'}, 13.999 INTO pm1.g1"); //$NON-NLS-1$
- }
-
- @Test public void testSelectInto() {
- helpResolve("SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2"); //$NON-NLS-1$
- }
-
- @Test public void testSelectIntoTempGroup() {
- helpResolve("SELECT 'a', 19, {b'true'}, 13.999 INTO #myTempTable"); //$NON-NLS-1$
- helpResolve("SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g1"); //$NON-NLS-1$
- }
-
- //procedural relational mapping
- @Test public void testProcInVirtualGroup1(){
- String sql = "select e1 from pm1.vsp26 where param1=1 and param2='a'"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @Test public void testProcInVirtualGroup2(){
- String sql = "select * from pm1.vsp26 as p where param1=1 and param2='a'"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @Test public void testProcInVirtualGroup3(){
- 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$
- helpResolve(sql);
- }
-
- @Test public void testProcInVirtualGroup4(){
- 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$
- helpResolve(sql);
- }
-
- @Test public void testProcInVirtualGroup5(){
- String sql = "SELECT * FROM (SELECT p.* FROM pm1.vsp26 as P, vm1.g1 where P.e1=g1.e1) x where param1=1 and param2='a'"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @Test public void testProcInVirtualGroup6(){
- String sql = "SELECT P.e1 as ve3, P.e2 as ve4 FROM pm1.vsp26 as P where param1=1 and param2='a'"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @Test public void testProcInVirtualGroup7(){
- 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$
- helpResolve(sql);
- }
-
- @Test public void testProcInVirtualGroup7a(){
- String sql = "SELECT P.e2 as ve3, P.e1 as ve4 FROM pm1.vsp47 as P where param1=1"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @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();
- AnalysisRecord analysis = AnalysisRecord.createNonRecordingRecord();
-
- Query query = (Query) helpResolve(userSql, metadata);
- From from = query.getFrom();
- Collection fromClauses = from.getClauses();
- SPParameter params[] = new SPParameter[2];
- Iterator iter = fromClauses.iterator();
- while(iter.hasNext()) {
- SubqueryFromClause clause = (SubqueryFromClause) iter.next();
- StoredProcedure proc = (StoredProcedure) clause.getCommand();
- List procParams = proc.getParameters();
- for(int i=0; i<procParams.size(); i++) {
- SPParameter param = (SPParameter) procParams.get(i);
- if(param.getParameterType() == ParameterInfo.IN) {
- if(params[0] == null) {
- params[0] = param;
- } else {
- params[1] = param;
- }
- }
- }
- }
-
- assertTrue("Params should be not equal", ! params[0].equals(params[1])); //$NON-NLS-1$
- }
-
- @Test public void testNullConstantInSelect() throws Exception {
- String userSql = "SELECT null as x"; //$NON-NLS-1$
- Query query = (Query)helpParse(userSql);
-
- QueryResolver.resolveCommand(query, FakeMetadataFactory.exampleBQTCached());
-
- // Check type of resolved null constant
- SingleElementSymbol symbol = (SingleElementSymbol) query.getSelect().getSymbols().get(0);
- assertNotNull(symbol.getType());
- assertEquals(DataTypeManager.DefaultDataClasses.STRING, symbol.getType());
- }
-
- @Test public void test11716() throws Exception {
- String sql = "SELECT e1 FROM pm1.g1 where e1='1'"; //$NON-NLS-1$
- Map externalMetadata = new HashMap();
- GroupSymbol inputSet = new GroupSymbol("INPUT"); //$NON-NLS-1$
- List inputSetElements = new ArrayList();
- ElementSymbol inputSetElement = new ElementSymbol("INPUT.e1"); //$NON-NLS-1$
- inputSetElements.add(inputSetElement);
- externalMetadata.put(inputSet, inputSetElements);
- Query command = (Query)helpParse(sql);
- QueryResolver.resolveCommand(command, metadata);
- Collection groups = GroupCollectorVisitor.getGroups(command, false);
- assertFalse(groups.contains(inputSet));
- }
-
- @Test public void testInputToInputsConversion() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = (Select pm1.g1.e2 from pm1.g1 where e2=INPUTS.e2);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e2=40"; //$NON-NLS-1$
-
- Command command = helpResolveUpdateProcedure(procedure, userUpdateStr);
- assertEquals("CREATE PROCEDURE\nBEGIN\nDECLARE integer var1;\nROWS_UPDATED = (SELECT pm1.g1.e2 FROM pm1.g1 WHERE e2 = INPUTS.e2);\nEND", command.toString());
- }
-
- @Test public void testDefect16894_resolverException_1() {
- helpResolve("SELECT * FROM (SELECT * FROM Pm1.g1 AS Y) AS X"); //$NON-NLS-1$
- }
-
- @Test public void testDefect16894_resolverException_2() {
- helpResolve("SELECT * FROM (SELECT * FROM Pm1.g1) AS X"); //$NON-NLS-1$
- }
-
- @Test public void testDefect17385() throws Exception{
- String sql = "select e1 as x ORDER BY x"; //$NON-NLS-1$
- helpResolveException(sql);
- }
-
- @Test public void testValidFullElementNotInQueryGroups() {
- helpResolveException("select pm1.g1.e1 FROM pm1.g1 g"); //$NON-NLS-1$
- }
-
- @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());
- }
-
- @Test public void testParameterError() throws Exception {
- helpResolveException("EXEC pm1.sp2(1, 2)", metadata, "Error Code:ERR.015.008.0007 Message:Incorrect number of parameters specified on the stored procedure pm1.sp2 - expected 1 but got 2"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testUnionOfAliasedLiteralsGetsModified() {
- String sql = "SELECT 5 AS x UNION ALL SELECT 10 AS x"; //$NON-NLS-1$
- Command c = helpResolve(sql);
- assertEquals(sql, c.toString());
- }
-
- @Test public void testXMLWithProcSubquery() {
- String sql = "SELECT * FROM xmltest.doc4 WHERE node2 IN (SELECT e1 FROM (EXEC pm1.vsp1()) AS x)"; //$NON-NLS-1$
- Command c = helpResolve(sql);
- assertEquals(sql, c.toString());
- }
-
- @Test public void testDefect18832() {
- String sql = "SELECT * from (SELECT null as a, e1 FROM pm1.g1) b"; //$NON-NLS-1$
- Command c = helpResolve(sql);
- List projectedSymbols = c.getProjectedSymbols();
- for(int i=0; i< projectedSymbols.size(); i++) {
- ElementSymbol symbol = (ElementSymbol)projectedSymbols.get(i);
- assertTrue(!symbol.getType().equals(DataTypeManager.DefaultDataClasses.NULL));
- }
- }
-
- @Test public void testDefect18832_2() {
- String sql = "SELECT a.*, b.* from (SELECT null as a, e1 FROM pm1.g1) a, (SELECT e1 FROM pm1.g1) b"; //$NON-NLS-1$
- Command c = helpResolve(sql);
- List projectedSymbols = c.getProjectedSymbols();
- for(int i=0; i< projectedSymbols.size(); i++) {
- ElementSymbol symbol = (ElementSymbol)projectedSymbols.get(i);
- assertTrue(!symbol.getType().equals(DataTypeManager.DefaultDataClasses.NULL));
- }
- }
-
- @Test public void testDefect20113() {
- String sql = "SELECT g1.* from pm1.g1"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @Test public void testDefect20113_2() {
- String sql = "SELECT g7.* from g7"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- private void verifyProjectedTypes(Command c, Class[] types) {
- List projSymbols = c.getProjectedSymbols();
- for(int i=0; i<projSymbols.size(); i++) {
- assertEquals("Found type mismatch at column " + i, types[i], ((SingleElementSymbol) projSymbols.get(i)).getType()); //$NON-NLS-1$
- }
- }
-
- @Test public void testNestedInlineViews() throws Exception {
- String sql = "SELECT * FROM (SELECT * FROM (SELECT * FROM pm1.g1) AS Y) AS X"; //$NON-NLS-1$
- Command c = helpResolve(sql);
- assertEquals(sql, c.toString());
-
- verifyProjectedTypes(c, new Class[] { String.class, Integer.class, Boolean.class, Double.class });
- }
-
- @Test public void testNestedInlineViewsNoStar() throws Exception {
- String sql = "SELECT e1 FROM (SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS Y) AS X"; //$NON-NLS-1$
- Command c = helpResolve(sql);
- assertEquals(sql, c.toString());
-
- verifyProjectedTypes(c, new Class[] { String.class });
- }
-
- @Test public void testNestedInlineViewsCount() throws Exception {
- String sql = "SELECT COUNT(*) FROM (SELECT * FROM (SELECT * FROM pm1.g1) AS Y) AS X"; //$NON-NLS-1$
- Command c = helpResolve(sql);
- assertEquals(sql, c.toString());
- verifyProjectedTypes(c, new Class[] { Integer.class });
- }
-
- @Test public void testAggOverInlineView() throws Exception {
- String sql = "SELECT SUM(x) FROM (SELECT (e2 + 1) AS x FROM pm1.g1) AS g"; //$NON-NLS-1$
- Command c = helpResolve(sql);
- assertEquals(sql, c.toString());
- verifyProjectedTypes(c, new Class[] { Long.class });
-
- }
-
- @Test public void testCaseOverInlineView() throws Exception {
- String sql = "SELECT CASE WHEN x > 0 THEN 1.0 ELSE 2.0 END FROM (SELECT e2 AS x FROM pm1.g1) AS g"; //$NON-NLS-1$
- Command c = helpResolve(sql);
- assertEquals(sql, c.toString());
- verifyProjectedTypes(c, new Class[] { Double.class });
-
- }
-
- //procedure - select * from temp table
- @Test public void testDefect20083_1 (){
- helpResolve("EXEC pm1.vsp56()"); //$NON-NLS-1$
- }
-
- //procedure - select * from temp table order by
- @Test public void testDefect20083_2 (){
- helpResolve("EXEC pm1.vsp57()"); //$NON-NLS-1$
- }
-
- @Test public void testTypeConversionOverUnion() throws Exception {
- String sql = "SELECT * FROM (SELECT e2, e1 FROM pm1.g1 UNION SELECT convert(e2, string), e1 FROM pm1.g1) FOO where e2/2 = 1"; //$NON-NLS-1$
- helpResolveException(sql);
- }
-
- @Test public void testVariableDeclarationAfterStatement() throws Exception{
- String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "select * from pm1.g1 where pm1.g1.e1 = VARIABLES.X;\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE string VARIABLES.X = 1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- helpResolveException(procedure, "Element \"VARIABLES.X\" is not defined by any relevant group."); //$NON-NLS-1$
- }
-
- /**
- * same as above, but with an xml query
- * @throws Exception
- */
- @Test public void testVariableDeclarationAfterStatement1() throws Exception{
- String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "select * from xmltest.doc1 where node1 = VARIABLES.X;\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE string VARIABLES.X = 1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- helpResolveException(procedure, "Error Code:ERR.015.008.0019 Message:Unable to resolve element: VARIABLES.X"); //$NON-NLS-1$
- }
-
- @Test public void testCreate() {
- String sql = "CREATE LOCAL TEMPORARY TABLE temp_table (column1 string)"; //$NON-NLS-1$
- Command c = helpResolve(sql);
- assertEquals(sql, c.toString());
- }
-
- @Test public void testCreateQualifiedName() {
- String sql = "CREATE LOCAL TEMPORARY TABLE pm1.g1 (column1 string)"; //$NON-NLS-1$
- helpResolveException(sql, "Cannot create temporary table \"pm1.g1\". Local temporary tables must be created with unqualified names."); //$NON-NLS-1$
- }
-
- @Test public void testProcedureConflict() {
- String sql = "create local temporary table MMSP6 (e1 string, e2 integer)"; //$NON-NLS-1$
- helpResolveException(sql, RealMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
- }
-
- @Test public void testCreatePk() {
- String sql = "CREATE LOCAL TEMPORARY TABLE foo (column1 string, column2 integer, primary key (column1, column2))"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @Test public void testCreateUnknownPk() {
- String sql = "CREATE LOCAL TEMPORARY TABLE foo (column1 string, primary key (column2))"; //$NON-NLS-1$
- helpResolveException(sql, "Element \"column2\" is not defined by any relevant group."); //$NON-NLS-1$
- }
-
- @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$
- }
-
- @Test public void testCreateImplicitName() {
- String sql = "CREATE LOCAL TEMPORARY TABLE #g1 (column1 string)"; //$NON-NLS-1$
- Command c = helpResolve(sql);
- assertEquals(sql, c.toString());
- }
-
- @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$
- }
-
- //this was the old virt.agg procedure. It was defined in such a way that relied on the scope leak of #temp
- //the exception here is a little weak since there are multiple uses of #temp in the block
- @Test public void testTempTableScope() {
- String proc = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
- + "BEGIN " //$NON-NLS-1$
- + " DECLARE integer VARIABLES.BITS;" //$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$
-
- helpResolveException(proc, FakeMetadataFactory.exampleBitwise(), "Group does not exist: #temp"); //$NON-NLS-1$
- }
-
- @Test public void testDrop() {
- String sql = "DROP TABLE temp_table"; //$NON-NLS-1$
- helpResolveException(sql, "Group does not exist: temp_table"); //$NON-NLS-1$
- }
-
- @Test public void testResolveUnqualifiedCriteria() throws Exception{
- Criteria criteria = QueryParser.getQueryParser().parseCriteria("e1 = 1"); //$NON-NLS-1$
-
- // resolve
- try {
- QueryResolver.resolveCriteria(criteria, metadata);
- fail("Exception expected"); //$NON-NLS-1$
- } catch(QueryResolverException e) {
- assertEquals("Symbol e1 is specified with an unknown group context", e.getMessage()); //$NON-NLS-1$
- }
- }
-
- @Test public void testSameNameRoot() {
- String sql = "select p.e1 from pm1.g1 as pp, pm1.g1 as p"; //$NON-NLS-1$
-
- helpResolve(sql);
- }
-
- @Test public void testBatchedUpdateResolver() throws Exception {
- String update1 = "update pm1.g1 set e1 =1"; //$NON-NLS-1$
- String update2 = "update pm2.g1 set e1 =1"; //$NON-NLS-1$
-
- List commands = new ArrayList();
- commands.add(QueryParser.getQueryParser().parseCommand(update1));
- commands.add(QueryParser.getQueryParser().parseCommand(update2));
- BatchedUpdateCommand command = new BatchedUpdateCommand(commands);
-
- helpResolve(command);
- }
-
- @Test public void testAmbiguousAllInGroup() {
- String sql = "SELECT g1.* from pm1.g1, pm2.g1"; //$NON-NLS-1$
- helpResolveException(sql, metadata, "The symbol g1.* refers to more than one group defined in the FROM clause."); //$NON-NLS-1$
- }
-
- @Test public void testRowsUpdatedInProcedure(){
- String sql = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
- + "BEGIN " //$NON-NLS-1$
- +"SELECT ROWS_UPDATED; " //$NON-NLS-1$
- +"end "; //$NON-NLS-1$
-
- helpResolveException(sql, metadata, "Element \"ROWS_UPDATED\" is not defined by any relevant group."); //$NON-NLS-1$
- }
-
- @Test public void testXMLQueryWithVariable() {
- String sql = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
- + "BEGIN " //$NON-NLS-1$
- + "declare string x = '1'; " //$NON-NLS-1$
- +"select * from xmltest.doc1 where node1 = x; " //$NON-NLS-1$
- +"end "; //$NON-NLS-1$
-
- CreateUpdateProcedureCommand command = (CreateUpdateProcedureCommand) helpResolve(sql);
-
- CommandStatement cmdStmt = (CommandStatement)command.getBlock().getStatements().get(1);
-
- CompareCriteria criteria = (CompareCriteria)((Query)cmdStmt.getCommand()).getCriteria();
-
- assertEquals(ProcedureReservedWords.VARIABLES, ((ElementSymbol)criteria.getRightExpression()).getGroupSymbol().getCanonicalName());
- }
-
- /**
- * We could check to see if the expressions are evaluatable to a constant, but that seems unnecessary
- */
- @Test public void testLookupWithoutConstant() throws Exception{
- String sql = "SELECT lookup('pm1.g1', convert('e3', float), 'e2', e2) FROM pm1.g1"; //$NON-NLS-1$
-
- helpResolveException(sql, metadata, "Error Code:ERR.015.008.0063 Message:The first three arguments for the LOOKUP function must be specified as constants."); //$NON-NLS-1$
- }
-
- /**
- * We cannot implicitly convert the argument to double due to lack of precision
- */
- @Test public void testPowerWithBigInteger_Fails() throws Exception {
- String sql = "SELECT power(10, 999999999999999999999999999999999999999999999)"; //$NON-NLS-1$
-
- helpResolveException(sql);
- }
-
- @Test public void testPowerWithLong_Fails() throws Exception {
- String sql = "SELECT power(10, 999999999999)"; //$NON-NLS-1$
-
- helpResolveException(sql);
- }
-
- @Test public void testUpdateError() {
- String userUpdateStr = "UPDATE vm1.g2 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveException(userUpdateStr, metadata, "Error Code:ERR.015.008.0009 Message:Update is not allowed on the view vm1.g2: a procedure must be defined to handle the Update."); //$NON-NLS-1$
- }
-
- @Test public void testInsertError() {
- String userUpdateStr = "INSERT into vm1.g2 (e1) values ('x')"; //$NON-NLS-1$
-
- helpResolveException(userUpdateStr, metadata, "Error Code:ERR.015.008.0009 Message:Insert is not allowed on the view vm1.g2: a procedure must be defined to handle the Insert."); //$NON-NLS-1$
- }
-
- @Test public void testDeleteError() {
- String userUpdateStr = "DELETE from vm1.g2 where e1='x'"; //$NON-NLS-1$
-
- helpResolveException(userUpdateStr, metadata, "Error Code:ERR.015.008.0009 Message:Delete is not allowed on the view vm1.g2: a procedure must be defined to handle the Delete."); //$NON-NLS-1$
- }
-
- @Test public void testResolveXMLSelect() {
- String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE string VARIABLES.X = 1;\n"; //$NON-NLS-1$
- procedure = procedure + "select VARIABLES.X from xmltest.doc1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- helpResolveException(procedure, "Error Code:ERR.015.008.0019 Message:Unable to resolve element: VARIABLES.X"); //$NON-NLS-1$
- }
-
- @Test public void testXMLJoinFail() {
- String query = "select * from xmltest.doc1, xmltest.doc2"; //$NON-NLS-1$
-
- helpResolveException(query, "Error Code:ERR.015.008.0003 Message:Only one XML document may be specified in the FROM clause of a query."); //$NON-NLS-1$
- }
-
- @Test public void testExecProjectedSymbols() {
- String query = "exec pm1.sq1()"; //$NON-NLS-1$
-
- StoredProcedure proc = (StoredProcedure)helpResolve(query);
-
- List projected = proc.getProjectedSymbols();
-
- assertEquals(2, projected.size());
-
- for (Iterator i = projected.iterator(); i.hasNext();) {
- ElementSymbol symbol = (ElementSymbol)i.next();
- assertNotNull(symbol.getGroupSymbol());
- }
- }
-
- @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$
-
- store.addObject(rs2);
- store.addObject(sq2);
-
- 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$
- }
-
- @Test public void testInlineViewNullLiteralInUnion() {
- String sql = "select e2 from pm1.g1 union all (select x from (select null as x) y)"; //$NON-NLS-1$
-
- helpResolve(sql);
- }
-
- @Test public void testSelectIntoWithDuplicateNames() {
- String sql = "select 1 as x, 2 as x into #temp"; //$NON-NLS-1$
-
- helpResolveException(sql, "Cannot create group '#temp' with multiple columns named 'x'"); //$NON-NLS-1$
- }
-
- @Test public void testCreateWithDuplicateNames() {
- String sql = "CREATE LOCAL TEMPORARY TABLE temp_table (column1 string, column1 string)"; //$NON-NLS-1$
-
- helpResolveException(sql, "Cannot create group \'temp_table\' with multiple columns named \'column1\'"); //$NON-NLS-1$
- }
-
- @Test public void testXMLQuery4() {
- helpResolveException("SELECT * FROM xmltest.doc1 group by a2", "Queries against XML documents can not have a GROUP By clause"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQuery5() {
- helpResolveException("SELECT * FROM xmltest.doc1 having a2='x'", "Queries against XML documents can not have a HAVING clause"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testSelectIntoWithOrderBy() {
- String sql = "select e1, e2 into #temp from pm1.g1 order by e1 limit 10"; //$NON-NLS-1$
-
- helpResolve(sql);
- }
-
- @Test public void testUnionBranchesWithDifferentElementCounts() {
- helpResolveException("SELECT e2, e3 FROM pm1.g1 UNION SELECT e2 FROM pm1.g2","Queries combined with the set operator UNION must have the same number of output elements."); //$NON-NLS-1$ //$NON-NLS-2$
- helpResolveException("SELECT e2 FROM pm1.g1 UNION SELECT e2, e3 FROM pm1.g2","Queries combined with the set operator UNION must have the same number of output elements."); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testSelectIntoWithNullLiteral() {
- String sql = "select null as x into #temp from pm1.g1"; //$NON-NLS-1$
-
- Query query = (Query)helpResolve(sql);
-
- TempMetadataStore store = new TempMetadataStore(query.getTemporaryMetadata());
-
- TempMetadataID id = store.getTempElementID("#temp.x"); //$NON-NLS-1$
-
- assertEquals(DataTypeManager.DefaultDataClasses.STRING, id.getType());
- }
-
- @Test public void testInsertWithNullLiteral() {
- String sql = "insert into #temp (x) values (null)"; //$NON-NLS-1$
-
- Insert insert = (Insert)helpResolve(sql);
-
- TempMetadataStore store = new TempMetadataStore(insert.getTemporaryMetadata());
-
- TempMetadataID id = store.getTempElementID("#temp.x"); //$NON-NLS-1$
-
- assertEquals(DataTypeManager.DefaultDataClasses.STRING, id.getType());
- }
-
- @Test public void testInsertWithoutColumnsFails() {
- String sql = "Insert into pm1.g1 values (1, 2)"; //$NON-NLS-1$
-
- helpResolveException(sql, "Error Code:ERR.015.008.0010 Message:INSERT statement must have the same number of elements and values specified. This statement has 4 elements and 2 values."); //$NON-NLS-1$
- }
-
- @Test public void testInsertWithoutColumnsFails1() {
- String sql = "Insert into pm1.g1 values (1, 2, 3, 4)"; //$NON-NLS-1$
-
- helpResolveException(sql, "Error Code:ERR.015.008.0041 Message:Expected value of type 'boolean' but '3' is of type 'integer' and no implicit conversion is available."); //$NON-NLS-1$
- }
-
- @Test public void testInsertWithQueryFails() {
- String sql = "Insert into pm1.g1 select 1, 2, 3, 4"; //$NON-NLS-1$
-
- 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 testInsertWithQueryImplicitWithoutColumns() {
- String sql = "Insert into #X select 1 as x, 2 as y, 3 as z"; //$NON-NLS-1$
- helpResolve(sql); //$NON-NLS-1$
- }
-
- @Test public void testInsertWithQueryImplicitWithoutColumns1() {
- String sql = "Insert into #X select 1 as x, 2 as y, 3 as y"; //$NON-NLS-1$
-
- helpResolveException(sql, "Cannot create group '#X' with multiple columns named 'y'"); //$NON-NLS-1$
- }
-
- @Test public void testInsertWithoutColumnsPasses() {
- String sql = "Insert into pm1.g1 values (1, 2, true, 4)"; //$NON-NLS-1$
-
- helpResolve(sql);
- Insert command = (Insert)helpResolve(sql);
- assertEquals(4, command.getVariables().size());
- }
-
- @Test public void testInsertWithoutColumnsUndefinedTemp() {
- String sql = "Insert into #temp values (1, 2)"; //$NON-NLS-1$
-
- Insert command = (Insert)helpResolve(sql);
- assertEquals(2, command.getVariables().size());
- }
-
- @Test public void testImplicitTempInsertWithNoColumns() {
- StringBuffer proc = new StringBuffer("CREATE VIRTUAL PROCEDURE") //$NON-NLS-1$
- .append("\nBEGIN") //$NON-NLS-1$
- .append("\n create local temporary table #matt (x integer);") //$NON-NLS-1$
- .append("\n insert into #matt values (1);") //$NON-NLS-1$
- .append("\nEND"); //$NON-NLS-1$
-
- Command cmd = helpResolve(proc.toString());
-
- String sExpected = "CREATE VIRTUAL PROCEDURE\nBEGIN\nCREATE LOCAL TEMPORARY TABLE #matt (x integer);\nINSERT INTO #matt (#matt.x) VALUES (1);\nEND\n\tCREATE LOCAL TEMPORARY TABLE #matt (x integer)\n\tINSERT INTO #matt (#matt.x) VALUES (1)\n"; //$NON-NLS-1$
- String sActual = cmd.printCommandTree();
- assertEquals( sExpected, sActual );
- }
-
- @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());
- }
-
- @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$
- }
-
- @Test public void testResolveOldProcRelational() {
- helpResolveException("SELECT * FROM pm1.g1, (exec pm1.sq2(pm1.g1.e1)) as a", "Symbol pm1.g1.e1 is specified with an unknown group context"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testResolverOrderOfPrecedence() {
- helpResolveException("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 CROSS JOIN (pm1.g2 LEFT OUTER JOIN pm2.g1 on pm1.g1.e1 = pm2.g1.e1)", "Symbol pm1.g1.e1 is specified with an unknown group context"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * The cross join should parse/resolve with higher precedence
- */
- @Test public void testResolverOrderOfPrecedence_1() {
- helpResolve("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 CROSS JOIN pm1.g2 LEFT OUTER JOIN pm2.g1 on pm1.g1.e1 = pm2.g1.e1"); //$NON-NLS-1$
- }
-
- @Test public void testInvalidColumnReferenceWithNestedJoin() {
- helpResolveException("SELECT a.* FROM (pm1.g2 a left outer join pm1.g2 b on a.e1= b.e1) LEFT OUTER JOIN (select a.e1) c on (a.e1 = c.e1)"); //$NON-NLS-1$
- }
-
- /**
- * should be the same as exec with too many params
- */
- @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$
- }
-
- @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());
-
- Expression ref = update.getChangeList().getClauses().get(1).getValue();
- assertTrue(ref instanceof Reference);
- assertNotNull(ref.getType());
- }
-
- @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$
- }
-
- @Test public void testReferenceInSelect() {
- String sql = "select ?, e1 from pm1.g1"; //$NON-NLS-1$
- Query command = (Query)helpResolve(sql, FakeMetadataFactory.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());
- 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());
- assertEquals(DataTypeManager.DefaultDataClasses.OBJECT, ((SingleElementSymbol)query.getProjectedSymbols().get(0)).getType());
- }
-
- @Test public void testUnionWithSubQuery() {
- String sql = "select 1 from pm1.g1 where exists (select 1) union select 2"; //$NON-NLS-1$
-
- SetQuery command = (SetQuery)helpResolve(sql);
-
- assertEquals(1, CommandCollectorVisitor.getCommands(command).size());
- }
- @Test public void testOrderBy_J658a() {
- Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2, e3 as x, (5+2) as y FROM pm1.g1 ORDER BY e3"); //$NON-NLS-1$
- OrderBy orderBy = resolvedQuery.getOrderBy();
- int[] expectedPositions = new int[] {2};
- helpTestOrderBy(orderBy, expectedPositions);
- }
-
- private void helpTestOrderBy(OrderBy orderBy, int[] expectedPositions) {
- assertEquals(expectedPositions.length, orderBy.getVariableCount());
- for (int i = 0; i < expectedPositions.length; i++) {
- assertEquals(expectedPositions[i], orderBy.getExpressionPosition(i));
- }
- }
- @Test public void testOrderBy_J658b() {
- Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2, e3 as x, (5+2) as y FROM pm1.g1 ORDER BY e2, e3 "); //$NON-NLS-1$
- helpTestOrderBy(resolvedQuery.getOrderBy(), new int[] {1, 2});
- }
- @Test public void testOrderBy_J658c() {
- Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2 as x, e3 as y FROM pm1.g1 ORDER BY x, e3 "); //$NON-NLS-1$
- helpTestOrderBy(resolvedQuery.getOrderBy(), new int[] {1, 2});
- }
-
- // ambiguous, should fail
- @Test public void testOrderBy_J658d() {
- helpResolveException("SELECT pm1.g1.e1, e2 as x, e3 as x FROM pm1.g1 ORDER BY x, e1 ", "Error Code:ERR.015.008.0042 Message:Element 'x' in ORDER BY is ambiguous and may refer to more than one element of SELECT clause."); //$NON-NLS-1$ //$NON-NLS-2$
- }
- @Test public void testOrderBy_J658e() {
- Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2 as x, e3 as e2 FROM pm1.g1 ORDER BY x, e2 "); //$NON-NLS-1$
- helpTestOrderBy(resolvedQuery.getOrderBy(), new int[] {1, 2});
- }
-
- @Test public void testSPOutParamWithExec() {
- StoredProcedure proc = (StoredProcedure)helpResolve("exec pm2.spTest8(1)", FakeMetadataFactory.exampleBQTCached());
- assertEquals(2, proc.getProjectedSymbols().size());
- }
-
- /**
- * Note that the call syntax is not quite correct, the output parameter is not in the arg list.
- * That hack is handled by the PreparedStatementRequest
- */
- @Test public void testSPOutParamWithCallableStatement() {
- StoredProcedure proc = (StoredProcedure)helpResolve("{call pm2.spTest8(1)}", FakeMetadataFactory.exampleBQTCached());
- assertEquals(3, proc.getProjectedSymbols().size());
- }
-
- @Test public void testOutWithWrongType() {
- helpResolveException("exec pm2.spTest8(inkey=>1, outkey=>{t '12:00:00'})", FakeMetadataFactory.exampleBQTCached());
- }
-
- @Test public void testProcRelationalWithOutParam() {
- Query proc = (Query)helpResolve("select * from pm2.spTest8 where inkey = 1", FakeMetadataFactory.exampleBQTCached());
- assertEquals(3, proc.getProjectedSymbols().size());
- }
-
- @Test public void testSPReturnParamWithNoResultSet() {
- StoredProcedure proc = (StoredProcedure)helpResolve("exec pm4.spTest9(1)", FakeMetadataFactory.exampleBQTCached());
- assertEquals(1, proc.getProjectedSymbols().size());
- }
-
- @Test public void testSecondPassFunctionResolving() {
- helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 where lower(?) = e1 "); //$NON-NLS-1$
- }
-
- @Test public void testSecondPassFunctionResolving1() {
- try {
- helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 where 1/(e1 - 2) <> 4 "); //$NON-NLS-1$
- fail("expected exception");
- } catch (RuntimeException e) {
- QueryResolverException qre = (QueryResolverException)e.getCause();
- assertEquals("ERR.015.008.0040", qre.getCode());
- }
- }
-
- @Ignore("currently not supported - we get type hints from the criteria not from the possible signatures")
- @Test public void testSecondPassFunctionResolving2() {
- helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 where (lower(?) || 1) = e1 "); //$NON-NLS-1$
- }
-
- /**
- * Test <code>QueryResolver</code>'s ability to resolve a query that
- * contains an aggregate <code>SUM</code> which uses a <code>CASE</code>
- * expression which contains <code>BETWEEN</code> criteria as its value.
- * <p>
- * For example:
- * <p>
- * SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1
- */
- @Test public void testAggregateWithBetweenInCaseInSelect() {
- String sql = "SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- /**
- * Test <code>QueryResolver</code>'s ability to resolve a query that
- * contains a <code>CASE</code> expression which contains
- * <code>BETWEEN</code> criteria in the queries <code>SELECT</code> clause.
- * <p>
- * For example:
- * <p>
- * SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1
- */
- @Test public void testBetweenInCaseInSelect() {
- String sql = "SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- /**
- * Test <code>QueryResolver</code>'s ability to resolve a query that
- * contains a <code>CASE</code> expression which contains
- * <code>BETWEEN</code> criteria in the queries <code>WHERE</code> clause.
- * <p>
- * For example:
- * <p>
- * SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END
- */
- @Test public void testBetweenInCase() {
- String sql = "SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END"; //$NON-NLS-1$
- helpResolve(sql);
- }
-
- @Test public void testOrderByUnrelated() {
- helpResolve("SELECT pm1.g1.e1, e2 as x, e3 as y FROM pm1.g1 ORDER BY e4"); //$NON-NLS-1$
- }
-
- @Test public void testOrderByUnrelated1() {
- helpResolveException("SELECT distinct pm1.g1.e1, e2 as x, e3 as y FROM pm1.g1 ORDER BY e4"); //$NON-NLS-1$
- }
-
- @Test public void testOrderByUnrelated2() {
- helpResolveException("SELECT max(e2) FROM pm1.g1 group by e1 ORDER BY e4"); //$NON-NLS-1$
- }
-
- @Test public void testOrderByExpression() {
- Query query = (Query)helpResolve("select pm1.g1.e1 from pm1.g1 order by e2 || e3 "); //$NON-NLS-1$
- assertEquals(-1, query.getOrderBy().getExpressionPosition(0));
- }
-
- @Test public void testOrderByExpression1() {
- Query query = (Query)helpResolve("select pm1.g1.e1 || e2 from pm1.g1 order by pm1.g1.e1 || e2 "); //$NON-NLS-1$
- assertEquals(0, query.getOrderBy().getExpressionPosition(0));
- }
-
- @Test public void testOrderByExpression2() {
- helpResolveException("select pm1.g1.e1 from pm1.g1 union select pm1.g2.e1 from pm1.g2 order by pm1.g1.e1 || 2", "ORDER BY expression '(pm1.g1.e1 || 2)' cannot be used with a set query."); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testOrderByConstantFails() {
- helpResolveException("select pm1.g1.e1 from pm1.g1 order by 2"); //$NON-NLS-1$
- }
-
- @Test public void testCorrelatedNestedTableReference() {
- helpResolve("select pm1.g1.e1 from pm1.g1, table (exec pm1.sq2(pm1.g1.e2)) x"); //$NON-NLS-1$
- helpResolveException("select pm1.g1.e1 from pm1.g1, (exec pm1.sq2(pm1.g1.e2)) x"); //$NON-NLS-1$
- }
-
- @Test public void testCorrelatedTextTable() {
- Command command = helpResolve("select x.* from pm1.g1, texttable(e1 COLUMNS x string) x"); //$NON-NLS-1$
- assertEquals(1, command.getProjectedSymbols().size());
- }
-
- @Test public void testQueryString() throws Exception {
- helpResolveException("select querystring(xmlparse(document '<a/>'))");
- }
-
- // validating AssignmentStatement, ROWS_UPDATED element assigned
- @Test(expected=QueryResolverException.class) public void testCreateUpdateProcedure9() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr);
- }
-
- CreateUpdateProcedureCommand helpResolveUpdateProcedure(String procedure,
- String userUpdateStr) throws QueryParserException,
- QueryResolverException, TeiidComponentException,
- QueryMetadataException {
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
-
- ProcedureContainer userCommand = (ProcedureContainer)QueryParser.getQueryParser().parseCommand(userUpdateStr);
- QueryResolver.resolveCommand(userCommand, metadata);
-
- return (CreateUpdateProcedureCommand)QueryResolver.expandCommand(userCommand, metadata, AnalysisRecord.createNonRecordingRecord());
- }
-
- // validating AssignmentStatement, variable type and assigned type
- // do not match
- @Test(expected=QueryResolverException.class) public void testCreateUpdateProcedure10() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userUpdateStr);
- }
-
- //return should be first, then out
- @Test public void testParamOrder() {
- Query resolvedQuery = (Query)helpResolve("SELECT * FROM (exec pm4.spRetOut()) as a", RealMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
-
- assertEquals("a.ret", resolvedQuery.getProjectedSymbols().get(0).getName());
- }
-
- @Test public void testOrderByAggregatesError() throws Exception {
- helpResolveException("select count(*) from pm1.g1 order by e1");
- }
-
- @Test public void testWithDuplidateName() {
- helpResolveException("with x as (TABLE pm1.g1), x as (TABLE pm1.g2) SELECT * from x");
- }
-
- @Test public void testWithColumns() {
- helpResolveException("with x (a, b) as (TABLE pm1.g1) SELECT * from x");
- }
-
- @Test public void testWithNameMatchesFrom() {
- helpResolve("with x as (TABLE pm1.g1) SELECT * from (TABLE x) x");
- }
-
- // variables cannot be used among insert elements
- @Test(expected=QueryResolverException.class) public void testCreateUpdateProcedure23() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Update pm1.g1 SET pm1.g1.e2 =1 , var1 = 2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
-
- helpResolveUpdateProcedure(procedure, userQuery);
- }
-}
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestResolver.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/resolver/TestResolver.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestResolver.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestResolver.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,2988 @@
+/*
+ * 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.resolver;
+
+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.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Before;
+import org.junit.Ignore;
+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.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;
+import org.teiid.query.function.FunctionTree;
+import org.teiid.query.mapping.relational.QueryNode;
+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;
+import org.teiid.query.sql.ProcedureReservedWords;
+import org.teiid.query.sql.lang.BatchedUpdateCommand;
+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.From;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.ProcedureContainer;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.SubqueryFromClause;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.navigator.DeepPreOrderNavigator;
+import org.teiid.query.sql.proc.CommandStatement;
+import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
+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.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.RealMetadataFactory;
+import org.teiid.query.unittest.TimestampUtil;
+
+ at SuppressWarnings("nls")
+public class TestResolver {
+
+ private QueryMetadataInterface metadata;
+
+ @Before public void setUp() {
+ metadata = RealMetadataFactory.example1Cached();
+ }
+
+ // ################################## TEST HELPERS ################################
+
+ static Command helpParse(String sql) {
+ try {
+ return QueryParser.getQueryParser().parseCommand(sql);
+ } catch(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Helps resolve command, then check that the actual resolved Elements variables are the same as
+ * the expected variable names. The variableNames param will be empty unless the subquery
+ * is a correlated subquery.
+ * @param sql Command to parse and resolve
+ * @param variableNames expected element symbol variable names, in order
+ * @return parsed and resolved Query
+ */
+ private Command helpResolveSubquery(String sql, String[] variableNames){
+ Query query = (Query)helpResolve(sql);
+ Collection<ElementSymbol> variables = getVariables(query);
+
+ assertTrue("Expected variables size " + variableNames.length + " but was " + variables.size(), //$NON-NLS-1$ //$NON-NLS-2$
+ variables.size() == variableNames.length);
+ Iterator<ElementSymbol> variablesIter = variables.iterator();
+ for (int i=0; variablesIter.hasNext(); i++) {
+ 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]));
+ }
+
+ if (variableNames.length == 0){
+ //There should be no TempMetadataIDs
+ Collection symbols = CheckNoTempMetadataIDsVisitor.checkSymbols(query);
+ assertTrue("Expected no symbols with temp metadataIDs, but got " + symbols, symbols.isEmpty()); //$NON-NLS-1$
+ }
+
+ return query;
+ }
+
+ public static Collection<ElementSymbol> getVariables(LanguageObject languageObject) {
+ Collection<ElementSymbol> variables = ElementCollectorVisitor.getElements(languageObject, false, true);
+ for (Iterator<ElementSymbol> iterator = variables.iterator(); iterator.hasNext();) {
+ ElementSymbol elementSymbol = iterator.next();
+ if (!elementSymbol.isExternalReference()) {
+ iterator.remove();
+ }
+ }
+ return variables;
+ }
+
+ public static Command helpResolve(String sql, QueryMetadataInterface queryMetadata){
+ return helpResolve(helpParse(sql), queryMetadata);
+ }
+
+ private Command helpResolve(String sql) {
+ return helpResolve(helpParse(sql));
+ }
+
+ private Command helpResolve(Command command) {
+ return helpResolve(command, this.metadata);
+ }
+
+ static Command helpResolve(Command command, QueryMetadataInterface queryMetadataInterface) {
+ // resolve
+ try {
+ QueryResolver.resolveCommand(command, queryMetadataInterface);
+ } catch(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+
+ CheckSymbolsAreResolvedVisitor vis = new CheckSymbolsAreResolvedVisitor();
+ DeepPreOrderNavigator.doVisit(command, vis);
+ Collection unresolvedSymbols = vis.getUnresolvedSymbols();
+ assertTrue("Found unresolved symbols: " + unresolvedSymbols, unresolvedSymbols.isEmpty()); //$NON-NLS-1$
+ return command;
+ }
+
+ /**
+ * Expect a QueryResolverException (not any other kind of Throwable)
+ */
+ private void helpResolveFails(Command command) {
+ // resolve
+ QueryResolverException exception = null;
+ try {
+ QueryResolver.resolveCommand(command, metadata);
+ } catch(QueryResolverException e) {
+ exception = e;
+ } catch(TeiidException e) {
+ fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ assertNotNull("Expected a QueryResolverException but got none.", exception); //$NON-NLS-1$
+ }
+
+ private Criteria helpResolveCriteria(String sql) {
+ Criteria criteria = null;
+
+ // parse
+ try {
+ criteria = QueryParser.getQueryParser().parseCriteria(sql);
+
+ } catch(TeiidException e) {
+ fail("Exception during parsing (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // resolve
+ try {
+ QueryResolver.resolveCriteria(criteria, metadata);
+ } catch(TeiidException e) {
+ e.printStackTrace();
+ fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ CheckSymbolsAreResolvedVisitor vis = new CheckSymbolsAreResolvedVisitor();
+ DeepPreOrderNavigator.doVisit(criteria, vis);
+ Collection unresolvedSymbols = vis.getUnresolvedSymbols();
+ assertTrue("Found unresolved symbols: " + unresolvedSymbols, unresolvedSymbols.isEmpty()); //$NON-NLS-1$
+ return criteria;
+ }
+
+ public static Command helpResolveWithBindings(String sql, QueryMetadataInterface metadata, List bindings) throws QueryResolverException, TeiidComponentException {
+
+ // parse
+ Command command = helpParse(sql);
+
+ QueryNode qn = new QueryNode(sql);
+ qn.setBindings(bindings);
+ // resolve
+ QueryResolver.resolveWithBindingMetadata(command, metadata, qn, true);
+
+ CheckSymbolsAreResolvedVisitor vis = new CheckSymbolsAreResolvedVisitor();
+ DeepPreOrderNavigator.doVisit(command, vis);
+
+ Collection unresolvedSymbols = vis.getUnresolvedSymbols();
+ assertTrue("Found unresolved symbols: " + unresolvedSymbols, unresolvedSymbols.isEmpty()); //$NON-NLS-1$
+ return command;
+ }
+
+ static void helpResolveException(String sql, QueryMetadataInterface queryMetadata){
+ helpResolveException(sql, queryMetadata, null);
+ }
+
+ static void helpResolveException(String sql, QueryMetadataInterface queryMetadata, String expectedExceptionMessage){
+
+ // parse
+ Command command = helpParse(sql);
+
+ // resolve
+ try {
+ QueryResolver.resolveCommand(command, queryMetadata);
+ fail("Expected exception for resolving " + sql); //$NON-NLS-1$
+ } catch(QueryResolverException e) {
+ if(expectedExceptionMessage != null){
+ assertEquals(expectedExceptionMessage, e.getMessage());
+ }
+ } catch(TeiidComponentException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void helpResolveException(String sql, String expectedExceptionMessage) {
+ TestResolver.helpResolveException(sql, this.metadata, expectedExceptionMessage);
+ }
+
+ private void helpResolveException(String sql) {
+ TestResolver.helpResolveException(sql, this.metadata);
+ }
+
+ private void helpCheckFrom(Query query, String[] groupIDs) {
+ From from = query.getFrom();
+ 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 = 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();
+ 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);
+ 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<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 = elements.get(i);
+ assertEquals("Element name does not match: ", elementNames[i].toUpperCase(), symbol.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);
+ }
+ }
+ }
+
+ private void helpTestIsXMLQuery(String sql, boolean isXML) throws QueryResolverException, QueryMetadataException, TeiidComponentException {
+ // parse
+ Query query = (Query) helpParse(sql);
+
+ // check whether it's xml
+ boolean actual = QueryResolver.isXMLQuery(query, metadata);
+ assertEquals("Wrong answer for isXMLQuery", isXML, actual); //$NON-NLS-1$
+ }
+
+ /**
+ * Helper method to resolve an exec aka stored procedure, then check that the
+ * expected parameter expressions are the same as actual parameter expressions.
+ * @param sql
+ * @param expectedParameterExpressions
+ * @since 4.3
+ */
+ private StoredProcedure helpResolveExec(String sql, Object[] expectedParameterExpressions) {
+
+ StoredProcedure proc = (StoredProcedure)helpResolve(sql);
+
+ List params = proc.getParameters();
+
+ // Remove all but IN and IN/OUT params
+ Iterator paramIter = params.iterator();
+ while (paramIter.hasNext()) {
+ final SPParameter param = (SPParameter)paramIter.next();
+ if (param.getParameterType() != ParameterInfo.IN && param.getParameterType() != ParameterInfo.INOUT) {
+ paramIter.remove();
+ }
+ }
+
+ // Check remaining params against expected expressions
+ assertEquals(expectedParameterExpressions.length, params.size());
+ for (int i=0; i<expectedParameterExpressions.length; i++) {
+ SPParameter param = (SPParameter)params.get(i);
+ if (expectedParameterExpressions[i] == null) {
+ assertNull(param.getExpression());
+ } else {
+ assertEquals(expectedParameterExpressions[i], param.getExpression());
+ }
+ }
+
+ return proc;
+ }
+
+
+ // ################################## ACTUAL TESTS ################################
+
+
+ @Test public void testElementSymbolForms() {
+ String sql = "SELECT pm1.g1.e1, e2, pm1.g1.e3 AS a, e4 AS b FROM pm1.g1"; //$NON-NLS-1$
+ Query resolvedQuery = (Query) helpResolve(sql);
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "pm1.g1.e2", "a", "b" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ 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$
+ assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
+ }
+
+ @Test public void testElementSymbolFormsWithAliasedGroup() {
+ String sql = "SELECT x.e1, e2, x.e3 AS a, e4 AS b FROM pm1.g1 AS x"; //$NON-NLS-1$
+ Query resolvedQuery = (Query) helpResolve(sql);
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "x.e1", "x.e2", "a", "b" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ 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$
+ assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
+ }
+
+ @Test public void testGroupWithVDB() {
+ 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 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 = 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 = 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 = 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 = 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 = 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 = 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 = RealMetadataFactory.example3();
+ String sql = "SELECT e1 FROM g4"; //$NON-NLS-1$
+ Query resolvedQuery = (Query) helpResolve(sql);
+ helpCheckFrom(resolvedQuery, new String[] { "pm3.g4" }); //$NON-NLS-1$
+ }
+
+ @Test public void testPartiallyQualifiedGroup8() {
+ 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 = 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 = 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$
+ }
+
+ /** defect 12536 */
+ @Test public void testPartiallyQualifiedElement2() {
+ 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$
+ }
+
+ /** defect 12536 */
+ @Test public void testPartiallyQualifiedElement3() {
+ 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$
+ }
+
+ /** defect 12536 */
+ @Test public void testPartiallyQualifiedElement4() {
+ 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 = 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 = 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 = 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 = RealMetadataFactory.example3();
+ helpResolveException("SELECT e1 FROM cat3.g1"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailPartiallyQualifiedGroup2() {
+ metadata = RealMetadataFactory.example3();
+ helpResolveException("SELECT e1 FROM g1"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailPartiallyQualifiedGroup3() {
+ metadata = RealMetadataFactory.example3();
+ helpResolveException("SELECT e1 FROM g2"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailPartiallyQualifiedGroup4() {
+ metadata = RealMetadataFactory.example3();
+ helpResolveException("SELECT e1 FROM g3"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailPartiallyQualifiedGroup5() {
+ metadata = RealMetadataFactory.example3();
+ helpResolveException("SELECT e1 FROM g5"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailPartiallyQualifiedElement1() {
+ 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 = RealMetadataFactory.example3();
+ helpResolveException("SELECT g1.e1 FROM pm1.cat1.cat2.cat3.g1, pm2.cat3.g1"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailPartiallyQualifiedElement3() {
+ metadata = RealMetadataFactory.example3();
+ helpResolveException("SELECT cat3.g1.e1 FROM pm2.cat2.g2, pm1.cat2.g3"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailPartiallyQualifiedElement4() {
+ metadata = RealMetadataFactory.example3();
+ helpResolveException("SELECT cat3.g1.e1 FROM pm2.cat2.g2"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailPartiallyQualifiedElement5() {
+ metadata = RealMetadataFactory.example3();
+ helpResolveException("SELECT cat3.g1.e1 FROM g1"); //$NON-NLS-1$
+ }
+
+ @Test public void testElementWithVDB() {
+ 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(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+ assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
+ }
+
+ @Test public void testAliasedElementWithVDB() {
+ 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$
+ new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+ }
+
+ @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$
+ }
+
+ @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$
+ }
+
+ @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$
+ }
+
+ @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$
+ }
+
+ @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$
+ }
+
+ @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$
+ }
+
+ @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$
+ }
+
+ @Test public void testSelectExpressions() {
+ Query resolvedQuery = (Query) helpResolve("SELECT e1, concat(e1, 's'), concat(e1, 's') as c FROM pm1.g1"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "expr", "c" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ helpCheckElements(resolvedQuery.getSelect(),
+ new String[] { "pm1.g1.e1", "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ new String[] { "pm1.g1.e1", "pm1.g1.e1", "pm1.g1.e1" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testSelectCountStar() {
+ Query resolvedQuery = (Query) helpResolve("SELECT count(*) FROM pm1.g1"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "count" }); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getSelect(), new String[] { }, new String[] { } );
+ }
+
+ @Test public void testMultipleIdenticalElements() {
+ Query resolvedQuery = (Query) helpResolve("SELECT e1, e1 FROM pm1.g1"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
+ helpCheckElements(resolvedQuery.getSelect(),
+ new String[] { "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testMultipleIdenticalElements2() {
+ Query resolvedQuery = (Query) helpResolve("SELECT e1, pm1.g1.e1 FROM pm1.g1"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
+ helpCheckElements(resolvedQuery.getSelect(),
+ new String[] { "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testMultipleIdenticalElements3() {
+ Query resolvedQuery = (Query) helpResolve("SELECT e1, e1 as x FROM pm1.g1"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "x" }); //$NON-NLS-1$ //$NON-NLS-2$
+ helpCheckElements(resolvedQuery.getSelect(),
+ new String[] { "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { "pm1.g1.e1", "pm1.g1.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDifferentElementsSameName() {
+ Query resolvedQuery = (Query) helpResolve("SELECT e1 as x, e2 as x FROM pm1.g2"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g2" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "x", "x" }); //$NON-NLS-1$ //$NON-NLS-2$
+ helpCheckElements(resolvedQuery.getSelect(),
+ new String[] { "pm1.g2.e1", "pm1.g2.e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { "pm1.g2.e1", "pm1.g2.e2" }); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDifferentConstantsSameName() {
+ Query resolvedQuery = (Query) helpResolve("SELECT 1 as x, 2 as x FROM pm1.g2"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g2" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "x", "x" }); //$NON-NLS-1$ //$NON-NLS-2$
+ helpCheckElements(resolvedQuery.getSelect(),
+ new String[] { },
+ new String[] { });
+ }
+
+ @Test public void testFailSameGroupsWithSameNames() {
+ helpResolveException("SELECT * FROM pm1.g1 as x, pm1.g1 as x"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailDifferentGroupsWithSameNames() {
+ helpResolveException("SELECT * FROM pm1.g1 as x, pm1.g2 as x"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailAmbiguousElement() {
+ helpResolveException("SELECT e1 FROM pm1.g1, pm1.g2"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailAmbiguousElementAliasedGroup() {
+ helpResolveException("SELECT e1 FROM pm1.g1 as x, pm1.g1"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailFullyQualifiedElementUnknownGroup() {
+ helpResolveException("SELECT pm1.g1.e1 FROM pm1.g2"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailUnknownGroup() {
+ helpResolveException("SELECT x.e1 FROM x"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailUnknownElement() {
+ helpResolveException("SELECT x FROM pm1.g1"); //$NON-NLS-1$
+ }
+
+ @Test public void testFailFunctionOfAggregatesInSelect() {
+ helpResolveException("SELECT (SUM(e0) * COUNT(e0)) FROM test.group GROUP BY e0"); //$NON-NLS-1$
+ }
+
+ /*
+ * per defect 4404
+ */
+ @Test public void testFailGroupNotReferencedByAlias() {
+ helpResolveException("SELECT pm1.g1.x FROM pm1.g1 as H"); //$NON-NLS-1$
+ }
+
+ /*
+ * per defect 4404 - this one reproduced the defect,
+ * then succeeded after the fix
+ */
+ @Test public void testFailGroupNotReferencedByAliasSelectAll() {
+ helpResolveException("SELECT pm1.g1.* FROM pm1.g1 as H"); //$NON-NLS-1$
+ }
+
+ @Test public void testComplicatedQuery() {
+ Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e2 as y, pm1.g1.E3 as z, CONVERT(pm1.g1.e1, integer) * 1000 as w FROM pm1.g1 WHERE e1 <> 'x'"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "y", "z", "w" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ helpCheckElements(resolvedQuery,
+ new String[] { "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e1" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ new String[] { "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e1" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testJoinQuery() {
+ Query resolvedQuery = (Query) helpResolve("SELECT pm3.g1.e2, pm3.g2.e2 FROM pm3.g1, pm3.g2 WHERE pm3.g1.e2=pm3.g2.e2"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "pm3.g1", "pm3.g2" }); //$NON-NLS-1$ //$NON-NLS-2$
+ helpCheckSelect(resolvedQuery, new String[] { "pm3.g1.e2", "pm3.g2.e2" }); //$NON-NLS-1$ //$NON-NLS-2$
+ helpCheckElements(resolvedQuery,
+ new String[] { "pm3.g1.e2", "pm3.g2.e2", "pm3.g1.e2", "pm3.g2.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ new String[] { "pm3.g1.e2", "pm3.g2.e2", "pm3.g1.e2", "pm3.g2.e2" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ @Test public void testHavingRequiringConvertOnAggregate1() {
+ helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING MAX(e2) > 1.2"); //$NON-NLS-1$
+ }
+
+ @Test public void testHavingRequiringConvertOnAggregate2() {
+ helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING MIN(e2) > 1.2"); //$NON-NLS-1$
+ }
+
+ @Test public void testHavingRequiringConvertOnAggregate3() {
+ helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING 1.2 > MAX(e2)"); //$NON-NLS-1$
+ }
+
+ @Test public void testHavingRequiringConvertOnAggregate4() {
+ helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING 1.2 > MIN(e2)"); //$NON-NLS-1$
+ }
+
+ @Test public void testHavingWithAggsOfDifferentTypes() {
+ helpResolve("SELECT * FROM pm1.g1 GROUP BY e4 HAVING MIN(e1) = MIN(e2)"); //$NON-NLS-1$
+ }
+
+ @Test public void testCaseInGroupBy() {
+ String sql = "SELECT SUM(e2) FROM pm1.g1 GROUP BY CASE WHEN e2 = 0 THEN 1 ELSE 2 END"; //$NON-NLS-1$
+ Command command = helpResolve(sql);
+ assertEquals(sql, command.toString());
+
+ helpCheckElements(command, new String[] {"pm1.g1.e2", "pm1.g1.e2"}, new String[] {"pm1.g1.e2", "pm1.g1.e2"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$
+ }
+
+ @Test public void testFunctionInGroupBy() {
+ String sql = "SELECT SUM(e2) FROM pm1.g1 GROUP BY (e2 + 1)"; //$NON-NLS-1$
+ Command command = helpResolve(sql);
+ assertEquals(sql, command.toString());
+
+ helpCheckElements(command, new String[] {"pm1.g1.e2", "pm1.g1.e2"}, new String[] {"pm1.g1.e2", "pm1.g1.e2"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-4$
+ }
+
+ @Test public void testUnknownFunction() {
+ helpResolveException("SELECT abc(e1) FROM pm1.g1", "Error Code:ERR.015.008.0039 Message:The function 'abc(e1)' is an unknown form. Check that the function name and number of arguments is correct."); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testConversionNotPossible() {
+ helpResolveException("SELECT dayofmonth('2002-01-01') FROM pm1.g1", "Error Code:ERR.015.008.0040 Message:The function 'dayofmonth('2002-01-01')' is a valid function form, but the arguments do not match a known type signature and cannot be converted using implicit type conversions."); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testResolveParameters() throws Exception {
+ List bindings = new ArrayList();
+ bindings.add("pm1.g2.e1"); //$NON-NLS-1$
+ bindings.add("pm1.g2.e2"); //$NON-NLS-1$
+
+ Query resolvedQuery = (Query) helpResolveWithBindings("SELECT pm1.g1.e1, ? FROM pm1.g1 WHERE pm1.g1.e1 = ?", metadata, bindings); //$NON-NLS-1$
+
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1", "expr" }); //$NON-NLS-1$ //$NON-NLS-2$
+ helpCheckElements(resolvedQuery.getCriteria(),
+ new String[] { "pm1.g1.e1", "pm1.g2.e2" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1", "pm1.g2.e2" } ); //$NON-NLS-1$
+
+ }
+
+ @Test public void testResolveParametersInsert() throws Exception {
+ List<String> bindings = Arrays.asList("pm1.g2.e1"); //$NON-NLS-1$
+
+ helpResolveWithBindings("INSERT INTO pm1.g1 (e1) VALUES (?)", metadata, bindings); //$NON-NLS-1$
+ }
+
+ @Test public void testResolveParametersExec() throws Exception {
+ List<String> bindings = Arrays.asList("pm1.g2.e1"); //$NON-NLS-1$
+
+ Query resolvedQuery = (Query)helpResolveWithBindings("SELECT * FROM (exec pm1.sq2(?)) as a", metadata, bindings); //$NON-NLS-1$
+ StoredProcedure sp = (StoredProcedure)((SubqueryFromClause)resolvedQuery.getFrom().getClauses().get(0)).getCommand();
+ assertEquals(String.class, sp.getInputParameters().get(0).getExpression().getType());
+ }
+
+ @Test public void testResolveParametersExecNamed() throws Exception {
+ List<String> bindings = Arrays.asList("pm1.g2.e1 as x"); //$NON-NLS-1$
+
+ helpResolveWithBindings("SELECT * FROM (exec pm1.sq2(input.x)) as a", metadata, bindings); //$NON-NLS-1$
+ }
+
+ @Test public void testUseNonExistentAlias() {
+ helpResolveException("SELECT portfoliob.e1 FROM ((pm1.g1 AS portfoliob JOIN pm1.g2 AS portidentb ON portfoliob.e1 = portidentb.e1) RIGHT OUTER JOIN pm1.g3 AS identifiersb ON portidentb.e1 = 'ISIN' and portidentb.e2 = identifiersb.e2) RIGHT OUTER JOIN pm1.g1 AS issuesb ON a.identifiersb.e1 = issuesb.e1"); //$NON-NLS-1$
+ }
+
+ @Test public void testCriteria1() {
+ CompareCriteria expected = new CompareCriteria();
+ ElementSymbol es = new ElementSymbol("pm1.g1.e1"); //$NON-NLS-1$
+ GroupSymbol gs = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
+ es.setGroupSymbol(gs);
+ expected.setLeftExpression(es);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(new Constant("abc")); //$NON-NLS-1$
+
+ Criteria actual = helpResolveCriteria("pm1.g1.e1 = 'abc'"); //$NON-NLS-1$
+
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testSubquery1() {
+ Query resolvedQuery = (Query) helpResolve("SELECT e1 FROM pm1.g1, (SELECT pm1.g2.e1 AS x FROM pm1.g2) AS y WHERE e1 = x"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g1", "y" }); //$NON-NLS-1$ //$NON-NLS-2$
+ helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getSelect(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+
+ }
+
+ @Test public void testStoredQuery1() {
+ StoredProcedure proc = (StoredProcedure) helpResolve("EXEC pm1.sq2('abc')"); //$NON-NLS-1$
+
+ // Check number of resolved parameters
+ List<SPParameter> params = proc.getParameters();
+ assertEquals("Did not get expected parameter count", 2, params.size()); //$NON-NLS-1$
+
+ // Check resolved parameters
+ SPParameter param1 = params.get(1);
+ helpCheckParameter(param1, ParameterInfo.RESULT_SET, 2, "pm1.sq2.ret", java.sql.ResultSet.class, null); //$NON-NLS-1$
+
+ 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$
+ }
+
+ /**
+ * per defect 8211 - Input params do not have to be numbered sequentially in metadata. For example,
+ * the first input param can be #1 and the second input param can be #3. (This occurs in
+ * QueryBuilder's metadata where the return param happens to be created in between the two
+ * input params and is numbered #2, but is not loaded into QueryBuilder's runtime env).
+ * When the user's query is parsed and resolved, the placeholder
+ * input params are numbered #1 and #2. This test tests that this disparity in ordering should not
+ * be a problem as long as RELATIVE ordering is in synch.
+ */
+ @Test public void testStoredQueryParamOrdering_8211() {
+ StoredProcedure proc = (StoredProcedure) helpResolve("EXEC pm1.sq3a('abc', 123)"); //$NON-NLS-1$
+
+ // Check number of resolved parameters
+ List<SPParameter> params = proc.getParameters();
+ assertEquals("Did not get expected parameter count", 3, params.size()); //$NON-NLS-1$
+
+ // Check resolved parameters
+ 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 = 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) {
+ 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$
+ assertEquals("Did not get expected type for param", type, param.getClassType()); //$NON-NLS-1$
+ assertEquals("Did not get expected type for param", expr, param.getExpression()); //$NON-NLS-1$
+ }
+
+ @Test public void testStoredSubQuery1() {
+ Query resolvedQuery = (Query) helpResolve("select x.e1 from (EXEC pm1.sq1()) as x"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "x.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testStoredSubQuery2() {
+ Query resolvedQuery = (Query) helpResolve("select x.e1 from (EXEC pm1.sq3('abc', 5)) as x"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "x.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testStoredSubQuery3() {
+ Query resolvedQuery = (Query) helpResolve("select * from (EXEC pm1.sq2('abc')) as x"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
+
+ List elements = (List) ElementCollectorVisitor.getElements(resolvedQuery.getSelect(), false);
+
+ ElementSymbol elem1 = (ElementSymbol)elements.get(0);
+ assertEquals("Did not get expected element", "x.e1", elem1.getName() ); //$NON-NLS-1$ //$NON-NLS-2$
+ assertEquals("Did not get expected type", DataTypeManager.DefaultDataClasses.STRING, elem1.getType()); //$NON-NLS-1$
+
+ ElementSymbol elem2 = (ElementSymbol)elements.get(1);
+ assertEquals("Did not get expected element", "x.e2", elem2.getName() ); //$NON-NLS-1$ //$NON-NLS-2$
+ assertEquals("Did not get expected type", DataTypeManager.DefaultDataClasses.INTEGER, elem2.getType()); //$NON-NLS-1$
+ }
+
+ @Test public void testStoredQueryTransformationWithVariable4() throws Exception {
+ Command command = QueryParser.getQueryParser().parseCommand("EXEC pm1.sq2(pm1.sq2.in)"); //$NON-NLS-1$
+
+ // resolve
+ try {
+ // Construct command metadata
+ GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
+ ArrayList sqParams = new ArrayList();
+ ElementSymbol in = new ElementSymbol("pm1.sq5.in1"); //$NON-NLS-1$
+ in.setType(DataTypeManager.DefaultDataClasses.STRING);
+ sqParams.add(in);
+ Map externalMetadata = new HashMap();
+ externalMetadata.put(sqGroup, sqParams);
+
+ QueryResolver.resolveCommand(command, metadata);
+
+ fail("Expected exception on invalid variable pm1.sq2.in"); //$NON-NLS-1$
+ } catch(QueryResolverException e) {
+ assertEquals("Symbol pm1.sq2.\"in\" is specified with an unknown group context", e.getMessage()); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testExec1() {
+ helpResolve("EXEC pm1.sq2('xyz')"); //$NON-NLS-1$
+ }
+
+ @Test public void testExec2() {
+ // implicity convert 5 to proper type
+ helpResolve("EXEC pm1.sq2(5)"); //$NON-NLS-1$
+ }
+
+ @Test public void testExecNamedParam() {
+ Object[] expectedParameterExpressions = new Object[] {new Constant("xyz")};//$NON-NLS-1$
+ helpResolveExec("EXEC pm1.sq2(\"in\" = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
+ }
+
+ @Test public void testExecNamedParamDup() {
+ helpResolveException("EXEC pm1.sq2(\"in\" = 'xyz', \"in\" = 'xyz1')");//$NON-NLS-1$
+ }
+
+ /** Should get exception because param name is wrong. */
+ @Test public void testExecWrongParamName() {
+ helpResolveException("EXEC pm1.sq2(in1 = 'xyz')");//$NON-NLS-1$
+ }
+
+ @Test public void testExecNamedParams() {
+ Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(new Integer(5))};//$NON-NLS-1$
+ helpResolveExec("EXEC pm1.sq3(\"in\" = 'xyz', in2 = 5)", expectedParameterExpressions);//$NON-NLS-1$
+ }
+
+ /** try entering params out of order */
+ @Test public void testExecNamedParamsReversed() {
+ Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(new Integer(5))};//$NON-NLS-1$
+ helpResolveExec("EXEC pm1.sq3(in2 = 5, \"in\" = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
+ }
+
+ /** test omitting an optional parameter */
+ @Test public void testExecNamedParamsOptionalParam() {
+ Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(null), new Constant("something")};//$NON-NLS-1$ //$NON-NLS-2$
+ helpResolveExec("EXEC pm1.sq3b(\"in\" = 'xyz', in3 = 'something')", expectedParameterExpressions);//$NON-NLS-1$
+ }
+
+ /** test omitting a required parameter that has a default value */
+ @Test public void testExecNamedParamsOmitRequiredParamWithDefaultValue() {
+ Object[] expectedParameterExpressions = new Object[] {new Constant("xyz"), new Constant(new Integer(666)), new Constant("YYZ")};//$NON-NLS-1$ //$NON-NLS-2$
+ StoredProcedure sp = helpResolveExec("EXEC pm1.sq3b(\"in\" = 'xyz', in2 = 666)", expectedParameterExpressions);//$NON-NLS-1$
+ assertEquals("EXEC pm1.sq3b(\"in\" => 'xyz', in2 => 666)", sp.toString());
+ }
+
+ @Test public void testExecNamedParamsOptionalParamWithDefaults() {
+ Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
+ //override the default value for the first parameter
+ expectedParameterExpressions[0] = new Constant("xyz"); //$NON-NLS-1$
+ helpResolveExec("EXEC pm1.sqDefaults(inString = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
+ }
+
+ @Test public void testExecNamedParamsOptionalParamWithDefaultsCaseInsensitive() {
+ Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
+ //override the default value for the first parameter
+ expectedParameterExpressions[0] = new Constant("xyz"); //$NON-NLS-1$
+ helpResolveExec("EXEC pm1.sqDefaults(iNsTrInG = 'xyz')", expectedParameterExpressions);//$NON-NLS-1$
+ }
+
+ /** try just a few named parameters, in no particular order */
+ @Test public void testExecNamedParamsOptionalParamWithDefaults2() {
+ Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
+ //override the proper default values in expected results
+ expectedParameterExpressions[3] = new Constant(Boolean.FALSE);
+ expectedParameterExpressions[9] = new Constant(new Integer(666));
+ helpResolveExec("EXEC pm1.sqDefaults(ininteger = 666, inboolean={b'false'})", expectedParameterExpressions);//$NON-NLS-1$
+ }
+
+ /**
+ * Try entering in no actual parameters, rely entirely on defaults.
+ * This also tests the default value transformation code in ExecResolver.
+ */
+ @Test public void testExecNamedParamsOptionalParamWithAllDefaults() {
+ Object[] expectedParameterExpressions = helpGetStoredProcDefaultValues();
+ helpResolveExec("EXEC pm1.sqDefaults()", expectedParameterExpressions);//$NON-NLS-1$
+ }
+
+ /**
+ * Retrieve the Object array of expected default values for the stored procedure
+ * "pm1.sqDefaults" in FakeMetadataFactory.example1().
+ * @return
+ * @since 4.3
+ */
+ private Object[] helpGetStoredProcDefaultValues() {
+
+ // This needs to match what's in FakeMetadataFactory.example1 for this stored proc
+ return new Object[] {
+ new Constant("x"), //$NON-NLS-1$
+ new Constant(new BigDecimal("13.0")),//$NON-NLS-1$
+ new Constant(new BigInteger("13")),//$NON-NLS-1$
+ new Constant(Boolean.TRUE),
+ new Constant(new Byte("1")),//$NON-NLS-1$
+ new Constant(new Character('q')),
+ new Constant(Date.valueOf("2003-03-20")),//$NON-NLS-1$
+ new Constant(new Double(13.0)),
+ new Constant(new Float(13.0)),
+ new Constant(new Integer(13)),
+ new Constant(new Long(13)),
+ new Constant(new Short((short)13)),
+ new Constant(Timestamp.valueOf("2003-03-20 21:26:00.000000")),//$NON-NLS-1$
+ new Constant(Time.valueOf("21:26:00")),//$NON-NLS-1$
+ };
+ }
+
+ /** Should get exception because there are two required params */
+ @Test public void testExceptionNotSupplyingRequiredParam() {
+ helpResolveException("EXEC pm1.sq3(in2 = 5)");//$NON-NLS-1$
+ }
+
+ /** Should get exception because the default value in metadata is bad for input param */
+ @Test public void testExceptionBadDefaultValue() {
+ helpResolveException("EXEC pm1.sqBadDefault()");//$NON-NLS-1$
+ }
+
+ @Test public void testExecWithForcedConvertOfStringToCorrectType() {
+ // force conversion of '5' to proper type (integer)
+ helpResolve("EXEC pm1.sq3('x', '5')"); //$NON-NLS-1$
+ }
+
+ /**
+ * True/false are consistently representable by integers
+ */
+ @Test public void testExecBadType() {
+ helpResolve("EXEC pm1.sq3('xyz', {b'true'})"); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryInUnion() {
+ String sql = "SELECT IntKey, FloatNum FROM BQT1.MediumA WHERE (IntKey >= 0) AND (IntKey < 15) " + //$NON-NLS-1$
+ "UNION ALL " + //$NON-NLS-1$
+ "SELECT BQT2.SmallB.IntKey, y.FloatNum " + //$NON-NLS-1$
+ "FROM BQT2.SmallB INNER JOIN " + //$NON-NLS-1$
+ "(SELECT IntKey, FloatNum FROM BQT1.MediumA ) AS y ON BQT2.SmallB.IntKey = y.IntKey " + //$NON-NLS-1$
+ "WHERE (y.IntKey >= 10) AND (y.IntKey < 30) " + //$NON-NLS-1$
+ "ORDER BY IntKey, FloatNum"; //$NON-NLS-1$
+
+ helpResolve(sql, RealMetadataFactory.exampleBQTCached());
+ }
+
+ @Test public void testSubQueryINClause1(){
+ //select e1 from pm1.g1 where e2 in (select e2 from pm4.g1)
+
+ //sub command
+ Select innerSelect = new Select();
+ ElementSymbol e2inner = new ElementSymbol("e2"); //$NON-NLS-1$
+ innerSelect.addSymbol(e2inner);
+ From innerFrom = new From();
+ GroupSymbol pm4g1 = new GroupSymbol("pm4.g1"); //$NON-NLS-1$
+ innerFrom.addGroup(pm4g1);
+ Query innerQuery = new Query();
+ innerQuery.setSelect(innerSelect);
+ innerQuery.setFrom(innerFrom);
+
+ //outer command
+ Select outerSelect = new Select();
+ ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ outerSelect.addSymbol(e1);
+ From outerFrom = new From();
+ GroupSymbol pm1g1 = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
+ outerFrom.addGroup(pm1g1);
+ ElementSymbol e2outer = new ElementSymbol("e2"); //$NON-NLS-1$
+ SubquerySetCriteria crit = new SubquerySetCriteria(e2outer, innerQuery);
+ Query outerQuery = new Query();
+ outerQuery.setSelect(outerSelect);
+ outerQuery.setFrom(outerFrom);
+ outerQuery.setCriteria(crit);
+
+ //test
+ helpResolve(outerQuery);
+
+ helpCheckFrom(outerQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckFrom(innerQuery, new String[] { "pm4.g1" }); //$NON-NLS-1$
+ helpCheckSelect(outerQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ helpCheckSelect(innerQuery, new String[] { "pm4.g1.e2" }); //$NON-NLS-1$
+ helpCheckElements(outerQuery.getSelect(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+ helpCheckElements(innerQuery.getSelect(),
+ new String[] { "pm4.g1.e2" }, //$NON-NLS-1$
+ new String[] { "pm4.g1.e2" } ); //$NON-NLS-1$
+
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm4.g1)"; //$NON-NLS-1$
+ assertEquals("Resolved string form was incorrect ", sql, outerQuery.toString()); //$NON-NLS-1$
+ }
+
+ /**
+ * An implicit type conversion needs to be inserted because the
+ * project symbol of the subquery is not the same type as the expression in
+ * the SubquerySetCriteria object
+ */
+ @Test public void testSubQueryINClauseImplicitConversion(){
+ //select e1 from pm1.g1 where e2 in (select e1 from pm4.g1)
+
+ //sub command
+ Select innerSelect = new Select();
+ ElementSymbol e1inner = new ElementSymbol("e1"); //$NON-NLS-1$
+ innerSelect.addSymbol(e1inner);
+ From innerFrom = new From();
+ GroupSymbol pm4g1 = new GroupSymbol("pm4.g1"); //$NON-NLS-1$
+ innerFrom.addGroup(pm4g1);
+ Query innerQuery = new Query();
+ innerQuery.setSelect(innerSelect);
+ innerQuery.setFrom(innerFrom);
+
+ //outer command
+ Select outerSelect = new Select();
+ ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ outerSelect.addSymbol(e1);
+ From outerFrom = new From();
+ GroupSymbol pm1g1 = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
+ outerFrom.addGroup(pm1g1);
+ ElementSymbol e2 = new ElementSymbol("e2"); //$NON-NLS-1$
+ SubquerySetCriteria crit = new SubquerySetCriteria(e2, innerQuery);
+ Query outerQuery = new Query();
+ outerQuery.setSelect(outerSelect);
+ outerQuery.setFrom(outerFrom);
+ outerQuery.setCriteria(crit);
+
+ //test
+ helpResolve(outerQuery);
+
+ helpCheckFrom(outerQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckFrom(innerQuery, new String[] { "pm4.g1" }); //$NON-NLS-1$
+ helpCheckSelect(outerQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ helpCheckSelect(innerQuery, new String[] { "pm4.g1.e1" }); //$NON-NLS-1$
+ helpCheckElements(outerQuery.getSelect(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+ helpCheckElements(innerQuery.getSelect(),
+ new String[] { "pm4.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm4.g1.e1" } ); //$NON-NLS-1$
+
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e1 FROM pm4.g1)"; //$NON-NLS-1$
+ assertEquals("Resolved string form was incorrect ", sql, outerQuery.toString()); //$NON-NLS-1$
+
+ //make sure there is a convert function wrapping the criteria left expression
+ Collection functions = FunctionCollectorVisitor.getFunctions(outerQuery, true);
+ assertTrue(functions.size() == 1);
+ Function function = (Function)functions.iterator().next();
+ assertTrue(function.getName().equals(FunctionLibrary.CONVERT));
+ Expression[] args = function.getArgs();
+ assertSame(e2, args[0]);
+ assertTrue(args[1] instanceof Constant);
+ }
+
+ /**
+ * Tests that resolving fails if there is no implicit conversion between the
+ * type of the expression of the SubquerySetCriteria and the type of the
+ * projected symbol of the subquery.
+ */
+ @Test public void testSubQueryINClauseNoConversionFails(){
+ //select e1 from pm1.g1 where e1 in (select e2 from pm4.g1)
+
+ //sub command
+ Select innerSelect = new Select();
+ ElementSymbol e2inner = new ElementSymbol("e2"); //$NON-NLS-1$
+ innerSelect.addSymbol(e2inner);
+ From innerFrom = new From();
+ GroupSymbol pm4g1 = new GroupSymbol("pm4.g1"); //$NON-NLS-1$
+ innerFrom.addGroup(pm4g1);
+ Query innerQuery = new Query();
+ innerQuery.setSelect(innerSelect);
+ innerQuery.setFrom(innerFrom);
+
+ //outer command
+ Select outerSelect = new Select();
+ ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
+ outerSelect.addSymbol(e1);
+ From outerFrom = new From();
+ GroupSymbol pm1g1 = new GroupSymbol("pm1.g1"); //$NON-NLS-1$
+ outerFrom.addGroup(pm1g1);
+ SubquerySetCriteria crit = new SubquerySetCriteria(e1, innerQuery);
+ Query outerQuery = new Query();
+ outerQuery.setSelect(outerSelect);
+ outerQuery.setFrom(outerFrom);
+ outerQuery.setCriteria(crit);
+
+ //test
+ this.helpResolveFails(outerQuery);
+ }
+
+ @Test public void testSubQueryINClauseTooManyColumns(){
+ String sql = "select e1 from pm1.g1 where e1 in (select e1, e2 from pm4.g1)"; //$NON-NLS-1$
+
+ //test
+ this.helpResolveException(sql);
+ }
+
+ @Test public void testStoredQueryInFROMSubquery() {
+ String sql = "select X.e1 from (EXEC pm1.sq3('abc', 123)) as X"; //$NON-NLS-1$
+
+ helpResolve(sql);
+ }
+
+ @Test public void testStoredQueryInINSubquery() throws Exception {
+ String sql = "select * from pm1.g1 where e1 in (EXEC pm1.sqsp1())"; //$NON-NLS-1$
+
+ helpResolve(sql);
+ }
+
+ @Test public void testIsXMLQuery1() throws Exception {
+ helpTestIsXMLQuery("SELECT * FROM pm1.g1", false); //$NON-NLS-1$
+ }
+
+ @Test public void testIsXMLQuery2() throws Exception {
+ helpTestIsXMLQuery("SELECT * FROM xmltest.doc1", true); //$NON-NLS-1$
+ }
+
+ /**
+ * Must be able to resolve XML query if short doc name
+ * is used (assuming short doc name isn't ambiguous in a
+ * VDB). Defect 11479.
+ */
+ @Test public void testIsXMLQuery3() throws Exception {
+ helpTestIsXMLQuery("SELECT * FROM doc1", true); //$NON-NLS-1$
+ }
+
+ @Test public void testIsXMLQueryFail1() throws Exception {
+ helpTestIsXMLQuery("SELECT * FROM xmltest.doc1, xmltest.doc2", false); //$NON-NLS-1$
+ }
+
+ @Test public void testIsXMLQueryFail2() throws Exception {
+ helpTestIsXMLQuery("SELECT * FROM xmltest.doc1, pm1.g1", false); //$NON-NLS-1$
+ }
+
+ @Test public void testIsXMLQueryFail3() throws Exception {
+ helpTestIsXMLQuery("SELECT * FROM pm1.g1, xmltest.doc1", false); //$NON-NLS-1$
+ }
+
+ /**
+ * "docA" is ambiguous as there exist two documents called
+ * xmlTest2.docA and xmlTest3.docA. Defect 11479.
+ */
+ @Test public void testIsXMLQueryFail4() throws Exception {
+ Query query = (Query) helpParse("SELECT * FROM docA"); //$NON-NLS-1$
+
+ try {
+ QueryResolver.isXMLQuery(query, metadata);
+ fail("expected exception"); //$NON-NLS-1$
+ } catch (QueryResolverException e) {
+ assertEquals("Group specified is ambiguous, resubmit the query by fully qualifying the group name: docA", e.getMessage()); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testStringConversion1() {
+ // Expected left expression
+ ElementSymbol e1 = new ElementSymbol("pm3.g1.e2"); //$NON-NLS-1$
+ e1.setType(DataTypeManager.DefaultDataClasses.DATE);
+
+ // Expected right expression
+ Class srcType = DataTypeManager.DefaultDataClasses.STRING;
+ String tgtTypeName = DataTypeManager.DefaultDataTypes.DATE;
+ Expression expression = new Constant("2003-02-27"); //$NON-NLS-1$
+
+ 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) });
+ conversion.setType(DataTypeManager.getDataTypeClass(tgtTypeName));
+ conversion.setFunctionDescriptor(fd);
+ conversion.makeImplicit();
+
+ // Expected criteria
+ CompareCriteria expected = new CompareCriteria();
+ expected.setLeftExpression(e1);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(conversion);
+
+ // Resolve the query and check against expected objects
+ CompareCriteria actual = (CompareCriteria) helpResolveCriteria("pm3.g1.e2='2003-02-27'"); //$NON-NLS-1$
+
+ //if (! actual.getLeftExpression().equals(expected.getLeftExpression())) {
+ // fail("left exprs not equal");
+ //} else if (!actual.getRightExpression().equals(expected.getRightExpression())) {
+ // fail("right not equal");
+ //}
+
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testStringConversion2() {
+ // Expected left expression
+ ElementSymbol e1 = new ElementSymbol("pm3.g1.e2"); //$NON-NLS-1$
+ e1.setType(DataTypeManager.DefaultDataClasses.DATE);
+
+ // Expected right expression
+ Class srcType = DataTypeManager.DefaultDataClasses.STRING;
+ String tgtTypeName = DataTypeManager.DefaultDataTypes.DATE;
+ Expression expression = new Constant("2003-02-27"); //$NON-NLS-1$
+
+ 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) });
+ conversion.setType(DataTypeManager.getDataTypeClass(tgtTypeName));
+ conversion.setFunctionDescriptor(fd);
+ conversion.makeImplicit();
+
+ // Expected criteria
+ CompareCriteria expected = new CompareCriteria();
+ expected.setLeftExpression(conversion);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(e1);
+
+ // Resolve the query and check against expected objects
+ CompareCriteria actual = (CompareCriteria) helpResolveCriteria("'2003-02-27'=pm3.g1.e2"); //$NON-NLS-1$
+
+ //if (! actual.getLeftExpression().equals(expected.getLeftExpression())) {
+ // fail("Left expressions not equal");
+ //} else if (!actual.getRightExpression().equals(expected.getRightExpression())) {
+ // fail("Right expressions not equal");
+ //}
+
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ // special test for both sides are String
+ @Test public void testStringConversion3() {
+ // Expected left expression
+ ElementSymbol e1 = new ElementSymbol("pm3.g1.e1"); //$NON-NLS-1$
+ e1.setType(DataTypeManager.DefaultDataClasses.STRING);
+
+ // Expected right expression
+ Constant e2 = new Constant("2003-02-27"); //$NON-NLS-1$
+
+ // Expected criteria
+ CompareCriteria expected = new CompareCriteria();
+ expected.setLeftExpression(e1);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(e2);
+
+ // Resolve the query and check against expected objects
+ CompareCriteria actual = (CompareCriteria) helpResolveCriteria("pm3.g1.e1='2003-02-27'"); //$NON-NLS-1$
+
+ //if (! actual.getLeftExpression().equals(expected.getLeftExpression())) {
+ // System.out.println("left exprs not equal");
+ //} else if (!actual.getRightExpression().equals(expected.getRightExpression())) {
+ // System.out.println("right exprs not equal");
+ //}
+
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testDateToTimestampConversion_defect9747() {
+ // Expected left expression
+ ElementSymbol e1 = new ElementSymbol("pm3.g1.e4"); //$NON-NLS-1$
+ e1.setType(DataTypeManager.DefaultDataClasses.TIMESTAMP);
+
+ // Expected right expression
+ Constant e2 = new Constant(TimestampUtil.createDate(96, 0, 31), DataTypeManager.DefaultDataClasses.DATE);
+ Function f1 = new Function("convert", new Expression[] { e2, new Constant(DataTypeManager.DefaultDataTypes.TIMESTAMP)}); //$NON-NLS-1$
+ f1.makeImplicit();
+
+ // Expected criteria
+ CompareCriteria expected = new CompareCriteria();
+ expected.setLeftExpression(e1);
+ expected.setOperator(CompareCriteria.GT);
+ expected.setRightExpression(f1);
+
+ // Resolve the query and check against expected objects
+ CompareCriteria actual = (CompareCriteria) helpResolveCriteria("pm3.g1.e4 > {d '1996-01-31'}"); //$NON-NLS-1$
+
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testFailedConversion_defect9725() throws Exception{
+ helpResolveException("select * from pm3.g1 where pm3.g1.e4 > {b 'true'}", "Error Code:ERR.015.008.0027 Message:The expressions in this criteria are being compared but are of differing types (timestamp and boolean) and no implicit conversion is available: pm3.g1.e4 > TRUE"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testLookupFunction() {
+ String sql = "SELECT lookup('pm1.g1', 'e1', 'e2', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
+ Query resolvedQuery = (Query) helpResolve(sql);
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "x", "y" }); //$NON-NLS-1$ //$NON-NLS-2$
+ helpCheckElements(resolvedQuery.getSelect(),
+ new String[] { "PM1.G1.E2", "PM1.G1.E3" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { "PM1.G1.E2", "PM1.G1.E3" } ); //$NON-NLS-1$ //$NON-NLS-2$
+ assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
+
+ List projSymbols = resolvedQuery.getSelect().getProjectedSymbols();
+ assertEquals("Wrong number of projected symbols", 2, projSymbols.size()); //$NON-NLS-1$
+ assertEquals("Wrong type for first symbol", String.class, ((SingleElementSymbol)projSymbols.get(0)).getType()); //$NON-NLS-1$
+ assertEquals("Wrong type for second symbol", Double.class, ((SingleElementSymbol)projSymbols.get(1)).getType()); //$NON-NLS-1$
+ }
+
+ @Test public void testLookupFunctionFailBadElement() {
+ String sql = "SELECT lookup('nosuch', 'elementhere', 'e2', e2) AS x FROM pm1.g1"; //$NON-NLS-1$
+ helpResolveException(sql);
+ }
+
+ @Test public void testLookupFunctionFailNotConstantArg1() {
+ String sql = "SELECT lookup(e1, 'e1', 'e2', e2) AS x FROM pm1.g1"; //$NON-NLS-1$
+ helpResolveException(sql);
+ }
+
+ @Test public void testLookupFunctionFailNotConstantArg2() {
+ String sql = "SELECT lookup('pm1.g1', e1, 'e2', e2) AS x FROM pm1.g1"; //$NON-NLS-1$
+ helpResolveException(sql);
+ }
+
+ @Test public void testLookupFunctionFailNotConstantArg3() {
+ String sql = "SELECT lookup('pm1.g1', 'e1', e1, e2) AS x FROM pm1.g1"; //$NON-NLS-1$
+ helpResolveException(sql);
+ }
+
+ @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, 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, RealMetadataFactory.example1Cached());
+ }
+
+ @Test public void testLookupFunctionFailBadKeyElement() throws Exception {
+ String sql = "SELECT lookup('pm1.g1', 'e1', 'x', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
+ Command command = QueryParser.getQueryParser().parseCommand(sql);
+ try {
+ QueryResolver.resolveCommand(command, metadata);
+ fail("exception expected"); //$NON-NLS-1$
+ } catch (QueryResolverException e) {
+
+ }
+ }
+
+ @Test public void testNamespacedFunction() throws Exception {
+ String sql = "SELECT namespace.func('e1') FROM vm1.g1 "; //$NON-NLS-1$
+
+ 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
+ @Test public void testSetCriteriaCastFromExpression_9657() {
+ // parse
+ Criteria expected = null;
+ Criteria actual = null;
+ try {
+ actual = QueryParser.getQueryParser().parseCriteria("bqt1.smalla.shortvalue IN (1, 2)"); //$NON-NLS-1$
+ expected = QueryParser.getQueryParser().parseCriteria("convert(bqt1.smalla.shortvalue, integer) IN (1, 2)"); //$NON-NLS-1$
+
+ } catch(TeiidException e) {
+ fail("Exception during parsing (" + e.getClass().getName() + "): " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // resolve
+ try {
+ 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$
+ }
+
+ // Tweak expected to hide convert function - this is expected
+ ((Function) ((SetCriteria)expected).getExpression()).makeImplicit();
+
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ /** select e1 from pm1.g1 where e2 BETWEEN 1000 AND 2000 */
+ @Test public void testBetween1(){
+ String sql = "select e1 from pm1.g1 where e2 BETWEEN 1000 AND 2000"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ /** select e1 from pm1.g1 where e2 NOT BETWEEN 1000 AND 2000 */
+ @Test public void testBetween2(){
+ String sql = "select e1 from pm1.g1 where e2 NOT BETWEEN 1000 AND 2000"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ /** select e2 from pm1.g1 where e4 BETWEEN 1000 AND e2 */
+ @Test public void testBetween3(){
+ String sql = "select e2 from pm1.g1 where e4 BETWEEN 1000 AND e2"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ /** select e2 from pm1.g1 where e2 BETWEEN 1000 AND e4 */
+ @Test public void testBetween4(){
+ String sql = "select e2 from pm1.g1 where e2 BETWEEN 1000 AND e4"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ /** select e1 from pm1.g1 where 1000 BETWEEN e1 AND e2 */
+ @Test public void testBetween5(){
+ String sql = "select e1 from pm1.g1 where 1000 BETWEEN e1 AND e2"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ /** select e1 from pm1.g1 where 1000 BETWEEN e2 AND e1 */
+ @Test public void testBetween6(){
+ String sql = "select e1 from pm1.g1 where 1000 BETWEEN e2 AND e1"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ /** select e1 from pm3.g1 where e2 BETWEEN e3 AND e4 */
+ @Test public void testBetween7(){
+ String sql = "select e1 from pm3.g1 where e2 BETWEEN e3 AND e4"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ /** select pm3.g1.e1 from pm3.g1, pm3.g2 where pm3.g1.e4 BETWEEN pm3.g1.e2 AND pm3.g2.e2 */
+ @Test public void testBetween8(){
+ String sql = "select pm3.g1.e1 from pm3.g1, pm3.g2 where pm3.g1.e4 BETWEEN pm3.g1.e2 AND pm3.g2.e2"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ /** select e1 from pm1.g1 where e2 = any (select e2 from pm4.g1) */
+ @Test public void testCompareSubQuery1(){
+
+ String sql = "select e1 from pm1.g1 where e2 = any (select e2 from pm4.g1)"; //$NON-NLS-1$
+ Query outerQuery = (Query) this.helpResolveSubquery(sql, new String[0]);
+
+ helpCheckFrom(outerQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckSelect(outerQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ helpCheckElements(outerQuery.getSelect(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+// helpCheckFrom(innerQuery, new String[] { "pm4.g1" });
+// helpCheckSelect(innerQuery, new String[] { "pm4.g1.e2" });
+// helpCheckElements(innerQuery.getSelect(),
+// new String[] { "pm4.g1.e2" },
+// new String[] { "pm4.g1.e2" } );
+
+ String sqlActual = "SELECT e1 FROM pm1.g1 WHERE e2 = ANY (SELECT e2 FROM pm4.g1)"; //$NON-NLS-1$
+ assertEquals("Resolved string form was incorrect ", sqlActual, outerQuery.toString()); //$NON-NLS-1$
+ }
+
+ /** select e1 from pm1.g1 where e2 = all (select e2 from pm4.g1) */
+ @Test public void testCompareSubQuery2(){
+ String sql = "select e1 from pm1.g1 where e2 = all (select e2 from pm4.g1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ /** select e1 from pm1.g1 where e2 < (select e2 from pm4.g1 where e1 = '3') */
+ @Test public void testCompareSubQuery3(){
+ String sql = "select e1 from pm1.g1 where e2 < (select e2 from pm4.g1 where e1 = '3')"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ /** select e1 from pm1.g1 where e2 < (select e2 from pm4.g1 where e1 = '3') */
+ @Test public void testCompareSubQueryImplicitConversion(){
+ String sql = "select e1 from pm1.g1 where e1 < (select e2 from pm4.g1 where e1 = '3')"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ @Test public void testExistsSubQuery(){
+ String sql = "select e1 from pm1.g1 where exists (select e2 from pm4.g1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ @Test public void testExistsSubQuery2(){
+ String sql = "select e1 from pm1.g1 where exists (select e1, e2 from pm4.g1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ @Test public void testScalarSubQueryInSelect(){
+ String sql = "select e1, (select e2 from pm4.g1 where e1 = '3') from pm1.g1"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ @Test public void testScalarSubQueryInSelect2(){
+ String sql = "select (select e2 from pm4.g1 where e1 = '3'), e1 from pm1.g1"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ @Test public void testScalarSubQueryInSelectWithAlias(){
+ String sql = "select e1, (select e2 from pm4.g1 where e1 = '3') as X from pm1.g1"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ @Test public void testSelectWithNoFrom() {
+ String sql = "SELECT 5"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @Test public void testSelectWithNoFrom_Alias() {
+ String sql = "SELECT 5 AS INTKEY"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @Test public void testSelectWithNoFrom_Alias_OrderBy() {
+ String sql = "SELECT 5 AS INTKEY ORDER BY INTKEY"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @Test public void testSubqueryCorrelatedInCriteria(){
+ String sql = "select e2 from pm1.g1 where e2 = all (select e2 from pm4.g1 where pm1.g1.e1 = pm4.g1.e1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"pm1.g1.e1"}); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryCorrelatedInCriteria2(){
+ String sql = "select e1 from pm1.g1 where e2 = all (select e2 from pm4.g1 where pm1.g1.e1 = e1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"pm1.g1.e1"}); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryCorrelatedInCriteria3(){
+ String sql = "select e1 from pm1.g1 X where e2 = all (select e2 from pm4.g1 where X.e1 = pm4.g1.e1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryCorrelatedInCriteria4(){
+ String sql = "select e2 from pm1.g1 X where e2 in (select e2 from pm1.g1 Y where X.e1 = Y.e1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryCorrelatedInCriteria5(){
+ String sql = "select e1 from pm1.g1 X where e2 = all (select e2 from pm1.g1 Y where X.e1 = e1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
+ }
+
+ /* 'e5' is only in pm4.g2 */
+ @Test public void testSubqueryCorrelatedInCriteria6(){
+ String sql = "select e1 from pm4.g2 where e2 = some (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+ }
+
+ /* 'e5' is only in pm4.g2 */
+ @Test public void testSubqueryCorrelatedInCriteria7(){
+ String sql = "select e1 from pm4.g2 where exists (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryCorrelatedInHaving(){
+ String sql = "select e1, e2 from pm4.g2 group by e2 having e2 in (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryCorrelatedInHaving2(){
+ String sql = "select e1, e2 from pm4.g2 group by e2 having e2 <= all (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+ }
+
+ /* 'e5' is only in pm4.g2 */
+ @Test public void testSubqueryCorrelatedInSelect(){
+ String sql = "select e1, (select e2 from pm4.g1 where e5 = e1) from pm4.g2"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryCorrelatedInSelect2(){
+ String sql = "select e1, (select e2 from pm4.g1 where pm4.g2.e5 = e1) from pm4.g2"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryCorrelatedInSelect3(){
+ String sql = "select e1, (select e2 from pm4.g1 Y where X.e5 = Y.e1) from pm4.g2 X"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"X.e5"}); //$NON-NLS-1$
+ }
+
+ /* 'e5' is only in pm4.g2 */
+ @Test public void testNestedCorrelatedSubqueries(){
+ String sql = "select e1, (select e2 from pm1.g1 where e2 = all (select e2 from pm4.g1 where e5 = e1)) from pm4.g2"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"pm4.g2.e5"}); //$NON-NLS-1$
+ }
+
+ /**
+ * 'e5' is in pm4.g2, so it will be resolved to the group aliased as 'Y'
+ */
+ @Test public void testNestedCorrelatedSubqueries2(){
+ String sql = "select e1, (select e2 from pm4.g2 Y where e2 = all (select e2 from pm4.g1 where e5 = e1)) from pm4.g2 X"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"Y.e5"}); //$NON-NLS-1$
+ }
+
+ /**
+ * 'e5' is in pm4.g2; it will be resolved to the group aliased as 'X'
+ */
+ @Test public void testNestedCorrelatedSubqueries3(){
+ String sql = "select e1, (select e2 from pm4.g2 Y where e2 = all (select e2 from pm4.g1 where X.e5 = e1)) from pm4.g2 X"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"X.e5"}); //$NON-NLS-1$
+ }
+
+ /**
+ * 'e5' is in X and Y
+ */
+ @Test public void testNestedCorrelatedSubqueries4(){
+ String sql = "select X.e2 from pm4.g2 Y, pm4.g2 X where X.e2 = all (select e2 from pm4.g1 where e5 = e1)"; //$NON-NLS-1$
+ helpResolveException(sql, metadata, "Element \"e5\" is ambiguous, it exists in two or more groups."); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryCorrelatedInCriteriaVirtualLayer(){
+ String sql = "select e2 from vm1.g1 where e2 = all (select e2 from vm1.g2 where vm1.g1.e1 = vm1.g2.e1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"vm1.g1.e1"}); //$NON-NLS-1$
+ }
+
+ @Test public void testSubqueryCorrelatedInCriteriaVirtualLayer2(){
+ String sql = "select e2 from vm1.g1 X where e2 = all (select e2 from vm1.g2 where X.e1 = vm1.g2.e1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[]{"X.e1"}); //$NON-NLS-1$
+ }
+
+ /**
+ * Although this query makes no sense, the "e1" in the nested criteria is
+ * NOT a correlated reference
+ */
+ @Test public void testSubqueryNonCorrelatedInCriteria(){
+ String sql = "select e2 from pm1.g1 where e2 = all (select e2 from pm4.g1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ /**
+ * Although this query makes no sense, the "e1" in the nested criteria is
+ * NOT a correlated reference
+ */
+ @Test public void testSubqueryNonCorrelatedInCriteria2(){
+ String sql = "SELECT e1 FROM pm1.g1 WHERE e2 IN (SELECT e2 FROM pm2.g1 WHERE e1 IN (SELECT e1 FROM pm1.g1))"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ /**
+ * Although this query makes no sense, the "e1" in the nested criteria is
+ * NOT a correlated reference
+ */
+ @Test public void testSubqueryNonCorrelatedInCriteria3(){
+ String sql = "SELECT e2 FROM pm2.g1 WHERE e1 IN (SELECT e1 FROM pm1.g1)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ /**
+ * The group pm1.g1 in the FROM clause of the subquery should resolve to the
+ * group in metadata, not the temporary child metadata group defined by the
+ * outer query.
+ */
+ @Test public void testSubquery_defect10090(){
+ String sql = "select pm1.g1.e1 from pm1.g1 where pm1.g1.e2 in (select pm1.g1.e2 from pm1.g1 where pm1.g1.e4 = 2.0)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ /**
+ * Workaround is to alias group in FROM of outer query (aliasing subquery group doesn't work)
+ */
+ @Test public void testSubquery_defect10090Workaround(){
+ String sql = "select X.e1 from pm1.g1 X where X.e2 in (select pm1.g1.e2 from pm1.g1 where pm1.g1.e4 = 2.0)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ @Test public void testSubquery2_defect10090(){
+ String sql = "select pm1.g1.e1 from pm1.g1 where pm1.g1.e2 in (select X.e2 from pm1.g1 X where X.e4 = 2.0)"; //$NON-NLS-1$
+ this.helpResolveSubquery(sql, new String[0]);
+ }
+
+ /** test jdbc USER method */
+ @Test public void testUser() {
+ //String sql = "select intkey from SmallA where user() = 'bqt2'";
+
+ // Expected left expression
+ FunctionLibrary library = RealMetadataFactory.SFM.getSystemFunctionLibrary();
+ FunctionDescriptor fd = library.findFunction(FunctionLibrary.USER, new Class[] { });
+ Function user = new Function(fd.getName(), new Expression[] {});
+ user.setFunctionDescriptor(fd);
+
+ // Expected criteria
+ CompareCriteria expected = new CompareCriteria();
+ // Expected right expression
+ Expression e1 = new Constant("bqt2", String.class); //$NON-NLS-1$
+ // Expected left expression
+ expected.setLeftExpression(user);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(e1);
+
+ // Resolve the query and check against expected objects
+ CompareCriteria actual = (CompareCriteria) helpResolveCriteria("user()='bqt2'"); //$NON-NLS-1$
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testCaseExpression1() {
+ String sql = "SELECT e1, CASE e2 WHEN 0 THEN 20 WHEN 1 THEN 21 WHEN 2 THEN 500 END AS testElement FROM pm1.g1" //$NON-NLS-1$
+ +" WHERE e1 = CASE WHEN e2 = 0 THEN 'a' WHEN e2 = 1 THEN 'b' ELSE 'c' END"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+
+ @Test public void testCaseExpression2() {
+ // nested case expressions
+ String sql = "SELECT CASE e2" + //$NON-NLS-1$
+ " WHEN 0 THEN CASE e1 " + //$NON-NLS-1$
+ " WHEN 'a' THEN 100" + //$NON-NLS-1$
+ " WHEN 'b' THEN 200 " + //$NON-NLS-1$
+ " ELSE 1000 " + //$NON-NLS-1$
+ " END" + //$NON-NLS-1$
+ " WHEN 1 THEN 21" + //$NON-NLS-1$
+ " WHEN (CASE WHEN e1 = 'z' THEN 2 WHEN e1 = 'y' THEN 100 ELSE 3 END) THEN 500" + //$NON-NLS-1$
+ " END AS testElement FROM pm1.g1"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @Test public void testCaseExpressionWithNestedFunction() {
+ String sql = "SELECT CASE WHEN e2 < 0 THEN abs(CASE WHEN e2 < 0 THEN -1 ELSE e2 END)" + //$NON-NLS-1$
+ " ELSE e2 END FROM pm1.g1"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @Test public void testFunctionWithNestedCaseExpression() {
+ String sql = "SELECT abs(CASE e1 WHEN 'testString1' THEN -13" + //$NON-NLS-1$
+ " WHEN 'testString2' THEN -5" + //$NON-NLS-1$
+ " ELSE abs(e2)" + //$NON-NLS-1$
+ " END) AS absVal FROM pm1.g1"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @Test public void testDefect10809(){
+ String sql = "select * from LOB_TESTING_ONE where CLOB_COLUMN LIKE '%fff%'"; //$NON-NLS-1$
+ helpResolve(helpParse(sql), RealMetadataFactory.exampleBQTCached());
+ }
+
+ @Test public void testNonAutoConversionOfLiteralIntegerToShort() throws Exception {
+ // parse
+ Query command = (Query) QueryParser.getQueryParser().parseCommand("SELECT intkey FROM bqt1.smalla WHERE shortvalue = 5"); //$NON-NLS-1$
+
+ // resolve
+ QueryResolver.resolveCommand(command, RealMetadataFactory.exampleBQTCached());
+
+ // Check whether an implicit conversion was added on the correct side
+ CompareCriteria crit = (CompareCriteria) command.getCriteria();
+
+ assertEquals(DataTypeManager.DefaultDataClasses.SHORT, crit.getRightExpression().getType());
+ assertEquals("Sql is incorrect after resolving", "SELECT intkey FROM bqt1.smalla WHERE shortvalue = 5", command.toString()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testNonAutoConversionOfLiteralIntegerToShort2() throws Exception {
+ // parse
+ Query command = (Query) QueryParser.getQueryParser().parseCommand("SELECT intkey FROM bqt1.smalla WHERE 5 = shortvalue"); //$NON-NLS-1$
+
+ // resolve
+ QueryResolver.resolveCommand(command, RealMetadataFactory.exampleBQTCached());
+
+ // Check whether an implicit conversion was added on the correct side
+ CompareCriteria crit = (CompareCriteria) command.getCriteria();
+
+ assertEquals(DataTypeManager.DefaultDataClasses.SHORT, crit.getLeftExpression().getType());
+ assertEquals("Sql is incorrect after resolving", "SELECT intkey FROM bqt1.smalla WHERE 5 = shortvalue", command.toString()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testAliasedOrderBy() {
+ Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1 as y FROM pm1.g1 ORDER BY y"); //$NON-NLS-1$
+ helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
+ helpCheckSelect(resolvedQuery, new String[] { "y" }); //$NON-NLS-1$
+ }
+
+ @Test public void testUnaliasedOrderBySucceeds() {
+ helpResolve("SELECT pm1.g1.e1 a, pm1.g1.e1 b FROM pm1.g1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
+ }
+
+ @Test public void testUnaliasedOrderBySucceeds1() {
+ helpResolve("SELECT pm1.g1.e1 a FROM pm1.g1 group by pm1.g1.e1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
+ }
+
+ @Test public void testUnaliasedOrderByFails() {
+ helpResolveException("SELECT pm1.g1.e1 e2 FROM pm1.g1 group by pm1.g1.e1 ORDER BY pm1.g1.e2"); //$NON-NLS-1$
+ }
+
+ @Test public void testUnaliasedOrderByFails1() {
+ helpResolveException("SELECT pm1.g1.e1 e2 FROM pm1.g1 group by pm1.g1.e1 ORDER BY pm1.g1.e2 + 1"); //$NON-NLS-1$
+ }
+
+ /**
+ * the group g1 is not known to the order by clause of a union
+ */
+ @Test public void testUnionOrderByFail() {
+ helpResolveException("SELECT pm1.g1.e1 FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY g1.e1", "ORDER BY expression 'g1.e1' cannot be used with a set query."); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testUnionOrderByFail1() {
+ helpResolveException("SELECT pm1.g1.e1 FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY pm1.g1.e1", "ORDER BY expression 'pm1.g1.e1' cannot be used with a set query."); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testOrderByPartiallyQualified() {
+ helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY g1.e1"); //$NON-NLS-1$
+ }
+
+ /**
+ * the group g1 is not known to the order by clause of a union
+ */
+ @Test public void testUnionOrderBy() {
+ helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY e1"); //$NON-NLS-1$
+ }
+
+ /**
+ * Test for defect 12087 - Insert with implicit conversion from integer to short
+ */
+ @Test public void testImplConversionBetweenIntAndShort() throws Exception {
+ Insert command = (Insert)QueryParser.getQueryParser().parseCommand("Insert into pm5.g3(e2) Values(100)"); //$NON-NLS-1$
+ QueryResolver.resolveCommand(command, metadata);
+ assertTrue(((Expression)command.getValues().get(0)).getType() == DataTypeManager.DefaultDataClasses.SHORT);
+ }
+
+ public static TransformationMetadata example_12968() {
+ MetadataStore metadataStore = new MetadataStore();
+ // Create models
+ Schema pm1 = RealMetadataFactory.createPhysicalModel("myModel", metadataStore); //$NON-NLS-1$
+ Schema pm2 = RealMetadataFactory.createPhysicalModel("myModel2", metadataStore); //$NON-NLS-1$
+
+ Table pm1g1 = RealMetadataFactory.createPhysicalGroup("myTable", pm1); //$NON-NLS-1$
+ Table pm2g1 = RealMetadataFactory.createPhysicalGroup("mySchema.myTable2", pm2); //$NON-NLS-1$
+
+ RealMetadataFactory.createElements(pm1g1,
+ new String[] { "myColumn", "myColumn2" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+ RealMetadataFactory.createElements(pm2g1,
+ new String[] { "myColumn", "myColumn2" }, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "12968");
+ }
+
+ @Test public void testDefect12968_union() {
+ helpResolve(
+ helpParse("SELECT myModel.myTable.myColumn AS myColumn from myModel.myTable UNION " + //$NON-NLS-1$
+ "SELECT convert(null, string) AS myColumn From myModel2.mySchema.myTable2"), //$NON-NLS-1$
+ example_12968());
+ }
+
+
+ @Test public void testUnionQueryWithNull() throws Exception{
+ helpResolve("SELECT NULL, e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
+ helpResolve("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT NULL, e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
+ helpResolve("SELECT e1, NULL FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
+ helpResolve("SELECT e1, NULL FROM pm1.g2 UNION ALL SELECT e1, NULL FROM pm1.g3"); //$NON-NLS-1$
+ helpResolve("SELECT e1, NULL as e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$
+ helpResolve("SELECT e1, NULL as e2 FROM pm1.g1 UNION ALL SELECT e1, e3 FROM pm1.g2"); //$NON-NLS-1$
+ }
+
+ @Test public void testUnionQueryWithDiffTypes() throws Exception{
+ helpResolve("SELECT e1, e3 FROM pm1.g1 UNION ALL SELECT e2, e3 FROM pm1.g2"); //$NON-NLS-1$
+ helpResolve("SELECT e1, e3 FROM pm1.g1 UNION ALL SELECT e2, e3 FROM pm1.g2 UNION ALL SELECT NULL, e3 FROM pm1.g2"); //$NON-NLS-1$
+ helpResolve("SELECT e1, e3 FROM pm1.g1 UNION ALL SELECT e3, e3 FROM pm1.g2 UNION ALL SELECT NULL, e3 FROM pm1.g2"); //$NON-NLS-1$
+ helpResolve("SELECT e1, e2 FROM pm1.g3 UNION ALL SELECT MAX(e4), e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2"); //$NON-NLS-1$
+ helpResolve("SELECT e1, e4 FROM pm1.g1 UNION ALL SELECT e2, e3 FROM pm1.g2"); //$NON-NLS-1$
+ helpResolve("SELECT e4, e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2"); //$NON-NLS-1$
+ helpResolve("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT e3, e4 FROM pm1.g2"); //$NON-NLS-1$
+ helpResolve("SELECT e4, e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g2"); //$NON-NLS-1$
+ helpResolve("SELECT e4, e2 FROM pm1.g1 UNION ALL SELECT e1, e2 FROM pm1.g2"); //$NON-NLS-1$
+ helpResolve("SELECT MAX(e4), e2 FROM pm1.g1 UNION ALL SELECT e3, e2 FROM pm1.g2"); //$NON-NLS-1$
+ //chooses a common type
+ helpResolve("select e2 from pm3.g1 union select e3 from pm3.g1 union select e4 from pm3.g1"); //$NON-NLS-1$
+ }
+
+ @Test public void testUnionQueryWithDiffTypesFails() throws Exception{
+ helpResolveException("SELECT e1 FROM pm1.g1 UNION (SELECT e2 FROM pm1.g2 UNION SELECT e2 from pm1.g1 order by e2)", "The Expression e2 used in a nested UNION ORDER BY clause cannot be implicitly converted from type integer to type string."); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testNestedUnionQueryWithNull() throws Exception{
+ SetQuery command = (SetQuery)helpResolve("SELECT e2, e3 FROM pm1.g1 UNION (SELECT null, e3 FROM pm1.g2 UNION SELECT null, e3 from pm1.g1)"); //$NON-NLS-1$
+
+ assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(0)).getType());
+ }
+
+ @Test public void testUnionQueryClone() throws Exception{
+ SetQuery command = (SetQuery)helpResolve("SELECT e2, e3 FROM pm1.g1 UNION SELECT e3, e2 from pm1.g1"); //$NON-NLS-1$
+
+ assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(1)).getType());
+
+ command = (SetQuery)command.clone();
+
+ assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((SingleElementSymbol)command.getProjectedSymbols().get(1)).getType());
+ }
+
+ @Test public void testSelectIntoNoFrom() {
+ helpResolve("SELECT 'a', 19, {b'true'}, 13.999 INTO pm1.g1"); //$NON-NLS-1$
+ }
+
+ @Test public void testSelectInto() {
+ helpResolve("SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2"); //$NON-NLS-1$
+ }
+
+ @Test public void testSelectIntoTempGroup() {
+ helpResolve("SELECT 'a', 19, {b'true'}, 13.999 INTO #myTempTable"); //$NON-NLS-1$
+ helpResolve("SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g1"); //$NON-NLS-1$
+ }
+
+ //procedural relational mapping
+ @Test public void testProcInVirtualGroup1(){
+ String sql = "select e1 from pm1.vsp26 where param1=1 and param2='a'"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @Test public void testProcInVirtualGroup2(){
+ String sql = "select * from pm1.vsp26 as p where param1=1 and param2='a'"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @Test public void testProcInVirtualGroup3(){
+ 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$
+ helpResolve(sql);
+ }
+
+ @Test public void testProcInVirtualGroup4(){
+ 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$
+ helpResolve(sql);
+ }
+
+ @Test public void testProcInVirtualGroup5(){
+ String sql = "SELECT * FROM (SELECT p.* FROM pm1.vsp26 as P, vm1.g1 where P.e1=g1.e1) x where param1=1 and param2='a'"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @Test public void testProcInVirtualGroup6(){
+ String sql = "SELECT P.e1 as ve3, P.e2 as ve4 FROM pm1.vsp26 as P where param1=1 and param2='a'"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @Test public void testProcInVirtualGroup7(){
+ 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$
+ helpResolve(sql);
+ }
+
+ @Test public void testProcInVirtualGroup7a(){
+ String sql = "SELECT P.e2 as ve3, P.e1 as ve4 FROM pm1.vsp47 as P where param1=1"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @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 = RealMetadataFactory.exampleBQTCached();
+ AnalysisRecord analysis = AnalysisRecord.createNonRecordingRecord();
+
+ Query query = (Query) helpResolve(userSql, metadata);
+ From from = query.getFrom();
+ Collection fromClauses = from.getClauses();
+ SPParameter params[] = new SPParameter[2];
+ Iterator iter = fromClauses.iterator();
+ while(iter.hasNext()) {
+ SubqueryFromClause clause = (SubqueryFromClause) iter.next();
+ StoredProcedure proc = (StoredProcedure) clause.getCommand();
+ List procParams = proc.getParameters();
+ for(int i=0; i<procParams.size(); i++) {
+ SPParameter param = (SPParameter) procParams.get(i);
+ if(param.getParameterType() == ParameterInfo.IN) {
+ if(params[0] == null) {
+ params[0] = param;
+ } else {
+ params[1] = param;
+ }
+ }
+ }
+ }
+
+ assertTrue("Params should be not equal", ! params[0].equals(params[1])); //$NON-NLS-1$
+ }
+
+ @Test public void testNullConstantInSelect() throws Exception {
+ String userSql = "SELECT null as x"; //$NON-NLS-1$
+ Query query = (Query)helpParse(userSql);
+
+ QueryResolver.resolveCommand(query, RealMetadataFactory.exampleBQTCached());
+
+ // Check type of resolved null constant
+ SingleElementSymbol symbol = (SingleElementSymbol) query.getSelect().getSymbols().get(0);
+ assertNotNull(symbol.getType());
+ assertEquals(DataTypeManager.DefaultDataClasses.STRING, symbol.getType());
+ }
+
+ @Test public void test11716() throws Exception {
+ String sql = "SELECT e1 FROM pm1.g1 where e1='1'"; //$NON-NLS-1$
+ Map externalMetadata = new HashMap();
+ GroupSymbol inputSet = new GroupSymbol("INPUT"); //$NON-NLS-1$
+ List inputSetElements = new ArrayList();
+ ElementSymbol inputSetElement = new ElementSymbol("INPUT.e1"); //$NON-NLS-1$
+ inputSetElements.add(inputSetElement);
+ externalMetadata.put(inputSet, inputSetElements);
+ Query command = (Query)helpParse(sql);
+ QueryResolver.resolveCommand(command, metadata);
+ Collection groups = GroupCollectorVisitor.getGroups(command, false);
+ assertFalse(groups.contains(inputSet));
+ }
+
+ @Test public void testInputToInputsConversion() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = (Select pm1.g1.e2 from pm1.g1 where e2=INPUTS.e2);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e2=40"; //$NON-NLS-1$
+
+ Command command = helpResolveUpdateProcedure(procedure, userUpdateStr);
+ assertEquals("CREATE PROCEDURE\nBEGIN\nDECLARE integer var1;\nROWS_UPDATED = (SELECT pm1.g1.e2 FROM pm1.g1 WHERE e2 = INPUTS.e2);\nEND", command.toString());
+ }
+
+ @Test public void testDefect16894_resolverException_1() {
+ helpResolve("SELECT * FROM (SELECT * FROM Pm1.g1 AS Y) AS X"); //$NON-NLS-1$
+ }
+
+ @Test public void testDefect16894_resolverException_2() {
+ helpResolve("SELECT * FROM (SELECT * FROM Pm1.g1) AS X"); //$NON-NLS-1$
+ }
+
+ @Test public void testDefect17385() throws Exception{
+ String sql = "select e1 as x ORDER BY x"; //$NON-NLS-1$
+ helpResolveException(sql);
+ }
+
+ @Test public void testValidFullElementNotInQueryGroups() {
+ helpResolveException("select pm1.g1.e1 FROM pm1.g1 g"); //$NON-NLS-1$
+ }
+
+ @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, RealMetadataFactory.exampleBQTCached());
+ }
+
+ @Test public void testParameterError() throws Exception {
+ helpResolveException("EXEC pm1.sp2(1, 2)", metadata, "Error Code:ERR.015.008.0007 Message:Incorrect number of parameters specified on the stored procedure pm1.sp2 - expected 1 but got 2"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testUnionOfAliasedLiteralsGetsModified() {
+ String sql = "SELECT 5 AS x UNION ALL SELECT 10 AS x"; //$NON-NLS-1$
+ Command c = helpResolve(sql);
+ assertEquals(sql, c.toString());
+ }
+
+ @Test public void testXMLWithProcSubquery() {
+ String sql = "SELECT * FROM xmltest.doc4 WHERE node2 IN (SELECT e1 FROM (EXEC pm1.vsp1()) AS x)"; //$NON-NLS-1$
+ Command c = helpResolve(sql);
+ assertEquals(sql, c.toString());
+ }
+
+ @Test public void testDefect18832() {
+ String sql = "SELECT * from (SELECT null as a, e1 FROM pm1.g1) b"; //$NON-NLS-1$
+ Command c = helpResolve(sql);
+ List projectedSymbols = c.getProjectedSymbols();
+ for(int i=0; i< projectedSymbols.size(); i++) {
+ ElementSymbol symbol = (ElementSymbol)projectedSymbols.get(i);
+ assertTrue(!symbol.getType().equals(DataTypeManager.DefaultDataClasses.NULL));
+ }
+ }
+
+ @Test public void testDefect18832_2() {
+ String sql = "SELECT a.*, b.* from (SELECT null as a, e1 FROM pm1.g1) a, (SELECT e1 FROM pm1.g1) b"; //$NON-NLS-1$
+ Command c = helpResolve(sql);
+ List projectedSymbols = c.getProjectedSymbols();
+ for(int i=0; i< projectedSymbols.size(); i++) {
+ ElementSymbol symbol = (ElementSymbol)projectedSymbols.get(i);
+ assertTrue(!symbol.getType().equals(DataTypeManager.DefaultDataClasses.NULL));
+ }
+ }
+
+ @Test public void testDefect20113() {
+ String sql = "SELECT g1.* from pm1.g1"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @Test public void testDefect20113_2() {
+ String sql = "SELECT g7.* from g7"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ private void verifyProjectedTypes(Command c, Class[] types) {
+ List projSymbols = c.getProjectedSymbols();
+ for(int i=0; i<projSymbols.size(); i++) {
+ assertEquals("Found type mismatch at column " + i, types[i], ((SingleElementSymbol) projSymbols.get(i)).getType()); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testNestedInlineViews() throws Exception {
+ String sql = "SELECT * FROM (SELECT * FROM (SELECT * FROM pm1.g1) AS Y) AS X"; //$NON-NLS-1$
+ Command c = helpResolve(sql);
+ assertEquals(sql, c.toString());
+
+ verifyProjectedTypes(c, new Class[] { String.class, Integer.class, Boolean.class, Double.class });
+ }
+
+ @Test public void testNestedInlineViewsNoStar() throws Exception {
+ String sql = "SELECT e1 FROM (SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS Y) AS X"; //$NON-NLS-1$
+ Command c = helpResolve(sql);
+ assertEquals(sql, c.toString());
+
+ verifyProjectedTypes(c, new Class[] { String.class });
+ }
+
+ @Test public void testNestedInlineViewsCount() throws Exception {
+ String sql = "SELECT COUNT(*) FROM (SELECT * FROM (SELECT * FROM pm1.g1) AS Y) AS X"; //$NON-NLS-1$
+ Command c = helpResolve(sql);
+ assertEquals(sql, c.toString());
+ verifyProjectedTypes(c, new Class[] { Integer.class });
+ }
+
+ @Test public void testAggOverInlineView() throws Exception {
+ String sql = "SELECT SUM(x) FROM (SELECT (e2 + 1) AS x FROM pm1.g1) AS g"; //$NON-NLS-1$
+ Command c = helpResolve(sql);
+ assertEquals(sql, c.toString());
+ verifyProjectedTypes(c, new Class[] { Long.class });
+
+ }
+
+ @Test public void testCaseOverInlineView() throws Exception {
+ String sql = "SELECT CASE WHEN x > 0 THEN 1.0 ELSE 2.0 END FROM (SELECT e2 AS x FROM pm1.g1) AS g"; //$NON-NLS-1$
+ Command c = helpResolve(sql);
+ assertEquals(sql, c.toString());
+ verifyProjectedTypes(c, new Class[] { Double.class });
+
+ }
+
+ //procedure - select * from temp table
+ @Test public void testDefect20083_1 (){
+ helpResolve("EXEC pm1.vsp56()"); //$NON-NLS-1$
+ }
+
+ //procedure - select * from temp table order by
+ @Test public void testDefect20083_2 (){
+ helpResolve("EXEC pm1.vsp57()"); //$NON-NLS-1$
+ }
+
+ @Test public void testTypeConversionOverUnion() throws Exception {
+ String sql = "SELECT * FROM (SELECT e2, e1 FROM pm1.g1 UNION SELECT convert(e2, string), e1 FROM pm1.g1) FOO where e2/2 = 1"; //$NON-NLS-1$
+ helpResolveException(sql);
+ }
+
+ @Test public void testVariableDeclarationAfterStatement() throws Exception{
+ String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "select * from pm1.g1 where pm1.g1.e1 = VARIABLES.X;\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE string VARIABLES.X = 1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ helpResolveException(procedure, "Element \"VARIABLES.X\" is not defined by any relevant group."); //$NON-NLS-1$
+ }
+
+ /**
+ * same as above, but with an xml query
+ * @throws Exception
+ */
+ @Test public void testVariableDeclarationAfterStatement1() throws Exception{
+ String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "select * from xmltest.doc1 where node1 = VARIABLES.X;\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE string VARIABLES.X = 1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ helpResolveException(procedure, "Error Code:ERR.015.008.0019 Message:Unable to resolve element: VARIABLES.X"); //$NON-NLS-1$
+ }
+
+ @Test public void testCreate() {
+ String sql = "CREATE LOCAL TEMPORARY TABLE temp_table (column1 string)"; //$NON-NLS-1$
+ Command c = helpResolve(sql);
+ assertEquals(sql, c.toString());
+ }
+
+ @Test public void testCreateQualifiedName() {
+ String sql = "CREATE LOCAL TEMPORARY TABLE pm1.g1 (column1 string)"; //$NON-NLS-1$
+ helpResolveException(sql, "Cannot create temporary table \"pm1.g1\". Local temporary tables must be created with unqualified names."); //$NON-NLS-1$
+ }
+
+ @Test public void testProcedureConflict() {
+ String sql = "create local temporary table MMSP6 (e1 string, e2 integer)"; //$NON-NLS-1$
+ helpResolveException(sql, RealMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
+ }
+
+ @Test public void testCreatePk() {
+ String sql = "CREATE LOCAL TEMPORARY TABLE foo (column1 string, column2 integer, primary key (column1, column2))"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @Test public void testCreateUnknownPk() {
+ String sql = "CREATE LOCAL TEMPORARY TABLE foo (column1 string, primary key (column2))"; //$NON-NLS-1$
+ helpResolveException(sql, "Element \"column2\" is not defined by any relevant group."); //$NON-NLS-1$
+ }
+
+ @Test public void testCreateAlreadyExists() {
+ String sql = "CREATE LOCAL TEMPORARY TABLE g1 (column1 string)"; //$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() {
+ String sql = "CREATE LOCAL TEMPORARY TABLE #g1 (column1 string)"; //$NON-NLS-1$
+ Command c = helpResolve(sql);
+ assertEquals(sql, c.toString());
+ }
+
+ @Test public void testCreateInProc() throws Exception{
+ 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
+ //the exception here is a little weak since there are multiple uses of #temp in the block
+ @Test public void testTempTableScope() {
+ String proc = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
+ + "BEGIN " //$NON-NLS-1$
+ + " DECLARE integer VARIABLES.BITS;" //$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$
+
+ helpResolveException(proc, RealMetadataFactory.exampleBitwise(), "Group does not exist: #temp"); //$NON-NLS-1$
+ }
+
+ @Test public void testDrop() {
+ String sql = "DROP TABLE temp_table"; //$NON-NLS-1$
+ helpResolveException(sql, "Group does not exist: temp_table"); //$NON-NLS-1$
+ }
+
+ @Test public void testResolveUnqualifiedCriteria() throws Exception{
+ Criteria criteria = QueryParser.getQueryParser().parseCriteria("e1 = 1"); //$NON-NLS-1$
+
+ // resolve
+ try {
+ QueryResolver.resolveCriteria(criteria, metadata);
+ fail("Exception expected"); //$NON-NLS-1$
+ } catch(QueryResolverException e) {
+ assertEquals("Symbol e1 is specified with an unknown group context", e.getMessage()); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testSameNameRoot() {
+ String sql = "select p.e1 from pm1.g1 as pp, pm1.g1 as p"; //$NON-NLS-1$
+
+ helpResolve(sql);
+ }
+
+ @Test public void testBatchedUpdateResolver() throws Exception {
+ String update1 = "update pm1.g1 set e1 =1"; //$NON-NLS-1$
+ String update2 = "update pm2.g1 set e1 =1"; //$NON-NLS-1$
+
+ List commands = new ArrayList();
+ commands.add(QueryParser.getQueryParser().parseCommand(update1));
+ commands.add(QueryParser.getQueryParser().parseCommand(update2));
+ BatchedUpdateCommand command = new BatchedUpdateCommand(commands);
+
+ helpResolve(command);
+ }
+
+ @Test public void testAmbiguousAllInGroup() {
+ String sql = "SELECT g1.* from pm1.g1, pm2.g1"; //$NON-NLS-1$
+ helpResolveException(sql, metadata, "The symbol g1.* refers to more than one group defined in the FROM clause."); //$NON-NLS-1$
+ }
+
+ @Test public void testRowsUpdatedInProcedure(){
+ String sql = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
+ + "BEGIN " //$NON-NLS-1$
+ +"SELECT ROWS_UPDATED; " //$NON-NLS-1$
+ +"end "; //$NON-NLS-1$
+
+ helpResolveException(sql, metadata, "Element \"ROWS_UPDATED\" is not defined by any relevant group."); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLQueryWithVariable() {
+ String sql = "CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
+ + "BEGIN " //$NON-NLS-1$
+ + "declare string x = '1'; " //$NON-NLS-1$
+ +"select * from xmltest.doc1 where node1 = x; " //$NON-NLS-1$
+ +"end "; //$NON-NLS-1$
+
+ CreateUpdateProcedureCommand command = (CreateUpdateProcedureCommand) helpResolve(sql);
+
+ CommandStatement cmdStmt = (CommandStatement)command.getBlock().getStatements().get(1);
+
+ CompareCriteria criteria = (CompareCriteria)((Query)cmdStmt.getCommand()).getCriteria();
+
+ assertEquals(ProcedureReservedWords.VARIABLES, ((ElementSymbol)criteria.getRightExpression()).getGroupSymbol().getCanonicalName());
+ }
+
+ /**
+ * We could check to see if the expressions are evaluatable to a constant, but that seems unnecessary
+ */
+ @Test public void testLookupWithoutConstant() throws Exception{
+ String sql = "SELECT lookup('pm1.g1', convert('e3', float), 'e2', e2) FROM pm1.g1"; //$NON-NLS-1$
+
+ helpResolveException(sql, metadata, "Error Code:ERR.015.008.0063 Message:The first three arguments for the LOOKUP function must be specified as constants."); //$NON-NLS-1$
+ }
+
+ /**
+ * We cannot implicitly convert the argument to double due to lack of precision
+ */
+ @Test public void testPowerWithBigInteger_Fails() throws Exception {
+ String sql = "SELECT power(10, 999999999999999999999999999999999999999999999)"; //$NON-NLS-1$
+
+ helpResolveException(sql);
+ }
+
+ @Test public void testPowerWithLong_Fails() throws Exception {
+ String sql = "SELECT power(10, 999999999999)"; //$NON-NLS-1$
+
+ helpResolveException(sql);
+ }
+
+ @Test public void testUpdateError() {
+ String userUpdateStr = "UPDATE vm1.g2 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveException(userUpdateStr, metadata, "Error Code:ERR.015.008.0009 Message:Update is not allowed on the view vm1.g2: a procedure must be defined to handle the Update."); //$NON-NLS-1$
+ }
+
+ @Test public void testInsertError() {
+ String userUpdateStr = "INSERT into vm1.g2 (e1) values ('x')"; //$NON-NLS-1$
+
+ helpResolveException(userUpdateStr, metadata, "Error Code:ERR.015.008.0009 Message:Insert is not allowed on the view vm1.g2: a procedure must be defined to handle the Insert."); //$NON-NLS-1$
+ }
+
+ @Test public void testDeleteError() {
+ String userUpdateStr = "DELETE from vm1.g2 where e1='x'"; //$NON-NLS-1$
+
+ helpResolveException(userUpdateStr, metadata, "Error Code:ERR.015.008.0009 Message:Delete is not allowed on the view vm1.g2: a procedure must be defined to handle the Delete."); //$NON-NLS-1$
+ }
+
+ @Test public void testResolveXMLSelect() {
+ String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE string VARIABLES.X = 1;\n"; //$NON-NLS-1$
+ procedure = procedure + "select VARIABLES.X from xmltest.doc1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ helpResolveException(procedure, "Error Code:ERR.015.008.0019 Message:Unable to resolve element: VARIABLES.X"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLJoinFail() {
+ String query = "select * from xmltest.doc1, xmltest.doc2"; //$NON-NLS-1$
+
+ helpResolveException(query, "Error Code:ERR.015.008.0003 Message:Only one XML document may be specified in the FROM clause of a query."); //$NON-NLS-1$
+ }
+
+ @Test public void testExecProjectedSymbols() {
+ String query = "exec pm1.sq1()"; //$NON-NLS-1$
+
+ StoredProcedure proc = (StoredProcedure)helpResolve(query);
+
+ List projected = proc.getProjectedSymbols();
+
+ assertEquals(2, projected.size());
+
+ for (Iterator i = projected.iterator(); i.hasNext();) {
+ ElementSymbol symbol = (ElementSymbol)i.next();
+ assertNotNull(symbol.getGroupSymbol());
+ }
+ }
+
+ @Test public void testExecWithDuplicateNames() {
+ MetadataStore metadataStore = new MetadataStore();
+
+ 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$
+ }
+
+ @Test public void testInlineViewNullLiteralInUnion() {
+ String sql = "select e2 from pm1.g1 union all (select x from (select null as x) y)"; //$NON-NLS-1$
+
+ helpResolve(sql);
+ }
+
+ @Test public void testSelectIntoWithDuplicateNames() {
+ String sql = "select 1 as x, 2 as x into #temp"; //$NON-NLS-1$
+
+ helpResolveException(sql, "Cannot create group '#temp' with multiple columns named 'x'"); //$NON-NLS-1$
+ }
+
+ @Test public void testCreateWithDuplicateNames() {
+ String sql = "CREATE LOCAL TEMPORARY TABLE temp_table (column1 string, column1 string)"; //$NON-NLS-1$
+
+ helpResolveException(sql, "Cannot create group \'temp_table\' with multiple columns named \'column1\'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLQuery4() {
+ helpResolveException("SELECT * FROM xmltest.doc1 group by a2", "Queries against XML documents can not have a GROUP By clause"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQuery5() {
+ helpResolveException("SELECT * FROM xmltest.doc1 having a2='x'", "Queries against XML documents can not have a HAVING clause"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testSelectIntoWithOrderBy() {
+ String sql = "select e1, e2 into #temp from pm1.g1 order by e1 limit 10"; //$NON-NLS-1$
+
+ helpResolve(sql);
+ }
+
+ @Test public void testUnionBranchesWithDifferentElementCounts() {
+ helpResolveException("SELECT e2, e3 FROM pm1.g1 UNION SELECT e2 FROM pm1.g2","Queries combined with the set operator UNION must have the same number of output elements."); //$NON-NLS-1$ //$NON-NLS-2$
+ helpResolveException("SELECT e2 FROM pm1.g1 UNION SELECT e2, e3 FROM pm1.g2","Queries combined with the set operator UNION must have the same number of output elements."); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testSelectIntoWithNullLiteral() {
+ String sql = "select null as x into #temp from pm1.g1"; //$NON-NLS-1$
+
+ Query query = (Query)helpResolve(sql);
+
+ TempMetadataStore store = new TempMetadataStore(query.getTemporaryMetadata());
+
+ TempMetadataID id = store.getTempElementID("#temp.x"); //$NON-NLS-1$
+
+ assertEquals(DataTypeManager.DefaultDataClasses.STRING, id.getType());
+ }
+
+ @Test public void testInsertWithNullLiteral() {
+ String sql = "insert into #temp (x) values (null)"; //$NON-NLS-1$
+
+ Insert insert = (Insert)helpResolve(sql);
+
+ TempMetadataStore store = new TempMetadataStore(insert.getTemporaryMetadata());
+
+ TempMetadataID id = store.getTempElementID("#temp.x"); //$NON-NLS-1$
+
+ assertEquals(DataTypeManager.DefaultDataClasses.STRING, id.getType());
+ }
+
+ @Test public void testInsertWithoutColumnsFails() {
+ String sql = "Insert into pm1.g1 values (1, 2)"; //$NON-NLS-1$
+
+ helpResolveException(sql, "Error Code:ERR.015.008.0010 Message:INSERT statement must have the same number of elements and values specified. This statement has 4 elements and 2 values."); //$NON-NLS-1$
+ }
+
+ @Test public void testInsertWithoutColumnsFails1() {
+ String sql = "Insert into pm1.g1 values (1, 2, 3, 4)"; //$NON-NLS-1$
+
+ helpResolveException(sql, "Error Code:ERR.015.008.0041 Message:Expected value of type 'boolean' but '3' is of type 'integer' and no implicit conversion is available."); //$NON-NLS-1$
+ }
+
+ @Test public void testInsertWithQueryFails() {
+ String sql = "Insert into pm1.g1 select 1, 2, 3, 4"; //$NON-NLS-1$
+
+ 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$
+ }
+
+ @Test public void testInsertWithQueryImplicitWithoutColumns1() {
+ String sql = "Insert into #X select 1 as x, 2 as y, 3 as y"; //$NON-NLS-1$
+
+ helpResolveException(sql, "Cannot create group '#X' with multiple columns named 'y'"); //$NON-NLS-1$
+ }
+
+ @Test public void testInsertWithoutColumnsPasses() {
+ String sql = "Insert into pm1.g1 values (1, 2, true, 4)"; //$NON-NLS-1$
+
+ helpResolve(sql);
+ Insert command = (Insert)helpResolve(sql);
+ assertEquals(4, command.getVariables().size());
+ }
+
+ @Test public void testInsertWithoutColumnsUndefinedTemp() {
+ String sql = "Insert into #temp values (1, 2)"; //$NON-NLS-1$
+
+ Insert command = (Insert)helpResolve(sql);
+ assertEquals(2, command.getVariables().size());
+ }
+
+ @Test public void testImplicitTempInsertWithNoColumns() {
+ StringBuffer proc = new StringBuffer("CREATE VIRTUAL PROCEDURE") //$NON-NLS-1$
+ .append("\nBEGIN") //$NON-NLS-1$
+ .append("\n create local temporary table #matt (x integer);") //$NON-NLS-1$
+ .append("\n insert into #matt values (1);") //$NON-NLS-1$
+ .append("\nEND"); //$NON-NLS-1$
+
+ Command cmd = helpResolve(proc.toString());
+
+ String sExpected = "CREATE VIRTUAL PROCEDURE\nBEGIN\nCREATE LOCAL TEMPORARY TABLE #matt (x integer);\nINSERT INTO #matt (#matt.x) VALUES (1);\nEND\n\tCREATE LOCAL TEMPORARY TABLE #matt (x integer)\n\tINSERT INTO #matt (#matt.x) VALUES (1)\n"; //$NON-NLS-1$
+ String sActual = cmd.printCommandTree();
+ assertEquals( sExpected, sActual );
+ }
+
+ @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, 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", RealMetadataFactory.exampleBQTCached(), "Cannot create group 'q1' with multiple columns named 'b'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testResolveOldProcRelational() {
+ helpResolveException("SELECT * FROM pm1.g1, (exec pm1.sq2(pm1.g1.e1)) as a", "Symbol pm1.g1.e1 is specified with an unknown group context"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testResolverOrderOfPrecedence() {
+ helpResolveException("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 CROSS JOIN (pm1.g2 LEFT OUTER JOIN pm2.g1 on pm1.g1.e1 = pm2.g1.e1)", "Symbol pm1.g1.e1 is specified with an unknown group context"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * The cross join should parse/resolve with higher precedence
+ */
+ @Test public void testResolverOrderOfPrecedence_1() {
+ helpResolve("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 CROSS JOIN pm1.g2 LEFT OUTER JOIN pm2.g1 on pm1.g1.e1 = pm2.g1.e1"); //$NON-NLS-1$
+ }
+
+ @Test public void testInvalidColumnReferenceWithNestedJoin() {
+ helpResolveException("SELECT a.* FROM (pm1.g2 a left outer join pm1.g2 b on a.e1= b.e1) LEFT OUTER JOIN (select a.e1) c on (a.e1 = c.e1)"); //$NON-NLS-1$
+ }
+
+ /**
+ * should be the same as exec with too many params
+ */
+ @Test public void testCallableStatementTooManyParameters() throws Exception {
+ String sql = "{call pm4.spTest9(?, ?)}"; //$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, RealMetadataFactory.example1Cached());
+
+ Expression ref = update.getChangeList().getClauses().get(1).getValue();
+ assertTrue(ref instanceof Reference);
+ assertNotNull(ref.getType());
+ }
+
+ @Test public void testNoTypeCriteria() {
+ String sql = "select * from pm1.g1 where ? = ?"; //$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, 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, 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, RealMetadataFactory.example1Cached());
+ assertEquals(DataTypeManager.DefaultDataClasses.OBJECT, ((SingleElementSymbol)query.getProjectedSymbols().get(0)).getType());
+ }
+
+ @Test public void testUnionWithSubQuery() {
+ String sql = "select 1 from pm1.g1 where exists (select 1) union select 2"; //$NON-NLS-1$
+
+ SetQuery command = (SetQuery)helpResolve(sql);
+
+ assertEquals(1, CommandCollectorVisitor.getCommands(command).size());
+ }
+ @Test public void testOrderBy_J658a() {
+ Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2, e3 as x, (5+2) as y FROM pm1.g1 ORDER BY e3"); //$NON-NLS-1$
+ OrderBy orderBy = resolvedQuery.getOrderBy();
+ int[] expectedPositions = new int[] {2};
+ helpTestOrderBy(orderBy, expectedPositions);
+ }
+
+ private void helpTestOrderBy(OrderBy orderBy, int[] expectedPositions) {
+ assertEquals(expectedPositions.length, orderBy.getVariableCount());
+ for (int i = 0; i < expectedPositions.length; i++) {
+ assertEquals(expectedPositions[i], orderBy.getExpressionPosition(i));
+ }
+ }
+ @Test public void testOrderBy_J658b() {
+ Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2, e3 as x, (5+2) as y FROM pm1.g1 ORDER BY e2, e3 "); //$NON-NLS-1$
+ helpTestOrderBy(resolvedQuery.getOrderBy(), new int[] {1, 2});
+ }
+ @Test public void testOrderBy_J658c() {
+ Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2 as x, e3 as y FROM pm1.g1 ORDER BY x, e3 "); //$NON-NLS-1$
+ helpTestOrderBy(resolvedQuery.getOrderBy(), new int[] {1, 2});
+ }
+
+ // ambiguous, should fail
+ @Test public void testOrderBy_J658d() {
+ helpResolveException("SELECT pm1.g1.e1, e2 as x, e3 as x FROM pm1.g1 ORDER BY x, e1 ", "Error Code:ERR.015.008.0042 Message:Element 'x' in ORDER BY is ambiguous and may refer to more than one element of SELECT clause."); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ @Test public void testOrderBy_J658e() {
+ Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.e1, e2 as x, e3 as e2 FROM pm1.g1 ORDER BY x, e2 "); //$NON-NLS-1$
+ helpTestOrderBy(resolvedQuery.getOrderBy(), new int[] {1, 2});
+ }
+
+ @Test public void testSPOutParamWithExec() {
+ StoredProcedure proc = (StoredProcedure)helpResolve("exec pm2.spTest8(1)", RealMetadataFactory.exampleBQTCached());
+ assertEquals(2, proc.getProjectedSymbols().size());
+ }
+
+ /**
+ * Note that the call syntax is not quite correct, the output parameter is not in the arg list.
+ * That hack is handled by the PreparedStatementRequest
+ */
+ @Test public void testSPOutParamWithCallableStatement() {
+ 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'})", RealMetadataFactory.exampleBQTCached());
+ }
+
+ @Test public void testProcRelationalWithOutParam() {
+ 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)", RealMetadataFactory.exampleBQTCached());
+ assertEquals(1, proc.getProjectedSymbols().size());
+ }
+
+ @Test public void testSecondPassFunctionResolving() {
+ helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 where lower(?) = e1 "); //$NON-NLS-1$
+ }
+
+ @Test public void testSecondPassFunctionResolving1() {
+ try {
+ helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 where 1/(e1 - 2) <> 4 "); //$NON-NLS-1$
+ fail("expected exception");
+ } catch (RuntimeException e) {
+ QueryResolverException qre = (QueryResolverException)e.getCause();
+ assertEquals("ERR.015.008.0040", qre.getCode());
+ }
+ }
+
+ @Ignore("currently not supported - we get type hints from the criteria not from the possible signatures")
+ @Test public void testSecondPassFunctionResolving2() {
+ helpResolve("SELECT pm1.g1.e1 FROM pm1.g1 where (lower(?) || 1) = e1 "); //$NON-NLS-1$
+ }
+
+ /**
+ * Test <code>QueryResolver</code>'s ability to resolve a query that
+ * contains an aggregate <code>SUM</code> which uses a <code>CASE</code>
+ * expression which contains <code>BETWEEN</code> criteria as its value.
+ * <p>
+ * For example:
+ * <p>
+ * SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1
+ */
+ @Test public void testAggregateWithBetweenInCaseInSelect() {
+ String sql = "SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ /**
+ * Test <code>QueryResolver</code>'s ability to resolve a query that
+ * contains a <code>CASE</code> expression which contains
+ * <code>BETWEEN</code> criteria in the queries <code>SELECT</code> clause.
+ * <p>
+ * For example:
+ * <p>
+ * SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1
+ */
+ @Test public void testBetweenInCaseInSelect() {
+ String sql = "SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ /**
+ * Test <code>QueryResolver</code>'s ability to resolve a query that
+ * contains a <code>CASE</code> expression which contains
+ * <code>BETWEEN</code> criteria in the queries <code>WHERE</code> clause.
+ * <p>
+ * For example:
+ * <p>
+ * SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END
+ */
+ @Test public void testBetweenInCase() {
+ String sql = "SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END"; //$NON-NLS-1$
+ helpResolve(sql);
+ }
+
+ @Test public void testOrderByUnrelated() {
+ helpResolve("SELECT pm1.g1.e1, e2 as x, e3 as y FROM pm1.g1 ORDER BY e4"); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderByUnrelated1() {
+ helpResolveException("SELECT distinct pm1.g1.e1, e2 as x, e3 as y FROM pm1.g1 ORDER BY e4"); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderByUnrelated2() {
+ helpResolveException("SELECT max(e2) FROM pm1.g1 group by e1 ORDER BY e4"); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderByExpression() {
+ Query query = (Query)helpResolve("select pm1.g1.e1 from pm1.g1 order by e2 || e3 "); //$NON-NLS-1$
+ assertEquals(-1, query.getOrderBy().getExpressionPosition(0));
+ }
+
+ @Test public void testOrderByExpression1() {
+ Query query = (Query)helpResolve("select pm1.g1.e1 || e2 from pm1.g1 order by pm1.g1.e1 || e2 "); //$NON-NLS-1$
+ assertEquals(0, query.getOrderBy().getExpressionPosition(0));
+ }
+
+ @Test public void testOrderByExpression2() {
+ helpResolveException("select pm1.g1.e1 from pm1.g1 union select pm1.g2.e1 from pm1.g2 order by pm1.g1.e1 || 2", "ORDER BY expression '(pm1.g1.e1 || 2)' cannot be used with a set query."); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testOrderByConstantFails() {
+ helpResolveException("select pm1.g1.e1 from pm1.g1 order by 2"); //$NON-NLS-1$
+ }
+
+ @Test public void testCorrelatedNestedTableReference() {
+ helpResolve("select pm1.g1.e1 from pm1.g1, table (exec pm1.sq2(pm1.g1.e2)) x"); //$NON-NLS-1$
+ helpResolveException("select pm1.g1.e1 from pm1.g1, (exec pm1.sq2(pm1.g1.e2)) x"); //$NON-NLS-1$
+ }
+
+ @Test public void testCorrelatedTextTable() {
+ Command command = helpResolve("select x.* from pm1.g1, texttable(e1 COLUMNS x string) x"); //$NON-NLS-1$
+ assertEquals(1, command.getProjectedSymbols().size());
+ }
+
+ @Test public void testQueryString() throws Exception {
+ helpResolveException("select querystring(xmlparse(document '<a/>'))");
+ }
+
+ // validating AssignmentStatement, ROWS_UPDATED element assigned
+ @Test(expected=QueryResolverException.class) public void testCreateUpdateProcedure9() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = Select pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr);
+ }
+
+ CreateUpdateProcedureCommand helpResolveUpdateProcedure(String procedure,
+ String userUpdateStr) throws QueryParserException,
+ QueryResolverException, TeiidComponentException,
+ QueryMetadataException {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(TriggerEvent.UPDATE, procedure);
+
+ ProcedureContainer userCommand = (ProcedureContainer)QueryParser.getQueryParser().parseCommand(userUpdateStr);
+ QueryResolver.resolveCommand(userCommand, metadata);
+
+ return (CreateUpdateProcedureCommand)QueryResolver.expandCommand(userCommand, metadata, AnalysisRecord.createNonRecordingRecord());
+ }
+
+ // validating AssignmentStatement, variable type and assigned type
+ // do not match
+ @Test(expected=QueryResolverException.class) public void testCreateUpdateProcedure10() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userUpdateStr);
+ }
+
+ //return should be first, then out
+ @Test public void testParamOrder() {
+ Query resolvedQuery = (Query)helpResolve("SELECT * FROM (exec pm4.spRetOut()) as a", RealMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
+
+ assertEquals("a.ret", resolvedQuery.getProjectedSymbols().get(0).getName());
+ }
+
+ @Test public void testOrderByAggregatesError() throws Exception {
+ helpResolveException("select count(*) from pm1.g1 order by e1");
+ }
+
+ @Test public void testWithDuplidateName() {
+ helpResolveException("with x as (TABLE pm1.g1), x as (TABLE pm1.g2) SELECT * from x");
+ }
+
+ @Test public void testWithColumns() {
+ helpResolveException("with x (a, b) as (TABLE pm1.g1) SELECT * from x");
+ }
+
+ @Test public void testWithNameMatchesFrom() {
+ helpResolve("with x as (TABLE pm1.g1) SELECT * from (TABLE x) x");
+ }
+
+ // variables cannot be used among insert elements
+ @Test(expected=QueryResolverException.class) public void testCreateUpdateProcedure23() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Update pm1.g1 SET pm1.g1.e2 =1 , var1 = 2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
+
+ helpResolveUpdateProcedure(procedure, userQuery);
+ }
+}
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestXMLResolver.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/resolver/TestXMLResolver.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestXMLResolver.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,430 +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.resolver;
-
-import junit.framework.TestCase;
-
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.resolver.util.ResolverUtil;
-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.Query;
-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.sql.symbol.GroupSymbol;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
-
-public class TestXMLResolver extends TestCase {
-
- public Command helpResolve(String sql) {
- Command cmd = TestResolver.helpResolve(sql, FakeMetadataFactory.example1Cached());
- ResolverUtil.fullyQualifyElements(cmd);
- return cmd;
- }
-
- public void helpResolveException(String sql) {
- TestResolver.helpResolveException(sql, FakeMetadataFactory.example1Cached());
- }
-
- public void helpResolveException(String sql, String expectedMessage) {
- TestResolver.helpResolveException(sql, FakeMetadataFactory.example1Cached(), expectedMessage);
- }
-
- 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$
- expected.setLeftExpression(es);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(new Constant("yyz")); //$NON-NLS-1$
-
- Query query = (Query) helpResolve("select * from xmltest.doc1 where node1 = 'yyz'"); //$NON-NLS-1$
- Criteria actual = query.getCriteria();
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- 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$
- es.setGroupSymbol(gs);
- expected.setLeftExpression(es);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(new Constant("yyz")); //$NON-NLS-1$
-
- Query query = (Query) helpResolve("select * from xmltest.doc1 where root.node1 = 'yyz'"); //$NON-NLS-1$
- Criteria actual = query.getCriteria();
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- 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$
- expected1.setLeftExpression(es1);
- expected1.setOperator(CompareCriteria.EQ);
- expected1.setRightExpression(new Constant("xyz")); //$NON-NLS-1$
-
- Query query = (Query) helpResolve("select * from xmltest.doc4 where root.node1 = 'xyz'"); //$NON-NLS-1$
- Criteria actual = query.getCriteria();
- assertEquals("Did not match expected criteria", expected1, actual); //$NON-NLS-1$
- }
-
- 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$
- es2.setGroupSymbol(gs);
- expected2.setLeftExpression(es2);
- expected2.setOperator(CompareCriteria.EQ);
- expected2.setRightExpression(new Constant("xyz")); //$NON-NLS-1$
-
- Query query = (Query) helpResolve("select * from xmltest.doc4 where root.node1. at node2 = 'xyz'"); //$NON-NLS-1$
- Criteria actual = query.getCriteria();
- assertEquals("Did not match expected criteria", expected2, actual); //$NON-NLS-1$
- }
-
- 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$
- expected3.setLeftExpression(es3);
- expected3.setOperator(CompareCriteria.EQ);
- expected3.setRightExpression(new Constant("xyz")); //$NON-NLS-1$
-
- Query query = (Query) helpResolve("select * from xmltest.doc4 where root.node3 = 'xyz'"); //$NON-NLS-1$
- Criteria actual = query.getCriteria();
- assertEquals("Did not match expected criteria", expected3, actual); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaLongElement5() {
- helpResolve("select * from xmltest.doc4 where root.node1 = 'yyz'"); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaLongElement6() {
- helpResolve("select * from xmltest.doc4 where root.node1. at node2 = 'yyz'"); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaLongElement7() {
- helpResolve("select * from xmltest.doc4 where root.node3 = 'yyz'"); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaLongElement8() {
- helpResolve("select * from xmltest.doc4 where node3 = 'yyz'"); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaLongElementFail1() {
- helpResolveException("select * from xmltest.doc4 where node3.node1.node2 = 'xyz'"); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaLongElementFail2() {
- helpResolveException("select * from xmltest.doc4 where root.node1.node2.node3 = 'xyz'"); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaLongElementFail3() {
- helpResolveException("select * from xmltest.doc4 where root.node1.node3 = 'xyz'"); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaLongElementFail4() {
- helpResolveException("select * from xmltest.doc4 where node2.node1.node2 = 'xyz'"); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaTempElement1() {
- helpResolve("select * from xmltest.doc4 where tm1.g1.e1 = 'x'"); //$NON-NLS-1$
- }
-
- 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() {
- helpResolve("select * from xmltest.doc4 where tm1.g1.e1 = 'x' and tm1.g1.e2 = 'y'"); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaTempElementFail1() {
- helpResolveException("select * from xmltest.doc4 where tm1.g2.e1 = 'xyz'"); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaTempElementFail2() {
- helpResolveException("select * from xmltest.doc4 where root.node1.node2.node3 = 'xyz' and e1 = 'x'"); //$NON-NLS-1$
- }
-
- 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() {
- helpResolve("select * from xmltest.doc4 where root.node1 is null"); //$NON-NLS-1$
- }
-
- public void testXMLAmbiguousName2() {
- helpResolve("select * from xmltest.doc4 where tm1.g1.node1 = 'yyz'"); //$NON-NLS-1$
- }
-
- public void testXMLAmbiguousName3() {
- helpResolveException("select * from xmltest.doc4 where node1 = 'yyz'"); //$NON-NLS-1$
- }
-
- 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$
- expected.setLeftExpression(es);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(new Constant("yyz")); //$NON-NLS-1$
-
- Query query = (Query) helpResolve("select * from xmltest.doc2 where root.node1.node3 = 'yyz'"); //$NON-NLS-1$
- Criteria actual = query.getCriteria();
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- public void testXMLAmbiguousShortName() {
- CompareCriteria expected = new CompareCriteria();
- ElementSymbol es = new ElementSymbol("node2"); //$NON-NLS-1$
- GroupSymbol gs = new GroupSymbol("doc3"); //$NON-NLS-1$
- es.setGroupSymbol(gs);
- expected.setLeftExpression(es);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(new Constant("yyz")); //$NON-NLS-1$
-
- helpResolveException("select * from xmltest.doc3 where node2 = 'yyz'"); //$NON-NLS-1$
- }
-
- /**
- * defect 9745
- */
- public void testXMLAttributeInCriteria() {
- helpResolve("select * from xmltest.doc4 where root.node1. at node2 = 'x'"); //$NON-NLS-1$
- }
-
- /**
- * defect 9745
- */
- public void testXMLAttributeInCriteria2() {
- helpResolve("select * from xmltest.doc4 where root.node1.node2 = 'x'"); //$NON-NLS-1$
- }
-
- /**
- * defect 9745
- */
- public void testXMLAttributeInCriteria3() {
- helpResolve("select * from xmltest.doc4 where node2 = 'x'"); //$NON-NLS-1$
- }
-
- public void testXMLAttributeElementAmbiguity1() {
- helpResolve("select * from xmltest.doc4 where root.node3.node4 = 'x'"); //$NON-NLS-1$
- }
-
- public void testXMLAttributeElementAmbiguity2() {
- helpResolve("select * from xmltest.doc4 where root.node3. at node4 = 'x'"); //$NON-NLS-1$
- }
-
- 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() {
- 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() {
- helpResolve("select * from xmltest.doc4 where root. at node6 = 'x'"); //$NON-NLS-1$
- }
-
- public void testXMLAttributeFullPath() {
- helpResolve("select * from xmltest.doc4 where xmltest.doc4.root. at node6 = 'x'"); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaLongElementWithGroup1() {
- helpResolve("select * from xmltest.doc4 where xmltest.doc4.root.node1 = 'yyz'"); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaLongElementWithGroup2() {
- helpResolve("select * from xmltest.doc4 where xmltest.doc4.root.node1. at node2 = 'yyz'"); //$NON-NLS-1$
- }
-
- public void testXMLCriteriaLongElementWithGroup3() {
- helpResolve("select * from xmltest.doc4 where xmltest.doc4.root.node3 = 'yyz'"); //$NON-NLS-1$
- }
-
- /*public void testXMLElementPotentialAmbiguous() {
- helpResolve("select * from xmltest.doc6 where node = 'yyz'");
- }*/
-
- public void testXMLSelect() {
- helpResolve("select root.node3. at node4 from xmltest.doc4"); //$NON-NLS-1$
- }
-
- public void testXMLSelect2() {
- helpResolve("select root.node3.node4 from xmltest.doc4"); //$NON-NLS-1$
- }
-
- public void testXMLSelect3() {
- helpResolve("select root. at node6 from xmltest.doc4"); //$NON-NLS-1$
- }
-
- public void testXMLSelect4() {
- helpResolve("select root.node6 from xmltest.doc4"); //$NON-NLS-1$
- }
-
- public void testXMLSelect5() {
- helpResolve("select node2 from xmltest.doc4"); //$NON-NLS-1$
- }
-
- public void testDEFECT_19771() {
- helpResolveException("select node2 AS NODE2 from xmltest.doc4"); //$NON-NLS-1$
- }
-
- 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$
- Expression[] exprs = new Expression[]{es1, es2};
-
- Function context = new Function("context", exprs); //$NON-NLS-1$
-
- CompareCriteria expected = new CompareCriteria();
- expected.setLeftExpression(context);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(new Constant("yyz")); //$NON-NLS-1$
-
- Query query = (Query) helpResolve("select * from xmltest.doc1 where context(node3, node1) = 'yyz'"); //$NON-NLS-1$
- Criteria actual = query.getCriteria();
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- 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);
- Expression[] exprs = new Expression[]{es1};
-
- Function context = new Function("rowlimit", exprs); //$NON-NLS-1$
-
- CompareCriteria expected = new CompareCriteria();
- expected.setLeftExpression(context);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(new Constant(new Integer(2)));
-
- Query query = (Query) helpResolve("select * from xmltest.doc1 where rowlimit(node3) = 2"); //$NON-NLS-1$
- Criteria actual = query.getCriteria();
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- 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};
-
- Function context = new Function("rowlimitexception", exprs); //$NON-NLS-1$
-
- CompareCriteria expected = new CompareCriteria();
- expected.setLeftExpression(context);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(new Constant(new Integer(2)));
-
- Query query = (Query) helpResolve("select * from xmltest.doc1 where rowlimitexception(node3) = 2"); //$NON-NLS-1$
- Criteria actual = query.getCriteria();
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- public void testXMLQueryFail1() {
- helpResolveException("SELECT DISTINCT * FROM vm1.doc1"); //$NON-NLS-1$
- }
-
- public void testXMLQueryFail2() {
- helpResolveException("SELECT a2 FROM vm1.doc1"); //$NON-NLS-1$
- }
-
- public void testXMLQueryFail3() {
- helpResolveException("SELECT * FROM vm1.doc1, vm1.doc2"); //$NON-NLS-1$
- }
-
- public void testXMLWithOrderBy1() {
- helpResolveException("select * from xmltest.doc4 order by node1"); //$NON-NLS-1$
- }
-
- 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$
-
- // Expected right expression
- Function convert = new Function("convert", new Expression[] { new Constant(new Integer(5)), new Constant("string") }); //$NON-NLS-1$ //$NON-NLS-2$
-
- // Expected criteria
- CompareCriteria expected = new CompareCriteria();
- expected.setLeftExpression(es1);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(convert);
-
- // Resolve the query and check against expected objects
- Query query = (Query) helpResolve("select * from xmltest.doc1 where node1 = convert(5, string)"); //$NON-NLS-1$
- Criteria actual = query.getCriteria();
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- Function actualRightExpr = (Function) ((CompareCriteria)actual).getRightExpression();
- assertNotNull("Failed to resolve function", actualRightExpr.getFunctionDescriptor()); //$NON-NLS-1$
- }
-
- 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$
- expected.setLeftExpression(es);
- 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$
- Criteria actual = query.getCriteria();
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
- 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() {
- CompareCriteria expected = new CompareCriteria();
- GroupSymbol gs = new GroupSymbol("xmltest.doc1"); //$NON-NLS-1$
- ElementSymbol es = new ElementSymbol("root.node1", null, gs); //$NON-NLS-1$
- expected.setLeftExpression(es);
- expected.setOperator(CompareCriteria.EQ);
- expected.setRightExpression(new Constant("yyz")); //$NON-NLS-1$
-
- Query query = (Query) helpResolve("select xmltest.doc1.xml from xmltest.doc1 where node1 = 'yyz'"); //$NON-NLS-1$
- Criteria actual = query.getCriteria();
- assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestXMLResolver.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/resolver/TestXMLResolver.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestXMLResolver.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/resolver/TestXMLResolver.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,431 @@
+/*
+ * 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.resolver;
+
+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;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Query;
+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.sql.symbol.GroupSymbol;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+
+public class TestXMLResolver {
+
+ public Command helpResolve(String sql) {
+ Command cmd = TestResolver.helpResolve(sql, RealMetadataFactory.example1Cached());
+ ResolverUtil.fullyQualifyElements(cmd);
+ return cmd;
+ }
+
+ public void helpResolveException(String sql) {
+ TestResolver.helpResolveException(sql, RealMetadataFactory.example1Cached());
+ }
+
+ public void helpResolveException(String sql, String expectedMessage) {
+ TestResolver.helpResolveException(sql, RealMetadataFactory.example1Cached(), expectedMessage);
+ }
+
+ @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$
+ expected.setLeftExpression(es);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(new Constant("yyz")); //$NON-NLS-1$
+
+ Query query = (Query) helpResolve("select * from xmltest.doc1 where node1 = 'yyz'"); //$NON-NLS-1$
+ Criteria actual = query.getCriteria();
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ @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$
+ es.setGroupSymbol(gs);
+ expected.setLeftExpression(es);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(new Constant("yyz")); //$NON-NLS-1$
+
+ Query query = (Query) helpResolve("select * from xmltest.doc1 where root.node1 = 'yyz'"); //$NON-NLS-1$
+ Criteria actual = query.getCriteria();
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ @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$
+ expected1.setLeftExpression(es1);
+ expected1.setOperator(CompareCriteria.EQ);
+ expected1.setRightExpression(new Constant("xyz")); //$NON-NLS-1$
+
+ Query query = (Query) helpResolve("select * from xmltest.doc4 where root.node1 = 'xyz'"); //$NON-NLS-1$
+ Criteria actual = query.getCriteria();
+ assertEquals("Did not match expected criteria", expected1, actual); //$NON-NLS-1$
+ }
+
+ @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$
+ es2.setGroupSymbol(gs);
+ expected2.setLeftExpression(es2);
+ expected2.setOperator(CompareCriteria.EQ);
+ expected2.setRightExpression(new Constant("xyz")); //$NON-NLS-1$
+
+ Query query = (Query) helpResolve("select * from xmltest.doc4 where root.node1. at node2 = 'xyz'"); //$NON-NLS-1$
+ Criteria actual = query.getCriteria();
+ assertEquals("Did not match expected criteria", expected2, actual); //$NON-NLS-1$
+ }
+
+ @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$
+ expected3.setLeftExpression(es3);
+ expected3.setOperator(CompareCriteria.EQ);
+ expected3.setRightExpression(new Constant("xyz")); //$NON-NLS-1$
+
+ Query query = (Query) helpResolve("select * from xmltest.doc4 where root.node3 = 'xyz'"); //$NON-NLS-1$
+ Criteria actual = query.getCriteria();
+ assertEquals("Did not match expected criteria", expected3, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaLongElement5() {
+ helpResolve("select * from xmltest.doc4 where root.node1 = 'yyz'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaLongElement6() {
+ helpResolve("select * from xmltest.doc4 where root.node1. at node2 = 'yyz'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaLongElement7() {
+ helpResolve("select * from xmltest.doc4 where root.node3 = 'yyz'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaLongElement8() {
+ helpResolve("select * from xmltest.doc4 where node3 = 'yyz'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaLongElementFail1() {
+ helpResolveException("select * from xmltest.doc4 where node3.node1.node2 = 'xyz'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaLongElementFail2() {
+ helpResolveException("select * from xmltest.doc4 where root.node1.node2.node3 = 'xyz'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaLongElementFail3() {
+ helpResolveException("select * from xmltest.doc4 where root.node1.node3 = 'xyz'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaLongElementFail4() {
+ helpResolveException("select * from xmltest.doc4 where node2.node1.node2 = 'xyz'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaTempElement1() {
+ helpResolve("select * from xmltest.doc4 where tm1.g1.e1 = 'x'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaTempElement2() {
+ helpResolve("select * from xmltest.doc4 where root.node1. at node2 = 'yyz' and tm1.g1.e2 = 'y'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaTempElement3() {
+ helpResolve("select * from xmltest.doc4 where tm1.g1.e1 = 'x' and tm1.g1.e2 = 'y'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaTempElementFail1() {
+ helpResolveException("select * from xmltest.doc4 where tm1.g2.e1 = 'xyz'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaTempElementFail2() {
+ helpResolveException("select * from xmltest.doc4 where root.node1.node2.node3 = 'xyz' and e1 = 'x'"); //$NON-NLS-1$
+ }
+
+ @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
+ @Test public void testXMLAmbiguousName1() {
+ helpResolve("select * from xmltest.doc4 where root.node1 is null"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLAmbiguousName2() {
+ helpResolve("select * from xmltest.doc4 where tm1.g1.node1 = 'yyz'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLAmbiguousName3() {
+ helpResolveException("select * from xmltest.doc4 where node1 = 'yyz'"); //$NON-NLS-1$
+ }
+
+ @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$
+ expected.setLeftExpression(es);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(new Constant("yyz")); //$NON-NLS-1$
+
+ Query query = (Query) helpResolve("select * from xmltest.doc2 where root.node1.node3 = 'yyz'"); //$NON-NLS-1$
+ Criteria actual = query.getCriteria();
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLAmbiguousShortName() {
+ CompareCriteria expected = new CompareCriteria();
+ ElementSymbol es = new ElementSymbol("node2"); //$NON-NLS-1$
+ GroupSymbol gs = new GroupSymbol("doc3"); //$NON-NLS-1$
+ es.setGroupSymbol(gs);
+ expected.setLeftExpression(es);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(new Constant("yyz")); //$NON-NLS-1$
+
+ helpResolveException("select * from xmltest.doc3 where node2 = 'yyz'"); //$NON-NLS-1$
+ }
+
+ /**
+ * defect 9745
+ */
+ @Test public void testXMLAttributeInCriteria() {
+ helpResolve("select * from xmltest.doc4 where root.node1. at node2 = 'x'"); //$NON-NLS-1$
+ }
+
+ /**
+ * defect 9745
+ */
+ @Test public void testXMLAttributeInCriteria2() {
+ helpResolve("select * from xmltest.doc4 where root.node1.node2 = 'x'"); //$NON-NLS-1$
+ }
+
+ /**
+ * defect 9745
+ */
+ @Test public void testXMLAttributeInCriteria3() {
+ helpResolve("select * from xmltest.doc4 where node2 = 'x'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLAttributeElementAmbiguity1() {
+ helpResolve("select * from xmltest.doc4 where root.node3.node4 = 'x'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLAttributeElementAmbiguity2() {
+ helpResolve("select * from xmltest.doc4 where root.node3. at node4 = 'x'"); //$NON-NLS-1$
+ }
+
+ @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
+ */
+ @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
+ */
+ @Test public void testXMLAttributeElementAmbiguity5() {
+ helpResolve("select * from xmltest.doc4 where root. at node6 = 'x'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLAttributeFullPath() {
+ helpResolve("select * from xmltest.doc4 where xmltest.doc4.root. at node6 = 'x'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaLongElementWithGroup1() {
+ helpResolve("select * from xmltest.doc4 where xmltest.doc4.root.node1 = 'yyz'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaLongElementWithGroup2() {
+ helpResolve("select * from xmltest.doc4 where xmltest.doc4.root.node1. at node2 = 'yyz'"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLCriteriaLongElementWithGroup3() {
+ helpResolve("select * from xmltest.doc4 where xmltest.doc4.root.node3 = 'yyz'"); //$NON-NLS-1$
+ }
+
+ /*@Test public void testXMLElementPotentialAmbiguous() {
+ helpResolve("select * from xmltest.doc6 where node = 'yyz'");
+ }*/
+
+ @Test public void testXMLSelect() {
+ helpResolve("select root.node3. at node4 from xmltest.doc4"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLSelect2() {
+ helpResolve("select root.node3.node4 from xmltest.doc4"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLSelect3() {
+ helpResolve("select root. at node6 from xmltest.doc4"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLSelect4() {
+ helpResolve("select root.node6 from xmltest.doc4"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLSelect5() {
+ helpResolve("select node2 from xmltest.doc4"); //$NON-NLS-1$
+ }
+
+ @Test public void testDEFECT_19771() {
+ helpResolveException("select node2 AS NODE2 from xmltest.doc4"); //$NON-NLS-1$
+ }
+
+ @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$
+ Expression[] exprs = new Expression[]{es1, es2};
+
+ Function context = new Function("context", exprs); //$NON-NLS-1$
+
+ CompareCriteria expected = new CompareCriteria();
+ expected.setLeftExpression(context);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(new Constant("yyz")); //$NON-NLS-1$
+
+ Query query = (Query) helpResolve("select * from xmltest.doc1 where context(node3, node1) = 'yyz'"); //$NON-NLS-1$
+ Criteria actual = query.getCriteria();
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ @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);
+ Expression[] exprs = new Expression[]{es1};
+
+ Function context = new Function("rowlimit", exprs); //$NON-NLS-1$
+
+ CompareCriteria expected = new CompareCriteria();
+ expected.setLeftExpression(context);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(new Constant(new Integer(2)));
+
+ Query query = (Query) helpResolve("select * from xmltest.doc1 where rowlimit(node3) = 2"); //$NON-NLS-1$
+ Criteria actual = query.getCriteria();
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ @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};
+
+ Function context = new Function("rowlimitexception", exprs); //$NON-NLS-1$
+
+ CompareCriteria expected = new CompareCriteria();
+ expected.setLeftExpression(context);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(new Constant(new Integer(2)));
+
+ Query query = (Query) helpResolve("select * from xmltest.doc1 where rowlimitexception(node3) = 2"); //$NON-NLS-1$
+ Criteria actual = query.getCriteria();
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLQueryFail1() {
+ helpResolveException("SELECT DISTINCT * FROM vm1.doc1"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLQueryFail2() {
+ helpResolveException("SELECT a2 FROM vm1.doc1"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLQueryFail3() {
+ helpResolveException("SELECT * FROM vm1.doc1, vm1.doc2"); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLWithOrderBy1() {
+ helpResolveException("select * from xmltest.doc4 order by node1"); //$NON-NLS-1$
+ }
+
+ @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$
+
+ // Expected right expression
+ Function convert = new Function("convert", new Expression[] { new Constant(new Integer(5)), new Constant("string") }); //$NON-NLS-1$ //$NON-NLS-2$
+
+ // Expected criteria
+ CompareCriteria expected = new CompareCriteria();
+ expected.setLeftExpression(es1);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(convert);
+
+ // Resolve the query and check against expected objects
+ Query query = (Query) helpResolve("select * from xmltest.doc1 where node1 = convert(5, string)"); //$NON-NLS-1$
+ Criteria actual = query.getCriteria();
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ Function actualRightExpr = (Function) ((CompareCriteria)actual).getRightExpression();
+ assertNotNull("Failed to resolve function", actualRightExpr.getFunctionDescriptor()); //$NON-NLS-1$
+ }
+
+ @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$
+ expected.setLeftExpression(es);
+ 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'"), RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ Criteria actual = query.getCriteria();
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ @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$
+ }
+
+ @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$
+ expected.setLeftExpression(es);
+ expected.setOperator(CompareCriteria.EQ);
+ expected.setRightExpression(new Constant("yyz")); //$NON-NLS-1$
+
+ Query query = (Query) helpResolve("select xmltest.doc1.xml from xmltest.doc1 where node1 = 'yyz'"); //$NON-NLS-1$
+ Criteria actual = query.getCriteria();
+ assertEquals("Did not match expected criteria", expected, actual); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestOrderByRewrite.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/rewriter/TestOrderByRewrite.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestOrderByRewrite.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,327 +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.rewriter;
-
-import static org.junit.Assert.*;
-import static org.teiid.query.rewriter.TestQueryRewriter.*;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-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;
-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.visitor.ElementCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-
-
-/**
- * Converted from older resolver tests
- */
-public class TestOrderByRewrite {
-
- private static Command getCommand(String sql) throws TeiidComponentException, TeiidProcessingException {
- Command command = QueryParser.getQueryParser().parseCommand(sql);
-
- QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
-
- return QueryRewriter.rewrite(command, FakeMetadataFactory.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);
- }
-
- 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);
- 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$
- }
- }
-
- private void helpCheckExpressionsSymbols(OrderBy langObj,
- String[] functionsNames) {
- int expCount = 0;
- for (Iterator i = langObj.getSortKeys().iterator(); i.hasNext();) {
- SingleElementSymbol ses = (SingleElementSymbol)i.next();
- if (ses instanceof ExpressionSymbol) {
- assertEquals("Expression Symbols does not match: ", functionsNames[expCount++], ses.toString()); //$NON-NLS-1$
- }
- }
- assertEquals("Wrong number of Symbols: ", functionsNames.length, expCount); //$NON-NLS-1$
- }
-
- @Test public void testNumberedOrderBy1() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1, e2, e3 as x, (5+2) as y FROM pm1.g1 ORDER BY 3, 4, 1, 2"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- new String[] { "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- helpCheckExpressionsSymbols(resolvedQuery.getOrderBy(),
- new String[] {});
- }
-
- @Test public void testNumberedOrderBy1_1() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1, e2, e3 as x, (5 + e4) FROM pm1.g1 ORDER BY 3, 4, 1, 2"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e3", "pm1.g1.e4", "pm1.g1.e1", "pm1.g1.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- new String[] { "pm1.g1.e3", "pm1.g1.e4", "pm1.g1.e1", "pm1.g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-
- helpCheckExpressionsSymbols(resolvedQuery.getOrderBy(),
- new String[] {"(5.0 + e4)"}); //$NON-NLS-1$
- }
-
- @Test public void testNumberedOrderBy1_2() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1, e2, concat(e3,'x'), concat(e2, 5) FROM pm1.g1 ORDER BY 3, 4, 1, 2"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e3", "pm1.g1.e2", "pm1.g1.e1", "pm1.g1.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- new String[] { "pm1.g1.e3", "pm1.g1.e2", "pm1.g1.e1", "pm1.g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-
- helpCheckExpressionsSymbols(resolvedQuery.getOrderBy(),
- new String[] {"concat(e3, 'x')", "concat(e2, '5')"}); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testNumberedOrderBy1_3() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1, avg(e2), e3, concat(e2, 5) FROM pm1.g1 ORDER BY 3, 4, 1, 2"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e3", "pm1.g1.e2", "pm1.g1.e1", "pm1.g1.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- new String[] { "pm1.g1.e3", "pm1.g1.e2", "pm1.g1.e1", "pm1.g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-
- helpCheckExpressionsSymbols(resolvedQuery.getOrderBy(),
- new String[] {"concat(e2, '5')", "AVG(e2)"}); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testNumberedOrderBy1_4() throws Exception {
- String sql = "select e1, (select e2 from pm4.g1) from pm4.g2 X order by 2"; //$NON-NLS-1$
- Query resolvedQuery = (Query) getCommand(sql);
-
- helpCheckExpressionsSymbols(resolvedQuery.getOrderBy(),
- new String[] {"(SELECT e2 FROM pm4.g1 LIMIT 2)"}); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy1() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1, e2, e3 as x, (5+2) as y FROM pm1.g1 ORDER BY x, y, pm1.g1.e1, e2"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- new String[] { "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testOrderBy2() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT * FROM pm1.g1 ORDER BY e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy3() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT * FROM pm1.g1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy4() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT e1 FROM pm1.g1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy5() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT e1 FROM pm1.g1 ORDER BY e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy6() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT e1 FROM pm1.g1 AS x ORDER BY e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "x.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy7() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT e1 FROM pm1.g1 AS x ORDER BY x.e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "x.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy8() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT x.e1 FROM pm1.g1 AS x ORDER BY e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "x.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy9() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT x.e1 FROM pm1.g1 AS x ORDER BY x.e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "x.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy10() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT a.e1, b.e1 FROM pm1.g1 AS a, pm1.g1 AS b ORDER BY a.e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "a.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy11() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT a.e1, b.e1 FROM pm1.g1 AS a, pm1.g1 AS b ORDER BY b.e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "b.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy12() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT a.e1, pm1.g1.e1 FROM pm1.g1 AS a, pm1.g1 ORDER BY a.e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "a.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy13() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT a.e1, pm1.g1.e1 FROM pm1.g1 AS a, pm1.g1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy14() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT a.e1 as x, pm1.g1.e1 as y FROM pm1.g1 AS a, pm1.g1 ORDER BY x"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "a.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testOrderBy15() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT a.e1 as x, pm1.g1.e1 as y FROM pm1.g1 AS a, pm1.g1 ORDER BY y"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testNumberedOrderBy2() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT * FROM pm1.g1 ORDER BY 1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testNumberedOrderBy3() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT * FROM pm1.g1 ORDER BY 1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testNumberedOrderBy4() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT e1 FROM pm1.g1 ORDER BY 1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testNumberedOrderBy5() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT x.e1 FROM pm1.g1 AS x ORDER BY 1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "x.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- @Test public void testNumberedOrderBy8() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT a.e1 as x, pm1.g1.e1 as y FROM pm1.g1 AS a, pm1.g1 ORDER BY 1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "a.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
- }
-
- /**
- * partially-qualified ORDER BY's with ambiguous short group names
- */
- @Test public void testDefect10729() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY g1.e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
- }
-
- /**
- * partially-qualified ORDER BY's with ambiguous short group names
- */
- @Test public void testDefect10729a() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY e1"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
- }
-
- @Test public void testAliasedOrderBy_ConstantElement() throws Exception {
- Query resolvedQuery = (Query) getCommand("SELECT 0 AS SOMEINT, pm1.g1.e1 as y FROM pm1.g1 ORDER BY y, SOMEINT"); //$NON-NLS-1$
- helpCheckElements(resolvedQuery.getOrderBy(),
- new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
- 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$
- }
-
- @Test public void testRewiteOrderBy1() {
- helpTestRewriteCommand("SELECT 1+1 as a FROM pm1.g1 union select pm1.g2.e1 from pm1.g2 order by a", "SELECT '2' AS a FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY a"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testOrderByDuplicateRemoval() {
- String sql = "SELECT pm1.g1.e1, pm1.g1.e1 as c1234567890123456789012345678901234567890, pm1.g1.e2 FROM pm1.g1 ORDER BY c1234567890123456789012345678901234567890, e2, e1 "; //$NON-NLS-1$
- helpTestRewriteCommand(sql, "SELECT pm1.g1.e1, pm1.g1.e1 AS c1234567890123456789012345678901234567890, pm1.g1.e2 FROM pm1.g1 ORDER BY c1234567890123456789012345678901234567890, pm1.g1.e2"); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestOrderByRewrite.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/rewriter/TestOrderByRewrite.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestOrderByRewrite.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestOrderByRewrite.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,326 @@
+/*
+ * 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.rewriter;
+
+import static org.junit.Assert.*;
+import static org.teiid.query.rewriter.TestQueryRewriter.*;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+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.lang.Command;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.Query;
+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.visitor.ElementCollectorVisitor;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+
+/**
+ * Converted from older resolver tests
+ */
+public class TestOrderByRewrite {
+
+ private static Command getCommand(String sql) throws TeiidComponentException, TeiidProcessingException {
+ Command command = QueryParser.getQueryParser().parseCommand(sql);
+
+ QueryResolver.resolveCommand(command, RealMetadataFactory.example1Cached());
+
+ return QueryRewriter.rewrite(command, RealMetadataFactory.example1Cached(), null);
+ }
+
+ private void helpCheckElements(OrderBy langObj,
+ String[] elementNames,
+ String[] elementIDs) {
+ 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 = elements.get(i);
+ assertEquals("Element name does not match: ", elementNames[i].toUpperCase(), symbol.getName().toUpperCase()); //$NON-NLS-1$
+
+ 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.getFullName().toUpperCase()); //$NON-NLS-1$
+ }
+ }
+
+ private void helpCheckExpressionsSymbols(OrderBy langObj,
+ String[] functionsNames) {
+ int expCount = 0;
+ 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$
+ }
+ }
+ assertEquals("Wrong number of Symbols: ", functionsNames.length, expCount); //$NON-NLS-1$
+ }
+
+ @Test public void testNumberedOrderBy1() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1, e2, e3 as x, (5+2) as y FROM pm1.g1 ORDER BY 3, 4, 1, 2"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ new String[] { "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+ helpCheckExpressionsSymbols(resolvedQuery.getOrderBy(),
+ new String[] {});
+ }
+
+ @Test public void testNumberedOrderBy1_1() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1, e2, e3 as x, (5 + e4) FROM pm1.g1 ORDER BY 3, 4, 1, 2"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e3", "pm1.g1.e4", "pm1.g1.e1", "pm1.g1.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ new String[] { "pm1.g1.e3", "pm1.g1.e4", "pm1.g1.e1", "pm1.g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+
+ helpCheckExpressionsSymbols(resolvedQuery.getOrderBy(),
+ new String[] {"(5.0 + e4)"}); //$NON-NLS-1$
+ }
+
+ @Test public void testNumberedOrderBy1_2() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1, e2, concat(e3,'x'), concat(e2, 5) FROM pm1.g1 ORDER BY 3, 4, 1, 2"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e3", "pm1.g1.e2", "pm1.g1.e1", "pm1.g1.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ new String[] { "pm1.g1.e3", "pm1.g1.e2", "pm1.g1.e1", "pm1.g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+
+ helpCheckExpressionsSymbols(resolvedQuery.getOrderBy(),
+ new String[] {"concat(e3, 'x')", "concat(e2, '5')"}); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testNumberedOrderBy1_3() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1, avg(e2), e3, concat(e2, 5) FROM pm1.g1 ORDER BY 3, 4, 1, 2"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e3", "pm1.g1.e2", "pm1.g1.e1", "pm1.g1.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ new String[] { "pm1.g1.e3", "pm1.g1.e2", "pm1.g1.e1", "pm1.g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+
+ helpCheckExpressionsSymbols(resolvedQuery.getOrderBy(),
+ new String[] {"concat(e2, '5')", "AVG(e2)"}); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testNumberedOrderBy1_4() throws Exception {
+ String sql = "select e1, (select e2 from pm4.g1) from pm4.g2 X order by 2"; //$NON-NLS-1$
+ Query resolvedQuery = (Query) getCommand(sql);
+
+ helpCheckExpressionsSymbols(resolvedQuery.getOrderBy(),
+ new String[] {"(SELECT e2 FROM pm4.g1 LIMIT 2)"}); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy1() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1, e2, e3 as x, (5+2) as y FROM pm1.g1 ORDER BY x, y, pm1.g1.e1, e2"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ new String[] { "pm1.g1.e3", "pm1.g1.e1", "pm1.g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testOrderBy2() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT * FROM pm1.g1 ORDER BY e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy3() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT * FROM pm1.g1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy4() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT e1 FROM pm1.g1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy5() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT e1 FROM pm1.g1 ORDER BY e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy6() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT e1 FROM pm1.g1 AS x ORDER BY e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "x.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy7() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT e1 FROM pm1.g1 AS x ORDER BY x.e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "x.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy8() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT x.e1 FROM pm1.g1 AS x ORDER BY e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "x.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy9() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT x.e1 FROM pm1.g1 AS x ORDER BY x.e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "x.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy10() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT a.e1, b.e1 FROM pm1.g1 AS a, pm1.g1 AS b ORDER BY a.e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "a.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy11() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT a.e1, b.e1 FROM pm1.g1 AS a, pm1.g1 AS b ORDER BY b.e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "b.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy12() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT a.e1, pm1.g1.e1 FROM pm1.g1 AS a, pm1.g1 ORDER BY a.e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "a.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy13() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT a.e1, pm1.g1.e1 FROM pm1.g1 AS a, pm1.g1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy14() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT a.e1 as x, pm1.g1.e1 as y FROM pm1.g1 AS a, pm1.g1 ORDER BY x"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "a.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testOrderBy15() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT a.e1 as x, pm1.g1.e1 as y FROM pm1.g1 AS a, pm1.g1 ORDER BY y"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testNumberedOrderBy2() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT * FROM pm1.g1 ORDER BY 1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testNumberedOrderBy3() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT * FROM pm1.g1 ORDER BY 1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testNumberedOrderBy4() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT e1 FROM pm1.g1 ORDER BY 1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testNumberedOrderBy5() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT x.e1 FROM pm1.g1 AS x ORDER BY 1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "x.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ @Test public void testNumberedOrderBy8() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT a.e1 as x, pm1.g1.e1 as y FROM pm1.g1 AS a, pm1.g1 ORDER BY 1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "a.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
+ }
+
+ /**
+ * partially-qualified ORDER BY's with ambiguous short group names
+ */
+ @Test public void testDefect10729() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY g1.e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+ }
+
+ /**
+ * partially-qualified ORDER BY's with ambiguous short group names
+ */
+ @Test public void testDefect10729a() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY e1"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$
+ }
+
+ @Test public void testAliasedOrderBy_ConstantElement() throws Exception {
+ Query resolvedQuery = (Query) getCommand("SELECT 0 AS SOMEINT, pm1.g1.e1 as y FROM pm1.g1 ORDER BY y, SOMEINT"); //$NON-NLS-1$
+ helpCheckElements(resolvedQuery.getOrderBy(),
+ new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
+ 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$
+ }
+
+ @Test public void testRewiteOrderBy1() {
+ helpTestRewriteCommand("SELECT 1+1 as a FROM pm1.g1 union select pm1.g2.e1 from pm1.g2 order by a", "SELECT '2' AS a FROM pm1.g1 UNION SELECT pm1.g2.e1 FROM pm1.g2 ORDER BY a"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testOrderByDuplicateRemoval() {
+ String sql = "SELECT pm1.g1.e1, pm1.g1.e1 as c1234567890123456789012345678901234567890, pm1.g1.e2 FROM pm1.g1 ORDER BY c1234567890123456789012345678901234567890, e2, e1 "; //$NON-NLS-1$
+ helpTestRewriteCommand(sql, "SELECT pm1.g1.e1, pm1.g1.e1 AS c1234567890123456789012345678901234567890, pm1.g1.e2 FROM pm1.g1 ORDER BY c1234567890123456789012345678901234567890, pm1.g1.e2"); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,2455 +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.rewriter;
-
-import static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.TimeZone;
-
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.client.metadata.ParameterInfo;
-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.TeiidRuntimeException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.TimestampWithTimezone;
-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;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.resolver.QueryResolver;
-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.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.IsNullCriteria;
-import org.teiid.query.sql.lang.MatchCriteria;
-import org.teiid.query.sql.lang.ProcedureContainer;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
-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.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.util.CommandContext;
-import org.teiid.query.util.ContextProperties;
-
-
- at SuppressWarnings("nls")
-public class TestQueryRewriter {
-
- private static final String TRUE_STR = "1 = 1"; //$NON-NLS-1$
- private static final String FALSE_STR = "1 = 0"; //$NON-NLS-1$
-
- // ################################## TEST HELPERS ################################
-
- private Criteria parseCriteria(String critStr, QueryMetadataInterface metadata) {
- try {
- Criteria crit = QueryParser.getQueryParser().parseCriteria(critStr);
-
- // resolve against metadata
- QueryResolver.resolveCriteria(crit, metadata);
-
- return crit;
- } catch(TeiidException e) {
- throw new RuntimeException(e);
- }
- }
-
- private Criteria helpTestRewriteCriteria(String original, String expected) {
- try {
- return helpTestRewriteCriteria(original, expected, false);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- private Criteria helpTestRewriteCriteria(String original, String expected, boolean rewrite) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Criteria expectedCrit = parseCriteria(expected, metadata);
- if (rewrite) {
- QueryResolver.resolveCriteria(expectedCrit, metadata);
- expectedCrit = QueryRewriter.rewriteCriteria(expectedCrit, null, null, metadata);
- }
- return helpTestRewriteCriteria(original, expectedCrit, metadata);
- }
-
- private Map<ElementSymbol, Integer> elements;
- private List<List> tuples;
-
- @Before public void setUp() {
- elements = null;
- tuples = new ArrayList<List>();
- }
-
- private Criteria helpTestRewriteCriteria(String original, Criteria expectedCrit, QueryMetadataInterface metadata) {
- Criteria origCrit = parseCriteria(original, metadata);
-
- Criteria actual = null;
- // rewrite
- try {
- ArrayList<Boolean> booleanVals = new ArrayList<Boolean>(tuples.size());
- for (List<Object> tuple : tuples) {
- booleanVals.add(new Evaluator(elements, null, null).evaluate(origCrit, tuple));
- }
- actual = QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
- assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
- for (int i = 0; i < tuples.size(); i++) {
- assertEquals(tuples.get(i).toString(), booleanVals.get(i), new Evaluator(elements, null, null).evaluate(actual, tuples.get(i)));
- }
- } catch(TeiidException e) {
- throw new RuntimeException(e);
- }
- return actual;
- }
-
- private Expression helpTestRewriteExpression(String original, String expected, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException {
- Expression actualExp = QueryParser.getQueryParser().parseExpression(original);
- ResolverVisitor.resolveLanguageObject(actualExp, metadata);
- CommandContext context = new CommandContext();
- context.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
- actualExp = QueryRewriter.rewriteExpression(actualExp, null, context, metadata);
- if (expected != null) {
- Expression expectedExp = QueryParser.getQueryParser().parseExpression(expected);
- ResolverVisitor.resolveLanguageObject(expectedExp, metadata);
- assertEquals(expectedExp, actualExp);
- }
- return actualExp;
- }
-
- private String getRewritenProcedure(String procedure, String userUpdateStr, String procedureType) throws TeiidComponentException, TeiidProcessingException {
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
-
- return getRewritenProcedure(userUpdateStr, metadata);
- }
-
- private String getRewritenProcedure(String userUpdateStr,
- QueryMetadataInterface metadata) throws TeiidComponentException,
- QueryMetadataException, TeiidProcessingException {
- ProcedureContainer userCommand = (ProcedureContainer)QueryParser.getQueryParser().parseCommand(userUpdateStr);
- QueryResolver.resolveCommand(userCommand, metadata);
- CreateUpdateProcedureCommand proc = (CreateUpdateProcedureCommand)QueryResolver.expandCommand(userCommand, metadata, null);
- QueryRewriter.rewrite(userCommand, metadata, null);
- Command result = QueryRewriter.rewrite(proc, metadata, null);
- return result.toString();
- }
-
- static Command helpTestRewriteCommand(String original, String expected) {
- try {
- return helpTestRewriteCommand(original, expected, FakeMetadataFactory.example1Cached());
- } catch(TeiidException e) {
- throw new TeiidRuntimeException(e);
- }
- }
-
- public static Command helpTestRewriteCommand(String original, String expected, QueryMetadataInterface metadata) throws TeiidException {
- Command command = QueryParser.getQueryParser().parseCommand(original);
- QueryResolver.resolveCommand(command, metadata);
- Command rewriteCommand = QueryRewriter.rewrite(command, metadata, null);
- assertEquals("Rewritten command was not expected", expected, rewriteCommand.toString()); //$NON-NLS-1$
- return rewriteCommand;
- }
-
- @Test public void testRewriteUnknown() {
- helpTestRewriteCriteria("pm1.g1.e1 = '1' and '1' = convert(null, string)", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteUnknown1() {
- helpTestRewriteCriteria("pm1.g1.e1 = '1' or '1' = convert(null, string)", "pm1.g1.e1 = '1'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteUnknown2() {
- helpTestRewriteCriteria("not('1' = convert(null, string))", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteUnknown3() {
- helpTestRewriteCriteria("pm1.g1.e1 like convert(null, string))", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteUnknown4() {
- helpTestRewriteCriteria("null in ('a', 'b', 'c')", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteUnknown5() {
- helpTestRewriteCriteria("(null <> null) and 1 = 0", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteUnknown6() {
- helpTestRewriteCriteria("not(pm1.g1.e1 = '1' and '1' = convert(null, string))", "pm1.g1.e1 <> '1'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteUnknown7() {
- helpTestRewriteCriteria("not(pm1.g1.e1 = '1' or '1' = convert(null, string))", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteUnknown8() {
- helpTestRewriteCriteria("pm1.g1.e1 in (2, null)", "pm1.g1.e1 = '2'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteInCriteriaWithRepeats() {
- helpTestRewriteCriteria("pm1.g1.e1 in ('1', '1', '2')", "pm1.g1.e1 IN ('1', '2')"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteInCriteriaWithSingleValue() {
- helpTestRewriteCriteria("pm1.g1.e1 in ('1')", "pm1.g1.e1 = '1'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteInCriteriaWithSingleValue1() {
- helpTestRewriteCriteria("pm1.g1.e1 not in ('1')", "pm1.g1.e1 != '1'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteInCriteriaWithConvert() {
- helpTestRewriteCriteria("convert(pm1.g1.e2, string) not in ('x')", "pm1.g1.e2 IS NOT NULL"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteInCriteriaWithNoValues() throws Exception {
- ElementSymbol e1 = new ElementSymbol("e1");
- e1.setGroupSymbol(new GroupSymbol("g1"));
- Criteria crit = new SetCriteria(e1, Collections.EMPTY_LIST); //$NON-NLS-1$
-
- Criteria actual = QueryRewriter.rewriteCriteria(crit, null, null, null);
-
- IsNullCriteria inc = new IsNullCriteria(e1);
- inc.setNegated(true);
- assertEquals(inc, actual);
- }
-
- @Test public void testRewriteBetweenCriteria1() {
- helpTestRewriteCriteria("pm1.g1.e1 BETWEEN 1000 AND 2000", "(pm1.g1.e1 >= '1000') AND (pm1.g1.e1 <= '2000')"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteBetweenCriteria2() {
- helpTestRewriteCriteria("pm1.g1.e1 NOT BETWEEN 1000 AND 2000", "(pm1.g1.e1 < '1000') OR (pm1.g1.e1 > '2000')"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCrit1() {
- helpTestRewriteCriteria("concat('a','b') = 'ab'", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCrit2() {
- helpTestRewriteCriteria("'x' = pm1.g1.e1", "(pm1.g1.e1 = 'x')"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCrit3() {
- helpTestRewriteCriteria("pm1.g1.e1 = convert('a', string)", "pm1.g1.e1 = 'a'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCrit4() {
- helpTestRewriteCriteria("pm1.g1.e1 = CONVERT('a', string)", "pm1.g1.e1 = 'a'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCrit5() {
- helpTestRewriteCriteria("pm1.g1.e1 in ('a')", "pm1.g1.e1 = 'a'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCrit6() {
- helpTestRewriteCriteria("1 = convert(pm1.g1.e1,integer) + 10", "pm1.g1.e1 = '-9'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCrit7() {
- helpTestRewriteCriteria("((pm1.g1.e1 = 1) and (pm1.g1.e1 = 1))", "pm1.g1.e1 = '1'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteMatchCritEscapeChar1() {
- helpTestRewriteCriteria("pm1.g1.e1 LIKE 'x_' ESCAPE '\\'", "pm1.g1.e1 LIKE 'x_'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteMatchCritEscapeChar2() {
- helpTestRewriteCriteria("pm1.g1.e1 LIKE '#%x' ESCAPE '#'", "pm1.g1.e1 LIKE '#%x' ESCAPE '#'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteMatchCritEscapeChar3() {
- helpTestRewriteCriteria("pm1.g1.e1 LIKE '#%x'", "pm1.g1.e1 LIKE '#%x'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteMatchCritEscapeChar4() {
- helpTestRewriteCriteria("pm1.g1.e1 LIKE pm1.g1.e1 ESCAPE '#'", "pm1.g1.e1 LIKE pm1.g1.e1 ESCAPE '#'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteMatchCritEscapeChar5() throws Exception {
- MatchCriteria mcrit = new MatchCriteria(new ElementSymbol("pm1.g1.e1"), new Constant(null, DataTypeManager.DefaultDataClasses.STRING), '#'); //$NON-NLS-1$
- Criteria expected = QueryRewriter.UNKNOWN_CRITERIA;
-
- Object actual = QueryRewriter.rewriteCriteria(mcrit, null, null, null);
- assertEquals("Did not get expected rewritten criteria", expected, actual); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMatchCrit1() {
- helpTestRewriteCriteria("pm1.g1.e1 LIKE 'x' ESCAPE '\\'", "pm1.g1.e1 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteMatchCrit2() {
- helpTestRewriteCriteria("pm1.g1.e1 NOT LIKE 'x'", "pm1.g1.e1 <> 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteMatchCrit3() {
- helpTestRewriteCriteria("pm1.g1.e1 NOT LIKE '%'", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritTimestampCreate1() {
- helpTestRewriteCriteria("timestampCreate(pm3.g1.e2, pm3.g1.e3) = {ts'2004-11-23 09:25:00'}", "(pm3.g1.e2 = {d'2004-11-23'}) AND (pm3.g1.e3 = {t'09:25:00'})"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritTimestampCreate2() {
- helpTestRewriteCriteria("{ts'2004-11-23 09:25:00'} = timestampCreate(pm3.g1.e2, pm3.g1.e3)", "(pm3.g1.e2 = {d'2004-11-23'}) AND (pm3.g1.e3 = {t'09:25:00'})"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritSwap1() {
- helpTestRewriteCriteria("'x' = pm1.g1.e1", "pm1.g1.e1 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritSwap2() {
- helpTestRewriteCriteria("'x' <> pm1.g1.e1", "pm1.g1.e1 <> 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritSwap3() {
- helpTestRewriteCriteria("'x' < pm1.g1.e1", "pm1.g1.e1 > 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritSwap4() {
- helpTestRewriteCriteria("'x' <= pm1.g1.e1", "pm1.g1.e1 >= 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritSwap5() {
- helpTestRewriteCriteria("'x' > pm1.g1.e1", "pm1.g1.e1 < 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritSwap6() {
- helpTestRewriteCriteria("'x' >= pm1.g1.e1", "pm1.g1.e1 <= 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritExpr_op1() {
- helpTestRewriteCriteria("pm1.g1.e2 + 5 = 10", "pm1.g1.e2 = 5"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritExpr_op2() {
- helpTestRewriteCriteria("pm1.g1.e2 - 5 = 10", "pm1.g1.e2 = 15"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritExpr_op3() {
- helpTestRewriteCriteria("pm1.g1.e2 * 5 = 10", "pm1.g1.e2 = 2"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritExpr_op4() {
- helpTestRewriteCriteria("pm1.g1.e2 / 5 = 10", "pm1.g1.e2 = 50"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritExpr_signFlip1() {
- helpTestRewriteCriteria("pm1.g1.e2 * -5 > 10", "pm1.g1.e2 < -2"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritExpr_signFlip2() {
- helpTestRewriteCriteria("pm1.g1.e2 * -5 >= 10", "pm1.g1.e2 <= -2"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritExpr_signFlip3() {
- helpTestRewriteCriteria("pm1.g1.e2 * -5 < 10", "pm1.g1.e2 > -2"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritExpr_signFlip4() {
- helpTestRewriteCriteria("pm1.g1.e2 * -5 <= 10", "pm1.g1.e2 >= -2"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritExpr_backwards1() {
- helpTestRewriteCriteria("5 + pm1.g1.e2 <= 10", "pm1.g1.e2 <= 5"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritExpr_backwards2() {
- helpTestRewriteCriteria("-5 * pm1.g1.e2 <= 10", "pm1.g1.e2 >= -2"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritExpr_unhandled1() {
- helpTestRewriteCriteria("5 / pm1.g1.e2 <= 10", "5 / pm1.g1.e2 <= 10"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritExpr_unhandled2() {
- helpTestRewriteCriteria("5 - pm1.g1.e2 <= 10", "5 - pm1.g1.e2 <= 10"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCrit_parseDate() {
- helpTestRewriteCriteria("PARSEDATE(pm3.g1.e1, 'yyyyMMdd') = {d'2003-05-01'}", //$NON-NLS-1$
- "pm3.g1.e1 = '20030501'" ); //$NON-NLS-1$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCrit_parseDate1() {
- helpTestRewriteCriteria("PARSEDATE(pm3.g1.e1, 'yyyyMM') = {d'2003-05-01'}", //$NON-NLS-1$
- "pm3.g1.e1 = '200305'" ); //$NON-NLS-1$
- }
-
- @Ignore(value="we're no longer considering parsedate directly")
- @Test public void testRewriteCrit_parseDate2() {
- helpTestRewriteCriteria("PARSEDATE(pm3.g1.e1, 'yyyyMM') = {d'2003-05-02'}", //$NON-NLS-1$
- "1 = 0" ); //$NON-NLS-1$
- }
-
- @Ignore(value="Should be moved to the validator")
- @Test public void testRewriteCrit_invalidParseDate() {
- QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
- Criteria origCrit = parseCriteria("PARSEDATE(pm3.g1.e1, '''') = {d'2003-05-01'}", metadata); //$NON-NLS-1$
-
- try {
- QueryRewriter.rewriteCriteria(origCrit, null, null, null);
- fail("Expected failure"); //$NON-NLS-1$
- } catch(TeiidException e) {
- assertEquals("Error Code:ERR.015.001.0003 Message:Error simplifying criteria: PARSEDATE(pm3.g1.e1, '''') = {d'2003-05-01'}", e.getMessage()); //$NON-NLS-1$
- }
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCrit_parseTime() {
- helpTestRewriteCriteria("PARSETIME(pm3.g1.e1, 'HH mm ss') = {t'13:25:04'}", //$NON-NLS-1$
- "pm3.g1.e1 = '13 25 04'" ); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCrit_parseTimestamp() {
- helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') = {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
- "1 = 0" ); //$NON-NLS-1$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCrit_parseTimestamp1() {
- helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') = {ts'2003-01-01 00:25:00.0'}", //$NON-NLS-1$
- "pm3.g1.e1 = '2003 01 25'" ); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCrit_parseTimestamp2() {
- helpTestRewriteCriteria("PARSETimestamp(CONVERT(pm3.g1.e2, string), 'yyyy-MM-dd') = {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
- "1 = 0" ); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCrit_parseTimestamp3() {
- helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') <> {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
- "pm3.g1.e1 is not null" ); //$NON-NLS-1$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCrit_parseTimestamp4() {
- helpTestRewriteCriteria("PARSETimestamp(CONVERT(pm3.g1.e2, string), 'yyyy-MM-dd') = {ts'2003-05-01 00:00:00.0'}", //$NON-NLS-1$
- "pm3.g1.e2 = {d'2003-05-01'}" ); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCrit_parseTimestamp_notEquality() {
- helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') > {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
- "PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') > {ts'2003-05-01 13:25:04.5'}" ); //$NON-NLS-1$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCrit_parseTimestamp_decompose() {
- helpTestRewriteCriteria("PARSETIMESTAMP(CONCAT(FORMATDATE(pm3.g1.e2, 'yyyyMMdd'), FORMATTIME(pm3.g1.e3, 'HHmmss')), 'yyyyMMddHHmmss') = PARSETIMESTAMP('19690920183045', 'yyyyMMddHHmmss')", //$NON-NLS-1$
- "(pm3.g1.e2 = {d'1969-09-20'}) AND (pm3.g1.e3 = {t'18:30:45'})" ); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCrit_timestampCreate_decompose() {
- helpTestRewriteCriteria("timestampCreate(pm3.g1.e2, pm3.g1.e3) = PARSETIMESTAMP('19690920183045', 'yyyyMMddHHmmss')", //$NON-NLS-1$
- "(pm3.g1.e2 = {d'1969-09-20'}) AND (pm3.g1.e3 = {t'18:30:45'})" ); //$NON-NLS-1$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCrit_parseInteger() {
- helpTestRewriteCriteria("parseInteger(pm1.g1.e1, '#,##0') = 1234", //$NON-NLS-1$
- "pm1.g1.e1 = '1,234'" ); //$NON-NLS-1$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCrit_parseLong() {
- helpTestRewriteCriteria("parseLong(pm1.g1.e1, '#,##0') = convert(1234, long)", //$NON-NLS-1$
- "pm1.g1.e1 = '1,234'" ); //$NON-NLS-1$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCrit_parseBigInteger() {
- helpTestRewriteCriteria("parseBigInteger(pm1.g1.e1, '#,##0') = convert(1234, biginteger)", //$NON-NLS-1$
- "pm1.g1.e1 = '1,234'" ); //$NON-NLS-1$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCrit_parseFloat() {
- helpTestRewriteCriteria("parseFloat(pm1.g1.e1, '#,##0.###') = convert(1234.123, float)", //$NON-NLS-1$
- "pm1.g1.e1 = '1,234.123'" ); //$NON-NLS-1$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCrit_parseDouble() {
- helpTestRewriteCriteria("parseDouble(pm1.g1.e1, '$#,##0.00') = convert(1234.5, double)", //$NON-NLS-1$
- "pm1.g1.e1 = '$1,234.50'" ); //$NON-NLS-1$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCrit_parseBigDecimal() {
- helpTestRewriteCriteria("parseBigDecimal(pm1.g1.e1, '#,##0.###') = convert(1234.1234, bigdecimal)", //$NON-NLS-1$
- "pm1.g1.e1 = '1,234.123'" ); //$NON-NLS-1$
- }
-
- @Ignore(value="Cannot deterime if the format is narrowing")
- @Test public void testRewriteCrit_formatDate() {
- helpTestRewriteCriteria("formatDate(pm3.g1.e2, 'yyyyMMdd') = '20030501'", //$NON-NLS-1$
- "pm3.g1.e2 = {d'2003-05-01'}" ); //$NON-NLS-1$
- }
-
- @Ignore(value="Cannot deterime if the format is narrowing")
- @Test public void testRewriteCrit_formatTime() {
- helpTestRewriteCriteria("formatTime(pm3.g1.e3, 'HH mm ss') = '13 25 04'", //$NON-NLS-1$
- "pm3.g1.e3 = {t'13:25:04'}" ); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCrit_formatTimestamp() {
- helpTestRewriteCriteria("formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss') = '05 01, 1974 - 07:00:00'", //$NON-NLS-1$
- "formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss') = '05 01, 1974 - 07:00:00'" ); //$NON-NLS-1$
- }
-
- @Ignore(value="Cannot deterime if the format is narrowing")
- @Test public void testRewriteCrit_formatTimestamp1() {
- helpTestRewriteCriteria("formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss.S') = '05 01, 1974 - 07:00:00.0'", //$NON-NLS-1$
- "pm3.g1.e4 = {ts'1974-05-01 07:00:00.0'}" ); //$NON-NLS-1$
- }
-
- @Ignore(value="Cannot deterime if the format is narrowing")
- @Test public void testRewriteCrit_formatInteger() {
- helpTestRewriteCriteria("formatInteger(pm1.g1.e2, '#,##0') = '1,234'", //$NON-NLS-1$
- "pm1.g1.e2 = 1234" ); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCrit_formatInteger1() {
- helpTestRewriteCriteria("formatInteger(pm1.g1.e2, '#5') = '105'", //$NON-NLS-1$
- "formatInteger(pm1.g1.e2, '#5') = '105'" ); //$NON-NLS-1$
- }
-
- @Ignore(value="Cannot deterime if the format is narrowing")
- @Test public void testRewriteCrit_formatLong() {
- helpTestRewriteCriteria("formatLong(convert(pm1.g1.e2, long), '#,##0') = '1,234,567,890,123'", //$NON-NLS-1$
- "1 = 0" ); //$NON-NLS-1$
- }
-
- @Ignore(value="Cannot deterime if the format is narrowing")
- @Test public void testRewriteCrit_formatLong1() {
- helpTestRewriteCriteria("formatLong(convert(pm1.g1.e2, long), '#,##0') = '1,234,567,890'", //$NON-NLS-1$
- "pm1.g1.e2 = 1234567890" ); //$NON-NLS-1$
- }
-
- @Ignore(value="Cannot deterime if the format is narrowing")
- @Test public void testRewriteCrit_formatTimestampInvert() {
- String original = "formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss.S') = ?"; //$NON-NLS-1$
- String expected = "pm3.g1.e4 = parseTimestamp(?, 'MM dd, yyyy - HH:mm:ss.S')"; //$NON-NLS-1$
-
- helpTestRewriteCriteria(original, expected);
- }
-
- @Test public void testRewriteCrit_plusInvert() {
- String original = "pm1.g1.e2 + 1.1 = ?"; //$NON-NLS-1$
- String expected = "pm1.g1.e2 = ? - 1.1"; //$NON-NLS-1$
-
- helpTestRewriteCriteria(original, expected);
- }
-
- @Ignore(value="Cannot deterime if the format is narrowing")
- @Test public void testRewriteCrit_formatBigInteger() throws Exception {
- 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();
- Criteria origCrit = parseCriteria(original, metadata);
- Criteria expectedCrit = parseCriteria(expected, metadata);
-
- // rewrite
- Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
- assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
- }
-
- @Ignore(value="Cannot deterime if the format is narrowing")
- @Test public void testRewriteCrit_formatFloat() throws Exception {
- 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();
- Criteria origCrit = parseCriteria(original, metadata);
-
- // rewrite
- Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
- assertEquals("Did not rewrite correctly: ", expected, actual.toString()); //$NON-NLS-1$
- }
-
- @Ignore(value="Cannot deterime if the format is narrowing")
- @Test public void testRewriteCrit_formatDouble() throws Exception {
- 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();
- Criteria origCrit = parseCriteria(original, metadata);
- Criteria expectedCrit = parseCriteria(expected, metadata);
- ((CompareCriteria)expectedCrit).setRightExpression(new Constant(new Double(1234.5)));
-
- // rewrite
- Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
- assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
- }
-
- @Ignore(value="Cannot deterime if the format is narrowing")
- @Test public void testRewriteCrit_formatBigDecimal() throws Exception {
- 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();
- Criteria origCrit = parseCriteria(original, metadata);
- Criteria expectedCrit = parseCriteria(expected, metadata);
-
- // rewrite
- Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
- assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCritTimestampDiffDate1() {
- helpTestRewriteCriteria("timestampdiff(SQL_TSI_DAY, {d'2003-05-15'}, {d'2003-05-17'} ) = 2", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCritTimestampDiffDate2() {
- helpTestRewriteCriteria("timestampdiff(SQL_TSI_DAY, {d'2003-06-02'}, {d'2003-05-17'} ) = -16", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCritTimestampDiffDate3() {
- helpTestRewriteCriteria("timestampdiff(SQL_TSI_QUARTER, {d'2002-01-25'}, {d'2003-06-01'} ) = 5", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCritTimestampDiffTime1() {
- helpTestRewriteCriteria("timestampdiff(SQL_TSI_HOUR, {t'03:04:45'}, {t'05:05:36'} ) = 2", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCritTimestampDiffTime1_ignorecase() {
- helpTestRewriteCriteria("timestampdiff(SQL_tsi_HOUR, {t'03:04:45'}, {t'05:05:36'} ) = 2", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteOr1() {
- helpTestRewriteCriteria("(5 = 5) OR (0 = 1)", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteOr2() {
- helpTestRewriteCriteria("(0 = 1) OR (5 = 5)", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteOr3() {
- helpTestRewriteCriteria("(1 = 1) OR (5 = 5)", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteOr4() {
- helpTestRewriteCriteria("(0 = 1) OR (4 = 5)", FALSE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteOr5() {
- helpTestRewriteCriteria("(0 = 1) OR (4 = 5) OR (pm1.g1.e1 = 'x')", "(pm1.g1.e1 = 'x')"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteOr6() {
- helpTestRewriteCriteria("(0 = 1) OR (4 = 5) OR (pm1.g1.e1 = 'x') OR (pm1.g1.e1 = 'y')", "pm1.g1.e1 IN ('x', 'y')"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteOr7() {
- helpTestRewriteCriteria("(pm1.g1.e1 = 'x') OR (pm1.g1.e1 = 'y')", "pm1.g1.e1 IN ('x', 'y')"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteAnd1() {
- helpTestRewriteCriteria("(5 = 5) AND (0 = 1)", FALSE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteAnd2() {
- helpTestRewriteCriteria("(0 = 1) AND (5 = 5)", FALSE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteAnd3() {
- helpTestRewriteCriteria("(1 = 1) AND (5 = 5)", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteAnd4() {
- helpTestRewriteCriteria("(0 = 1) AND (4 = 5)", FALSE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteAnd5() {
- helpTestRewriteCriteria("(1 = 1) AND (5 = 5) AND (pm1.g1.e1 = 'x')", "(pm1.g1.e1 = 'x')"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteAnd6() {
- helpTestRewriteCriteria("(1 = 1) AND (5 = 5) AND (pm1.g1.e1 = 'x')", "(pm1.g1.e1 = 'x')"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteAnd7() {
- helpTestRewriteCriteria("(pm1.g1.e1 = 'x') AND (lower(pm1.g1.e1) = 'y')", "(pm1.g1.e1 = 'x') AND (lcase(pm1.g1.e1) = 'y')"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteMixed1() {
- helpTestRewriteCriteria("((1=1) AND (1=1)) OR ((1=1) AND (1=1))", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed2() {
- helpTestRewriteCriteria("((1=2) AND (1=1)) OR ((1=1) AND (1=1))", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed3() {
- helpTestRewriteCriteria("((1=1) AND (1=2)) OR ((1=1) AND (1=1))", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed4() {
- helpTestRewriteCriteria("((1=1) AND (1=1)) OR ((1=2) AND (1=1))", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed5() {
- helpTestRewriteCriteria("((1=1) AND (1=1)) OR ((1=1) AND (1=2))", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed6() {
- helpTestRewriteCriteria("((1=2) AND (1=1)) OR ((1=2) AND (1=1))", FALSE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed7() {
- helpTestRewriteCriteria("((1=1) AND (1=2)) OR ((1=1) AND (1=2))", FALSE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed8() {
- helpTestRewriteCriteria("((1=2) AND (1=2)) OR ((1=2) AND (1=2))", FALSE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed9() {
- helpTestRewriteCriteria("((1=1) OR (1=1)) AND ((1=1) OR (1=1))", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed10() {
- helpTestRewriteCriteria("((1=2) OR (1=1)) AND ((1=1) OR (1=1))", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed11() {
- helpTestRewriteCriteria("((1=1) OR (1=2)) AND ((1=1) OR (1=1))", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed12() {
- helpTestRewriteCriteria("((1=1) OR (1=1)) AND ((1=2) OR (1=1))", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed13() {
- helpTestRewriteCriteria("((1=1) OR (1=1)) AND ((1=1) OR (1=2))", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed14() {
- helpTestRewriteCriteria("((1=2) OR (1=1)) AND ((1=2) OR (1=1))", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed15() {
- helpTestRewriteCriteria("((1=1) OR (1=2)) AND ((1=1) OR (1=2))", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteMixed16() {
- helpTestRewriteCriteria("((1=2) OR (1=2)) AND ((1=2) OR (1=2))", FALSE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteNot1() {
- helpTestRewriteCriteria("NOT (1=1)", FALSE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteNot2() {
- helpTestRewriteCriteria("NOT (1=2)", TRUE_STR); //$NON-NLS-1$
- }
-
- @Test public void testRewriteNot3() {
- helpTestRewriteCriteria("NOT (pm1.g1.e1='x')", "pm1.g1.e1 <> 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteDefect1() {
- helpTestRewriteCriteria("(('DE' = 'LN') AND (null > '2002-01-01')) OR (('DE' = 'DE') AND (pm1.g1.e1 > '9000000'))", "(pm1.g1.e1 > '9000000')"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteQueryCriteriaAlwaysTrue() {
- helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE 0 = 0", //$NON-NLS-1$
- "SELECT e1 FROM pm1.g1"); //$NON-NLS-1$
- }
-
- @Test public void testSubquery1() {
- helpTestRewriteCommand("SELECT e1 FROM (SELECT e1 FROM pm1.g1 WHERE (1 - 1) = (0 + 0)) AS x", //$NON-NLS-1$
- "SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS x"); //$NON-NLS-1$
- }
-
- @Test public void testExistsSubquery() {
- helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE EXISTS (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
- "SELECT e1 FROM pm1.g1 WHERE EXISTS (SELECT e1 FROM pm1.g2 LIMIT 1)"); //$NON-NLS-1$
- }
-
- @Test public void testCompareSubqueryANY() {
- helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE '3' = ANY (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
- "SELECT e1 FROM pm1.g1 WHERE '3' IN (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
- }
-
- @Test public void testCompareSubquery() {
- helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE '3' = SOME (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
- "SELECT e1 FROM pm1.g1 WHERE '3' IN (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
- }
-
- @Test public void testCompareSubqueryUnknown() {
- helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE null = SOME (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
- "SELECT e1 FROM pm1.g1 WHERE 1 = 0"); //$NON-NLS-1$
- }
-
- @Test public void testINClauseSubquery() {
- helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE '3' IN (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
- "SELECT e1 FROM pm1.g1 WHERE '3' IN (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
- }
-
- @Test public void testRewriteXMLCriteria1() {
- helpTestRewriteCriteria("context(pm1.g1.e1, pm1.g1.e1) = convert(5, string)", "context(pm1.g1.e1, pm1.g1.e1) = '5'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteXMLCriteria2() {
- helpTestRewriteCriteria("context(pm1.g1.e1, convert(5, string)) = 2+3", "context(pm1.g1.e1, '5') = '5'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // HAS Criteria
- @Test public void testRewriteProcedure1() throws Exception {
-
- String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // HAS Criteria
- @Test public void testRewriteProcedure2() throws Exception {
-
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ELSE \n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // HAS Criteria
- @Test public void testRewriteProcedure3() throws Exception {
-
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ELSE \n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- @Test public void testRewriteProcedure4() throws Exception {
-
- String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "IF (INPUT.e2 = 1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // CHANGING
- @Test public void testRewriteProcedure5() throws Exception {
-
- String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "IF (CHANGING.e1 = 'false')\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e2);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // CHANGING
- @Test public void testRewriteProcedure6() throws Exception {
-
- String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "IF (CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // TRANSLATE CRITERIA
- @Test public void testRewriteProcedure7() throws Exception {
-
- String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "IF (CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select e2 from pm1.g1 where TRANSLATE = CRITERIA ON (vm1.g1.e2);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT e2 FROM pm1.g1 WHERE pm1.g1.e2 = 10;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // TRANSLATE CRITERIA
- @Test public void testRewriteProcedure8() throws Exception {
-
- String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "IF (CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select e2 from pm1.g1 where TRANSLATE = CRITERIA ON (vm1.g1.e2) with (vm1.g1.e2 = convert(sqrt(pm1.g1.e2), integer));\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT e2 FROM pm1.g1 WHERE convert(sqrt(pm1.g1.e2), integer) = 10;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // rewrite input/ changing variables
- @Test public void testRewriteProcedure9() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Declare String var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(var1 = 'x' or var1 = 'y')\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2, Input.e2, CHANGING.e2, CHANGING.e1 from pm1.g1 order by CHANGING.e1 + 1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "INSERT into vm1.g1 (e1) values('x')"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- 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 + "END\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- @Test public void testRewriteProcedure10() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e2) WITH (e2 = pm1.g1.e2 + 20);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g1 SET e1='x' where e2 = e2 + 50"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1, pm1.g2 WHERE (pm1.g1.e2 + 20) = ((pm1.g1.e2 + 20) + 50);\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // virtual group elements used in procedure in if statement(HAS CRITERIA)
- @Test public void testRewriteProcedure11() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE string var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = INPUT.e1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g1 SET e1=40"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "DECLARE string var1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "var1 = '40';\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- // with complex query transform
- @Test public void testRewriteProcedure12() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (x = CONCAT(e1 , 'z'));\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where x =CONCAT(x , 'y')"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE CONCAT(e1, 'z') = CONCAT(CONCAT(e1, 'z'), 'y');\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- // with complex query transform
- @Test public void testRewriteProcedure13() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (x = CONCAT(e1 , 'z'), y = convert(CONCAT(e1 , 'k'), integer));\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where x =CONCAT(x , 'y') and y= 1"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE (CONCAT(e1, 'z') = CONCAT(CONCAT(e1, 'z'), 'y')) AND (convert(CONCAT(e1, 'k'), integer) = 1);\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- @Test public void testRewriteProcedure14() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (e4 = sqrt(e4));\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where e4= 1"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE sqrt(e4) = 1.0;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- @Test public void testRewriteProcedure15() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (e4 = e4/50);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y= 1"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE e2 = 0;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // virtual group elements used in procedure (TRANSLATE CRITERIA)
- @Test public void testRewriteProcedure16() throws Exception {
- String procedure = exampleTranslateUpdate();
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where e4= 1"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = 'x' WHERE e4 = 0.02;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- @Test public void testRewriteNoUserCriteria() throws Exception {
- String procedure = exampleTranslateUpdate();
-
- String userQuery = "UPDATE vm1.g3 SET x='x'"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = 'x' WHERE 1 = 1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- @Test public void testRewriteOrUserCriteria() throws Exception {
- String procedure = exampleTranslateUpdate();
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where x = '1' or x = '2'"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = 'x' WHERE CONCAT(e1, 'm') IN ('2', '1');\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- private String exampleTranslateUpdate() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "update pm1.g1 set pm1.g1.e1 = inputs.x where TRANSLATE CRITERIA;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- return procedure;
- }
-
- @Test public void testRewriteProcedure17() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE LIKE CRITERIA WITH (e4 = e4/50);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where e4= 1"; //$NON-NLS-1$
-
- this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // Bug 8212 elements in INPUT and CHANGING special groups are cese sensitive
- @Test public void testRewriteProcedure18() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select Input.E1, Input.e2, CHANGING.e2, CHANGING.E1 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "INSERT into vm1.g1 (e1, E2) values('x', 1)"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT 'x', 1, TRUE, TRUE FROM pm1.g1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // elements being set in updates are dropped if INPUT var is not available, unless a default is available
- // Note that this test is a little odd in that it is an update inside of an insert
- @Test public void testRewriteProcedure19() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "update pm1.g1 set e1=Input.E1, e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "INSERT into vm1.g1 (E2) values(1)"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = 'xyz', e2 = 1, e3 = TRUE;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // elements being set in updates are dropped if INPUT var is not available, unless a default is supplied
-
- //this test fails because the default for E1 'xyz' cannot be converted into a integer
- @Test(expected=ExpressionEvaluationException.class) public void testRewriteProcedure21() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "update pm1.g1 set e1=convert(Input.E1, integer)+INPUT.E2, e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "INSERT into vm1.g1 (E3) values({b'true'})"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- 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);
- }
-
- @Test public void testRewriteProcedure21a() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "update pm1.g1 set e1=convert(Input.E1, integer)+INPUT.E2, e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "INSERT into vm1.g1 (E1) values(1)"; //$NON-NLS-1$
-
- 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 + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // none of input variables on update statement changing
- @Test public void testRewriteProcedure22() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "update pm1.g1 set e1=convert(Input.E1, integer)+INPUT.E2, e2=Input.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "update vm1.g1 set E3 = {b'true'}"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // none of input variables on update statement changing
- @Test public void testRewriteProcedure23() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "update pm1.g1 set e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "update vm1.g1 set E1 = 'x'"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- //with an insert, defaults are used
- @Test public void testRewriteProcedure23a() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "update pm1.g1 set e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "INSERT into vm1.g1 (E1) values('x')"; //$NON-NLS-1$
-
- 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 + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- @Test public void testRewriteProcedure24() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "UPDATE pm1.g1 SET e2=Input.e2 WHERE TRANSLATE LIKE CRITERIA ON (e1) WITH (e1=concat(pm1.g1.e1, '%'));\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- 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);
- }
-
- // INPUT vars in insert statements replaced by default variable when user's inser ignores values
- @Test public void testRewriteProcedure25() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "INSERT into pm1.g1 (e1,e2,e3,e4) values (Input.e1, Input.e2, Input.e3, Input.e4);"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "INSERT into vm1.g1 (E2) values (1)"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "INSERT INTO pm1.g1 (e1, e2, e3, e4) VALUES ('xyz', 1, TRUE, 123.456);\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- @Test public void testRewriteProcedure26() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e2);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g1 SET e1='x' where e2 = e2 + 50"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e2 = (pm1.g1.e2 + 50);\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- @Test public void testRewriteProcedure27() throws Exception {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e2);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g1 SET e1='x' where e2 LIKE 'xyz'"; //$NON-NLS-1$
-
- this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- /**
- * Per defect 9380 -
- * A criteria of the form
- * (? + 1) < (null)
- * caused a problem in the QueryRewriter.simplifyMathematicalCriteria method.
- * At the beginning of the method, the null constant is rewritten so that it
- * loses it's implicit type conversion to integer, then later on a function
- * descriptor couldn't be found for the "minus" operation for the two types
- * integer and MetaMatrix's null type.
- */
- @Test public void testRewriteProcedure_9380() throws Exception {
-
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var2;\n"; //$NON-NLS-1$
- procedure = procedure + "if((var1 + 1) < length(input.e1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "var2 = INPUT.e2;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g1 SET e2=30"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "DECLARE integer var2;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- //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());
- }
-
- @Test public void testRewriteLookupFunction1b() {
- helpTestRewriteCriteria("lookup('pm1.g1','e1', 'e2', pm1.g1.e2) = 'ab'", "lookup('pm1.g1','e1', 'e2', pm1.g1.e2) = 'ab'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** 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$
- }
-
- @Test public void testSelectWithNoFrom() {
- helpTestRewriteCommand("SELECT 5", "SELECT 5"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- //defect 9822
- @Test public void testStoredProcedure_9822() throws Exception {
-
- QueryParser parser = new QueryParser();
- Command command = parser.parseCommand("exec pm1.sp4(5)"); //$NON-NLS-1$
-
- // resolve
- QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
- QueryResolver.resolveCommand(command, metadata);
-
- // rewrite
- Command rewriteCommand = QueryRewriter.rewrite(command, metadata, null);
-
- List<SPParameter> parameters = ((StoredProcedure)rewriteCommand).getParameters();
-
- for (SPParameter param : parameters) {
- if(param.getParameterType() == ParameterInfo.IN || param.getParameterType() == ParameterInfo.INOUT){
- assertTrue(param.getExpression() instanceof Constant);
- }
- }
- }
-
- @Test public void testRewriteFunctionThrowsEvaluationError() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Criteria origCrit = parseCriteria("5 / 0 = 5", metadata); //$NON-NLS-1$
-
- // rewrite
- try {
- QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
- fail("Expected QueryValidatorException due to divide by 0"); //$NON-NLS-1$
- } catch(TeiidException e) {
- // looks like message is being wrapped with another exception with same message
- assertEquals("Error Code:ERR.015.001.0003 Message:Unable to evaluate (5 / 0): Error Code:ERR.015.001.0003 Message:Error while evaluating function /", e.getMessage()); //$NON-NLS-1$
- }
- }
-
- @Test public void testRewriteConvertThrowsEvaluationError() {
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
- Criteria origCrit = parseCriteria("convert('x', integer) = 0", metadata); //$NON-NLS-1$
-
- // rewrite
- try {
- QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
- fail("Expected QueryValidatorException due to invalid string"); //$NON-NLS-1$
- } catch(TeiidException e) {
- assertEquals("Error Code:ERR.015.001.0003 Message:Unable to evaluate convert('x', integer): Error Code:ERR.015.001.0003 Message:Error while evaluating function convert", e.getMessage()); //$NON-NLS-1$
- }
- }
-
- @Test public void testDefect13458() throws Exception {
-
- String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "delete from vm1.g1 where e1='1'"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.DELETE_PROCEDURE);
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCase1954() {
- helpTestRewriteCriteria("convert(pm1.g1.e2, string) = '3'", "pm1.g1.e2 = 3"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCase1954a() {
- helpTestRewriteCriteria("cast(pm1.g1.e2 as string) = '3'", "pm1.g1.e2 = 3"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCase1954b() throws Exception{
- FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-
- CompareCriteria expected = new CompareCriteria();
- ElementSymbol leftElement = new ElementSymbol("pm1.g1.e4"); //$NON-NLS-1$
- Constant constant = new Constant(new Double(3.0), DataTypeManager.DefaultDataClasses.DOUBLE);
- expected.setLeftExpression(leftElement);
- expected.setRightExpression(constant);
- // resolve against metadata
- QueryResolver.resolveCriteria(expected, metadata);
-
- helpTestRewriteCriteria("convert(pm1.g1.e4, string) = '3.0'", expected, metadata); //$NON-NLS-1$
- }
-
- @Test public void testRewriteCase1954c() {
- helpTestRewriteCriteria("convert(pm1.g1.e1, string) = 'x'", "pm1.g1.e1 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteCase1954d() {
- helpTestRewriteCriteria("convert(pm1.g1.e1, timestamp) = {ts '2005-01-03 00:00:00.0'}", "pm1.g1.e1 = '2005-01-03 00:00:00.0'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCase1954e() {
- helpTestRewriteCriteria("convert(pm1.g1.e4, integer) = 2", "convert(pm1.g1.e4, integer) = 2"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** Check that this fails, x is not convertable to an int */
- @Test public void testRewriteCase1954f() {
- helpTestRewriteCriteria("convert(pm1.g1.e2, string) = 'x'", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** Check that this returns true, x is not convertable to an int */
- @Test public void testRewriteCase1954f1() {
- helpTestRewriteCriteria("convert(pm1.g1.e2, string) != 'x'", "pm1.g1.e2 is not null"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCase1954Set() {
- helpTestRewriteCriteria("convert(pm1.g1.e2, string) in ('2', '3')", "pm1.g1.e2 IN (2,3)"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCase1954SetA() {
- helpTestRewriteCriteria("convert(pm1.g1.e2, string) in ('2', 'x')", "pm1.g1.e2 = 2"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCase1954SetB() {
- helpTestRewriteCriteria("cast(pm1.g1.e2 as string) in ('2', '3')", "pm1.g1.e2 IN (2,3)"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCase1954SetC() {
- helpTestRewriteCriteria("concat(pm1.g1.e2, 'string') in ('2', '3')", "concat(pm1.g1.e2, 'string') in ('2', '3')"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCase1954SetD() {
- helpTestRewriteCriteria("convert(pm1.g1.e2, string) in ('2', pm1.g1.e1)", "convert(pm1.g1.e2, string) in ('2', pm1.g1.e1)"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // First WHEN always true, so rewrite as THEN expression
- @Test public void testRewriteCaseExpr1() {
- helpTestRewriteCriteria("case when 0=0 then 1 else 2 end = 1", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // First WHEN always false, so rewrite as ELSE expression
- @Test public void testRewriteCaseExpr2() {
- helpTestRewriteCriteria("case when 0=1 then 1 else 2 end = 1", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // First WHEN can't be rewritten, so no changes
- @Test public void testRewriteCaseExpr3() {
- helpTestRewriteCriteria("case when 0 = pm1.g1.e2 then 1 else 2 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 1 ELSE 2 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCaseExpr4() {
- helpTestRewriteCriteria("lookup('pm1.g1', 'e2', 'e1', case when 1=1 then pm1.g1.e1 end) = 0", "lookup('pm1.g1', 'e2', 'e1', pm1.g1.e1) = 0"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // First WHEN always false, so remove it
- @Test public void testRewriteCaseExpr5() {
- helpTestRewriteCriteria("case when 0=1 then 1 when 0 = pm1.g1.e2 then 2 else 3 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 2 ELSE 3 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCaseExprForCase5413aFrom502() {
- 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$
- }
-
- @Test public void testRewriteCaseExprForCase5413bFrom502() {
- helpTestRewriteCriteria("case when 0 = pm1.g1.e2 then null else null end IS NULL", TRUE_STR); //$NON-NLS-1$
- }
-
-
- @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$
- }
-
- @Test public void testRewriteCaseExprForCase5413b() {
- helpTestRewriteCriteria("case when 0 = pm1.g1.e2 then null else null end IS NULL", TRUE_STR); //$NON-NLS-1$
- }
-
- // First WHEN always true, so rewrite as THEN expression
- @Test public void testRewriteSearchedCaseExpr1() {
- helpTestRewriteCriteria("case 0 when 0 then 1 else 2 end = 1", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // First WHEN always false, so rewrite as ELSE expression
- @Test public void testRewriteSearchedCaseExpr2() {
- helpTestRewriteCriteria("case 0 when 1 then 1 else 2 end = 1", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteSearchedCaseExpr3() {
- helpTestRewriteCriteria("case 0 when pm1.g1.e2 then 1 else 2 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 1 ELSE 2 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @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$
- }
-
- // First WHEN always false, so remove it
- @Test public void testRewriteSearchedCaseExpr5() {
- helpTestRewriteCriteria("case 0 when 1 then 1 when pm1.g1.e2 then 2 else 3 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 2 ELSE 3 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testDefect16879_1(){
- helpTestRewriteCommand("SELECT decodestring(e1, 'a, b') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testDefect16879_2(){
- helpTestRewriteCommand("SELECT decodestring(e1, 'a, b, c, d') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 = 'c' THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testDefect16879_3(){
- helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testDefect16879_4(){
- helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b, c, d') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 = 'c' THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testDefect16879_5(){
- helpTestRewriteCommand("SELECT decodeinteger(e1, 'null, b, c, d') FROM pm1.g1", "SELECT CASE WHEN e1 IS NULL THEN 'b' WHEN e1 = 'c' THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testDefect16879_6(){
- helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b, null, d') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 IS NULL THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testDefect16879_7(){
- helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b, null, d, e') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 IS NULL THEN 'd' ELSE 'e' END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testCaseExpressionThatResolvesToNull() {
- String sqlBefore = "SELECT CASE 'x' WHEN 'Old Inventory System' THEN NULL WHEN 'New Inventory System' THEN NULL END"; //$NON-NLS-1$
- String sqlAfter = "SELECT null"; //$NON-NLS-1$
-
- Command cmd = helpTestRewriteCommand( sqlBefore, sqlAfter );
-
- ExpressionSymbol es = (ExpressionSymbol)cmd.getProjectedSymbols().get(0);
- assertEquals( DataTypeManager.DefaultDataClasses.STRING, es.getType() );
- }
-
-
- //note that the env is now treated as deterministic, however it is really only deterministic within a session
- @Test public void testRewriteExecEnv() throws Exception {
- Command command = QueryParser.getQueryParser().parseCommand("exec pm1.sq2(env('sessionid'))"); //$NON-NLS-1$
-
- QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
-
- CommandContext context = new CommandContext();
- Properties props = new Properties();
- props.setProperty(ContextProperties.SESSION_ID, "1"); //$NON-NLS-1$
- context.setEnvironmentProperties(props);
- Command rewriteCommand = QueryRewriter.rewrite(command, FakeMetadataFactory.example1Cached(), context);
-
- assertEquals("EXEC pm1.sq2('1')", rewriteCommand.toString()); //$NON-NLS-1$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteNestedFunctions() {
- helpTestRewriteCommand("SELECT e1 FROM pm1.g1 where convert(parsedate(e1, 'yyyy-MM-dd'), string) = '2006-07-01'", "SELECT e1 FROM pm1.g1 WHERE e1 = '2006-07-01'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Ignore(value="It's not generally possible to invert a narrowing conversion")
- @Test public void testRewriteWithReference() {
- helpTestRewriteCommand("SELECT e1 FROM pm1.g1 where parsetimestamp(e1, 'yyyy-MM-dd') != ?", "SELECT e1 FROM pm1.g1 WHERE e1 <> formattimestamp(?, 'yyyy-MM-dd')"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewiteJoinCriteria() {
- helpTestRewriteCommand("SELECT pm1.g1.e1 FROM pm1.g1 inner join pm1.g2 on (pm1.g1.e1 = null)", "SELECT pm1.g1.e1 FROM pm1.g1 INNER JOIN pm1.g2 ON 1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewiteCompoundCriteria() {
- helpTestRewriteCriteria("(pm1.g1.e1 = 1 and pm1.g1.e2 = 2) and (pm1.g1.e3 = 1 and pm1.g1.e4 = 2)", "(pm1.g1.e1 = '1') AND (pm1.g1.e2 = 2) AND (pm1.g1.e3 = TRUE) AND (pm1.g1.e4 = 2.0)"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteWhile() throws Exception {
-
- String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "while (1 = 1)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select vm1.g1.e1 from vm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-
- try {
- getRewritenProcedure(procedure, userQuery, FakeMetadataObject.Props.INSERT_PROCEDURE);
- fail("exception expected"); //$NON-NLS-1$
- } catch (QueryValidatorException e) {
- assertEquals("Infinite loop detected, procedure will not be executed.", e.getMessage()); //$NON-NLS-1$
- }
- }
-
- @Test public void testRewriteWhile1() throws Exception {
-
- String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "while (1 = 0)\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select vm1.g1.e1 from vm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- /**
- * Tests that VariableSubstitutionVisitor does not cause an NPE on count(*)
- */
- @Test public void testRewriteProcedureWithCount() throws Exception {
-
- String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select count(*) from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
-
- String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "SELECT COUNT(*) FROM pm1.g1;\n"; //$NON-NLS-1$
- rewritProc = rewritProc + "END"; //$NON-NLS-1$
-
- String procReturned = this.getRewritenProcedure(procedure, userQuery,
- FakeMetadataObject.Props.INSERT_PROCEDURE);
-
- assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
- }
-
- /**
- * Test to ensure the update changing list retains e1 = ?
- */
- @Test public void testVariableSubstitutionVisitor() throws Exception {
- String procedure1 = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure1 += "BEGIN\n"; //$NON-NLS-1$
- procedure1 += "DECLARE string var1 = INPUT.e1;\n"; //$NON-NLS-1$
- procedure1 += "ROWS_UPDATED = UPDATE vm1.g2 SET e1=var1;\n"; //$NON-NLS-1$
- procedure1 += "END"; //$NON-NLS-1$
-
- String procedure2 = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure2 += "BEGIN\n"; //$NON-NLS-1$
- procedure2 += "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure2 += "IF (INPUT.e1 = 1)\n"; //$NON-NLS-1$
- procedure2 += "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
- procedure2 += "ELSE\n"; //$NON-NLS-1$
- procedure2 += "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
- procedure2 += "END"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1 = 'x' WHERE e2 = 5"; //$NON-NLS-1$
-
- FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure1, procedure2);
-
- String rewriten = getRewritenProcedure(userUpdateStr, metadata);
-
- String expected = "CREATE PROCEDURE\nBEGIN\nDECLARE string var1 = 'x';\nUPDATE vm1.g2 SET e1 = var1;\nROWS_UPDATED = VARIABLES.ROWCOUNT;\nEND"; //$NON-NLS-1$
-
- assertEquals(expected, rewriten);
- }
-
- @Test public void testRemoveEmptyLoop() {
- String procedure1 = "CREATE virtual PROCEDURE "; //$NON-NLS-1$
- procedure1 += "BEGIN\n"; //$NON-NLS-1$
- procedure1 += "loop on (select e1 from pm1.g1) as myCursor\n"; //$NON-NLS-1$
- procedure1 += "begin\n"; //$NON-NLS-1$
- procedure1 += "end\n"; //$NON-NLS-1$
- procedure1 += "select e1 from pm1.g1;\n"; //$NON-NLS-1$
- procedure1 += "END"; //$NON-NLS-1$
-
- String expected = "CREATE VIRTUAL PROCEDURE\nBEGIN\nSELECT e1 FROM pm1.g1;\nEND"; //$NON-NLS-1$
-
- helpTestRewriteCommand(procedure1, expected);
- }
-
- @Test public void testRewriteDeclare() {
- String procedure1 = "CREATE virtual PROCEDURE "; //$NON-NLS-1$
- procedure1 += "BEGIN\n"; //$NON-NLS-1$
- procedure1 += "declare integer x = 1 + 1;\n"; //$NON-NLS-1$
- procedure1 += "END"; //$NON-NLS-1$
-
- String expected = "CREATE VIRTUAL PROCEDURE\nBEGIN\nDECLARE integer x = 2;\nEND"; //$NON-NLS-1$
-
- helpTestRewriteCommand(procedure1, expected);
- }
-
- @Test public void testRewriteUnionJoin() {
- String sql = "select pm1.g1.e1 from pm1.g1 union join pm1.g2 where g1.e1 = 1"; //$NON-NLS-1$
- String expected = "SELECT pm1.g1.e1 FROM pm1.g1 FULL OUTER JOIN pm1.g2 ON 1 = 0 WHERE g1.e1 = '1'"; //$NON-NLS-1$
-
- helpTestRewriteCommand(sql, expected);
- }
-
- @Test public void testRewriteNonNullDependentFunction() {
- helpTestRewriteCriteria("pm1.g1.e1 = concat(null, pm1.g1.e2)", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteInWithNull() {
- helpTestRewriteCriteria("convert(null, string) in (pm1.g1.e1, pm1.g1.e2)", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteXMLCriteriaCases5630And5640() {
- helpTestRewriteCommand("select * from xmltest.doc1 where node1 = null", "SELECT * FROM xmltest.doc1 WHERE node1 = null"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCorrelatedSubqueryInHaving() {
- String sql = "select pm1.g1.e1 from pm1.g1 group by pm1.g1.e1 having pm1.g1.e1 in (select pm1.g1.e1 from pm1.g2)"; //$NON-NLS-1$
- String expected = "SELECT pm1.g1.e1 FROM pm1.g1 GROUP BY pm1.g1.e1 HAVING pm1.g1.e1 IN (SELECT pm1.g1.e1 FROM pm1.g2)"; //$NON-NLS-1$
-
- Query query = (Query)helpTestRewriteCommand(sql, expected);
-
- List<Reference> refs = new LinkedList<Reference>();
-
- CorrelatedReferenceCollectorVisitor.collectReferences(query, Arrays.asList(new GroupSymbol("pm1.g1")), refs);//$NON-NLS-1$
-
- assertEquals(1, refs.size());
- }
-
- @Test public void testRewriteSelectInto() {
- String sql = "select distinct pm1.g1.e1 into #temp from pm1.g1"; //$NON-NLS-1$
- String expected = "INSERT INTO #temp (#temp.e1) SELECT DISTINCT pm1.g1.e1 FROM pm1.g1"; //$NON-NLS-1$
-
- helpTestRewriteCommand(sql, expected);
- }
-
- /**
- * Accounts for type change with duplicate names
- */
- @Test public void testRewriteSelectInto1() {
- String sql = "select distinct e2, e2, e3, e4 into pm1.g1 from pm1.g2"; //$NON-NLS-1$
- String expected = "INSERT INTO pm1.g1 (pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4) SELECT X.e2 AS e1, X.E2_0 AS e2, X.e3, X.e4 FROM (SELECT DISTINCT e2, e2 AS E2_0, e3, e4 FROM pm1.g2) AS X"; //$NON-NLS-1$
-
- helpTestRewriteCommand(sql, expected);
- }
-
- @Test public void testUnionQueryNullInOneBranch() throws Exception {
- verifyProjectedTypesOnUnionBranches("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT e1, null FROM pm1.g2", //$NON-NLS-1$
- new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER });
- }
-
- @Test public void testUnionQueryNullInOneBranch2() throws Exception {
- verifyProjectedTypesOnUnionBranches("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT e1, e2 FROM pm1.g2 UNION ALL SELECT e1, null FROM pm1.g2", //$NON-NLS-1$
- new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER });
- }
-
- @Test public void testUnionQueryNullInOneBranch3() throws Exception {
- verifyProjectedTypesOnUnionBranches("SELECT e1, null FROM pm1.g1 UNION ALL SELECT e1, null FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g2", //$NON-NLS-1$
- new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER });
- }
-
- @Test public void testUnionQueryNullInAllBranches() throws Exception {
- verifyProjectedTypesOnUnionBranches("SELECT e1, null FROM pm1.g1 UNION ALL SELECT e1, null FROM pm1.g2 UNION ALL SELECT e1, null FROM pm1.g2", //$NON-NLS-1$
- new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING });
- }
-
- @Test public void testUnionQueryWithTypeConversion() throws Exception {
- verifyProjectedTypesOnUnionBranches("SELECT e1 FROM pm1.g1 UNION ALL SELECT e2 FROM pm1.g2", //$NON-NLS-1$
- new Class[] { DataTypeManager.DefaultDataClasses.STRING});
- }
-
- private void verifyProjectedTypesOnUnionBranches(String unionQuery, Class<?>[] types) throws TeiidComponentException, TeiidProcessingException {
- SetQuery union = (SetQuery)QueryParser.getQueryParser().parseCommand(unionQuery);
- QueryResolver.resolveCommand(union, FakeMetadataFactory.example1Cached());
-
- union = (SetQuery)QueryRewriter.rewrite(union, FakeMetadataFactory.example1Cached(), null);
-
- for (QueryCommand query : union.getQueryCommands()) {
- List<SingleElementSymbol> projSymbols = query.getProjectedSymbols();
- for(int i=0; i<projSymbols.size(); i++) {
- assertEquals("Found type mismatch at column " + i, types[i], projSymbols.get(i).getType()); //$NON-NLS-1$
- }
- }
- }
-
- /**
- * The rewrite creates inline view to do the type conversion.
- *
- * It also ensures that all project symbols are uniquely named in the inline view
- */
- @Test public void testSelectIntoWithOrderByAndTypeConversion() throws Exception {
- String procedure = "CREATE VIRTUAL PROCEDURE\n"; //$NON-NLS-1$
- procedure += "BEGIN\n"; //$NON-NLS-1$
- procedure += "CREATE local temporary table temp (x string, y integer, z integer);\n"; //$NON-NLS-1$
- procedure += "Select pm1.g1.e2, 1 as x, 2 as x into temp from pm1.g1 order by pm1.g1.e2 limit 1;\n"; //$NON-NLS-1$
- procedure += "Select x from temp;\n"; //$NON-NLS-1$
- procedure += "END\n"; //$NON-NLS-1$
-
- helpTestRewriteCommand(procedure, "CREATE VIRTUAL PROCEDURE\nBEGIN\nCREATE LOCAL TEMPORARY TABLE temp (x string, y integer, z integer);\nINSERT INTO temp (temp.x, temp.y, temp.z) SELECT X.e2 AS x, X.x AS y, X.X_0 AS z FROM (SELECT pm1.g1.e2, 1 AS x, 2 AS X_0 FROM pm1.g1 ORDER BY pm1.g1.e2 LIMIT 1) AS X;\nSELECT x FROM temp;\nEND"); //$NON-NLS-1$
- }
-
- @Test public void testRewriteNot() {
- helpTestRewriteCriteria("not(not(pm1.g1.e1 = 1 + 1))", "pm1.g1.e1 = '2'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteQueryWithNoFrom() {
- String sql = "select 1 as a order by a"; //$NON-NLS-1$
-
- helpTestRewriteCommand(sql, "SELECT 1 AS a"); //$NON-NLS-1$
- }
-
- /**
- * Case 4814
- */
- @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$
- }
-
- /**
- * Case 4814
- */
- @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$
- }
-
- @Test public void testRewriteConcat2() {
- helpTestRewriteCriteria("concat2('a','b') = 'ab'", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteConcat2_1() {
- helpTestRewriteCriteria("concat2(null, null) is null", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteConcat2_2() throws Exception {
- helpTestRewriteCriteria("concat2(pm1.g1.e1, null) = 'xyz'", "CASE WHEN pm1.g1.e1 IS NULL THEN null ELSE concat(ifnull(pm1.g1.e1, ''), '') END = 'xyz'", true); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteConcat2_3() throws Exception {
- helpTestRewriteCriteria("concat2(pm1.g1.e1, convert(pm1.g1.e2, string)) = 'xyz'", "CASE WHEN (pm1.g1.e1 IS NULL) AND (convert(pm1.g1.e2, string) IS NULL) THEN null ELSE concat(ifnull(pm1.g1.e1, ''), ifnull(convert(pm1.g1.e2, string), '')) END = 'xyz'", true); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteConcat2_4() throws Exception {
- 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 {
- helpTestRewriteCriteria("from_unixtime(pm1.g1.e2) = '1992-12-01 07:00:00'", "timestampadd(SQL_TSI_SECOND, pm1.g1.e2, {ts'1969-12-31 18:00:00.0'}) = {ts'1992-12-01 07:00:00.0'}"); //$NON-NLS-1$ //$NON-NLS-2$
- } finally {
- TimestampWithTimezone.resetCalendar(null);
- }
- }
-
- @Test public void testRewriteNullIf() throws Exception {
- helpTestRewriteCriteria("nullif(pm1.g1.e2, pm1.g1.e4) = 1", "CASE WHEN pm1.g1.e2 = pm1.g1.e4 THEN convert(null, double) ELSE pm1.g1.e2 END = 1.0", true); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCoalesce() throws Exception {
- helpTestRewriteCriteria("coalesce(convert(pm1.g1.e2, double), pm1.g1.e4) = 1", "ifnull(convert(pm1.g1.e2, double), pm1.g1.e4) = 1", true); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Test <code>QueryRewriter</code>'s ability to rewrite a query that
- * contains an aggregate function which uses a <code>CASE</code>
- * expression which contains <code>BETWEEN</code> criteria as its value.
- * <p>
- * An aggregate function list is defined and queries are created that
- * use each function from the list. The list includes:
- * <p>
- * "SUM", "MAX", "MIN", "AVG", "COUNT"
- * <p>
- * It is expected that the BETWEEN expression will be rewritten as
- * <code>CompoundCriteria</code>.
- * <p>
- * <table>
- * <tr><th align="left" colspan=2>For example:
- * <tr><td width="10*"><td>SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5
- * THEN e2 ELSE -1 END) FROM pm1.g1
- * <tr><th align="left" colspan=2>Is rewritten as:
- * <tr><td width="10*"><td>SELECT SUM(CASE WHEN (e2 >= 3) AND (e2 <= 5)
- * THEN e2 ELSE -1 END) FROM pm1.g1
- * </table>
- *
- * @see org.teiid.query.rewriter.QueryRewriter
- * @see org.teiid.query.sql.lang.BetweenCriteria
- * @see org.teiid.query.sql.lang.CompoundCriteria
- * @see org.teiid.query.sql.symbol.AggregateSymbol
- * @see org.teiid.query.sql.symbol.SearchedCaseExpression
- */
- @Test public void testAggregateWithBetweenInCaseInSelect() {
- // Define a list of aggregates to test against
- List<String> aggregateCommands = Arrays.asList( new String[] { "SUM", "MAX", "MIN", "AVG", "COUNT" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-
- // Define a query and the expected rewritten query
- // ?AGGREGATE? represents the string substitution for an aggregate from aggregateCommands
- String sqlBefore = "SELECT ?AGGREGATE?(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
- String sqlAfter = "SELECT ?AGGREGATE?(CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
-
- // Iterate through the aggregateCommands
- for ( String aCmd : aggregateCommands ) {
- // Replace ?AGGREGATE? with the command from aggregateCommands
- String sql = sqlBefore.replace("?AGGREGATE?", aCmd); //$NON-NLS-1$
- String exSql = sqlAfter.replace("?AGGREGATE?", aCmd); //$NON-NLS-1$
- // Test QueryRewriter
- Command cmd = helpTestRewriteCommand( sql, exSql );
- // Check the rewritten command to verify that CompundCriteria replaced BetweenCriteria
- CompoundCriteria ccrit = (CompoundCriteria) ((SearchedCaseExpression) ((ExpressionSymbol) cmd.getProjectedSymbols().get(0)).getExpression()).getWhen().get(0);
- assertEquals( "e2 >= 3", ccrit.getCriteria(0).toString() ); //$NON-NLS-1$
- assertEquals( "e2 <= 5", ccrit.getCriteria(1).toString() ); //$NON-NLS-1$
- }
- }
-
- /**
- * Test <code>QueryRewriter</code>'s ability to rewrite a query that
- * contains a <code>CASE</code> expression which contains
- * <code>BETWEEN</code> criteria in the queries <code>SELECT</code> clause.
- * <p>
- * It is expected that the BETWEEN expression will be rewritten as
- * <code>CompoundCriteria</code>.
- * <p>
- * <table>
- * <tr><th align="left" colspan=2>For example:
- * <tr><td width="10*"><td>SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2
- * ELSE -1 END FROM pm1.g1
- * <tr><th align="left" colspan=2>Is rewritten as:
- * <tr><td width="10*"><td>SELECT CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2
- * ELSE -1 END FROM pm1.g1
- * </table>
- *
- * @see org.teiid.query.rewriter.QueryRewriter
- * @see org.teiid.query.sql.lang.BetweenCriteria
- * @see org.teiid.query.sql.lang.CompoundCriteria
- * @see org.teiid.query.sql.symbol.SearchedCaseExpression
- */
- @Test public void testBetweenInCaseInSelect() {
- String sqlBefore = "SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
- String sqlAfter = "SELECT CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
-
- Command cmd = helpTestRewriteCommand( sqlBefore, sqlAfter );
- CompoundCriteria ccrit = (CompoundCriteria) ((SearchedCaseExpression) ((ExpressionSymbol) cmd.getProjectedSymbols().get(0)).getExpression()).getWhen().get(0);
- assertEquals( "e2 >= 3", ccrit.getCriteria(0).toString() ); //$NON-NLS-1$
- assertEquals( "e2 <= 5", ccrit.getCriteria(1).toString() ); //$NON-NLS-1$
- }
-
- /**
- * Test <code>QueryRewriter</code>'s ability to rewrite a query that
- * contains a <code>CASE</code> expression which contains
- * <code>BETWEEN</code> criteria in the queries <code>WHERE</code> clause.
- * <p>
- * It is expected that the BETWEEN expression will be rewritten as
- * <code>CompoundCriteria</code>.
- * <p>
- * <table>
- * <tr><th align="left" colspan=2>For example:
- * <tr><td width="10*"><td>SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2
- * BETWEEN 3 AND 5 THEN e2 ELSE -1 END
- * <tr><th align="left" colspan=2>Is rewritten as:
- * <tr><td width="10*"><td>SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN
- * (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END
- * </table>
- *
- * @see org.teiid.query.rewriter.QueryRewriter
- * @see org.teiid.query.sql.lang.BetweenCriteria
- * @see org.teiid.query.sql.lang.CompoundCriteria
- * @see org.teiid.query.sql.symbol.SearchedCaseExpression
- */
- @Test public void testBetweenInCase() {
- String sqlBefore = "SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END"; //$NON-NLS-1$
- String sqlAfter = "SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END"; //$NON-NLS-1$
-
- Command cmd = helpTestRewriteCommand( sqlBefore, sqlAfter );
- CompoundCriteria ccrit = (CompoundCriteria) ((SearchedCaseExpression) ((CompareCriteria) ((Query) cmd).getCriteria()).getRightExpression()).getWhen().get(0);
- assertEquals( "e2 >= 3", ccrit.getCriteria(0).toString() ); //$NON-NLS-1$
- assertEquals( "e2 <= 5", ccrit.getCriteria(1).toString() ); //$NON-NLS-1$
- }
-
- @Test public void testRewriteNullHandling() {
- String original = "pm1.g1.e1 like '%'"; //$NON-NLS-1$
- String expected = "pm1.g1.e1 is not null"; //$NON-NLS-1$
- addTestData();
-
- helpTestRewriteCriteria(original, expected);
- }
-
- private void addTestData() {
- this.elements = new HashMap<ElementSymbol, Integer>();
- elements.put(new ElementSymbol("pm1.g1.e1"), 0);
- elements.put(new ElementSymbol("pm1.g1.e2"), 1);
- elements.put(new ElementSymbol("pm1.g1.e3"), 2);
- for (String s : Arrays.asList("a", null, "*")) {
- for (Integer i : Arrays.asList(1, null, 6)) {
- for (Boolean b : Arrays.asList(true, false, null)) {
- tuples.add(Arrays.asList(s, i, b));
- }
- }
- }
- }
-
- @Test public void testRewriteNullHandling1() {
- String original = "not(pm1.g1.e1 like '%' or pm1.g1.e1 = '1')"; //$NON-NLS-1$
- String expected = "1 = 0"; //$NON-NLS-1$
- addTestData();
- helpTestRewriteCriteria(original, expected);
- }
-
- @Test public void testRewriteNullHandling2() {
- String original = "not(pm1.g1.e1 like '%' and pm1.g1.e1 = '1')"; //$NON-NLS-1$
- String expected = "pm1.g1.e1 <> '1'"; //$NON-NLS-1$
- addTestData();
- helpTestRewriteCriteria(original, expected);
- }
-
- @Test public void testRewriteNullHandling3() {
- String original = "pm1.g1.e1 like '%' or pm1.g1.e1 = '1'"; //$NON-NLS-1$
- String expected = "(pm1.g1.e1 IS NOT NULL) OR (pm1.g1.e1 = '1')"; //$NON-NLS-1$
- addTestData();
- helpTestRewriteCriteria(original, expected);
- }
-
- @Test public void testRewriteNullHandling4() {
- String original = "not((pm1.g1.e1 like '%' or pm1.g1.e3 = true) and pm1.g1.e2 < 5)"; //$NON-NLS-1$
- String expected = "pm1.g1.e2 >= 5"; //$NON-NLS-1$
- addTestData();
- helpTestRewriteCriteria(original, expected);
- }
-
- @Test public void testRewriteNullHandling4a() {
- String original = "not(not((pm1.g1.e1 like '%' or pm1.g1.e3 = true) and pm1.g1.e2 < 5))"; //$NON-NLS-1$
- String expected = "((pm1.g1.e1 IS NOT NULL) OR (pm1.g1.e3 = TRUE)) AND (pm1.g1.e2 < 5)"; //$NON-NLS-1$
- addTestData();
- helpTestRewriteCriteria(original, expected);
- }
-
- @Test public void testRewriteNullHandling5() {
- String original = "not((pm1.g1.e1 not like '%' or pm1.g1.e3 = true) and pm1.g1.e2 < 5)"; //$NON-NLS-1$
- String expected = "((pm1.g1.e1 IS NOT NULL) AND (pm1.g1.e3 <> TRUE)) OR (pm1.g1.e2 >= 5)"; //$NON-NLS-1$
- addTestData();
- helpTestRewriteCriteria(original, expected);
- }
-
- @Test public void testRewriteNullHandling6() {
- String original = "not((pm1.g1.e1 not like '%' and pm1.g1.e3 = true) or pm1.g1.e2 < 5)"; //$NON-NLS-1$
- String expected = "((pm1.g1.e1 IS NOT NULL) OR (pm1.g1.e3 <> TRUE)) AND (pm1.g1.e2 >= 5)"; //$NON-NLS-1$
- addTestData();
- helpTestRewriteCriteria(original, expected);
- }
-
- @Test public void testRewriteNullHandling7() {
- String original = "not(not(pm1.g1.e1 not like '%' and pm1.g1.e3 = true) or pm1.g1.e2 < 5)"; //$NON-NLS-1$
- String expected = "1 = 0"; //$NON-NLS-1$
- addTestData();
- helpTestRewriteCriteria(original, expected);
- }
-
- @Test public void testRewriteNullHandling7a() {
- String original = "not(not(pm1.g1.e1 like '*%' and pm1.g1.e3 = true) or pm1.g1.e2 < 5)"; //$NON-NLS-1$
- String expected = "(pm1.g1.e1 LIKE '*%') AND (pm1.g1.e3 = TRUE) AND (pm1.g1.e2 >= 5)"; //$NON-NLS-1$
- addTestData();
- helpTestRewriteCriteria(original, expected);
- }
-
- @Test public void testRewriteChar() {
- String original = "convert(pm1.g1.e1, char) = '100'"; //$NON-NLS-1$
- String expected = "1 = 0"; //$NON-NLS-1$
-
- helpTestRewriteCriteria(original, expected);
- }
-
- /**
- * Test ensures that '22.0' is a valid long via bigdecimal
- */
- @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());
- }
-
- /**
- * Test ensures that we will not attempt to invert the widening conversion
- */
- @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$
- }
-
- @Test public void testRewriteParseDate() {
- String original = "parsedate(BQT1.SmallA.stringkey, 'yymmdd') = {d'1970-01-01'}"; //$NON-NLS-1$
- QueryMetadataInterface metadata = FakeMetadataFactory.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();
- 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();
- 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();
- 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();
- 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();
- 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();
- 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();
- helpTestRewriteExpression(original, "'path?%26x=value&y=%20%26%20'", metadata);
- }
-
- @Test public void testRewriteExpressionCriteria() throws Exception {
- helpTestRewriteCriteria("pm1.g1.e3", "pm1.g1.e3 = true");
- }
-
- @Test public void testRewritePredicateOptimization() throws Exception {
- helpTestRewriteCriteria("pm1.g1.e2 in (1, 2, 3) and pm1.g1.e2 in (2, 3, 4)", "pm1.g1.e2 in (2, 3)");
- }
-
- @Test public void testRewritePredicateOptimization1() throws Exception {
- helpTestRewriteCriteria("pm1.g1.e2 < 5 and pm1.g1.e2 = 2", "pm1.g1.e2 = 2");
- }
-
- @Test public void testRewritePredicateOptimization2() throws Exception {
- helpTestRewriteCriteria("pm1.g1.e2 < 5 and pm1.g1.e2 = 6", "1 = 0");
- }
-
- @Test public void testRewritePredicateOptimization2a() throws Exception {
- helpTestRewriteCriteria("pm1.g1.e2 < 5 and pm1.g1.e2 = 2", "pm1.g1.e2 = 2");
- }
-
- @Test public void testRewritePredicateOptimization3() throws Exception {
- helpTestRewriteCriteria("pm1.g1.e2 in (1, 2) and pm1.g1.e2 = 6", "1 = 0");
- }
-
- @Test public void testRewritePredicateOptimization4() throws Exception {
- helpTestRewriteCriteria("pm1.g1.e2 in (1, 2) and pm1.g1.e2 is null", "1 = 0");
- }
-
- @Test public void testRewritePredicateOptimization5() throws Exception {
- helpTestRewriteCriteria("pm1.g1.e2 <> 5 and pm1.g1.e2 in (2, 3, 5)", "pm1.g1.e2 in (2, 3)");
- }
-
- @Test public void testRewritePredicateOptimization6() throws Exception {
- helpTestRewriteCriteria("pm1.g1.e2 = 5 and pm1.g1.e2 in (5, 6)", "pm1.g1.e2 = 5");
- }
-
- @Test public void testRewritePredicateOptimization6a() throws Exception {
- helpTestRewriteCriteria("pm1.g1.e2 in (5, 6) and pm1.g1.e2 = 5", "pm1.g1.e2 = 5");
- }
-
- @Ignore("TODO")
- @Test public void testRewritePredicateOptimization7() throws Exception {
- helpTestRewriteCriteria("pm1.g1.e2 > 5 and pm1.g1.e2 < 2", "1 = 0");
- }
-
- @Test public void testRewritePredicateOptimizationOr() throws Exception {
- helpTestRewriteCriteria("pm1.g1.e2 in (5, 6) or pm1.g1.e2 = 2", "pm1.g1.e2 IN (2, 5, 6)");
- }
-
- @Test public void testRewriteCritSubqueryNegate() {
- helpTestRewriteCriteria("not(pm1.g1.e1 > SOME (select 'a' from pm1.g2))", "pm1.g1.e1 <= ALL (SELECT 'a' FROM pm1.g2)"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritSubqueryFalse() {
- helpTestRewriteCriteria("exists(select 1 from pm1.g1 where 1=0)", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritSubqueryFalse1() {
- helpTestRewriteCriteria("not(pm1.g1.e1 > SOME (select 'a' from pm1.g1 where 1=0))", "pm1.g1.e1 IS NOT NULL"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testRewriteCritSubqueryFalse2() {
- helpTestRewriteCriteria("pm1.g1.e1 < ALL (select 'a' from pm1.g1 where 1=0)", "pm1.g1.e1 IS NOT NULL"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @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);
- String sql = "parsedate_(pm1.g1.e1) = {d'2001-01-01'}";
- helpTestRewriteCriteria(sql, parseCriteria(sql, metadata), metadata);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,2452 @@
+/*
+ * 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.rewriter;
+
+import static org.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.TimeZone;
+
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.client.metadata.ParameterInfo;
+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.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.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.resolver.util.ResolverVisitor;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.MatchCriteria;
+import org.teiid.query.sql.lang.ProcedureContainer;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
+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.SearchedCaseExpression;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.visitor.CorrelatedReferenceCollectorVisitor;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
+import org.teiid.query.util.ContextProperties;
+
+
+ at SuppressWarnings("nls")
+public class TestQueryRewriter {
+
+ private static final String TRUE_STR = "1 = 1"; //$NON-NLS-1$
+ private static final String FALSE_STR = "1 = 0"; //$NON-NLS-1$
+
+ // ################################## TEST HELPERS ################################
+
+ private Criteria parseCriteria(String critStr, QueryMetadataInterface metadata) {
+ try {
+ Criteria crit = QueryParser.getQueryParser().parseCriteria(critStr);
+
+ // resolve against metadata
+ QueryResolver.resolveCriteria(crit, metadata);
+
+ return crit;
+ } catch(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private Criteria helpTestRewriteCriteria(String original, String expected) {
+ try {
+ return helpTestRewriteCriteria(original, expected, false);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private Criteria helpTestRewriteCriteria(String original, String expected, boolean rewrite) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ Criteria expectedCrit = parseCriteria(expected, metadata);
+ if (rewrite) {
+ QueryResolver.resolveCriteria(expectedCrit, metadata);
+ expectedCrit = QueryRewriter.rewriteCriteria(expectedCrit, null, null, metadata);
+ }
+ return helpTestRewriteCriteria(original, expectedCrit, metadata);
+ }
+
+ private Map<ElementSymbol, Integer> elements;
+ private List<List> tuples;
+
+ @Before public void setUp() {
+ elements = null;
+ tuples = new ArrayList<List>();
+ }
+
+ private Criteria helpTestRewriteCriteria(String original, Criteria expectedCrit, QueryMetadataInterface metadata) {
+ Criteria origCrit = parseCriteria(original, metadata);
+
+ Criteria actual = null;
+ // rewrite
+ try {
+ ArrayList<Boolean> booleanVals = new ArrayList<Boolean>(tuples.size());
+ for (List<Object> tuple : tuples) {
+ booleanVals.add(new Evaluator(elements, null, null).evaluate(origCrit, tuple));
+ }
+ actual = QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
+ assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
+ for (int i = 0; i < tuples.size(); i++) {
+ assertEquals(tuples.get(i).toString(), booleanVals.get(i), new Evaluator(elements, null, null).evaluate(actual, tuples.get(i)));
+ }
+ } catch(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+ return actual;
+ }
+
+ private Expression helpTestRewriteExpression(String original, String expected, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException {
+ Expression actualExp = QueryParser.getQueryParser().parseExpression(original);
+ ResolverVisitor.resolveLanguageObject(actualExp, metadata);
+ CommandContext context = new CommandContext();
+ context.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
+ actualExp = QueryRewriter.rewriteExpression(actualExp, null, context, metadata);
+ if (expected != null) {
+ Expression expectedExp = QueryParser.getQueryParser().parseExpression(expected);
+ ResolverVisitor.resolveLanguageObject(expectedExp, metadata);
+ assertEquals(expectedExp, actualExp);
+ }
+ return actualExp;
+ }
+
+ private String getRewritenProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType) throws TeiidComponentException, TeiidProcessingException {
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(procedureType, procedure);
+
+ return getRewritenProcedure(userUpdateStr, metadata);
+ }
+
+ private String getRewritenProcedure(String userUpdateStr,
+ QueryMetadataInterface metadata) throws TeiidComponentException,
+ QueryMetadataException, TeiidProcessingException {
+ ProcedureContainer userCommand = (ProcedureContainer)QueryParser.getQueryParser().parseCommand(userUpdateStr);
+ QueryResolver.resolveCommand(userCommand, metadata);
+ CreateUpdateProcedureCommand proc = (CreateUpdateProcedureCommand)QueryResolver.expandCommand(userCommand, metadata, null);
+ QueryRewriter.rewrite(userCommand, metadata, null);
+ Command result = QueryRewriter.rewrite(proc, metadata, null);
+ return result.toString();
+ }
+
+ static Command helpTestRewriteCommand(String original, String expected) {
+ try {
+ return helpTestRewriteCommand(original, expected, RealMetadataFactory.example1Cached());
+ } catch(TeiidException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+
+ public static Command helpTestRewriteCommand(String original, String expected, QueryMetadataInterface metadata) throws TeiidException {
+ Command command = QueryParser.getQueryParser().parseCommand(original);
+ QueryResolver.resolveCommand(command, metadata);
+ Command rewriteCommand = QueryRewriter.rewrite(command, metadata, null);
+ assertEquals("Rewritten command was not expected", expected, rewriteCommand.toString()); //$NON-NLS-1$
+ return rewriteCommand;
+ }
+
+ @Test public void testRewriteUnknown() {
+ helpTestRewriteCriteria("pm1.g1.e1 = '1' and '1' = convert(null, string)", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteUnknown1() {
+ helpTestRewriteCriteria("pm1.g1.e1 = '1' or '1' = convert(null, string)", "pm1.g1.e1 = '1'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteUnknown2() {
+ helpTestRewriteCriteria("not('1' = convert(null, string))", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteUnknown3() {
+ helpTestRewriteCriteria("pm1.g1.e1 like convert(null, string))", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteUnknown4() {
+ helpTestRewriteCriteria("null in ('a', 'b', 'c')", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteUnknown5() {
+ helpTestRewriteCriteria("(null <> null) and 1 = 0", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteUnknown6() {
+ helpTestRewriteCriteria("not(pm1.g1.e1 = '1' and '1' = convert(null, string))", "pm1.g1.e1 <> '1'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteUnknown7() {
+ helpTestRewriteCriteria("not(pm1.g1.e1 = '1' or '1' = convert(null, string))", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteUnknown8() {
+ helpTestRewriteCriteria("pm1.g1.e1 in (2, null)", "pm1.g1.e1 = '2'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteInCriteriaWithRepeats() {
+ helpTestRewriteCriteria("pm1.g1.e1 in ('1', '1', '2')", "pm1.g1.e1 IN ('1', '2')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteInCriteriaWithSingleValue() {
+ helpTestRewriteCriteria("pm1.g1.e1 in ('1')", "pm1.g1.e1 = '1'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteInCriteriaWithSingleValue1() {
+ helpTestRewriteCriteria("pm1.g1.e1 not in ('1')", "pm1.g1.e1 != '1'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteInCriteriaWithConvert() {
+ helpTestRewriteCriteria("convert(pm1.g1.e2, string) not in ('x')", "pm1.g1.e2 IS NOT NULL"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteInCriteriaWithNoValues() throws Exception {
+ ElementSymbol e1 = new ElementSymbol("e1");
+ e1.setGroupSymbol(new GroupSymbol("g1"));
+ Criteria crit = new SetCriteria(e1, Collections.EMPTY_LIST); //$NON-NLS-1$
+
+ Criteria actual = QueryRewriter.rewriteCriteria(crit, null, null, null);
+
+ IsNullCriteria inc = new IsNullCriteria(e1);
+ inc.setNegated(true);
+ assertEquals(inc, actual);
+ }
+
+ @Test public void testRewriteBetweenCriteria1() {
+ helpTestRewriteCriteria("pm1.g1.e1 BETWEEN 1000 AND 2000", "(pm1.g1.e1 >= '1000') AND (pm1.g1.e1 <= '2000')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteBetweenCriteria2() {
+ helpTestRewriteCriteria("pm1.g1.e1 NOT BETWEEN 1000 AND 2000", "(pm1.g1.e1 < '1000') OR (pm1.g1.e1 > '2000')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCrit1() {
+ helpTestRewriteCriteria("concat('a','b') = 'ab'", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCrit2() {
+ helpTestRewriteCriteria("'x' = pm1.g1.e1", "(pm1.g1.e1 = 'x')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCrit3() {
+ helpTestRewriteCriteria("pm1.g1.e1 = convert('a', string)", "pm1.g1.e1 = 'a'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCrit4() {
+ helpTestRewriteCriteria("pm1.g1.e1 = CONVERT('a', string)", "pm1.g1.e1 = 'a'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCrit5() {
+ helpTestRewriteCriteria("pm1.g1.e1 in ('a')", "pm1.g1.e1 = 'a'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCrit6() {
+ helpTestRewriteCriteria("1 = convert(pm1.g1.e1,integer) + 10", "pm1.g1.e1 = '-9'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCrit7() {
+ helpTestRewriteCriteria("((pm1.g1.e1 = 1) and (pm1.g1.e1 = 1))", "pm1.g1.e1 = '1'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteMatchCritEscapeChar1() {
+ helpTestRewriteCriteria("pm1.g1.e1 LIKE 'x_' ESCAPE '\\'", "pm1.g1.e1 LIKE 'x_'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteMatchCritEscapeChar2() {
+ helpTestRewriteCriteria("pm1.g1.e1 LIKE '#%x' ESCAPE '#'", "pm1.g1.e1 LIKE '#%x' ESCAPE '#'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteMatchCritEscapeChar3() {
+ helpTestRewriteCriteria("pm1.g1.e1 LIKE '#%x'", "pm1.g1.e1 LIKE '#%x'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteMatchCritEscapeChar4() {
+ helpTestRewriteCriteria("pm1.g1.e1 LIKE pm1.g1.e1 ESCAPE '#'", "pm1.g1.e1 LIKE pm1.g1.e1 ESCAPE '#'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteMatchCritEscapeChar5() throws Exception {
+ MatchCriteria mcrit = new MatchCriteria(new ElementSymbol("pm1.g1.e1"), new Constant(null, DataTypeManager.DefaultDataClasses.STRING), '#'); //$NON-NLS-1$
+ Criteria expected = QueryRewriter.UNKNOWN_CRITERIA;
+
+ Object actual = QueryRewriter.rewriteCriteria(mcrit, null, null, null);
+ assertEquals("Did not get expected rewritten criteria", expected, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMatchCrit1() {
+ helpTestRewriteCriteria("pm1.g1.e1 LIKE 'x' ESCAPE '\\'", "pm1.g1.e1 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteMatchCrit2() {
+ helpTestRewriteCriteria("pm1.g1.e1 NOT LIKE 'x'", "pm1.g1.e1 <> 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteMatchCrit3() {
+ helpTestRewriteCriteria("pm1.g1.e1 NOT LIKE '%'", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritTimestampCreate1() {
+ helpTestRewriteCriteria("timestampCreate(pm3.g1.e2, pm3.g1.e3) = {ts'2004-11-23 09:25:00'}", "(pm3.g1.e2 = {d'2004-11-23'}) AND (pm3.g1.e3 = {t'09:25:00'})"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritTimestampCreate2() {
+ helpTestRewriteCriteria("{ts'2004-11-23 09:25:00'} = timestampCreate(pm3.g1.e2, pm3.g1.e3)", "(pm3.g1.e2 = {d'2004-11-23'}) AND (pm3.g1.e3 = {t'09:25:00'})"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritSwap1() {
+ helpTestRewriteCriteria("'x' = pm1.g1.e1", "pm1.g1.e1 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritSwap2() {
+ helpTestRewriteCriteria("'x' <> pm1.g1.e1", "pm1.g1.e1 <> 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritSwap3() {
+ helpTestRewriteCriteria("'x' < pm1.g1.e1", "pm1.g1.e1 > 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritSwap4() {
+ helpTestRewriteCriteria("'x' <= pm1.g1.e1", "pm1.g1.e1 >= 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritSwap5() {
+ helpTestRewriteCriteria("'x' > pm1.g1.e1", "pm1.g1.e1 < 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritSwap6() {
+ helpTestRewriteCriteria("'x' >= pm1.g1.e1", "pm1.g1.e1 <= 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritExpr_op1() {
+ helpTestRewriteCriteria("pm1.g1.e2 + 5 = 10", "pm1.g1.e2 = 5"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritExpr_op2() {
+ helpTestRewriteCriteria("pm1.g1.e2 - 5 = 10", "pm1.g1.e2 = 15"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritExpr_op3() {
+ helpTestRewriteCriteria("pm1.g1.e2 * 5 = 10", "pm1.g1.e2 = 2"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritExpr_op4() {
+ helpTestRewriteCriteria("pm1.g1.e2 / 5 = 10", "pm1.g1.e2 = 50"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritExpr_signFlip1() {
+ helpTestRewriteCriteria("pm1.g1.e2 * -5 > 10", "pm1.g1.e2 < -2"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritExpr_signFlip2() {
+ helpTestRewriteCriteria("pm1.g1.e2 * -5 >= 10", "pm1.g1.e2 <= -2"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritExpr_signFlip3() {
+ helpTestRewriteCriteria("pm1.g1.e2 * -5 < 10", "pm1.g1.e2 > -2"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritExpr_signFlip4() {
+ helpTestRewriteCriteria("pm1.g1.e2 * -5 <= 10", "pm1.g1.e2 >= -2"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritExpr_backwards1() {
+ helpTestRewriteCriteria("5 + pm1.g1.e2 <= 10", "pm1.g1.e2 <= 5"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritExpr_backwards2() {
+ helpTestRewriteCriteria("-5 * pm1.g1.e2 <= 10", "pm1.g1.e2 >= -2"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritExpr_unhandled1() {
+ helpTestRewriteCriteria("5 / pm1.g1.e2 <= 10", "5 / pm1.g1.e2 <= 10"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritExpr_unhandled2() {
+ helpTestRewriteCriteria("5 - pm1.g1.e2 <= 10", "5 - pm1.g1.e2 <= 10"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCrit_parseDate() {
+ helpTestRewriteCriteria("PARSEDATE(pm3.g1.e1, 'yyyyMMdd') = {d'2003-05-01'}", //$NON-NLS-1$
+ "pm3.g1.e1 = '20030501'" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCrit_parseDate1() {
+ helpTestRewriteCriteria("PARSEDATE(pm3.g1.e1, 'yyyyMM') = {d'2003-05-01'}", //$NON-NLS-1$
+ "pm3.g1.e1 = '200305'" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="we're no longer considering parsedate directly")
+ @Test public void testRewriteCrit_parseDate2() {
+ helpTestRewriteCriteria("PARSEDATE(pm3.g1.e1, 'yyyyMM') = {d'2003-05-02'}", //$NON-NLS-1$
+ "1 = 0" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="Should be moved to the validator")
+ @Test public void testRewriteCrit_invalidParseDate() {
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ Criteria origCrit = parseCriteria("PARSEDATE(pm3.g1.e1, '''') = {d'2003-05-01'}", metadata); //$NON-NLS-1$
+
+ try {
+ QueryRewriter.rewriteCriteria(origCrit, null, null, null);
+ fail("Expected failure"); //$NON-NLS-1$
+ } catch(TeiidException e) {
+ assertEquals("Error Code:ERR.015.001.0003 Message:Error simplifying criteria: PARSEDATE(pm3.g1.e1, '''') = {d'2003-05-01'}", e.getMessage()); //$NON-NLS-1$
+ }
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCrit_parseTime() {
+ helpTestRewriteCriteria("PARSETIME(pm3.g1.e1, 'HH mm ss') = {t'13:25:04'}", //$NON-NLS-1$
+ "pm3.g1.e1 = '13 25 04'" ); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCrit_parseTimestamp() {
+ helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') = {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
+ "1 = 0" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCrit_parseTimestamp1() {
+ helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') = {ts'2003-01-01 00:25:00.0'}", //$NON-NLS-1$
+ "pm3.g1.e1 = '2003 01 25'" ); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCrit_parseTimestamp2() {
+ helpTestRewriteCriteria("PARSETimestamp(CONVERT(pm3.g1.e2, string), 'yyyy-MM-dd') = {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
+ "1 = 0" ); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCrit_parseTimestamp3() {
+ helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') <> {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
+ "pm3.g1.e1 is not null" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCrit_parseTimestamp4() {
+ helpTestRewriteCriteria("PARSETimestamp(CONVERT(pm3.g1.e2, string), 'yyyy-MM-dd') = {ts'2003-05-01 00:00:00.0'}", //$NON-NLS-1$
+ "pm3.g1.e2 = {d'2003-05-01'}" ); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCrit_parseTimestamp_notEquality() {
+ helpTestRewriteCriteria("PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') > {ts'2003-05-01 13:25:04.5'}", //$NON-NLS-1$
+ "PARSETimestamp(pm3.g1.e1, 'yyyy dd mm') > {ts'2003-05-01 13:25:04.5'}" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCrit_parseTimestamp_decompose() {
+ helpTestRewriteCriteria("PARSETIMESTAMP(CONCAT(FORMATDATE(pm3.g1.e2, 'yyyyMMdd'), FORMATTIME(pm3.g1.e3, 'HHmmss')), 'yyyyMMddHHmmss') = PARSETIMESTAMP('19690920183045', 'yyyyMMddHHmmss')", //$NON-NLS-1$
+ "(pm3.g1.e2 = {d'1969-09-20'}) AND (pm3.g1.e3 = {t'18:30:45'})" ); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCrit_timestampCreate_decompose() {
+ helpTestRewriteCriteria("timestampCreate(pm3.g1.e2, pm3.g1.e3) = PARSETIMESTAMP('19690920183045', 'yyyyMMddHHmmss')", //$NON-NLS-1$
+ "(pm3.g1.e2 = {d'1969-09-20'}) AND (pm3.g1.e3 = {t'18:30:45'})" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCrit_parseInteger() {
+ helpTestRewriteCriteria("parseInteger(pm1.g1.e1, '#,##0') = 1234", //$NON-NLS-1$
+ "pm1.g1.e1 = '1,234'" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCrit_parseLong() {
+ helpTestRewriteCriteria("parseLong(pm1.g1.e1, '#,##0') = convert(1234, long)", //$NON-NLS-1$
+ "pm1.g1.e1 = '1,234'" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCrit_parseBigInteger() {
+ helpTestRewriteCriteria("parseBigInteger(pm1.g1.e1, '#,##0') = convert(1234, biginteger)", //$NON-NLS-1$
+ "pm1.g1.e1 = '1,234'" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCrit_parseFloat() {
+ helpTestRewriteCriteria("parseFloat(pm1.g1.e1, '#,##0.###') = convert(1234.123, float)", //$NON-NLS-1$
+ "pm1.g1.e1 = '1,234.123'" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCrit_parseDouble() {
+ helpTestRewriteCriteria("parseDouble(pm1.g1.e1, '$#,##0.00') = convert(1234.5, double)", //$NON-NLS-1$
+ "pm1.g1.e1 = '$1,234.50'" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCrit_parseBigDecimal() {
+ helpTestRewriteCriteria("parseBigDecimal(pm1.g1.e1, '#,##0.###') = convert(1234.1234, bigdecimal)", //$NON-NLS-1$
+ "pm1.g1.e1 = '1,234.123'" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="Cannot deterime if the format is narrowing")
+ @Test public void testRewriteCrit_formatDate() {
+ helpTestRewriteCriteria("formatDate(pm3.g1.e2, 'yyyyMMdd') = '20030501'", //$NON-NLS-1$
+ "pm3.g1.e2 = {d'2003-05-01'}" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="Cannot deterime if the format is narrowing")
+ @Test public void testRewriteCrit_formatTime() {
+ helpTestRewriteCriteria("formatTime(pm3.g1.e3, 'HH mm ss') = '13 25 04'", //$NON-NLS-1$
+ "pm3.g1.e3 = {t'13:25:04'}" ); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCrit_formatTimestamp() {
+ helpTestRewriteCriteria("formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss') = '05 01, 1974 - 07:00:00'", //$NON-NLS-1$
+ "formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss') = '05 01, 1974 - 07:00:00'" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="Cannot deterime if the format is narrowing")
+ @Test public void testRewriteCrit_formatTimestamp1() {
+ helpTestRewriteCriteria("formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss.S') = '05 01, 1974 - 07:00:00.0'", //$NON-NLS-1$
+ "pm3.g1.e4 = {ts'1974-05-01 07:00:00.0'}" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="Cannot deterime if the format is narrowing")
+ @Test public void testRewriteCrit_formatInteger() {
+ helpTestRewriteCriteria("formatInteger(pm1.g1.e2, '#,##0') = '1,234'", //$NON-NLS-1$
+ "pm1.g1.e2 = 1234" ); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCrit_formatInteger1() {
+ helpTestRewriteCriteria("formatInteger(pm1.g1.e2, '#5') = '105'", //$NON-NLS-1$
+ "formatInteger(pm1.g1.e2, '#5') = '105'" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="Cannot deterime if the format is narrowing")
+ @Test public void testRewriteCrit_formatLong() {
+ helpTestRewriteCriteria("formatLong(convert(pm1.g1.e2, long), '#,##0') = '1,234,567,890,123'", //$NON-NLS-1$
+ "1 = 0" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="Cannot deterime if the format is narrowing")
+ @Test public void testRewriteCrit_formatLong1() {
+ helpTestRewriteCriteria("formatLong(convert(pm1.g1.e2, long), '#,##0') = '1,234,567,890'", //$NON-NLS-1$
+ "pm1.g1.e2 = 1234567890" ); //$NON-NLS-1$
+ }
+
+ @Ignore(value="Cannot deterime if the format is narrowing")
+ @Test public void testRewriteCrit_formatTimestampInvert() {
+ String original = "formatTimestamp(pm3.g1.e4, 'MM dd, yyyy - HH:mm:ss.S') = ?"; //$NON-NLS-1$
+ String expected = "pm3.g1.e4 = parseTimestamp(?, 'MM dd, yyyy - HH:mm:ss.S')"; //$NON-NLS-1$
+
+ helpTestRewriteCriteria(original, expected);
+ }
+
+ @Test public void testRewriteCrit_plusInvert() {
+ String original = "pm1.g1.e2 + 1.1 = ?"; //$NON-NLS-1$
+ String expected = "pm1.g1.e2 = ? - 1.1"; //$NON-NLS-1$
+
+ helpTestRewriteCriteria(original, expected);
+ }
+
+ @Ignore(value="Cannot deterime if the format is narrowing")
+ @Test public void testRewriteCrit_formatBigInteger() throws Exception {
+ 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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ Criteria origCrit = parseCriteria(original, metadata);
+ Criteria expectedCrit = parseCriteria(expected, metadata);
+
+ // rewrite
+ Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
+ assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
+ }
+
+ @Ignore(value="Cannot deterime if the format is narrowing")
+ @Test public void testRewriteCrit_formatFloat() throws Exception {
+ 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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ Criteria origCrit = parseCriteria(original, metadata);
+
+ // rewrite
+ Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
+ assertEquals("Did not rewrite correctly: ", expected, actual.toString()); //$NON-NLS-1$
+ }
+
+ @Ignore(value="Cannot deterime if the format is narrowing")
+ @Test public void testRewriteCrit_formatDouble() throws Exception {
+ 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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ Criteria origCrit = parseCriteria(original, metadata);
+ Criteria expectedCrit = parseCriteria(expected, metadata);
+ ((CompareCriteria)expectedCrit).setRightExpression(new Constant(new Double(1234.5)));
+
+ // rewrite
+ Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
+ assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
+ }
+
+ @Ignore(value="Cannot deterime if the format is narrowing")
+ @Test public void testRewriteCrit_formatBigDecimal() throws Exception {
+ 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$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ Criteria origCrit = parseCriteria(original, metadata);
+ Criteria expectedCrit = parseCriteria(expected, metadata);
+
+ // rewrite
+ Criteria actual = QueryRewriter.rewriteCriteria(origCrit, null, null, null);
+ assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCritTimestampDiffDate1() {
+ helpTestRewriteCriteria("timestampdiff(SQL_TSI_DAY, {d'2003-05-15'}, {d'2003-05-17'} ) = 2", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCritTimestampDiffDate2() {
+ helpTestRewriteCriteria("timestampdiff(SQL_TSI_DAY, {d'2003-06-02'}, {d'2003-05-17'} ) = -16", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCritTimestampDiffDate3() {
+ helpTestRewriteCriteria("timestampdiff(SQL_TSI_QUARTER, {d'2002-01-25'}, {d'2003-06-01'} ) = 5", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCritTimestampDiffTime1() {
+ helpTestRewriteCriteria("timestampdiff(SQL_TSI_HOUR, {t'03:04:45'}, {t'05:05:36'} ) = 2", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCritTimestampDiffTime1_ignorecase() {
+ helpTestRewriteCriteria("timestampdiff(SQL_tsi_HOUR, {t'03:04:45'}, {t'05:05:36'} ) = 2", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteOr1() {
+ helpTestRewriteCriteria("(5 = 5) OR (0 = 1)", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteOr2() {
+ helpTestRewriteCriteria("(0 = 1) OR (5 = 5)", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteOr3() {
+ helpTestRewriteCriteria("(1 = 1) OR (5 = 5)", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteOr4() {
+ helpTestRewriteCriteria("(0 = 1) OR (4 = 5)", FALSE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteOr5() {
+ helpTestRewriteCriteria("(0 = 1) OR (4 = 5) OR (pm1.g1.e1 = 'x')", "(pm1.g1.e1 = 'x')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteOr6() {
+ helpTestRewriteCriteria("(0 = 1) OR (4 = 5) OR (pm1.g1.e1 = 'x') OR (pm1.g1.e1 = 'y')", "pm1.g1.e1 IN ('x', 'y')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteOr7() {
+ helpTestRewriteCriteria("(pm1.g1.e1 = 'x') OR (pm1.g1.e1 = 'y')", "pm1.g1.e1 IN ('x', 'y')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteAnd1() {
+ helpTestRewriteCriteria("(5 = 5) AND (0 = 1)", FALSE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteAnd2() {
+ helpTestRewriteCriteria("(0 = 1) AND (5 = 5)", FALSE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteAnd3() {
+ helpTestRewriteCriteria("(1 = 1) AND (5 = 5)", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteAnd4() {
+ helpTestRewriteCriteria("(0 = 1) AND (4 = 5)", FALSE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteAnd5() {
+ helpTestRewriteCriteria("(1 = 1) AND (5 = 5) AND (pm1.g1.e1 = 'x')", "(pm1.g1.e1 = 'x')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteAnd6() {
+ helpTestRewriteCriteria("(1 = 1) AND (5 = 5) AND (pm1.g1.e1 = 'x')", "(pm1.g1.e1 = 'x')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteAnd7() {
+ helpTestRewriteCriteria("(pm1.g1.e1 = 'x') AND (lower(pm1.g1.e1) = 'y')", "(pm1.g1.e1 = 'x') AND (lcase(pm1.g1.e1) = 'y')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteMixed1() {
+ helpTestRewriteCriteria("((1=1) AND (1=1)) OR ((1=1) AND (1=1))", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed2() {
+ helpTestRewriteCriteria("((1=2) AND (1=1)) OR ((1=1) AND (1=1))", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed3() {
+ helpTestRewriteCriteria("((1=1) AND (1=2)) OR ((1=1) AND (1=1))", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed4() {
+ helpTestRewriteCriteria("((1=1) AND (1=1)) OR ((1=2) AND (1=1))", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed5() {
+ helpTestRewriteCriteria("((1=1) AND (1=1)) OR ((1=1) AND (1=2))", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed6() {
+ helpTestRewriteCriteria("((1=2) AND (1=1)) OR ((1=2) AND (1=1))", FALSE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed7() {
+ helpTestRewriteCriteria("((1=1) AND (1=2)) OR ((1=1) AND (1=2))", FALSE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed8() {
+ helpTestRewriteCriteria("((1=2) AND (1=2)) OR ((1=2) AND (1=2))", FALSE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed9() {
+ helpTestRewriteCriteria("((1=1) OR (1=1)) AND ((1=1) OR (1=1))", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed10() {
+ helpTestRewriteCriteria("((1=2) OR (1=1)) AND ((1=1) OR (1=1))", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed11() {
+ helpTestRewriteCriteria("((1=1) OR (1=2)) AND ((1=1) OR (1=1))", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed12() {
+ helpTestRewriteCriteria("((1=1) OR (1=1)) AND ((1=2) OR (1=1))", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed13() {
+ helpTestRewriteCriteria("((1=1) OR (1=1)) AND ((1=1) OR (1=2))", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed14() {
+ helpTestRewriteCriteria("((1=2) OR (1=1)) AND ((1=2) OR (1=1))", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed15() {
+ helpTestRewriteCriteria("((1=1) OR (1=2)) AND ((1=1) OR (1=2))", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteMixed16() {
+ helpTestRewriteCriteria("((1=2) OR (1=2)) AND ((1=2) OR (1=2))", FALSE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteNot1() {
+ helpTestRewriteCriteria("NOT (1=1)", FALSE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteNot2() {
+ helpTestRewriteCriteria("NOT (1=2)", TRUE_STR); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteNot3() {
+ helpTestRewriteCriteria("NOT (pm1.g1.e1='x')", "pm1.g1.e1 <> 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteDefect1() {
+ helpTestRewriteCriteria("(('DE' = 'LN') AND (null > '2002-01-01')) OR (('DE' = 'DE') AND (pm1.g1.e1 > '9000000'))", "(pm1.g1.e1 > '9000000')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteQueryCriteriaAlwaysTrue() {
+ helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE 0 = 0", //$NON-NLS-1$
+ "SELECT e1 FROM pm1.g1"); //$NON-NLS-1$
+ }
+
+ @Test public void testSubquery1() {
+ helpTestRewriteCommand("SELECT e1 FROM (SELECT e1 FROM pm1.g1 WHERE (1 - 1) = (0 + 0)) AS x", //$NON-NLS-1$
+ "SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS x"); //$NON-NLS-1$
+ }
+
+ @Test public void testExistsSubquery() {
+ helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE EXISTS (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
+ "SELECT e1 FROM pm1.g1 WHERE EXISTS (SELECT e1 FROM pm1.g2 LIMIT 1)"); //$NON-NLS-1$
+ }
+
+ @Test public void testCompareSubqueryANY() {
+ helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE '3' = ANY (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
+ "SELECT e1 FROM pm1.g1 WHERE '3' IN (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
+ }
+
+ @Test public void testCompareSubquery() {
+ helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE '3' = SOME (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
+ "SELECT e1 FROM pm1.g1 WHERE '3' IN (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
+ }
+
+ @Test public void testCompareSubqueryUnknown() {
+ helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE null = SOME (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
+ "SELECT e1 FROM pm1.g1 WHERE 1 = 0"); //$NON-NLS-1$
+ }
+
+ @Test public void testINClauseSubquery() {
+ helpTestRewriteCommand("SELECT e1 FROM pm1.g1 WHERE '3' IN (SELECT e1 FROM pm1.g2)", //$NON-NLS-1$
+ "SELECT e1 FROM pm1.g1 WHERE '3' IN (SELECT e1 FROM pm1.g2)"); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteXMLCriteria1() {
+ helpTestRewriteCriteria("context(pm1.g1.e1, pm1.g1.e1) = convert(5, string)", "context(pm1.g1.e1, pm1.g1.e1) = '5'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteXMLCriteria2() {
+ helpTestRewriteCriteria("context(pm1.g1.e1, convert(5, string)) = 2+3", "context(pm1.g1.e1, '5') = '5'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // HAS Criteria
+ @Test public void testRewriteProcedure1() throws Exception {
+
+ String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.INSERT);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // HAS Criteria
+ @Test public void testRewriteProcedure2() throws Exception {
+
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ELSE \n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.INSERT);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // HAS Criteria
+ @Test public void testRewriteProcedure3() throws Exception {
+
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ELSE \n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.INSERT);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteProcedure4() throws Exception {
+
+ String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "IF (INPUT.e2 = 1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1 WHERE "+FALSE_STR+";\n"; //$NON-NLS-1$ //$NON-NLS-2$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.INSERT);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // CHANGING
+ @Test public void testRewriteProcedure5() throws Exception {
+
+ String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "IF (CHANGING.e1 = 'false')\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e2);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // CHANGING
+ @Test public void testRewriteProcedure6() throws Exception {
+
+ String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "IF (CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // TRANSLATE CRITERIA
+ @Test public void testRewriteProcedure7() throws Exception {
+
+ String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "IF (CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select e2 from pm1.g1 where TRANSLATE = CRITERIA ON (vm1.g1.e2);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT e2 FROM pm1.g1 WHERE pm1.g1.e2 = 10;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // TRANSLATE CRITERIA
+ @Test public void testRewriteProcedure8() throws Exception {
+
+ String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "IF (CHANGING.e1 = 'true')\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select e2 from pm1.g1 where TRANSLATE = CRITERIA ON (vm1.g1.e2) with (vm1.g1.e2 = convert(sqrt(pm1.g1.e2), integer));\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "Update vm1.g1 SET e1 = 'String', e2 =1 where e2 = 10"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT e2 FROM pm1.g1 WHERE convert(sqrt(pm1.g1.e2), integer) = 10;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // rewrite input/ changing variables
+ @Test public void testRewriteProcedure9() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Declare String var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(var1 = 'x' or var1 = 'y')\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2, Input.e2, CHANGING.e2, CHANGING.e1 from pm1.g1 order by CHANGING.e1 + 1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "INSERT into vm1.g1 (e1) values('x')"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ 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, 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,
+ Table.TriggerEvent.INSERT);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ @Test public void testRewriteProcedure10() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e2) WITH (e2 = pm1.g1.e2 + 20);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g1 SET e1='x' where e2 = e2 + 50"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1, pm1.g2 WHERE (pm1.g1.e2 + 20) = ((pm1.g1.e2 + 20) + 50);\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // virtual group elements used in procedure in if statement(HAS CRITERIA)
+ @Test public void testRewriteProcedure11() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE string var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = INPUT.e1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g1 SET e1=40"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "DECLARE string var1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "var1 = '40';\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ // with complex query transform
+ @Test public void testRewriteProcedure12() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (x = CONCAT(e1 , 'z'));\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where x =CONCAT(x , 'y')"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE CONCAT(e1, 'z') = CONCAT(CONCAT(e1, 'z'), 'y');\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ // with complex query transform
+ @Test public void testRewriteProcedure13() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (x = CONCAT(e1 , 'z'), y = convert(CONCAT(e1 , 'k'), integer));\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where x =CONCAT(x , 'y') and y= 1"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE (CONCAT(e1, 'z') = CONCAT(CONCAT(e1, 'z'), 'y')) AND (convert(CONCAT(e1, 'k'), integer) = 1);\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ @Test public void testRewriteProcedure14() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (e4 = sqrt(e4));\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where e4= 1"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE sqrt(e4) = 1.0;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ @Test public void testRewriteProcedure15() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (e4 = e4/50);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y= 1"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1 WHERE e2 = 0;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // virtual group elements used in procedure (TRANSLATE CRITERIA)
+ @Test public void testRewriteProcedure16() throws Exception {
+ String procedure = exampleTranslateUpdate();
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where e4= 1"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = 'x' WHERE e4 = 0.02;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteNoUserCriteria() throws Exception {
+ String procedure = exampleTranslateUpdate();
+
+ String userQuery = "UPDATE vm1.g3 SET x='x'"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = 'x' WHERE 1 = 1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteOrUserCriteria() throws Exception {
+ String procedure = exampleTranslateUpdate();
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where x = '1' or x = '2'"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = 'x' WHERE CONCAT(e1, 'm') IN ('2', '1');\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ private String exampleTranslateUpdate() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "update pm1.g1 set pm1.g1.e1 = inputs.x where TRANSLATE CRITERIA;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ return procedure;
+ }
+
+ @Test public void testRewriteProcedure17() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE LIKE CRITERIA WITH (e4 = e4/50);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where e4= 1"; //$NON-NLS-1$
+
+ this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // Bug 8212 elements in INPUT and CHANGING special groups are cese sensitive
+ @Test public void testRewriteProcedure18() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select Input.E1, Input.e2, CHANGING.e2, CHANGING.E1 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "INSERT into vm1.g1 (e1, E2) values('x', 1)"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT 'x', 1, TRUE, TRUE FROM pm1.g1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.INSERT);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // elements being set in updates are dropped if INPUT var is not available, unless a default is available
+ // Note that this test is a little odd in that it is an update inside of an insert
+ @Test public void testRewriteProcedure19() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "update pm1.g1 set e1=Input.E1, e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "INSERT into vm1.g1 (E2) values(1)"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = 'xyz', e2 = 1, e3 = TRUE;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.INSERT);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // elements being set in updates are dropped if INPUT var is not available, unless a default is supplied
+
+ //this test fails because the default for E1 'xyz' cannot be converted into a integer
+ @Test(expected=ExpressionEvaluationException.class) public void testRewriteProcedure21() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "update pm1.g1 set e1=convert(Input.E1, integer)+INPUT.E2, e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "INSERT into vm1.g1 (E3) values({b'true'})"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "UPDATE pm1.g1 SET e3 = TRUE;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ this.getRewritenProcedure(procedure, userQuery, Table.TriggerEvent.INSERT);
+ }
+
+ @Test public void testRewriteProcedure21a() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "update pm1.g1 set e1=convert(Input.E1, integer)+INPUT.E2, e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "INSERT into vm1.g1 (E1) values(1)"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\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,
+ Table.TriggerEvent.INSERT);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // none of input variables on update statement changing
+ @Test public void testRewriteProcedure22() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "update pm1.g1 set e1=convert(Input.E1, integer)+INPUT.E2, e2=Input.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "update vm1.g1 set E3 = {b'true'}"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // none of input variables on update statement changing
+ @Test public void testRewriteProcedure23() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "update pm1.g1 set e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "update vm1.g1 set E1 = 'x'"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ //with an insert, defaults are used
+ @Test public void testRewriteProcedure23a() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "update pm1.g1 set e2=Input.e2, e3=Input.e3;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "INSERT into vm1.g1 (E1) values('x')"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\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,
+ Table.TriggerEvent.INSERT);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteProcedure24() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "UPDATE pm1.g1 SET e2=Input.e2 WHERE TRANSLATE LIKE CRITERIA ON (e1) WITH (e1=concat(pm1.g1.e1, '%'));\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g1 set E2=1 where e2 = 1 and e1 LIKE 'mnopxyz_'"; //$NON-NLS-1$
+
+ this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // INPUT vars in insert statements replaced by default variable when user's inser ignores values
+ @Test public void testRewriteProcedure25() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "INSERT into pm1.g1 (e1,e2,e3,e4) values (Input.e1, Input.e2, Input.e3, Input.e4);"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "INSERT into vm1.g1 (E2) values (1)"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "INSERT INTO pm1.g1 (e1, e2, e3, e4) VALUES ('xyz', 1, TRUE, 123.456);\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.INSERT);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ @Test public void testRewriteProcedure26() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e2);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g1 SET e1='x' where e2 = e2 + 50"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT pm1.g1.e2 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e2 = (pm1.g1.e2 + 50);\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteProcedure27() throws Exception {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e2);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g1 SET e1='x' where e2 LIKE 'xyz'"; //$NON-NLS-1$
+
+ this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ /**
+ * Per defect 9380 -
+ * A criteria of the form
+ * (? + 1) < (null)
+ * caused a problem in the QueryRewriter.simplifyMathematicalCriteria method.
+ * At the beginning of the method, the null constant is rewritten so that it
+ * loses it's implicit type conversion to integer, then later on a function
+ * descriptor couldn't be found for the "minus" operation for the two types
+ * integer and MetaMatrix's null type.
+ */
+ @Test public void testRewriteProcedure_9380() throws Exception {
+
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var2;\n"; //$NON-NLS-1$
+ procedure = procedure + "if((var1 + 1) < length(input.e1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "var2 = INPUT.e2;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g1 SET e2=30"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "DECLARE integer var2;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ //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, RealMetadataFactory.example1Cached());
+ helpTestRewriteCriteria(criteria, expected, RealMetadataFactory.example1Cached());
+ }
+
+ @Test public void testRewriteLookupFunction1b() {
+ helpTestRewriteCriteria("lookup('pm1.g1','e1', 'e2', pm1.g1.e2) = 'ab'", "lookup('pm1.g1','e1', 'e2', pm1.g1.e2) = 'ab'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** 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, 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() {
+ helpTestRewriteCommand("SELECT 5", "SELECT 5"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ //defect 9822
+ @Test public void testStoredProcedure_9822() throws Exception {
+
+ QueryParser parser = new QueryParser();
+ Command command = parser.parseCommand("exec pm1.sp4(5)"); //$NON-NLS-1$
+
+ // resolve
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ QueryResolver.resolveCommand(command, metadata);
+
+ // rewrite
+ Command rewriteCommand = QueryRewriter.rewrite(command, metadata, null);
+
+ List<SPParameter> parameters = ((StoredProcedure)rewriteCommand).getParameters();
+
+ for (SPParameter param : parameters) {
+ if(param.getParameterType() == ParameterInfo.IN || param.getParameterType() == ParameterInfo.INOUT){
+ assertTrue(param.getExpression() instanceof Constant);
+ }
+ }
+ }
+
+ @Test public void testRewriteFunctionThrowsEvaluationError() {
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ Criteria origCrit = parseCriteria("5 / 0 = 5", metadata); //$NON-NLS-1$
+
+ // rewrite
+ try {
+ QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
+ fail("Expected QueryValidatorException due to divide by 0"); //$NON-NLS-1$
+ } catch(TeiidException e) {
+ // looks like message is being wrapped with another exception with same message
+ assertEquals("Error Code:ERR.015.001.0003 Message:Unable to evaluate (5 / 0): Error Code:ERR.015.001.0003 Message:Error while evaluating function /", e.getMessage()); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testRewriteConvertThrowsEvaluationError() {
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ Criteria origCrit = parseCriteria("convert('x', integer) = 0", metadata); //$NON-NLS-1$
+
+ // rewrite
+ try {
+ QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
+ fail("Expected QueryValidatorException due to invalid string"); //$NON-NLS-1$
+ } catch(TeiidException e) {
+ assertEquals("Error Code:ERR.015.001.0003 Message:Unable to evaluate convert('x', integer): Error Code:ERR.015.001.0003 Message:Error while evaluating function convert", e.getMessage()); //$NON-NLS-1$
+ }
+ }
+
+ @Test public void testDefect13458() throws Exception {
+
+ String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "IF (HAS = CRITERIA ON (vm1.g1.e1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select vm1.g1.e1 from vm1.g1 where HAS = CRITERIA ON (vm1.g1.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "delete from vm1.g1 where e1='1'"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT vm1.g1.e1 FROM vm1.g1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.DELETE);
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCase1954() {
+ helpTestRewriteCriteria("convert(pm1.g1.e2, string) = '3'", "pm1.g1.e2 = 3"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCase1954a() {
+ helpTestRewriteCriteria("cast(pm1.g1.e2 as string) = '3'", "pm1.g1.e2 = 3"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCase1954b() throws Exception{
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ CompareCriteria expected = new CompareCriteria();
+ ElementSymbol leftElement = new ElementSymbol("pm1.g1.e4"); //$NON-NLS-1$
+ Constant constant = new Constant(new Double(3.0), DataTypeManager.DefaultDataClasses.DOUBLE);
+ expected.setLeftExpression(leftElement);
+ expected.setRightExpression(constant);
+ // resolve against metadata
+ QueryResolver.resolveCriteria(expected, metadata);
+
+ helpTestRewriteCriteria("convert(pm1.g1.e4, string) = '3.0'", expected, metadata); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteCase1954c() {
+ helpTestRewriteCriteria("convert(pm1.g1.e1, string) = 'x'", "pm1.g1.e1 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteCase1954d() {
+ helpTestRewriteCriteria("convert(pm1.g1.e1, timestamp) = {ts '2005-01-03 00:00:00.0'}", "pm1.g1.e1 = '2005-01-03 00:00:00.0'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCase1954e() {
+ helpTestRewriteCriteria("convert(pm1.g1.e4, integer) = 2", "convert(pm1.g1.e4, integer) = 2"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** Check that this fails, x is not convertable to an int */
+ @Test public void testRewriteCase1954f() {
+ helpTestRewriteCriteria("convert(pm1.g1.e2, string) = 'x'", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** Check that this returns true, x is not convertable to an int */
+ @Test public void testRewriteCase1954f1() {
+ helpTestRewriteCriteria("convert(pm1.g1.e2, string) != 'x'", "pm1.g1.e2 is not null"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCase1954Set() {
+ helpTestRewriteCriteria("convert(pm1.g1.e2, string) in ('2', '3')", "pm1.g1.e2 IN (2,3)"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCase1954SetA() {
+ helpTestRewriteCriteria("convert(pm1.g1.e2, string) in ('2', 'x')", "pm1.g1.e2 = 2"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCase1954SetB() {
+ helpTestRewriteCriteria("cast(pm1.g1.e2 as string) in ('2', '3')", "pm1.g1.e2 IN (2,3)"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCase1954SetC() {
+ helpTestRewriteCriteria("concat(pm1.g1.e2, 'string') in ('2', '3')", "concat(pm1.g1.e2, 'string') in ('2', '3')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCase1954SetD() {
+ helpTestRewriteCriteria("convert(pm1.g1.e2, string) in ('2', pm1.g1.e1)", "convert(pm1.g1.e2, string) in ('2', pm1.g1.e1)"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // First WHEN always true, so rewrite as THEN expression
+ @Test public void testRewriteCaseExpr1() {
+ helpTestRewriteCriteria("case when 0=0 then 1 else 2 end = 1", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // First WHEN always false, so rewrite as ELSE expression
+ @Test public void testRewriteCaseExpr2() {
+ helpTestRewriteCriteria("case when 0=1 then 1 else 2 end = 1", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // First WHEN can't be rewritten, so no changes
+ @Test public void testRewriteCaseExpr3() {
+ helpTestRewriteCriteria("case when 0 = pm1.g1.e2 then 1 else 2 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 1 ELSE 2 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCaseExpr4() {
+ helpTestRewriteCriteria("lookup('pm1.g1', 'e2', 'e1', case when 1=1 then pm1.g1.e1 end) = 0", "lookup('pm1.g1', 'e2', 'e1', pm1.g1.e1) = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // First WHEN always false, so remove it
+ @Test public void testRewriteCaseExpr5() {
+ helpTestRewriteCriteria("case when 0=1 then 1 when 0 = pm1.g1.e2 then 2 else 3 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 2 ELSE 3 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCaseExprForCase5413aFrom502() {
+ 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$
+ }
+
+ @Test public void testRewriteCaseExprForCase5413bFrom502() {
+ helpTestRewriteCriteria("case when 0 = pm1.g1.e2 then null else null end IS NULL", TRUE_STR); //$NON-NLS-1$
+ }
+
+
+ @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$
+ }
+
+ @Test public void testRewriteCaseExprForCase5413b() {
+ helpTestRewriteCriteria("case when 0 = pm1.g1.e2 then null else null end IS NULL", TRUE_STR); //$NON-NLS-1$
+ }
+
+ // First WHEN always true, so rewrite as THEN expression
+ @Test public void testRewriteSearchedCaseExpr1() {
+ helpTestRewriteCriteria("case 0 when 0 then 1 else 2 end = 1", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // First WHEN always false, so rewrite as ELSE expression
+ @Test public void testRewriteSearchedCaseExpr2() {
+ helpTestRewriteCriteria("case 0 when 1 then 1 else 2 end = 1", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteSearchedCaseExpr3() {
+ helpTestRewriteCriteria("case 0 when pm1.g1.e2 then 1 else 2 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 1 ELSE 2 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteSearchedCaseExpr4() {
+ String criteria = "lookup('pm1.g1', 'e2', 'e1', '2') = 0"; //$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
+ @Test public void testRewriteSearchedCaseExpr5() {
+ helpTestRewriteCriteria("case 0 when 1 then 1 when pm1.g1.e2 then 2 else 3 end = 1", "CASE WHEN pm1.g1.e2 = 0 THEN 2 ELSE 3 END = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDefect16879_1(){
+ helpTestRewriteCommand("SELECT decodestring(e1, 'a, b') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDefect16879_2(){
+ helpTestRewriteCommand("SELECT decodestring(e1, 'a, b, c, d') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 = 'c' THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDefect16879_3(){
+ helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDefect16879_4(){
+ helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b, c, d') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 = 'c' THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDefect16879_5(){
+ helpTestRewriteCommand("SELECT decodeinteger(e1, 'null, b, c, d') FROM pm1.g1", "SELECT CASE WHEN e1 IS NULL THEN 'b' WHEN e1 = 'c' THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDefect16879_6(){
+ helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b, null, d') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 IS NULL THEN 'd' ELSE e1 END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testDefect16879_7(){
+ helpTestRewriteCommand("SELECT decodeinteger(e1, 'a, b, null, d, e') FROM pm1.g1", "SELECT CASE WHEN e1 = 'a' THEN 'b' WHEN e1 IS NULL THEN 'd' ELSE 'e' END FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testCaseExpressionThatResolvesToNull() {
+ String sqlBefore = "SELECT CASE 'x' WHEN 'Old Inventory System' THEN NULL WHEN 'New Inventory System' THEN NULL END"; //$NON-NLS-1$
+ String sqlAfter = "SELECT null"; //$NON-NLS-1$
+
+ Command cmd = helpTestRewriteCommand( sqlBefore, sqlAfter );
+
+ ExpressionSymbol es = (ExpressionSymbol)cmd.getProjectedSymbols().get(0);
+ assertEquals( DataTypeManager.DefaultDataClasses.STRING, es.getType() );
+ }
+
+
+ //note that the env is now treated as deterministic, however it is really only deterministic within a session
+ @Test public void testRewriteExecEnv() throws Exception {
+ Command command = QueryParser.getQueryParser().parseCommand("exec pm1.sq2(env('sessionid'))"); //$NON-NLS-1$
+
+ 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, RealMetadataFactory.example1Cached(), context);
+
+ assertEquals("EXEC pm1.sq2('1')", rewriteCommand.toString()); //$NON-NLS-1$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteNestedFunctions() {
+ helpTestRewriteCommand("SELECT e1 FROM pm1.g1 where convert(parsedate(e1, 'yyyy-MM-dd'), string) = '2006-07-01'", "SELECT e1 FROM pm1.g1 WHERE e1 = '2006-07-01'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Ignore(value="It's not generally possible to invert a narrowing conversion")
+ @Test public void testRewriteWithReference() {
+ helpTestRewriteCommand("SELECT e1 FROM pm1.g1 where parsetimestamp(e1, 'yyyy-MM-dd') != ?", "SELECT e1 FROM pm1.g1 WHERE e1 <> formattimestamp(?, 'yyyy-MM-dd')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewiteJoinCriteria() {
+ helpTestRewriteCommand("SELECT pm1.g1.e1 FROM pm1.g1 inner join pm1.g2 on (pm1.g1.e1 = null)", "SELECT pm1.g1.e1 FROM pm1.g1 INNER JOIN pm1.g2 ON 1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewiteCompoundCriteria() {
+ helpTestRewriteCriteria("(pm1.g1.e1 = 1 and pm1.g1.e2 = 2) and (pm1.g1.e3 = 1 and pm1.g1.e4 = 2)", "(pm1.g1.e1 = '1') AND (pm1.g1.e2 = 2) AND (pm1.g1.e3 = TRUE) AND (pm1.g1.e4 = 2.0)"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteWhile() throws Exception {
+
+ String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "while (1 = 1)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select vm1.g1.e1 from vm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+
+ try {
+ 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$
+ }
+ }
+
+ @Test public void testRewriteWhile1() throws Exception {
+
+ String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "while (1 = 0)\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select vm1.g1.e1 from vm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.INSERT);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ /**
+ * Tests that VariableSubstitutionVisitor does not cause an NPE on count(*)
+ */
+ @Test public void testRewriteProcedureWithCount() throws Exception {
+
+ String procedure = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select count(*) from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
+
+ String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "SELECT COUNT(*) FROM pm1.g1;\n"; //$NON-NLS-1$
+ rewritProc = rewritProc + "END"; //$NON-NLS-1$
+
+ String procReturned = this.getRewritenProcedure(procedure, userQuery,
+ Table.TriggerEvent.INSERT);
+
+ assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
+ }
+
+ /**
+ * Test to ensure the update changing list retains e1 = ?
+ */
+ @Test public void testVariableSubstitutionVisitor() throws Exception {
+ String procedure1 = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure1 += "BEGIN\n"; //$NON-NLS-1$
+ procedure1 += "DECLARE string var1 = INPUT.e1;\n"; //$NON-NLS-1$
+ procedure1 += "ROWS_UPDATED = UPDATE vm1.g2 SET e1=var1;\n"; //$NON-NLS-1$
+ procedure1 += "END"; //$NON-NLS-1$
+
+ String procedure2 = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure2 += "BEGIN\n"; //$NON-NLS-1$
+ procedure2 += "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure2 += "IF (INPUT.e1 = 1)\n"; //$NON-NLS-1$
+ procedure2 += "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
+ procedure2 += "ELSE\n"; //$NON-NLS-1$
+ procedure2 += "ROWS_UPDATED = 5;\n"; //$NON-NLS-1$
+ procedure2 += "END"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1 = 'x' WHERE e2 = 5"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure1, procedure2);
+
+ String rewriten = getRewritenProcedure(userUpdateStr, metadata);
+
+ String expected = "CREATE PROCEDURE\nBEGIN\nDECLARE string var1 = 'x';\nUPDATE vm1.g2 SET e1 = var1;\nROWS_UPDATED = VARIABLES.ROWCOUNT;\nEND"; //$NON-NLS-1$
+
+ assertEquals(expected, rewriten);
+ }
+
+ @Test public void testRemoveEmptyLoop() {
+ String procedure1 = "CREATE virtual PROCEDURE "; //$NON-NLS-1$
+ procedure1 += "BEGIN\n"; //$NON-NLS-1$
+ procedure1 += "loop on (select e1 from pm1.g1) as myCursor\n"; //$NON-NLS-1$
+ procedure1 += "begin\n"; //$NON-NLS-1$
+ procedure1 += "end\n"; //$NON-NLS-1$
+ procedure1 += "select e1 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure1 += "END"; //$NON-NLS-1$
+
+ String expected = "CREATE VIRTUAL PROCEDURE\nBEGIN\nSELECT e1 FROM pm1.g1;\nEND"; //$NON-NLS-1$
+
+ helpTestRewriteCommand(procedure1, expected);
+ }
+
+ @Test public void testRewriteDeclare() {
+ String procedure1 = "CREATE virtual PROCEDURE "; //$NON-NLS-1$
+ procedure1 += "BEGIN\n"; //$NON-NLS-1$
+ procedure1 += "declare integer x = 1 + 1;\n"; //$NON-NLS-1$
+ procedure1 += "END"; //$NON-NLS-1$
+
+ String expected = "CREATE VIRTUAL PROCEDURE\nBEGIN\nDECLARE integer x = 2;\nEND"; //$NON-NLS-1$
+
+ helpTestRewriteCommand(procedure1, expected);
+ }
+
+ @Test public void testRewriteUnionJoin() {
+ String sql = "select pm1.g1.e1 from pm1.g1 union join pm1.g2 where g1.e1 = 1"; //$NON-NLS-1$
+ String expected = "SELECT pm1.g1.e1 FROM pm1.g1 FULL OUTER JOIN pm1.g2 ON 1 = 0 WHERE g1.e1 = '1'"; //$NON-NLS-1$
+
+ helpTestRewriteCommand(sql, expected);
+ }
+
+ @Test public void testRewriteNonNullDependentFunction() {
+ helpTestRewriteCriteria("pm1.g1.e1 = concat(null, pm1.g1.e2)", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteInWithNull() {
+ helpTestRewriteCriteria("convert(null, string) in (pm1.g1.e1, pm1.g1.e2)", "null <> null"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteXMLCriteriaCases5630And5640() {
+ helpTestRewriteCommand("select * from xmltest.doc1 where node1 = null", "SELECT * FROM xmltest.doc1 WHERE node1 = null"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCorrelatedSubqueryInHaving() {
+ String sql = "select pm1.g1.e1 from pm1.g1 group by pm1.g1.e1 having pm1.g1.e1 in (select pm1.g1.e1 from pm1.g2)"; //$NON-NLS-1$
+ String expected = "SELECT pm1.g1.e1 FROM pm1.g1 GROUP BY pm1.g1.e1 HAVING pm1.g1.e1 IN (SELECT pm1.g1.e1 FROM pm1.g2)"; //$NON-NLS-1$
+
+ Query query = (Query)helpTestRewriteCommand(sql, expected);
+
+ List<Reference> refs = new LinkedList<Reference>();
+
+ CorrelatedReferenceCollectorVisitor.collectReferences(query, Arrays.asList(new GroupSymbol("pm1.g1")), refs);//$NON-NLS-1$
+
+ assertEquals(1, refs.size());
+ }
+
+ @Test public void testRewriteSelectInto() {
+ String sql = "select distinct pm1.g1.e1 into #temp from pm1.g1"; //$NON-NLS-1$
+ String expected = "INSERT INTO #temp (#temp.e1) SELECT DISTINCT pm1.g1.e1 FROM pm1.g1"; //$NON-NLS-1$
+
+ helpTestRewriteCommand(sql, expected);
+ }
+
+ /**
+ * Accounts for type change with duplicate names
+ */
+ @Test public void testRewriteSelectInto1() {
+ String sql = "select distinct e2, e2, e3, e4 into pm1.g1 from pm1.g2"; //$NON-NLS-1$
+ String expected = "INSERT INTO pm1.g1 (pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4) SELECT X.e2 AS e1, X.E2_0 AS e2, X.e3, X.e4 FROM (SELECT DISTINCT e2, e2 AS E2_0, e3, e4 FROM pm1.g2) AS X"; //$NON-NLS-1$
+
+ helpTestRewriteCommand(sql, expected);
+ }
+
+ @Test public void testUnionQueryNullInOneBranch() throws Exception {
+ verifyProjectedTypesOnUnionBranches("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT e1, null FROM pm1.g2", //$NON-NLS-1$
+ new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER });
+ }
+
+ @Test public void testUnionQueryNullInOneBranch2() throws Exception {
+ verifyProjectedTypesOnUnionBranches("SELECT e1, e2 FROM pm1.g1 UNION ALL SELECT e1, e2 FROM pm1.g2 UNION ALL SELECT e1, null FROM pm1.g2", //$NON-NLS-1$
+ new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER });
+ }
+
+ @Test public void testUnionQueryNullInOneBranch3() throws Exception {
+ verifyProjectedTypesOnUnionBranches("SELECT e1, null FROM pm1.g1 UNION ALL SELECT e1, null FROM pm1.g2 UNION ALL SELECT e1, e2 FROM pm1.g2", //$NON-NLS-1$
+ new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.INTEGER });
+ }
+
+ @Test public void testUnionQueryNullInAllBranches() throws Exception {
+ verifyProjectedTypesOnUnionBranches("SELECT e1, null FROM pm1.g1 UNION ALL SELECT e1, null FROM pm1.g2 UNION ALL SELECT e1, null FROM pm1.g2", //$NON-NLS-1$
+ new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING });
+ }
+
+ @Test public void testUnionQueryWithTypeConversion() throws Exception {
+ verifyProjectedTypesOnUnionBranches("SELECT e1 FROM pm1.g1 UNION ALL SELECT e2 FROM pm1.g2", //$NON-NLS-1$
+ new Class[] { DataTypeManager.DefaultDataClasses.STRING});
+ }
+
+ private void verifyProjectedTypesOnUnionBranches(String unionQuery, Class<?>[] types) throws TeiidComponentException, TeiidProcessingException {
+ SetQuery union = (SetQuery)QueryParser.getQueryParser().parseCommand(unionQuery);
+ QueryResolver.resolveCommand(union, RealMetadataFactory.example1Cached());
+
+ union = (SetQuery)QueryRewriter.rewrite(union, RealMetadataFactory.example1Cached(), null);
+
+ for (QueryCommand query : union.getQueryCommands()) {
+ List<SingleElementSymbol> projSymbols = query.getProjectedSymbols();
+ for(int i=0; i<projSymbols.size(); i++) {
+ assertEquals("Found type mismatch at column " + i, types[i], projSymbols.get(i).getType()); //$NON-NLS-1$
+ }
+ }
+ }
+
+ /**
+ * The rewrite creates inline view to do the type conversion.
+ *
+ * It also ensures that all project symbols are uniquely named in the inline view
+ */
+ @Test public void testSelectIntoWithOrderByAndTypeConversion() throws Exception {
+ String procedure = "CREATE VIRTUAL PROCEDURE\n"; //$NON-NLS-1$
+ procedure += "BEGIN\n"; //$NON-NLS-1$
+ procedure += "CREATE local temporary table temp (x string, y integer, z integer);\n"; //$NON-NLS-1$
+ procedure += "Select pm1.g1.e2, 1 as x, 2 as x into temp from pm1.g1 order by pm1.g1.e2 limit 1;\n"; //$NON-NLS-1$
+ procedure += "Select x from temp;\n"; //$NON-NLS-1$
+ procedure += "END\n"; //$NON-NLS-1$
+
+ helpTestRewriteCommand(procedure, "CREATE VIRTUAL PROCEDURE\nBEGIN\nCREATE LOCAL TEMPORARY TABLE temp (x string, y integer, z integer);\nINSERT INTO temp (temp.x, temp.y, temp.z) SELECT X.e2 AS x, X.x AS y, X.X_0 AS z FROM (SELECT pm1.g1.e2, 1 AS x, 2 AS X_0 FROM pm1.g1 ORDER BY pm1.g1.e2 LIMIT 1) AS X;\nSELECT x FROM temp;\nEND"); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteNot() {
+ helpTestRewriteCriteria("not(not(pm1.g1.e1 = 1 + 1))", "pm1.g1.e1 = '2'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteQueryWithNoFrom() {
+ String sql = "select 1 as a order by a"; //$NON-NLS-1$
+
+ helpTestRewriteCommand(sql, "SELECT 1 AS a"); //$NON-NLS-1$
+ }
+
+ /**
+ * Case 4814
+ */
+ @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", RealMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
+ }
+
+ /**
+ * Case 4814
+ */
+ @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", RealMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteConcat2() {
+ helpTestRewriteCriteria("concat2('a','b') = 'ab'", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteConcat2_1() {
+ helpTestRewriteCriteria("concat2(null, null) is null", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteConcat2_2() throws Exception {
+ helpTestRewriteCriteria("concat2(pm1.g1.e1, null) = 'xyz'", "CASE WHEN pm1.g1.e1 IS NULL THEN null ELSE concat(ifnull(pm1.g1.e1, ''), '') END = 'xyz'", true); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteConcat2_3() throws Exception {
+ helpTestRewriteCriteria("concat2(pm1.g1.e1, convert(pm1.g1.e2, string)) = 'xyz'", "CASE WHEN (pm1.g1.e1 IS NULL) AND (convert(pm1.g1.e2, string) IS NULL) THEN null ELSE concat(ifnull(pm1.g1.e1, ''), ifnull(convert(pm1.g1.e2, string), '')) END = 'xyz'", true); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteConcat2_4() throws Exception {
+ 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 {
+ helpTestRewriteCriteria("from_unixtime(pm1.g1.e2) = '1992-12-01 07:00:00'", "timestampadd(SQL_TSI_SECOND, pm1.g1.e2, {ts'1969-12-31 18:00:00.0'}) = {ts'1992-12-01 07:00:00.0'}"); //$NON-NLS-1$ //$NON-NLS-2$
+ } finally {
+ TimestampWithTimezone.resetCalendar(null);
+ }
+ }
+
+ @Test public void testRewriteNullIf() throws Exception {
+ helpTestRewriteCriteria("nullif(pm1.g1.e2, pm1.g1.e4) = 1", "CASE WHEN pm1.g1.e2 = pm1.g1.e4 THEN convert(null, double) ELSE pm1.g1.e2 END = 1.0", true); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCoalesce() throws Exception {
+ helpTestRewriteCriteria("coalesce(convert(pm1.g1.e2, double), pm1.g1.e4) = 1", "ifnull(convert(pm1.g1.e2, double), pm1.g1.e4) = 1", true); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Test <code>QueryRewriter</code>'s ability to rewrite a query that
+ * contains an aggregate function which uses a <code>CASE</code>
+ * expression which contains <code>BETWEEN</code> criteria as its value.
+ * <p>
+ * An aggregate function list is defined and queries are created that
+ * use each function from the list. The list includes:
+ * <p>
+ * "SUM", "MAX", "MIN", "AVG", "COUNT"
+ * <p>
+ * It is expected that the BETWEEN expression will be rewritten as
+ * <code>CompoundCriteria</code>.
+ * <p>
+ * <table>
+ * <tr><th align="left" colspan=2>For example:
+ * <tr><td width="10*"><td>SELECT SUM(CASE WHEN e2 BETWEEN 3 AND 5
+ * THEN e2 ELSE -1 END) FROM pm1.g1
+ * <tr><th align="left" colspan=2>Is rewritten as:
+ * <tr><td width="10*"><td>SELECT SUM(CASE WHEN (e2 >= 3) AND (e2 <= 5)
+ * THEN e2 ELSE -1 END) FROM pm1.g1
+ * </table>
+ *
+ * @see org.teiid.query.rewriter.QueryRewriter
+ * @see org.teiid.query.sql.lang.BetweenCriteria
+ * @see org.teiid.query.sql.lang.CompoundCriteria
+ * @see org.teiid.query.sql.symbol.AggregateSymbol
+ * @see org.teiid.query.sql.symbol.SearchedCaseExpression
+ */
+ @Test public void testAggregateWithBetweenInCaseInSelect() {
+ // Define a list of aggregates to test against
+ List<String> aggregateCommands = Arrays.asList( new String[] { "SUM", "MAX", "MIN", "AVG", "COUNT" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+
+ // Define a query and the expected rewritten query
+ // ?AGGREGATE? represents the string substitution for an aggregate from aggregateCommands
+ String sqlBefore = "SELECT ?AGGREGATE?(CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
+ String sqlAfter = "SELECT ?AGGREGATE?(CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END) FROM pm1.g1"; //$NON-NLS-1$
+
+ // Iterate through the aggregateCommands
+ for ( String aCmd : aggregateCommands ) {
+ // Replace ?AGGREGATE? with the command from aggregateCommands
+ String sql = sqlBefore.replace("?AGGREGATE?", aCmd); //$NON-NLS-1$
+ String exSql = sqlAfter.replace("?AGGREGATE?", aCmd); //$NON-NLS-1$
+ // Test QueryRewriter
+ Command cmd = helpTestRewriteCommand( sql, exSql );
+ // Check the rewritten command to verify that CompundCriteria replaced BetweenCriteria
+ CompoundCriteria ccrit = (CompoundCriteria) ((SearchedCaseExpression) ((ExpressionSymbol) cmd.getProjectedSymbols().get(0)).getExpression()).getWhen().get(0);
+ assertEquals( "e2 >= 3", ccrit.getCriteria(0).toString() ); //$NON-NLS-1$
+ assertEquals( "e2 <= 5", ccrit.getCriteria(1).toString() ); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Test <code>QueryRewriter</code>'s ability to rewrite a query that
+ * contains a <code>CASE</code> expression which contains
+ * <code>BETWEEN</code> criteria in the queries <code>SELECT</code> clause.
+ * <p>
+ * It is expected that the BETWEEN expression will be rewritten as
+ * <code>CompoundCriteria</code>.
+ * <p>
+ * <table>
+ * <tr><th align="left" colspan=2>For example:
+ * <tr><td width="10*"><td>SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2
+ * ELSE -1 END FROM pm1.g1
+ * <tr><th align="left" colspan=2>Is rewritten as:
+ * <tr><td width="10*"><td>SELECT CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2
+ * ELSE -1 END FROM pm1.g1
+ * </table>
+ *
+ * @see org.teiid.query.rewriter.QueryRewriter
+ * @see org.teiid.query.sql.lang.BetweenCriteria
+ * @see org.teiid.query.sql.lang.CompoundCriteria
+ * @see org.teiid.query.sql.symbol.SearchedCaseExpression
+ */
+ @Test public void testBetweenInCaseInSelect() {
+ String sqlBefore = "SELECT CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
+ String sqlAfter = "SELECT CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END FROM pm1.g1"; //$NON-NLS-1$
+
+ Command cmd = helpTestRewriteCommand( sqlBefore, sqlAfter );
+ CompoundCriteria ccrit = (CompoundCriteria) ((SearchedCaseExpression) ((ExpressionSymbol) cmd.getProjectedSymbols().get(0)).getExpression()).getWhen().get(0);
+ assertEquals( "e2 >= 3", ccrit.getCriteria(0).toString() ); //$NON-NLS-1$
+ assertEquals( "e2 <= 5", ccrit.getCriteria(1).toString() ); //$NON-NLS-1$
+ }
+
+ /**
+ * Test <code>QueryRewriter</code>'s ability to rewrite a query that
+ * contains a <code>CASE</code> expression which contains
+ * <code>BETWEEN</code> criteria in the queries <code>WHERE</code> clause.
+ * <p>
+ * It is expected that the BETWEEN expression will be rewritten as
+ * <code>CompoundCriteria</code>.
+ * <p>
+ * <table>
+ * <tr><th align="left" colspan=2>For example:
+ * <tr><td width="10*"><td>SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2
+ * BETWEEN 3 AND 5 THEN e2 ELSE -1 END
+ * <tr><th align="left" colspan=2>Is rewritten as:
+ * <tr><td width="10*"><td>SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN
+ * (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END
+ * </table>
+ *
+ * @see org.teiid.query.rewriter.QueryRewriter
+ * @see org.teiid.query.sql.lang.BetweenCriteria
+ * @see org.teiid.query.sql.lang.CompoundCriteria
+ * @see org.teiid.query.sql.symbol.SearchedCaseExpression
+ */
+ @Test public void testBetweenInCase() {
+ String sqlBefore = "SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN e2 BETWEEN 3 AND 5 THEN e2 ELSE -1 END"; //$NON-NLS-1$
+ String sqlAfter = "SELECT * FROM pm1.g1 WHERE e3 = CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END"; //$NON-NLS-1$
+
+ Command cmd = helpTestRewriteCommand( sqlBefore, sqlAfter );
+ CompoundCriteria ccrit = (CompoundCriteria) ((SearchedCaseExpression) ((CompareCriteria) ((Query) cmd).getCriteria()).getRightExpression()).getWhen().get(0);
+ assertEquals( "e2 >= 3", ccrit.getCriteria(0).toString() ); //$NON-NLS-1$
+ assertEquals( "e2 <= 5", ccrit.getCriteria(1).toString() ); //$NON-NLS-1$
+ }
+
+ @Test public void testRewriteNullHandling() {
+ String original = "pm1.g1.e1 like '%'"; //$NON-NLS-1$
+ String expected = "pm1.g1.e1 is not null"; //$NON-NLS-1$
+ addTestData();
+
+ helpTestRewriteCriteria(original, expected);
+ }
+
+ private void addTestData() {
+ this.elements = new HashMap<ElementSymbol, Integer>();
+ elements.put(new ElementSymbol("pm1.g1.e1"), 0);
+ elements.put(new ElementSymbol("pm1.g1.e2"), 1);
+ elements.put(new ElementSymbol("pm1.g1.e3"), 2);
+ for (String s : Arrays.asList("a", null, "*")) {
+ for (Integer i : Arrays.asList(1, null, 6)) {
+ for (Boolean b : Arrays.asList(true, false, null)) {
+ tuples.add(Arrays.asList(s, i, b));
+ }
+ }
+ }
+ }
+
+ @Test public void testRewriteNullHandling1() {
+ String original = "not(pm1.g1.e1 like '%' or pm1.g1.e1 = '1')"; //$NON-NLS-1$
+ String expected = "1 = 0"; //$NON-NLS-1$
+ addTestData();
+ helpTestRewriteCriteria(original, expected);
+ }
+
+ @Test public void testRewriteNullHandling2() {
+ String original = "not(pm1.g1.e1 like '%' and pm1.g1.e1 = '1')"; //$NON-NLS-1$
+ String expected = "pm1.g1.e1 <> '1'"; //$NON-NLS-1$
+ addTestData();
+ helpTestRewriteCriteria(original, expected);
+ }
+
+ @Test public void testRewriteNullHandling3() {
+ String original = "pm1.g1.e1 like '%' or pm1.g1.e1 = '1'"; //$NON-NLS-1$
+ String expected = "(pm1.g1.e1 IS NOT NULL) OR (pm1.g1.e1 = '1')"; //$NON-NLS-1$
+ addTestData();
+ helpTestRewriteCriteria(original, expected);
+ }
+
+ @Test public void testRewriteNullHandling4() {
+ String original = "not((pm1.g1.e1 like '%' or pm1.g1.e3 = true) and pm1.g1.e2 < 5)"; //$NON-NLS-1$
+ String expected = "pm1.g1.e2 >= 5"; //$NON-NLS-1$
+ addTestData();
+ helpTestRewriteCriteria(original, expected);
+ }
+
+ @Test public void testRewriteNullHandling4a() {
+ String original = "not(not((pm1.g1.e1 like '%' or pm1.g1.e3 = true) and pm1.g1.e2 < 5))"; //$NON-NLS-1$
+ String expected = "((pm1.g1.e1 IS NOT NULL) OR (pm1.g1.e3 = TRUE)) AND (pm1.g1.e2 < 5)"; //$NON-NLS-1$
+ addTestData();
+ helpTestRewriteCriteria(original, expected);
+ }
+
+ @Test public void testRewriteNullHandling5() {
+ String original = "not((pm1.g1.e1 not like '%' or pm1.g1.e3 = true) and pm1.g1.e2 < 5)"; //$NON-NLS-1$
+ String expected = "((pm1.g1.e1 IS NOT NULL) AND (pm1.g1.e3 <> TRUE)) OR (pm1.g1.e2 >= 5)"; //$NON-NLS-1$
+ addTestData();
+ helpTestRewriteCriteria(original, expected);
+ }
+
+ @Test public void testRewriteNullHandling6() {
+ String original = "not((pm1.g1.e1 not like '%' and pm1.g1.e3 = true) or pm1.g1.e2 < 5)"; //$NON-NLS-1$
+ String expected = "((pm1.g1.e1 IS NOT NULL) OR (pm1.g1.e3 <> TRUE)) AND (pm1.g1.e2 >= 5)"; //$NON-NLS-1$
+ addTestData();
+ helpTestRewriteCriteria(original, expected);
+ }
+
+ @Test public void testRewriteNullHandling7() {
+ String original = "not(not(pm1.g1.e1 not like '%' and pm1.g1.e3 = true) or pm1.g1.e2 < 5)"; //$NON-NLS-1$
+ String expected = "1 = 0"; //$NON-NLS-1$
+ addTestData();
+ helpTestRewriteCriteria(original, expected);
+ }
+
+ @Test public void testRewriteNullHandling7a() {
+ String original = "not(not(pm1.g1.e1 like '*%' and pm1.g1.e3 = true) or pm1.g1.e2 < 5)"; //$NON-NLS-1$
+ String expected = "(pm1.g1.e1 LIKE '*%') AND (pm1.g1.e3 = TRUE) AND (pm1.g1.e2 >= 5)"; //$NON-NLS-1$
+ addTestData();
+ helpTestRewriteCriteria(original, expected);
+ }
+
+ @Test public void testRewriteChar() {
+ String original = "convert(pm1.g1.e1, char) = '100'"; //$NON-NLS-1$
+ String expected = "1 = 0"; //$NON-NLS-1$
+
+ helpTestRewriteCriteria(original, expected);
+ }
+
+ /**
+ * Test ensures that '22.0' is a valid long via bigdecimal
+ */
+ @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, RealMetadataFactory.exampleBQTCached());
+ }
+
+ /**
+ * Test ensures that we will not attempt to invert the widening conversion
+ */
+ @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'})", 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = RealMetadataFactory.exampleBQTCached();
+ helpTestRewriteExpression(original, "'path?%26x=value&y=%20%26%20'", metadata);
+ }
+
+ @Test public void testRewriteExpressionCriteria() throws Exception {
+ helpTestRewriteCriteria("pm1.g1.e3", "pm1.g1.e3 = true");
+ }
+
+ @Test public void testRewritePredicateOptimization() throws Exception {
+ helpTestRewriteCriteria("pm1.g1.e2 in (1, 2, 3) and pm1.g1.e2 in (2, 3, 4)", "pm1.g1.e2 in (2, 3)");
+ }
+
+ @Test public void testRewritePredicateOptimization1() throws Exception {
+ helpTestRewriteCriteria("pm1.g1.e2 < 5 and pm1.g1.e2 = 2", "pm1.g1.e2 = 2");
+ }
+
+ @Test public void testRewritePredicateOptimization2() throws Exception {
+ helpTestRewriteCriteria("pm1.g1.e2 < 5 and pm1.g1.e2 = 6", "1 = 0");
+ }
+
+ @Test public void testRewritePredicateOptimization2a() throws Exception {
+ helpTestRewriteCriteria("pm1.g1.e2 < 5 and pm1.g1.e2 = 2", "pm1.g1.e2 = 2");
+ }
+
+ @Test public void testRewritePredicateOptimization3() throws Exception {
+ helpTestRewriteCriteria("pm1.g1.e2 in (1, 2) and pm1.g1.e2 = 6", "1 = 0");
+ }
+
+ @Test public void testRewritePredicateOptimization4() throws Exception {
+ helpTestRewriteCriteria("pm1.g1.e2 in (1, 2) and pm1.g1.e2 is null", "1 = 0");
+ }
+
+ @Test public void testRewritePredicateOptimization5() throws Exception {
+ helpTestRewriteCriteria("pm1.g1.e2 <> 5 and pm1.g1.e2 in (2, 3, 5)", "pm1.g1.e2 in (2, 3)");
+ }
+
+ @Test public void testRewritePredicateOptimization6() throws Exception {
+ helpTestRewriteCriteria("pm1.g1.e2 = 5 and pm1.g1.e2 in (5, 6)", "pm1.g1.e2 = 5");
+ }
+
+ @Test public void testRewritePredicateOptimization6a() throws Exception {
+ helpTestRewriteCriteria("pm1.g1.e2 in (5, 6) and pm1.g1.e2 = 5", "pm1.g1.e2 = 5");
+ }
+
+ @Ignore("TODO")
+ @Test public void testRewritePredicateOptimization7() throws Exception {
+ helpTestRewriteCriteria("pm1.g1.e2 > 5 and pm1.g1.e2 < 2", "1 = 0");
+ }
+
+ @Test public void testRewritePredicateOptimizationOr() throws Exception {
+ helpTestRewriteCriteria("pm1.g1.e2 in (5, 6) or pm1.g1.e2 = 2", "pm1.g1.e2 IN (2, 5, 6)");
+ }
+
+ @Test public void testRewriteCritSubqueryNegate() {
+ helpTestRewriteCriteria("not(pm1.g1.e1 > SOME (select 'a' from pm1.g2))", "pm1.g1.e1 <= ALL (SELECT 'a' FROM pm1.g2)"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritSubqueryFalse() {
+ helpTestRewriteCriteria("exists(select 1 from pm1.g1 where 1=0)", "1 = 0"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritSubqueryFalse1() {
+ helpTestRewriteCriteria("not(pm1.g1.e1 > SOME (select 'a' from pm1.g1 where 1=0))", "pm1.g1.e1 IS NOT NULL"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testRewriteCritSubqueryFalse2() {
+ helpTestRewriteCriteria("pm1.g1.e1 < ALL (select 'a' from pm1.g1 where 1=0)", "pm1.g1.e1 IS NOT NULL"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testUDFParse() throws Exception {
+ 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);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/util/TestElementSymbolOptimizer.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/sql/util/TestElementSymbolOptimizer.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/util/TestElementSymbolOptimizer.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,176 +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.util;
-
-
-import static org.junit.Assert.*;
-
-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.core.TeiidComponentException;
-import org.teiid.query.metadata.QueryMetadataInterface;
-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.unittest.FakeMetadataFactory;
-
-/**
- */
-public class TestElementSymbolOptimizer {
-
- public Command helpResolve(String sql, QueryMetadataInterface metadata) throws QueryParserException, QueryResolverException, TeiidComponentException {
- Command command = QueryParser.getQueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(command, metadata);
-
- return command;
- }
-
- public void helpTestOptimize(String sql, QueryMetadataInterface metadata, String expected) throws QueryMetadataException, TeiidComponentException, QueryParserException, QueryResolverException {
- try {
- ResolverVisitor.setFindShortName(true);
- Command command = helpResolve(sql, metadata);
- String actual = command.toString();
-
- assertEquals("Expected different optimized string", expected, actual); //$NON-NLS-1$
- }
- finally {
- ResolverVisitor.setFindShortName(false);
- }
- }
-
- /** 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(),
- "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(),
- "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(),
- "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(),
- "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(),
- "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(),
- "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(),
- "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(),
- "SELECT 1, 'xyz'"); //$NON-NLS-1$
- }
-
- public void helpTestFullyQualify(String sql, QueryMetadataInterface metadata, String expected) throws QueryParserException, QueryResolverException, TeiidComponentException {
- Command command = helpResolve(sql, metadata);
- ResolverUtil.fullyQualifyElements(command);
- String actual = command.toString();
-
- assertEquals("Expected different fully qualified string", expected, actual); //$NON-NLS-1$
- }
-
- @Test public void testFullyQualify1() throws Exception {
- helpTestFullyQualify("SELECT e1, e2 FROM pm1.g1", //$NON-NLS-1$
- FakeMetadataFactory.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(),
- "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(),
- "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(),
- "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(),
- "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(),
- "SELECT e1 FROM pm1.g1 ORDER BY e1"); //$NON-NLS-1$
- }
-
- /**
- * It is by design that order by optimization only works in one direction. It is not desirable to
- * fully qualify order by elements
- */
- @Test public void testOptimizeOrderBy1() throws Exception {
- helpTestFullyQualify("SELECT e1 FROM pm1.g1 order by e1", //$NON-NLS-1$
- FakeMetadataFactory.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(),
- "SELECT e1, COUNT(*) AS x FROM pm1.g1 ORDER BY x"); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/util/TestElementSymbolOptimizer.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/sql/util/TestElementSymbolOptimizer.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/util/TestElementSymbolOptimizer.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/util/TestElementSymbolOptimizer.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.query.sql.util;
+
+
+import static org.junit.Assert.*;
+
+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.core.TeiidComponentException;
+import org.teiid.query.metadata.QueryMetadataInterface;
+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.unittest.RealMetadataFactory;
+
+/**
+ */
+public class TestElementSymbolOptimizer {
+
+ public Command helpResolve(String sql, QueryMetadataInterface metadata) throws QueryParserException, QueryResolverException, TeiidComponentException {
+ Command command = QueryParser.getQueryParser().parseCommand(sql);
+ QueryResolver.resolveCommand(command, metadata);
+
+ return command;
+ }
+
+ public void helpTestOptimize(String sql, QueryMetadataInterface metadata, String expected) throws QueryMetadataException, TeiidComponentException, QueryParserException, QueryResolverException {
+ try {
+ ResolverVisitor.setFindShortName(true);
+ Command command = helpResolve(sql, metadata);
+ String actual = command.toString();
+
+ assertEquals("Expected different optimized string", expected, actual); //$NON-NLS-1$
+ }
+ finally {
+ ResolverVisitor.setFindShortName(false);
+ }
+ }
+
+ /** Can be optimized */
+ @Test public void testOptimize1() throws Exception {
+ helpTestOptimize("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1", //$NON-NLS-1$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ RealMetadataFactory.example1Cached(),
+ "SELECT 1, 'xyz'"); //$NON-NLS-1$
+ }
+
+ public void helpTestFullyQualify(String sql, QueryMetadataInterface metadata, String expected) throws QueryParserException, QueryResolverException, TeiidComponentException {
+ Command command = helpResolve(sql, metadata);
+ ResolverUtil.fullyQualifyElements(command);
+ String actual = command.toString();
+
+ assertEquals("Expected different fully qualified string", expected, actual); //$NON-NLS-1$
+ }
+
+ @Test public void testFullyQualify1() throws Exception {
+ helpTestFullyQualify("SELECT e1, e2 FROM pm1.g1", //$NON-NLS-1$
+ 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$
+ 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$
+ 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$
+ 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$
+ 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$
+ RealMetadataFactory.example1Cached(),
+ "SELECT e1 FROM pm1.g1 ORDER BY e1"); //$NON-NLS-1$
+ }
+
+ /**
+ * It is by design that order by optimization only works in one direction. It is not desirable to
+ * fully qualify order by elements
+ */
+ @Test public void testOptimizeOrderBy1() throws Exception {
+ helpTestFullyQualify("SELECT e1 FROM pm1.g1 order by e1", //$NON-NLS-1$
+ 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$
+ RealMetadataFactory.example1Cached(),
+ "SELECT e1, COUNT(*) AS x FROM pm1.g1 ORDER BY x"); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestEvaluatableVisitor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/sql/visitor/TestEvaluatableVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestEvaluatableVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,40 +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.visitor;
-
-import org.junit.Test;
-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 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$
- assertTrue(EvaluatableVisitor.needsProcessingEvaluation(command));
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestEvaluatableVisitor.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/sql/visitor/TestEvaluatableVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestEvaluatableVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestEvaluatableVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.query.sql.visitor;
+
+import org.junit.Test;
+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.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 = ?)", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ assertTrue(EvaluatableVisitor.needsProcessingEvaluation(command));
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestSQLStringVisitor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/sql/visitor/TestSQLStringVisitor.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestSQLStringVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1896 +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.visitor;
-
-import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.language.SQLConstants.NonReserved;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.lang.BetweenCriteria;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.DynamicCommand;
-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.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.Option;
-import org.teiid.query.sql.lang.OrderBy;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.SubqueryCompareCriteria;
-import org.teiid.query.sql.lang.SubqueryFromClause;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.lang.UnaryFromClause;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.lang.SetQuery.Operation;
-import org.teiid.query.sql.proc.AssignmentStatement;
-import org.teiid.query.sql.proc.Block;
-import org.teiid.query.sql.proc.CommandStatement;
-import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
-import org.teiid.query.sql.proc.CriteriaSelector;
-import org.teiid.query.sql.proc.DeclareStatement;
-import org.teiid.query.sql.proc.HasCriteria;
-import org.teiid.query.sql.proc.IfStatement;
-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;
-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.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;
-
-
-public class TestSQLStringVisitor extends TestCase {
-
- // ################################## FRAMEWORK ################################
-
- public TestSQLStringVisitor(String name) {
- super(name);
- }
-
- // ################################## TEST HELPERS ################################
-
- private void helpTest(LanguageObject obj, String expectedStr) {
- String actualStr = SQLStringVisitor.getSQLString(obj);
- assertEquals("Expected and actual strings don't match: ", expectedStr, actualStr); //$NON-NLS-1$
- }
-
- // ################################## ACTUAL TESTS ################################
-
- public void testNull() {
- String sql = SQLStringVisitor.getSQLString(null);
-
- assertEquals("Incorrect string for null object", SQLStringVisitor.UNDEFINED, sql); //$NON-NLS-1$
- }
-
- public void testBetweenCriteria1() {
- BetweenCriteria bc = new BetweenCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- new Constant(new Integer(1000)),
- new Constant(new Integer(2000)) );
- helpTest(bc, "m.g.c1 BETWEEN 1000 AND 2000"); //$NON-NLS-1$
- }
-
- public void testBetweenCriteria2() {
- BetweenCriteria bc = new BetweenCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- new Constant(new Integer(1000)),
- new Constant(new Integer(2000)) );
- bc.setNegated(true);
- helpTest(bc, "m.g.c1 NOT BETWEEN 1000 AND 2000"); //$NON-NLS-1$
- }
-
- public void testCompareCriteria1() {
- CompareCriteria cc = new CompareCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new Constant("abc") ); //$NON-NLS-1$
-
- helpTest(cc, "m.g.c1 = 'abc'"); //$NON-NLS-1$
- }
-
- public void testCompareCriteria2() {
- CompareCriteria cc = new CompareCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- CompareCriteria.NE,
- new Constant("abc") ); //$NON-NLS-1$
-
- helpTest(cc, "m.g.c1 <> 'abc'"); //$NON-NLS-1$
- }
-
- public void testCompareCriteria3() {
- CompareCriteria cc = new CompareCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- CompareCriteria.GT,
- new Constant("abc") ); //$NON-NLS-1$
-
- helpTest(cc, "m.g.c1 > 'abc'"); //$NON-NLS-1$
- }
-
- public void testCompareCriteria4() {
- CompareCriteria cc = new CompareCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- CompareCriteria.GE,
- new Constant("abc") ); //$NON-NLS-1$
-
- helpTest(cc, "m.g.c1 >= 'abc'"); //$NON-NLS-1$
- }
-
- public void testCompareCriteria5() {
- CompareCriteria cc = new CompareCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- CompareCriteria.LT,
- new Constant("abc") ); //$NON-NLS-1$
-
- helpTest(cc, "m.g.c1 < 'abc'"); //$NON-NLS-1$
- }
-
- public void testCompareCriteria6() {
- CompareCriteria cc = new CompareCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- CompareCriteria.LE,
- new Constant("abc") ); //$NON-NLS-1$
-
- helpTest(cc, "m.g.c1 <= 'abc'"); //$NON-NLS-1$
- }
-
- public void testCompareCriteria7() {
- CompareCriteria cc = new CompareCriteria(
- null,
- CompareCriteria.EQ,
- null );
-
- helpTest(cc, "<undefined> = <undefined>"); //$NON-NLS-1$
- }
-
- public void testCompoundCriteria1() {
- CompareCriteria cc = new CompareCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new Constant("abc") ); //$NON-NLS-1$
- List<Criteria> crits = new ArrayList<Criteria>();
- crits.add(cc);
- CompoundCriteria comp = new CompoundCriteria(CompoundCriteria.AND, crits);
-
- helpTest(comp, "m.g.c1 = 'abc'"); //$NON-NLS-1$
- }
-
- public void testCompoundCriteria2() {
- CompareCriteria cc1 = new CompareCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new Constant("abc") ); //$NON-NLS-1$
- CompareCriteria cc2 = new CompareCriteria(
- new ElementSymbol("m.g.c2"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new Constant("abc") ); //$NON-NLS-1$
- List<Criteria> crits = new ArrayList<Criteria>();
- crits.add(cc1);
- crits.add(cc2);
- CompoundCriteria comp = new CompoundCriteria(CompoundCriteria.AND, crits);
-
- helpTest(comp, "(m.g.c1 = 'abc') AND (m.g.c2 = 'abc')"); //$NON-NLS-1$
- }
-
- public void testCompoundCriteria3() {
- CompareCriteria cc1 = new CompareCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new Constant("abc") ); //$NON-NLS-1$
- CompareCriteria cc2 = new CompareCriteria(
- new ElementSymbol("m.g.c2"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new Constant("abc") ); //$NON-NLS-1$
- CompareCriteria cc3 = new CompareCriteria(
- new ElementSymbol("m.g.c3"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new Constant("abc") ); //$NON-NLS-1$
- List<Criteria> crits = new ArrayList<Criteria>();
- crits.add(cc1);
- crits.add(cc2);
- crits.add(cc3);
- CompoundCriteria comp = new CompoundCriteria(CompoundCriteria.OR, crits);
-
- helpTest(comp, "(m.g.c1 = 'abc') OR (m.g.c2 = 'abc') OR (m.g.c3 = 'abc')"); //$NON-NLS-1$
- }
-
- public void testCompoundCriteria4() {
- CompareCriteria cc1 = new CompareCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new Constant("abc") ); //$NON-NLS-1$
- List<Criteria> crits = new ArrayList<Criteria>();
- crits.add(cc1);
- crits.add(null);
- CompoundCriteria comp = new CompoundCriteria(CompoundCriteria.OR, crits);
-
- helpTest(comp, "(m.g.c1 = 'abc') OR (<undefined>)"); //$NON-NLS-1$
- }
-
- public void testCompoundCriteria5() {
- CompareCriteria cc1 = new CompareCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new Constant("abc") ); //$NON-NLS-1$
- List<Criteria> crits = new ArrayList<Criteria>();
- crits.add(null);
- crits.add(cc1);
- CompoundCriteria comp = new CompoundCriteria(CompoundCriteria.OR, crits);
-
- helpTest(comp, "(<undefined>) OR (m.g.c1 = 'abc')"); //$NON-NLS-1$
- }
-
- public void testCompoundCriteria6() {
- CompareCriteria cc1 = new CompareCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new Constant("abc") ); //$NON-NLS-1$
- List<Criteria> crits = new ArrayList<Criteria>();
- crits.add(cc1);
- crits.add(null);
- CompoundCriteria comp = new CompoundCriteria(CompoundCriteria.OR, crits);
-
- helpTest(comp, "(m.g.c1 = 'abc') OR (<undefined>)"); //$NON-NLS-1$
- }
-
- 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() {
- Delete delete = new Delete();
- delete.setGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- delete.setCriteria(new CompareCriteria(
- new ElementSymbol("m.g.c1"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new Constant("abc")) ); //$NON-NLS-1$
-
-
- helpTest(delete, "DELETE FROM m.g WHERE m.g.c1 = 'abc'"); //$NON-NLS-1$
- }
-
- 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$
-
- helpTest(from, "FROM m.g1, m.g2"); //$NON-NLS-1$
- }
-
- public void testFrom2() {
- From from = new From();
- from.addClause(new UnaryFromClause(new GroupSymbol("m.g1"))); //$NON-NLS-1$
- from.addClause(new JoinPredicate(
- new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
- new UnaryFromClause(new GroupSymbol("m.g3")), //$NON-NLS-1$
- JoinType.JOIN_CROSS) );
-
- helpTest(from, "FROM m.g1, m.g2 CROSS JOIN m.g3"); //$NON-NLS-1$
- }
-
- 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() {
- GroupBy gb = new GroupBy();
- gb.addSymbol(new ElementSymbol("m.g.e1")); //$NON-NLS-1$
- gb.addSymbol(new ElementSymbol("m.g.e2")); //$NON-NLS-1$
- gb.addSymbol(new ElementSymbol("m.g.e3")); //$NON-NLS-1$
-
- helpTest(gb, "GROUP BY m.g.e1, m.g.e2, m.g.e3"); //$NON-NLS-1$
- }
-
- public void testInsert1() {
- Insert insert = new Insert();
- insert.setGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
-
- List vars = new ArrayList();
- vars.add(new ElementSymbol("e1")); //$NON-NLS-1$
- vars.add(new ElementSymbol("e2")); //$NON-NLS-1$
- insert.setVariables(vars);
- List values = new ArrayList();
- values.add(new Constant(new Integer(5)));
- values.add(new Constant("abc")); //$NON-NLS-1$
- insert.setValues(values);
-
- helpTest(insert, "INSERT INTO m.g1 (e1, e2) VALUES (5, 'abc')"); //$NON-NLS-1$
- }
-
- 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() {
- 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() {
- IsNullCriteria inc = new IsNullCriteria();
- helpTest(inc, "<undefined> IS NULL"); //$NON-NLS-1$
- }
-
- 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() {
- JoinPredicate jp = new JoinPredicate(
- new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
- new UnaryFromClause(new GroupSymbol("m.g3")), //$NON-NLS-1$
- JoinType.JOIN_CROSS);
-
- helpTest(jp, "m.g2 CROSS JOIN m.g3"); //$NON-NLS-1$
- }
-
- 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$
- JoinType.JOIN_CROSS);
- jp.setOptional(true);
- helpTest(jp, "/*+ optional */ (m.g2 CROSS JOIN m.g3)"); //$NON-NLS-1$
- }
-
- 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(
- new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
- new UnaryFromClause(new GroupSymbol("m.g3")), //$NON-NLS-1$
- JoinType.JOIN_INNER,
- crits );
-
- helpTest(jp, "m.g2 INNER JOIN m.g3 ON m.g2.e1 = m.g3.e1"); //$NON-NLS-1$
- }
-
- 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$
- JoinPredicate jp = new JoinPredicate(
- new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
- new UnaryFromClause(new GroupSymbol("m.g3")), //$NON-NLS-1$
- JoinType.JOIN_INNER,
- crits );
-
- 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() {
- 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(
- new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
- new UnaryFromClause(new GroupSymbol("m.g3")), //$NON-NLS-1$
- JoinType.JOIN_INNER,
- crits );
-
- JoinPredicate jp2 = new JoinPredicate(
- jp,
- new UnaryFromClause(new GroupSymbol("m.g1")), //$NON-NLS-1$
- JoinType.JOIN_CROSS);
-
- 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() {
- 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(
- new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
- new UnaryFromClause(new GroupSymbol("m.g3")), //$NON-NLS-1$
- JoinType.JOIN_INNER,
- crits );
-
- helpTest(jp, "m.g2 INNER JOIN m.g3 ON NOT (m.g2.e1 = m.g3.e1)"); //$NON-NLS-1$
- }
-
- public void testJoinType1() {
- helpTest(JoinType.JOIN_CROSS, "CROSS JOIN"); //$NON-NLS-1$
- }
-
- public void testJoinType2() {
- helpTest(JoinType.JOIN_INNER, "INNER JOIN"); //$NON-NLS-1$
- }
-
- public void testJoinType3() {
- helpTest(JoinType.JOIN_RIGHT_OUTER, "RIGHT OUTER JOIN"); //$NON-NLS-1$
- }
-
- public void testJoinType4() {
- helpTest(JoinType.JOIN_LEFT_OUTER, "LEFT OUTER JOIN"); //$NON-NLS-1$
- }
-
- public void testJoinType5() {
- helpTest(JoinType.JOIN_FULL_OUTER, "FULL OUTER JOIN"); //$NON-NLS-1$
- }
-
- 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$
-
- helpTest(mc, "m.g.e1 LIKE 'abc'"); //$NON-NLS-1$
- }
-
- public void testMatchCriteria2() {
- MatchCriteria mc = new MatchCriteria();
- mc.setLeftExpression(new ElementSymbol("m.g.e1")); //$NON-NLS-1$
- mc.setRightExpression(new Constant("%")); //$NON-NLS-1$
- mc.setEscapeChar('#');
-
- helpTest(mc, "m.g.e1 LIKE '%' ESCAPE '#'"); //$NON-NLS-1$
- }
-
- 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$
- mc.setNegated(true);
- helpTest(mc, "m.g.e1 NOT LIKE 'abc'"); //$NON-NLS-1$
- }
-
- 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() {
- NotCriteria not = new NotCriteria();
- helpTest(not, "NOT (<undefined>)"); //$NON-NLS-1$
- }
-
- public void testOption1() {
- Option option = new Option();
- helpTest(option, "OPTION"); //$NON-NLS-1$
- }
-
- public void testOption5() {
- Option option = new Option();
- option.addDependentGroup("abc"); //$NON-NLS-1$
- option.addDependentGroup("def"); //$NON-NLS-1$
- option.addDependentGroup("xyz"); //$NON-NLS-1$
- helpTest(option, "OPTION MAKEDEP abc, def, xyz"); //$NON-NLS-1$
- }
-
- public void testOption6() {
- Option option = new Option();
- option.addDependentGroup("abc"); //$NON-NLS-1$
- option.addDependentGroup("def"); //$NON-NLS-1$
- option.addDependentGroup("xyz"); //$NON-NLS-1$
- helpTest(option, "OPTION MAKEDEP abc, def, xyz"); //$NON-NLS-1$
- }
-
- public void testOption8() {
- Option option = new Option();
- option.addNoCacheGroup("abc"); //$NON-NLS-1$
- option.addNoCacheGroup("def"); //$NON-NLS-1$
- option.addNoCacheGroup("xyz"); //$NON-NLS-1$
- helpTest(option, "OPTION NOCACHE abc, def, xyz"); //$NON-NLS-1$
- }
-
-// related to defect 14423
- public void testOption9() {
- Option option = new Option();
- option.setNoCache(true);
- helpTest(option, "OPTION NOCACHE"); //$NON-NLS-1$
- }
-
- 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() {
- 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$
-
- helpTest(ob, "ORDER BY e1, x"); //$NON-NLS-1$
- }
-
- 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$
-
- helpTest(ob, "ORDER BY e1 DESC, x DESC"); //$NON-NLS-1$
- }
-
- public void testQuery1() {
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- From from = new From();
- from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
-
- helpTest(query, "SELECT * FROM m.g"); //$NON-NLS-1$
- }
-
- public void testQuery2() {
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- 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$
- GroupBy groupBy = new GroupBy();
- groupBy.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- CompareCriteria having = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.GT, new Constant(new Integer(0))); //$NON-NLS-1$
- OrderBy orderBy = new OrderBy();
- orderBy.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(cc);
- query.setGroupBy(groupBy);
- query.setHaving(having);
- query.setOrderBy(orderBy);
-
- helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 GROUP BY e1 HAVING e1 > 0 ORDER BY e1"); //$NON-NLS-1$
- }
-
- public void testQuery3() {
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- From from = new From();
- from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
- GroupBy groupBy = new GroupBy();
- groupBy.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- CompareCriteria having = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.GT, new Constant(new Integer(0))); //$NON-NLS-1$
- OrderBy orderBy = new OrderBy();
- orderBy.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setGroupBy(groupBy);
- query.setHaving(having);
- query.setOrderBy(orderBy);
-
- helpTest(query, "SELECT * FROM m.g GROUP BY e1 HAVING e1 > 0 ORDER BY e1"); //$NON-NLS-1$
- }
-
- public void testQuery4() {
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- 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$
- CompareCriteria having = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.GT, new Constant(new Integer(0))); //$NON-NLS-1$
- OrderBy orderBy = new OrderBy();
- orderBy.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(cc);
- query.setHaving(having);
- query.setOrderBy(orderBy);
-
- helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 HAVING e1 > 0 ORDER BY e1"); //$NON-NLS-1$
- }
-
- public void testQuery5() {
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- 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$
- GroupBy groupBy = new GroupBy();
- groupBy.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- OrderBy orderBy = new OrderBy();
- orderBy.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(cc);
- query.setGroupBy(groupBy);
- query.setOrderBy(orderBy);
-
- helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 GROUP BY e1 ORDER BY e1"); //$NON-NLS-1$
- }
-
- public void testQuery6() {
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- 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$
- GroupBy groupBy = new GroupBy();
- groupBy.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- CompareCriteria having = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.GT, new Constant(new Integer(0))); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(cc);
- query.setGroupBy(groupBy);
- query.setHaving(having);
-
- helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 GROUP BY e1 HAVING e1 > 0"); //$NON-NLS-1$
- }
-
- public void testQuery7() {
- Select select = new Select();
- select.addSymbol(new AllSymbol());
- 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$
- GroupBy groupBy = new GroupBy();
- groupBy.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- CompareCriteria having = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.GT, new Constant(new Integer(0))); //$NON-NLS-1$
- OrderBy orderBy = new OrderBy();
- orderBy.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
-
- Query query = new Query();
- query.setSelect(select);
- query.setFrom(from);
- query.setCriteria(cc);
- query.setGroupBy(groupBy);
- query.setHaving(having);
- query.setOrderBy(orderBy);
-
- helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 GROUP BY e1 HAVING e1 > 0 ORDER BY e1"); //$NON-NLS-1$
- }
-
- 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() {
- Select select = new Select();
- select.setDistinct(true);
- select.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
-
- helpTest(select, "SELECT DISTINCT e1"); //$NON-NLS-1$
- }
-
- public void testSelect3() {
- Select select = new Select();
- select.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- select.addSymbol(new ElementSymbol("e2")); //$NON-NLS-1$
-
- helpTest(select, "SELECT e1, e2"); //$NON-NLS-1$
- }
-
- public void testSetCriteria1() {
- SetCriteria sc = new SetCriteria();
- sc.setExpression(new ElementSymbol("e1")); //$NON-NLS-1$
- sc.setValues(new ArrayList());
-
- helpTest(sc, "e1 IN ()"); //$NON-NLS-1$
- }
-
- public void testSetCriteria2() {
- SetCriteria sc = new SetCriteria();
- sc.setExpression(new ElementSymbol("e1")); //$NON-NLS-1$
- ArrayList values = new ArrayList();
- values.add(new ElementSymbol("e2")); //$NON-NLS-1$
- values.add(new Constant("abc")); //$NON-NLS-1$
- sc.setValues(values);
-
- helpTest(sc, "e1 IN (e2, 'abc')"); //$NON-NLS-1$
- }
-
- public void testSetCriteria3() {
- SetCriteria sc = new SetCriteria();
- sc.setExpression(new ElementSymbol("e1")); //$NON-NLS-1$
- ArrayList values = new ArrayList();
- values.add(null);
- values.add(new Constant("b")); //$NON-NLS-1$
- sc.setValues(values);
-
- helpTest(sc, "e1 IN (<undefined>, 'b')"); //$NON-NLS-1$
- }
-
- public void testSetCriteria4() {
- SetCriteria sc = new SetCriteria();
- sc.setExpression(new ElementSymbol("e1")); //$NON-NLS-1$
- ArrayList values = new ArrayList();
- values.add(new ElementSymbol("e2")); //$NON-NLS-1$
- values.add(new Constant("abc")); //$NON-NLS-1$
- sc.setValues(values);
- sc.setNegated(true);
- helpTest(sc, "e1 NOT IN (e2, 'abc')"); //$NON-NLS-1$
- }
-
- public void testSetQuery1() {
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
-
- SetQuery sq = new SetQuery(Operation.UNION, false, q1, q2);
-
- helpTest(sq, "SELECT e1 FROM m.g1 UNION SELECT e1 FROM m.g2"); //$NON-NLS-1$
- }
-
- public void testSetQuery2() {
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
-
- SetQuery sq = new SetQuery(Operation.UNION, true, q1, q2);
-
- helpTest(sq, "SELECT e1 FROM m.g1 UNION ALL SELECT e1 FROM m.g2"); //$NON-NLS-1$
- }
-
- public void testSetQuery3() {
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
-
- OrderBy orderBy = new OrderBy();
- orderBy.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
-
- SetQuery sq = new SetQuery(Operation.UNION, false, q1, q2);
- sq.setOrderBy(orderBy);
-
- helpTest(sq, "SELECT e1 FROM m.g1 UNION SELECT e1 FROM m.g2 ORDER BY e1"); //$NON-NLS-1$
- }
-
- public void testSetQuery4() {
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
-
- SetQuery sq = new SetQuery(Operation.UNION, false, q1, q2);
-
- helpTest(sq, "SELECT e1 FROM m.g1 UNION SELECT e1 FROM m.g2"); //$NON-NLS-1$
- }
-
- public void testSetQuery5() {
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
-
- Select s3 = new Select();
- s3.addSymbol(new ElementSymbol("e3")); //$NON-NLS-1$
- From f3 = new From();
- f3.addGroup(new GroupSymbol("m.g3")); //$NON-NLS-1$
- Query q3 = new Query();
- q3.setSelect(s3);
- q3.setFrom(f3);
-
- SetQuery sq = new SetQuery(Operation.UNION, false, q1, q2);
-
- SetQuery sq2 = new SetQuery(Operation.UNION, true, q3, sq);
-
- 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() {
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- SubqueryFromClause sfc = new SubqueryFromClause("temp", q1); //$NON-NLS-1$
- helpTest(sfc, "(SELECT e1 FROM m.g1) AS temp"); //$NON-NLS-1$
- }
-
- public void testOptionalSubqueryFromClause1() {
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- SubqueryFromClause sfc = new SubqueryFromClause("temp", q1); //$NON-NLS-1$
- sfc.setOptional(true);
- helpTest(sfc, "/*+ optional */ (SELECT e1 FROM m.g1) AS temp"); //$NON-NLS-1$
- }
-
- public void testSubquerySetCriteria1() {
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- ElementSymbol expr = new ElementSymbol("e2"); //$NON-NLS-1$
-
- SubquerySetCriteria ssc = new SubquerySetCriteria(expr, q1);
- helpTest(ssc, "e2 IN (SELECT e1 FROM m.g1)"); //$NON-NLS-1$
- }
-
- public void testSubquerySetCriteria2() {
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- ElementSymbol expr = new ElementSymbol("e2"); //$NON-NLS-1$
-
- SubquerySetCriteria ssc = new SubquerySetCriteria(expr, q1);
- ssc.setNegated(true);
- helpTest(ssc, "e2 NOT IN (SELECT e1 FROM m.g1)"); //$NON-NLS-1$
- }
-
- public void testUnaryFromClause() {
- helpTest(new UnaryFromClause(new GroupSymbol("m.g1")), "m.g1"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- 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() {
- 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$
-
- helpTest(update, "UPDATE m.g1 SET e1 = 'abc'"); //$NON-NLS-1$
- }
-
- 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$
- update.addChange(new ElementSymbol("e2"), new Constant("xyz")); //$NON-NLS-1$ //$NON-NLS-2$
-
- helpTest(update, "UPDATE m.g1 SET e1 = 'abc', e2 = 'xyz'"); //$NON-NLS-1$
- }
-
- 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$
- update.setCriteria(new CompareCriteria(
- new ElementSymbol("e2"), //$NON-NLS-1$
- CompareCriteria.EQ,
- new Constant("abc")) ); //$NON-NLS-1$
-
-
- helpTest(update, "UPDATE m.g1 SET e1 = 'abc' WHERE e2 = 'abc'"); //$NON-NLS-1$
- }
-
- 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() {
- 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() {
- AggregateSymbol agg = new AggregateSymbol("abc", NonReserved.COUNT, false, null); //$NON-NLS-1$
- helpTest(agg, "COUNT(*)"); //$NON-NLS-1$
- }
-
- 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() {
- 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() {
- 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() {
- 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() {
- 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() {
- 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$
- }
-
- public void testAllInGroupSymbol() {
- helpTest(new AllInGroupSymbol("m.g.*"), "m.g.*"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testConstantNull() {
- helpTest(new Constant(null), "null"); //$NON-NLS-1$
- }
-
- public void testConstantString() {
- helpTest(new Constant("abc"), "'abc'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testConstantInteger() {
- helpTest(new Constant(new Integer(5)), "5"); //$NON-NLS-1$
- }
-
- public void testConstantBigDecimal() {
- helpTest(new Constant(new BigDecimal("5.4")), "5.4"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testConstantStringWithTick() {
- helpTest(new Constant("O'Leary"), "'O''Leary'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testConstantStringWithTicks() {
- helpTest(new Constant("'abc'"), "'''abc'''"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testConstantStringWithMoreTicks() {
- helpTest(new Constant("a'b'c"), "'a''b''c'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testConstantStringWithDoubleTick() {
- helpTest(new Constant("group=\"x\""), "'group=\"x\"'"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public void testConstantBooleanTrue() {
- helpTest(new Constant(Boolean.TRUE), "TRUE"); //$NON-NLS-1$
- }
-
- public void testConstantBooleanFalse() {
- helpTest(new Constant(Boolean.FALSE), "FALSE"); //$NON-NLS-1$
- }
-
- 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() {
- helpTest(new Constant(java.sql.Time.valueOf("5:00:00")), "{t'05:00:00'}"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- 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() {
- ElementSymbol es = new ElementSymbol("elem"); //$NON-NLS-1$
- helpTest(es, "elem"); //$NON-NLS-1$
- }
-
- 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() {
- 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() {
- ElementSymbol es = new ElementSymbol("vdb.m.g.elem", true); //$NON-NLS-1$
- helpTest(es, "vdb.m.g.elem"); //$NON-NLS-1$
- }
-
- 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() {
- ExpressionSymbol expr = new ExpressionSymbol("abc", new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
- helpTest(expr, "'abc'"); //$NON-NLS-1$
- }
-
- 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() {
- Function func = new Function("now", new Expression[] {}); //$NON-NLS-1$
- helpTest(func, "now()"); //$NON-NLS-1$
- }
-
- 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() {
- Function func1 = new Function("power", new Expression[] { //$NON-NLS-1$
- new Constant(new Integer(5)),
- new Constant(new Integer(3)) });
- Function func2 = new Function("power", new Expression[] { //$NON-NLS-1$
- func1,
- new Constant(new Integer(3)) });
- Function func3 = new Function("+", new Expression[] { //$NON-NLS-1$
- new Constant(new Integer(1000)),
- func2 });
- helpTest(func3, "(1000 + power(power(5, 3), 3))"); //$NON-NLS-1$
- }
-
- public void testFunction5() {
- Function func1 = new Function("concat", new Expression[] { //$NON-NLS-1$
- new ElementSymbol("elem2"), //$NON-NLS-1$
- null });
- Function func2 = new Function("concat", new Expression[] { //$NON-NLS-1$
- new ElementSymbol("elem1"), //$NON-NLS-1$
- func1 });
- helpTest(func2, "concat(elem1, concat(elem2, <undefined>))"); //$NON-NLS-1$
- }
-
- 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$
- });
- helpTest(func, "convert('5', integer)"); //$NON-NLS-1$
- }
-
- public void testConvertFunction2() {
- Function func = new Function("convert", new Expression[] { //$NON-NLS-1$
- null,
- new Constant("integer") //$NON-NLS-1$
- });
- helpTest(func, "convert(<undefined>, integer)"); //$NON-NLS-1$
- }
-
- public void testConvertFunction3() {
- Function func = new Function("convert", new Expression[] { //$NON-NLS-1$
- new Constant(null),
- new Constant("integer") //$NON-NLS-1$
- });
- helpTest(func, "convert(null, integer)"); //$NON-NLS-1$
- }
-
- public void testConvertFunction4() {
- Function func = new Function("convert", new Expression[] { //$NON-NLS-1$
- new Constant("abc"), //$NON-NLS-1$
- null
- });
- helpTest(func, "convert('abc', <undefined>)"); //$NON-NLS-1$
- }
-
- public void testConvertFunction5() {
- Function func = new Function("convert", null); //$NON-NLS-1$
- helpTest(func, "convert()"); //$NON-NLS-1$
- }
-
- public void testConvertFunction6() {
- Function func = new Function("convert", new Expression[0]); //$NON-NLS-1$
- helpTest(func, "convert()"); //$NON-NLS-1$
- }
-
- 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() {
- Function func = new Function("cast", new Expression[] { //$NON-NLS-1$
- new Constant("5"), //$NON-NLS-1$
- new Constant("integer") //$NON-NLS-1$
- });
- helpTest(func, "cast('5' AS integer)"); //$NON-NLS-1$
- }
-
- public void testCastFunction2() {
- Function func = new Function("cast", new Expression[] { //$NON-NLS-1$
- null,
- new Constant("integer") //$NON-NLS-1$
- });
- helpTest(func, "cast(<undefined> AS integer)"); //$NON-NLS-1$
- }
-
- public void testCastFunction3() {
- Function func = new Function("cast", new Expression[] { //$NON-NLS-1$
- new Constant(null),
- new Constant("integer") //$NON-NLS-1$
- });
- helpTest(func, "cast(null AS integer)"); //$NON-NLS-1$
- }
-
- public void testCastFunction4() {
- Function func = new Function("cast", new Expression[] { //$NON-NLS-1$
- new Constant("abc"), //$NON-NLS-1$
- null
- });
- helpTest(func, "cast('abc' AS <undefined>)"); //$NON-NLS-1$
- }
-
- 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() {
- GroupSymbol gs = new GroupSymbol("g"); //$NON-NLS-1$
- helpTest(gs, "g"); //$NON-NLS-1$
- }
-
- 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() {
- GroupSymbol gs = new GroupSymbol("vdb.g"); //$NON-NLS-1$
- helpTest(gs, "vdb.g"); //$NON-NLS-1$
- }
-
- 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() {
- 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() {
- 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() {
- StoredProcedure proc = new StoredProcedure();
- proc.setProcedureName("myproc"); //$NON-NLS-1$
- helpTest(proc, "EXEC myproc()"); //$NON-NLS-1$
- }
-
- public void testExecInputParam() {
- StoredProcedure proc = new StoredProcedure();
- proc.setProcedureName("myproc"); //$NON-NLS-1$
- SPParameter param = new SPParameter(1, new Reference(0));
- proc.setParameter(param);
- helpTest(proc, "EXEC myproc(?)"); //$NON-NLS-1$
- }
-
- public void testExecInputOutputParam() {
- StoredProcedure proc = new StoredProcedure();
- proc.setProcedureName("myproc"); //$NON-NLS-1$
- SPParameter param1 = new SPParameter(1, new Constant(new Integer(5)));
- param1.setParameterType(ParameterInfo.IN);
- proc.setParameter(param1);
-
- SPParameter param2 = new SPParameter(2, ParameterInfo.OUT, "x"); //$NON-NLS-1$
- proc.setParameter(param2);
-
- helpTest(proc, "EXEC myproc(5)"); //$NON-NLS-1$
- }
-
- public void testExecOutputInputParam() {
- StoredProcedure proc = new StoredProcedure();
- proc.setProcedureName("myproc"); //$NON-NLS-1$
-
- SPParameter param2 = new SPParameter(2, ParameterInfo.OUT, "x"); //$NON-NLS-1$
- proc.setParameter(param2);
-
- SPParameter param1 = new SPParameter(1, new Constant(new Integer(5)));
- param1.setParameterType(ParameterInfo.IN);
- proc.setParameter(param1);
-
- helpTest(proc, "EXEC myproc(5)"); //$NON-NLS-1$
- }
-
- public void testExecReturnParam() {
- StoredProcedure proc = new StoredProcedure();
- proc.setProcedureName("myproc"); //$NON-NLS-1$
-
- SPParameter param = new SPParameter(1, ParameterInfo.RETURN_VALUE, "ret"); //$NON-NLS-1$
- proc.setParameter(param);
- helpTest(proc, "EXEC myproc()"); //$NON-NLS-1$
- }
-
- public void testExecNamedParam() {
- StoredProcedure proc = new StoredProcedure();
- proc.setDisplayNamedParameters(true);
- proc.setProcedureName("myproc"); //$NON-NLS-1$
- SPParameter param = new SPParameter(1, new Reference(0));
- param.setName("p1");//$NON-NLS-1$
- proc.setParameter(param);
- helpTest(proc, "EXEC myproc(p1 => ?)"); //$NON-NLS-1$
- }
-
- public void testExecNamedParams() {
- StoredProcedure proc = new StoredProcedure();
- proc.setDisplayNamedParameters(true);
- proc.setProcedureName("myproc"); //$NON-NLS-1$
- SPParameter param = new SPParameter(1, new Reference(0));
- param.setName("p1");//$NON-NLS-1$
- proc.setParameter(param);
- SPParameter param2 = new SPParameter(2, new Reference(0));
- param2.setName("p2");//$NON-NLS-1$
- proc.setParameter(param2);
- helpTest(proc, "EXEC myproc(p1 => ?, p2 => ?)"); //$NON-NLS-1$
- }
-
- /**
- * Test when a parameter's name is a reserved word.
- * (Note: parameters should always have short names, not
- * multiple period-delimited name components.)
- *
- * @since 4.3
- */
- public void testExecNamedParamsReservedWord() {
- StoredProcedure proc = new StoredProcedure();
- proc.setDisplayNamedParameters(true);
- proc.setProcedureName("myproc"); //$NON-NLS-1$
- SPParameter param = new SPParameter(1, new Reference(0));
- param.setName("in");//$NON-NLS-1$
- proc.setParameter(param);
- SPParameter param2 = new SPParameter(2, new Reference(0));
- param2.setName("in2");//$NON-NLS-1$
- proc.setParameter(param2);
- helpTest(proc, "EXEC myproc(\"in\" => ?, in2 => ?)"); //$NON-NLS-1$
- }
-
- // Test methods for Update Procedure Language Objects
-
- 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() {
- RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
- helpTest(errStmt, "ERROR 'My Error';"); //$NON-NLS-1$
- }
-
- public void testRaiseErrorStatementWithExpression() {
- RaiseErrorStatement errStmt = new RaiseErrorStatement(new ElementSymbol("a")); //$NON-NLS-1$
- helpTest(errStmt, "ERROR a;"); //$NON-NLS-1$
- }
-
- 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() {
- Query q1 = new Query();
- Select select = new Select();
- select.addSymbol(new ElementSymbol("x")); //$NON-NLS-1$
- q1.setSelect(select);
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
- q1.setFrom(from);
-
- AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), q1); //$NON-NLS-1$
- helpTest(assigStmt, "a = (SELECT x FROM g);"); //$NON-NLS-1$
- }
-
- 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$
- List elmnts = new ArrayList(3);
- elmnts.add(sy1);
- elmnts.add(sy2);
- elmnts.add(sy3);
- CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.COMPARE_EQ, elmnts);
- helpTest(cs, "= CRITERIA ON (a, b, c)"); //$NON-NLS-1$
- }
-
- 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$
- List elmnts = new ArrayList(3);
- elmnts.add(sy1);
- elmnts.add(sy2);
- elmnts.add(sy3);
- CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
- helpTest(cs, "LIKE CRITERIA ON (x, y, z)"); //$NON-NLS-1$
- }
-
- 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$
- List elmnts = new ArrayList(3);
- elmnts.add(sy1);
- elmnts.add(sy2);
- elmnts.add(sy3);
- CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.BETWEEN, elmnts);
- helpTest(cs, "BETWEEN CRITERIA ON (x, y, z)"); //$NON-NLS-1$
- }
-
- 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$
- List elmnts = new ArrayList(3);
- elmnts.add(sy1);
- elmnts.add(sy2);
- elmnts.add(sy3);
- CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
- helpTest(new HasCriteria(cs), "HAS LIKE CRITERIA ON (x, y, z)"); //$NON-NLS-1$
- }
-
- 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$
- List elmnts = new ArrayList(3);
- elmnts.add(sy1);
- elmnts.add(sy2);
- elmnts.add(sy3);
- CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
- helpTest(new HasCriteria(cs), "HAS LIKE CRITERIA ON (x, y, z)"); //$NON-NLS-1$
- }
-
- 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$
- List elmnts = new ArrayList(3);
- elmnts.add(sy1);
- elmnts.add(sy2);
- elmnts.add(sy3);
- CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.BETWEEN, elmnts);
- helpTest(new HasCriteria(cs), "HAS BETWEEN CRITERIA ON (x, y, z)"); //$NON-NLS-1$
- }
-
- public void testCommandStatement1() {
- Query q1 = new Query();
- Select select = new Select();
- select.addSymbol(new ElementSymbol("x")); //$NON-NLS-1$
- q1.setSelect(select);
- From from = new From();
- from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
- q1.setFrom(from);
-
- CommandStatement cmdStmt = new CommandStatement(q1);
- helpTest(cmdStmt, "SELECT x FROM g;"); //$NON-NLS-1$
- }
-
- 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() {
- Delete d1 = new Delete();
- d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
- CommandStatement cmdStmt = new CommandStatement(d1);
- AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), new Constant(new Integer(1))); //$NON-NLS-1$
- RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
- Block b = new Block();
- b.addStatement(cmdStmt);
- b.addStatement(assigStmt);
- b.addStatement(errStmt);
- helpTest(b, "BEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND"); //$NON-NLS-1$
- }
-
- public void testBlock2() {
- // construct If statement
-
- Delete d1 = new Delete();
- d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
- CommandStatement cmdStmt = new CommandStatement(d1);
- Block ifblock = new Block(cmdStmt);
- // construct If criteria
- ElementSymbol sy1 = new ElementSymbol("x"); //$NON-NLS-1$
- List elmnts = new ArrayList(1);
- elmnts.add(sy1);
- CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
- Criteria crit = new HasCriteria(cs);
- IfStatement ifStmt = new IfStatement(crit, ifblock);
-
- // other statements
- RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
- Block b = new Block();
- b.addStatement(cmdStmt);
- b.addStatement(ifStmt);
- b.addStatement(errStmt);
-
- 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() {
- // construct If block
- Delete d1 = new Delete();
- d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
- CommandStatement cmdStmt = new CommandStatement(d1);
- AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), new Constant(new Integer(1))); //$NON-NLS-1$
- RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
- Block ifblock = new Block();
- ifblock.addStatement(cmdStmt);
- ifblock.addStatement(assigStmt);
- ifblock.addStatement(errStmt);
-
- // construct If criteria
- ElementSymbol sy1 = new ElementSymbol("x"); //$NON-NLS-1$
- List elmnts = new ArrayList(1);
- elmnts.add(sy1);
- CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
- Criteria crit = new HasCriteria(cs);
-
- IfStatement ifStmt = new IfStatement(crit, ifblock);
- helpTest(ifStmt, "IF(HAS LIKE CRITERIA ON (x))\nBEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND"); //$NON-NLS-1$
- }
-
- public void testIfStatement2() {
- // construct If block
- Delete d1 = new Delete();
- d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
- CommandStatement cmdStmt = new CommandStatement(d1);
- Block ifblock = new Block(cmdStmt);
-
- // construct If criteria
- ElementSymbol sy1 = new ElementSymbol("x"); //$NON-NLS-1$
- List elmnts = new ArrayList(1);
- elmnts.add(sy1);
- CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
- Criteria crit = new HasCriteria(cs);
-
- IfStatement ifStmt = new IfStatement(crit, ifblock);
- helpTest(ifStmt, "IF(HAS LIKE CRITERIA ON (x))\nBEGIN\nDELETE FROM g;\nEND"); //$NON-NLS-1$
- }
-
- public void testIfStatement3() {
- // construct If block
- Delete d1 = new Delete();
- d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
- CommandStatement cmdStmt = new CommandStatement(d1);
- AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), new Constant(new Integer(1))); //$NON-NLS-1$
- RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
- Block ifblock = new Block();
- ifblock.addStatement(cmdStmt);
- ifblock.addStatement(assigStmt);
- ifblock.addStatement(errStmt);
-
- // construct If criteria
- ElementSymbol sy1 = new ElementSymbol("x"); //$NON-NLS-1$
- List elmnts = new ArrayList(1);
- elmnts.add(sy1);
- CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
- Criteria crit = new HasCriteria(cs);
-
- Block elseblock = new Block();
- elseblock.addStatement(cmdStmt);
-
- IfStatement ifStmt = new IfStatement(crit, ifblock, elseblock);
- 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() {
- Delete d1 = new Delete();
- d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
- CommandStatement cmdStmt = new CommandStatement(d1);
- AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), new Constant(new Integer(1))); //$NON-NLS-1$
- RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
- Block b = new Block();
- b.addStatement(cmdStmt);
- b.addStatement(assigStmt);
- b.addStatement(errStmt);
- CreateUpdateProcedureCommand cup = new CreateUpdateProcedureCommand(b);
- helpTest(cup, "CREATE PROCEDURE\nBEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND"); //$NON-NLS-1$
- }
-
- public void testCreateUpdateProcedure2() {
- Delete d1 = new Delete();
- d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
- CommandStatement cmdStmt = new CommandStatement(d1);
- AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), new Constant(new Integer(1))); //$NON-NLS-1$
- RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
- Block b = new Block();
- b.addStatement(cmdStmt);
- b.addStatement(assigStmt);
- b.addStatement(errStmt);
- CreateUpdateProcedureCommand cup = new CreateUpdateProcedureCommand(b);
- helpTest(cup, "CREATE PROCEDURE\nBEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND"); //$NON-NLS-1$
- }
-
- public void testCreateUpdateProcedure3() {
- Delete d1 = new Delete();
- d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
- CommandStatement cmdStmt = new CommandStatement(d1);
- AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), new Constant(new Integer(1))); //$NON-NLS-1$
- RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
- Block b = new Block();
- b.addStatement(cmdStmt);
- b.addStatement(assigStmt);
- b.addStatement(errStmt);
- CreateUpdateProcedureCommand cup = new CreateUpdateProcedureCommand(b);
- helpTest(cup, "CREATE PROCEDURE\nBEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND"); //$NON-NLS-1$
- }
-
- public void testSubqueryCompareCriteria1() {
-
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- ElementSymbol expr = new ElementSymbol("e2"); //$NON-NLS-1$
-
- SubqueryCompareCriteria scc = new SubqueryCompareCriteria(expr, q1, SubqueryCompareCriteria.EQ, SubqueryCompareCriteria.ANY);
-
- helpTest(scc, "e2 = ANY (SELECT e1 FROM m.g1)"); //$NON-NLS-1$
- }
-
- public void testSubqueryCompareCriteria2() {
-
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- ElementSymbol expr = new ElementSymbol("e2"); //$NON-NLS-1$
-
- SubqueryCompareCriteria scc = new SubqueryCompareCriteria(expr, q1, SubqueryCompareCriteria.LE, SubqueryCompareCriteria.SOME);
-
- helpTest(scc, "e2 <= SOME (SELECT e1 FROM m.g1)"); //$NON-NLS-1$
- }
-
- public void testExistsCriteria1() {
-
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- ExistsCriteria ec = new ExistsCriteria(q1);
-
- helpTest(ec, "EXISTS (SELECT e1 FROM m.g1)"); //$NON-NLS-1$
- }
-
- public void testDynamicCommand() {
- List symbols = new ArrayList();
-
- ElementSymbol a1 = new ElementSymbol("a1"); //$NON-NLS-1$
- a1.setType(DataTypeManager.DefaultDataClasses.STRING);
- symbols.add(a1);
-
- DynamicCommand obj = new DynamicCommand();
- Expression sql = new Constant("SELECT a1 FROM g WHERE a2 = 5"); //$NON-NLS-1$
-
- obj.setSql(sql);
- obj.setAsColumns(symbols);
- obj.setAsClauseSet(true);
- obj.setIntoGroup(new GroupSymbol("#g")); //$NON-NLS-1$
-
- helpTest(obj, "EXECUTE 'SELECT a1 FROM g WHERE a2 = 5' AS a1 string INTO #g"); //$NON-NLS-1$
- }
-
- public void testScalarSubquery() {
-
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- ScalarSubquery obj = new ScalarSubquery(q1);
-
- helpTest(obj, "(SELECT e1 FROM m.g1)"); //$NON-NLS-1$
- }
-
- public void testNewSubqueryObjects(){
-
- Select s1 = new Select();
- s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- From f1 = new From();
- f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
- Query q1 = new Query();
- q1.setSelect(s1);
- q1.setFrom(f1);
-
- Select s2 = new Select();
- s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
- s2.addSymbol(new ExpressionSymbol("blargh", new ScalarSubquery(q1))); //$NON-NLS-1$
- From f2 = new From();
- f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
- Criteria left = new SubqueryCompareCriteria(new ElementSymbol("e3"), q1, SubqueryCompareCriteria.GE, SubqueryCompareCriteria.ANY); //$NON-NLS-1$
- Criteria right = new ExistsCriteria(q1);
- Criteria outer = new CompoundCriteria(CompoundCriteria.AND, left, right);
- Query q2 = new Query();
- q2.setSelect(s2);
- q2.setFrom(f2);
- q2.setCriteria(outer);
-
- 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() {
- helpTest(TestCaseExpression.example(2),
- "CASE x WHEN 'a' THEN 0 WHEN 'b' THEN 1 ELSE 9999 END"); //$NON-NLS-1$
- }
-
- 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() {
- 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() {
- 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() {
- helpTest(TestSearchedCaseExpression.example(2),
- "CASE WHEN x = 0 THEN 0 WHEN x = 1 THEN 1 ELSE 9999 END"); //$NON-NLS-1$
-
- }
-
- public void testSearchedCaseExpression2() {
- SearchedCaseExpression example = TestSearchedCaseExpression.example(2);
- example.setElseExpression(null);
- helpTest(example,
- "CASE WHEN x = 0 THEN 0 WHEN x = 1 THEN 1 END"); //$NON-NLS-1$
-
- }
-
- /**
- * For some reason this test was outputting
- * SELECT 'A' AS FOO UNION SELECT 'A' AS FOO
- */
- public void testSetQueryUnionOfLiteralsCase3102() {
-
- String expected = "SELECT 'A' AS FOO UNION SELECT 'B' AS FOO"; //$NON-NLS-1$
-
- Select s1 = new Select();
- s1.addSymbol(new AliasSymbol("FOO", new ExpressionSymbol("xxx", new Constant("A")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Query q1 = new Query();
- q1.setSelect(s1);
-
- Select s2 = new Select();
- s2.addSymbol(new AliasSymbol("FOO", new ExpressionSymbol("xxx", new Constant("B")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Query q2 = new Query();
- q2.setSelect(s2);
-
- SetQuery sq = new SetQuery(Operation.UNION, false, q1, q2);
-
- helpTest(sq, expected);
- }
-
- /**
- * For some reason this test was outputting
- * SELECT 'A' AS FOO UNION SELECT 'A' AS FOO
- * Same as above except that ExpressionSymbols' internal names (which aren't visible
- * in the query) are different
- */
- public void testSetQueryUnionOfLiteralsCase3102a() {
-
- String expected = "SELECT 'A' AS FOO UNION SELECT 'B' AS FOO"; //$NON-NLS-1$
-
- Select s1 = new Select();
- s1.addSymbol(new AliasSymbol("FOO", new ExpressionSymbol("xxx", new Constant("A")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Query q1 = new Query();
- q1.setSelect(s1);
-
- Select s2 = new Select();
- s2.addSymbol(new AliasSymbol("FOO", new ExpressionSymbol("yyy", new Constant("B")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- Query q2 = new Query();
- q2.setSelect(s2);
-
- SetQuery sq = new SetQuery(Operation.UNION, false, q1, q2);
-
- helpTest(sq, expected);
- }
-
- 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(query, "SELECT * FROM a LIMIT 100"); //$NON-NLS-1$
- }
-
- 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(query, "SELECT * FROM a LIMIT 50, 100"); //$NON-NLS-1$
- }
-
- 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());
- 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 {
- 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());
- 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 {
- 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());
- helpTest(command, "SELECT pm1.g1.e1 AS a FROM pm1.g1 ORDER BY a"); //$NON-NLS-1$
- }
-
- 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());
- helpTest(command, "SELECT pm1.g1.e1 AS a FROM pm1.g1 ORDER BY 1"); //$NON-NLS-1$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestSQLStringVisitor.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/sql/visitor/TestSQLStringVisitor.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestSQLStringVisitor.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/sql/visitor/TestSQLStringVisitor.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1896 @@
+/*
+ * 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.visitor;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import org.teiid.client.metadata.ParameterInfo;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.language.SQLConstants.NonReserved;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.lang.BetweenCriteria;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.DynamicCommand;
+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.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.Option;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.SubqueryCompareCriteria;
+import org.teiid.query.sql.lang.SubqueryFromClause;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.lang.SetQuery.Operation;
+import org.teiid.query.sql.proc.AssignmentStatement;
+import org.teiid.query.sql.proc.Block;
+import org.teiid.query.sql.proc.CommandStatement;
+import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
+import org.teiid.query.sql.proc.CriteriaSelector;
+import org.teiid.query.sql.proc.DeclareStatement;
+import org.teiid.query.sql.proc.HasCriteria;
+import org.teiid.query.sql.proc.IfStatement;
+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;
+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.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.RealMetadataFactory;
+
+
+public class TestSQLStringVisitor extends TestCase {
+
+ // ################################## FRAMEWORK ################################
+
+ public TestSQLStringVisitor(String name) {
+ super(name);
+ }
+
+ // ################################## TEST HELPERS ################################
+
+ private void helpTest(LanguageObject obj, String expectedStr) {
+ String actualStr = SQLStringVisitor.getSQLString(obj);
+ assertEquals("Expected and actual strings don't match: ", expectedStr, actualStr); //$NON-NLS-1$
+ }
+
+ // ################################## ACTUAL TESTS ################################
+
+ public void testNull() {
+ String sql = SQLStringVisitor.getSQLString(null);
+
+ assertEquals("Incorrect string for null object", SQLStringVisitor.UNDEFINED, sql); //$NON-NLS-1$
+ }
+
+ public void testBetweenCriteria1() {
+ BetweenCriteria bc = new BetweenCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ new Constant(new Integer(1000)),
+ new Constant(new Integer(2000)) );
+ helpTest(bc, "m.g.c1 BETWEEN 1000 AND 2000"); //$NON-NLS-1$
+ }
+
+ public void testBetweenCriteria2() {
+ BetweenCriteria bc = new BetweenCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ new Constant(new Integer(1000)),
+ new Constant(new Integer(2000)) );
+ bc.setNegated(true);
+ helpTest(bc, "m.g.c1 NOT BETWEEN 1000 AND 2000"); //$NON-NLS-1$
+ }
+
+ public void testCompareCriteria1() {
+ CompareCriteria cc = new CompareCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new Constant("abc") ); //$NON-NLS-1$
+
+ helpTest(cc, "m.g.c1 = 'abc'"); //$NON-NLS-1$
+ }
+
+ public void testCompareCriteria2() {
+ CompareCriteria cc = new CompareCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ CompareCriteria.NE,
+ new Constant("abc") ); //$NON-NLS-1$
+
+ helpTest(cc, "m.g.c1 <> 'abc'"); //$NON-NLS-1$
+ }
+
+ public void testCompareCriteria3() {
+ CompareCriteria cc = new CompareCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ CompareCriteria.GT,
+ new Constant("abc") ); //$NON-NLS-1$
+
+ helpTest(cc, "m.g.c1 > 'abc'"); //$NON-NLS-1$
+ }
+
+ public void testCompareCriteria4() {
+ CompareCriteria cc = new CompareCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ CompareCriteria.GE,
+ new Constant("abc") ); //$NON-NLS-1$
+
+ helpTest(cc, "m.g.c1 >= 'abc'"); //$NON-NLS-1$
+ }
+
+ public void testCompareCriteria5() {
+ CompareCriteria cc = new CompareCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ CompareCriteria.LT,
+ new Constant("abc") ); //$NON-NLS-1$
+
+ helpTest(cc, "m.g.c1 < 'abc'"); //$NON-NLS-1$
+ }
+
+ public void testCompareCriteria6() {
+ CompareCriteria cc = new CompareCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ CompareCriteria.LE,
+ new Constant("abc") ); //$NON-NLS-1$
+
+ helpTest(cc, "m.g.c1 <= 'abc'"); //$NON-NLS-1$
+ }
+
+ public void testCompareCriteria7() {
+ CompareCriteria cc = new CompareCriteria(
+ null,
+ CompareCriteria.EQ,
+ null );
+
+ helpTest(cc, "<undefined> = <undefined>"); //$NON-NLS-1$
+ }
+
+ public void testCompoundCriteria1() {
+ CompareCriteria cc = new CompareCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new Constant("abc") ); //$NON-NLS-1$
+ List<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(cc);
+ CompoundCriteria comp = new CompoundCriteria(CompoundCriteria.AND, crits);
+
+ helpTest(comp, "m.g.c1 = 'abc'"); //$NON-NLS-1$
+ }
+
+ public void testCompoundCriteria2() {
+ CompareCriteria cc1 = new CompareCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new Constant("abc") ); //$NON-NLS-1$
+ CompareCriteria cc2 = new CompareCriteria(
+ new ElementSymbol("m.g.c2"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new Constant("abc") ); //$NON-NLS-1$
+ List<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(cc1);
+ crits.add(cc2);
+ CompoundCriteria comp = new CompoundCriteria(CompoundCriteria.AND, crits);
+
+ helpTest(comp, "(m.g.c1 = 'abc') AND (m.g.c2 = 'abc')"); //$NON-NLS-1$
+ }
+
+ public void testCompoundCriteria3() {
+ CompareCriteria cc1 = new CompareCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new Constant("abc") ); //$NON-NLS-1$
+ CompareCriteria cc2 = new CompareCriteria(
+ new ElementSymbol("m.g.c2"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new Constant("abc") ); //$NON-NLS-1$
+ CompareCriteria cc3 = new CompareCriteria(
+ new ElementSymbol("m.g.c3"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new Constant("abc") ); //$NON-NLS-1$
+ List<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(cc1);
+ crits.add(cc2);
+ crits.add(cc3);
+ CompoundCriteria comp = new CompoundCriteria(CompoundCriteria.OR, crits);
+
+ helpTest(comp, "(m.g.c1 = 'abc') OR (m.g.c2 = 'abc') OR (m.g.c3 = 'abc')"); //$NON-NLS-1$
+ }
+
+ public void testCompoundCriteria4() {
+ CompareCriteria cc1 = new CompareCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new Constant("abc") ); //$NON-NLS-1$
+ List<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(cc1);
+ crits.add(null);
+ CompoundCriteria comp = new CompoundCriteria(CompoundCriteria.OR, crits);
+
+ helpTest(comp, "(m.g.c1 = 'abc') OR (<undefined>)"); //$NON-NLS-1$
+ }
+
+ public void testCompoundCriteria5() {
+ CompareCriteria cc1 = new CompareCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new Constant("abc") ); //$NON-NLS-1$
+ List<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(null);
+ crits.add(cc1);
+ CompoundCriteria comp = new CompoundCriteria(CompoundCriteria.OR, crits);
+
+ helpTest(comp, "(<undefined>) OR (m.g.c1 = 'abc')"); //$NON-NLS-1$
+ }
+
+ public void testCompoundCriteria6() {
+ CompareCriteria cc1 = new CompareCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new Constant("abc") ); //$NON-NLS-1$
+ List<Criteria> crits = new ArrayList<Criteria>();
+ crits.add(cc1);
+ crits.add(null);
+ CompoundCriteria comp = new CompoundCriteria(CompoundCriteria.OR, crits);
+
+ helpTest(comp, "(m.g.c1 = 'abc') OR (<undefined>)"); //$NON-NLS-1$
+ }
+
+ 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() {
+ Delete delete = new Delete();
+ delete.setGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ delete.setCriteria(new CompareCriteria(
+ new ElementSymbol("m.g.c1"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new Constant("abc")) ); //$NON-NLS-1$
+
+
+ helpTest(delete, "DELETE FROM m.g WHERE m.g.c1 = 'abc'"); //$NON-NLS-1$
+ }
+
+ 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$
+
+ helpTest(from, "FROM m.g1, m.g2"); //$NON-NLS-1$
+ }
+
+ public void testFrom2() {
+ From from = new From();
+ from.addClause(new UnaryFromClause(new GroupSymbol("m.g1"))); //$NON-NLS-1$
+ from.addClause(new JoinPredicate(
+ new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
+ new UnaryFromClause(new GroupSymbol("m.g3")), //$NON-NLS-1$
+ JoinType.JOIN_CROSS) );
+
+ helpTest(from, "FROM m.g1, m.g2 CROSS JOIN m.g3"); //$NON-NLS-1$
+ }
+
+ 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() {
+ GroupBy gb = new GroupBy();
+ gb.addSymbol(new ElementSymbol("m.g.e1")); //$NON-NLS-1$
+ gb.addSymbol(new ElementSymbol("m.g.e2")); //$NON-NLS-1$
+ gb.addSymbol(new ElementSymbol("m.g.e3")); //$NON-NLS-1$
+
+ helpTest(gb, "GROUP BY m.g.e1, m.g.e2, m.g.e3"); //$NON-NLS-1$
+ }
+
+ public void testInsert1() {
+ Insert insert = new Insert();
+ insert.setGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+
+ List vars = new ArrayList();
+ vars.add(new ElementSymbol("e1")); //$NON-NLS-1$
+ vars.add(new ElementSymbol("e2")); //$NON-NLS-1$
+ insert.setVariables(vars);
+ List values = new ArrayList();
+ values.add(new Constant(new Integer(5)));
+ values.add(new Constant("abc")); //$NON-NLS-1$
+ insert.setValues(values);
+
+ helpTest(insert, "INSERT INTO m.g1 (e1, e2) VALUES (5, 'abc')"); //$NON-NLS-1$
+ }
+
+ 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() {
+ 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() {
+ IsNullCriteria inc = new IsNullCriteria();
+ helpTest(inc, "<undefined> IS NULL"); //$NON-NLS-1$
+ }
+
+ 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() {
+ JoinPredicate jp = new JoinPredicate(
+ new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
+ new UnaryFromClause(new GroupSymbol("m.g3")), //$NON-NLS-1$
+ JoinType.JOIN_CROSS);
+
+ helpTest(jp, "m.g2 CROSS JOIN m.g3"); //$NON-NLS-1$
+ }
+
+ 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$
+ JoinType.JOIN_CROSS);
+ jp.setOptional(true);
+ helpTest(jp, "/*+ optional */ (m.g2 CROSS JOIN m.g3)"); //$NON-NLS-1$
+ }
+
+ 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(
+ new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
+ new UnaryFromClause(new GroupSymbol("m.g3")), //$NON-NLS-1$
+ JoinType.JOIN_INNER,
+ crits );
+
+ helpTest(jp, "m.g2 INNER JOIN m.g3 ON m.g2.e1 = m.g3.e1"); //$NON-NLS-1$
+ }
+
+ 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$
+ JoinPredicate jp = new JoinPredicate(
+ new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
+ new UnaryFromClause(new GroupSymbol("m.g3")), //$NON-NLS-1$
+ JoinType.JOIN_INNER,
+ crits );
+
+ 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() {
+ 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(
+ new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
+ new UnaryFromClause(new GroupSymbol("m.g3")), //$NON-NLS-1$
+ JoinType.JOIN_INNER,
+ crits );
+
+ JoinPredicate jp2 = new JoinPredicate(
+ jp,
+ new UnaryFromClause(new GroupSymbol("m.g1")), //$NON-NLS-1$
+ JoinType.JOIN_CROSS);
+
+ 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() {
+ 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(
+ new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
+ new UnaryFromClause(new GroupSymbol("m.g3")), //$NON-NLS-1$
+ JoinType.JOIN_INNER,
+ crits );
+
+ helpTest(jp, "m.g2 INNER JOIN m.g3 ON NOT (m.g2.e1 = m.g3.e1)"); //$NON-NLS-1$
+ }
+
+ public void testJoinType1() {
+ helpTest(JoinType.JOIN_CROSS, "CROSS JOIN"); //$NON-NLS-1$
+ }
+
+ public void testJoinType2() {
+ helpTest(JoinType.JOIN_INNER, "INNER JOIN"); //$NON-NLS-1$
+ }
+
+ public void testJoinType3() {
+ helpTest(JoinType.JOIN_RIGHT_OUTER, "RIGHT OUTER JOIN"); //$NON-NLS-1$
+ }
+
+ public void testJoinType4() {
+ helpTest(JoinType.JOIN_LEFT_OUTER, "LEFT OUTER JOIN"); //$NON-NLS-1$
+ }
+
+ public void testJoinType5() {
+ helpTest(JoinType.JOIN_FULL_OUTER, "FULL OUTER JOIN"); //$NON-NLS-1$
+ }
+
+ 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$
+
+ helpTest(mc, "m.g.e1 LIKE 'abc'"); //$NON-NLS-1$
+ }
+
+ public void testMatchCriteria2() {
+ MatchCriteria mc = new MatchCriteria();
+ mc.setLeftExpression(new ElementSymbol("m.g.e1")); //$NON-NLS-1$
+ mc.setRightExpression(new Constant("%")); //$NON-NLS-1$
+ mc.setEscapeChar('#');
+
+ helpTest(mc, "m.g.e1 LIKE '%' ESCAPE '#'"); //$NON-NLS-1$
+ }
+
+ 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$
+ mc.setNegated(true);
+ helpTest(mc, "m.g.e1 NOT LIKE 'abc'"); //$NON-NLS-1$
+ }
+
+ 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() {
+ NotCriteria not = new NotCriteria();
+ helpTest(not, "NOT (<undefined>)"); //$NON-NLS-1$
+ }
+
+ public void testOption1() {
+ Option option = new Option();
+ helpTest(option, "OPTION"); //$NON-NLS-1$
+ }
+
+ public void testOption5() {
+ Option option = new Option();
+ option.addDependentGroup("abc"); //$NON-NLS-1$
+ option.addDependentGroup("def"); //$NON-NLS-1$
+ option.addDependentGroup("xyz"); //$NON-NLS-1$
+ helpTest(option, "OPTION MAKEDEP abc, def, xyz"); //$NON-NLS-1$
+ }
+
+ public void testOption6() {
+ Option option = new Option();
+ option.addDependentGroup("abc"); //$NON-NLS-1$
+ option.addDependentGroup("def"); //$NON-NLS-1$
+ option.addDependentGroup("xyz"); //$NON-NLS-1$
+ helpTest(option, "OPTION MAKEDEP abc, def, xyz"); //$NON-NLS-1$
+ }
+
+ public void testOption8() {
+ Option option = new Option();
+ option.addNoCacheGroup("abc"); //$NON-NLS-1$
+ option.addNoCacheGroup("def"); //$NON-NLS-1$
+ option.addNoCacheGroup("xyz"); //$NON-NLS-1$
+ helpTest(option, "OPTION NOCACHE abc, def, xyz"); //$NON-NLS-1$
+ }
+
+// related to defect 14423
+ public void testOption9() {
+ Option option = new Option();
+ option.setNoCache(true);
+ helpTest(option, "OPTION NOCACHE"); //$NON-NLS-1$
+ }
+
+ 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() {
+ 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$
+
+ helpTest(ob, "ORDER BY e1, x"); //$NON-NLS-1$
+ }
+
+ 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$
+
+ helpTest(ob, "ORDER BY e1 DESC, x DESC"); //$NON-NLS-1$
+ }
+
+ public void testQuery1() {
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ From from = new From();
+ from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+
+ helpTest(query, "SELECT * FROM m.g"); //$NON-NLS-1$
+ }
+
+ public void testQuery2() {
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ 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$
+ GroupBy groupBy = new GroupBy();
+ groupBy.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ CompareCriteria having = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.GT, new Constant(new Integer(0))); //$NON-NLS-1$
+ OrderBy orderBy = new OrderBy();
+ orderBy.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(cc);
+ query.setGroupBy(groupBy);
+ query.setHaving(having);
+ query.setOrderBy(orderBy);
+
+ helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 GROUP BY e1 HAVING e1 > 0 ORDER BY e1"); //$NON-NLS-1$
+ }
+
+ public void testQuery3() {
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ From from = new From();
+ from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
+ GroupBy groupBy = new GroupBy();
+ groupBy.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ CompareCriteria having = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.GT, new Constant(new Integer(0))); //$NON-NLS-1$
+ OrderBy orderBy = new OrderBy();
+ orderBy.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setGroupBy(groupBy);
+ query.setHaving(having);
+ query.setOrderBy(orderBy);
+
+ helpTest(query, "SELECT * FROM m.g GROUP BY e1 HAVING e1 > 0 ORDER BY e1"); //$NON-NLS-1$
+ }
+
+ public void testQuery4() {
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ 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$
+ CompareCriteria having = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.GT, new Constant(new Integer(0))); //$NON-NLS-1$
+ OrderBy orderBy = new OrderBy();
+ orderBy.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(cc);
+ query.setHaving(having);
+ query.setOrderBy(orderBy);
+
+ helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 HAVING e1 > 0 ORDER BY e1"); //$NON-NLS-1$
+ }
+
+ public void testQuery5() {
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ 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$
+ GroupBy groupBy = new GroupBy();
+ groupBy.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ OrderBy orderBy = new OrderBy();
+ orderBy.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(cc);
+ query.setGroupBy(groupBy);
+ query.setOrderBy(orderBy);
+
+ helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 GROUP BY e1 ORDER BY e1"); //$NON-NLS-1$
+ }
+
+ public void testQuery6() {
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ 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$
+ GroupBy groupBy = new GroupBy();
+ groupBy.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ CompareCriteria having = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.GT, new Constant(new Integer(0))); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(cc);
+ query.setGroupBy(groupBy);
+ query.setHaving(having);
+
+ helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 GROUP BY e1 HAVING e1 > 0"); //$NON-NLS-1$
+ }
+
+ public void testQuery7() {
+ Select select = new Select();
+ select.addSymbol(new AllSymbol());
+ 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$
+ GroupBy groupBy = new GroupBy();
+ groupBy.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ CompareCriteria having = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.GT, new Constant(new Integer(0))); //$NON-NLS-1$
+ OrderBy orderBy = new OrderBy();
+ orderBy.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
+
+ Query query = new Query();
+ query.setSelect(select);
+ query.setFrom(from);
+ query.setCriteria(cc);
+ query.setGroupBy(groupBy);
+ query.setHaving(having);
+ query.setOrderBy(orderBy);
+
+ helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 GROUP BY e1 HAVING e1 > 0 ORDER BY e1"); //$NON-NLS-1$
+ }
+
+ 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() {
+ Select select = new Select();
+ select.setDistinct(true);
+ select.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+
+ helpTest(select, "SELECT DISTINCT e1"); //$NON-NLS-1$
+ }
+
+ public void testSelect3() {
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ select.addSymbol(new ElementSymbol("e2")); //$NON-NLS-1$
+
+ helpTest(select, "SELECT e1, e2"); //$NON-NLS-1$
+ }
+
+ public void testSetCriteria1() {
+ SetCriteria sc = new SetCriteria();
+ sc.setExpression(new ElementSymbol("e1")); //$NON-NLS-1$
+ sc.setValues(new ArrayList());
+
+ helpTest(sc, "e1 IN ()"); //$NON-NLS-1$
+ }
+
+ public void testSetCriteria2() {
+ SetCriteria sc = new SetCriteria();
+ sc.setExpression(new ElementSymbol("e1")); //$NON-NLS-1$
+ ArrayList values = new ArrayList();
+ values.add(new ElementSymbol("e2")); //$NON-NLS-1$
+ values.add(new Constant("abc")); //$NON-NLS-1$
+ sc.setValues(values);
+
+ helpTest(sc, "e1 IN (e2, 'abc')"); //$NON-NLS-1$
+ }
+
+ public void testSetCriteria3() {
+ SetCriteria sc = new SetCriteria();
+ sc.setExpression(new ElementSymbol("e1")); //$NON-NLS-1$
+ ArrayList values = new ArrayList();
+ values.add(null);
+ values.add(new Constant("b")); //$NON-NLS-1$
+ sc.setValues(values);
+
+ helpTest(sc, "e1 IN (<undefined>, 'b')"); //$NON-NLS-1$
+ }
+
+ public void testSetCriteria4() {
+ SetCriteria sc = new SetCriteria();
+ sc.setExpression(new ElementSymbol("e1")); //$NON-NLS-1$
+ ArrayList values = new ArrayList();
+ values.add(new ElementSymbol("e2")); //$NON-NLS-1$
+ values.add(new Constant("abc")); //$NON-NLS-1$
+ sc.setValues(values);
+ sc.setNegated(true);
+ helpTest(sc, "e1 NOT IN (e2, 'abc')"); //$NON-NLS-1$
+ }
+
+ public void testSetQuery1() {
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+
+ SetQuery sq = new SetQuery(Operation.UNION, false, q1, q2);
+
+ helpTest(sq, "SELECT e1 FROM m.g1 UNION SELECT e1 FROM m.g2"); //$NON-NLS-1$
+ }
+
+ public void testSetQuery2() {
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+
+ SetQuery sq = new SetQuery(Operation.UNION, true, q1, q2);
+
+ helpTest(sq, "SELECT e1 FROM m.g1 UNION ALL SELECT e1 FROM m.g2"); //$NON-NLS-1$
+ }
+
+ public void testSetQuery3() {
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+
+ OrderBy orderBy = new OrderBy();
+ orderBy.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
+
+ SetQuery sq = new SetQuery(Operation.UNION, false, q1, q2);
+ sq.setOrderBy(orderBy);
+
+ helpTest(sq, "SELECT e1 FROM m.g1 UNION SELECT e1 FROM m.g2 ORDER BY e1"); //$NON-NLS-1$
+ }
+
+ public void testSetQuery4() {
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+
+ SetQuery sq = new SetQuery(Operation.UNION, false, q1, q2);
+
+ helpTest(sq, "SELECT e1 FROM m.g1 UNION SELECT e1 FROM m.g2"); //$NON-NLS-1$
+ }
+
+ public void testSetQuery5() {
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+
+ Select s3 = new Select();
+ s3.addSymbol(new ElementSymbol("e3")); //$NON-NLS-1$
+ From f3 = new From();
+ f3.addGroup(new GroupSymbol("m.g3")); //$NON-NLS-1$
+ Query q3 = new Query();
+ q3.setSelect(s3);
+ q3.setFrom(f3);
+
+ SetQuery sq = new SetQuery(Operation.UNION, false, q1, q2);
+
+ SetQuery sq2 = new SetQuery(Operation.UNION, true, q3, sq);
+
+ 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() {
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ SubqueryFromClause sfc = new SubqueryFromClause("temp", q1); //$NON-NLS-1$
+ helpTest(sfc, "(SELECT e1 FROM m.g1) AS temp"); //$NON-NLS-1$
+ }
+
+ public void testOptionalSubqueryFromClause1() {
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ SubqueryFromClause sfc = new SubqueryFromClause("temp", q1); //$NON-NLS-1$
+ sfc.setOptional(true);
+ helpTest(sfc, "/*+ optional */ (SELECT e1 FROM m.g1) AS temp"); //$NON-NLS-1$
+ }
+
+ public void testSubquerySetCriteria1() {
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ ElementSymbol expr = new ElementSymbol("e2"); //$NON-NLS-1$
+
+ SubquerySetCriteria ssc = new SubquerySetCriteria(expr, q1);
+ helpTest(ssc, "e2 IN (SELECT e1 FROM m.g1)"); //$NON-NLS-1$
+ }
+
+ public void testSubquerySetCriteria2() {
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ ElementSymbol expr = new ElementSymbol("e2"); //$NON-NLS-1$
+
+ SubquerySetCriteria ssc = new SubquerySetCriteria(expr, q1);
+ ssc.setNegated(true);
+ helpTest(ssc, "e2 NOT IN (SELECT e1 FROM m.g1)"); //$NON-NLS-1$
+ }
+
+ public void testUnaryFromClause() {
+ helpTest(new UnaryFromClause(new GroupSymbol("m.g1")), "m.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ 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() {
+ 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$
+
+ helpTest(update, "UPDATE m.g1 SET e1 = 'abc'"); //$NON-NLS-1$
+ }
+
+ 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$
+ update.addChange(new ElementSymbol("e2"), new Constant("xyz")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ helpTest(update, "UPDATE m.g1 SET e1 = 'abc', e2 = 'xyz'"); //$NON-NLS-1$
+ }
+
+ 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$
+ update.setCriteria(new CompareCriteria(
+ new ElementSymbol("e2"), //$NON-NLS-1$
+ CompareCriteria.EQ,
+ new Constant("abc")) ); //$NON-NLS-1$
+
+
+ helpTest(update, "UPDATE m.g1 SET e1 = 'abc' WHERE e2 = 'abc'"); //$NON-NLS-1$
+ }
+
+ 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() {
+ 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() {
+ AggregateSymbol agg = new AggregateSymbol("abc", NonReserved.COUNT, false, null); //$NON-NLS-1$
+ helpTest(agg, "COUNT(*)"); //$NON-NLS-1$
+ }
+
+ 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() {
+ 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() {
+ 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() {
+ 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() {
+ 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() {
+ 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$
+ }
+
+ public void testAllInGroupSymbol() {
+ helpTest(new AllInGroupSymbol("m.g.*"), "m.g.*"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ public void testConstantNull() {
+ helpTest(new Constant(null), "null"); //$NON-NLS-1$
+ }
+
+ public void testConstantString() {
+ helpTest(new Constant("abc"), "'abc'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ public void testConstantInteger() {
+ helpTest(new Constant(new Integer(5)), "5"); //$NON-NLS-1$
+ }
+
+ public void testConstantBigDecimal() {
+ helpTest(new Constant(new BigDecimal("5.4")), "5.4"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ public void testConstantStringWithTick() {
+ helpTest(new Constant("O'Leary"), "'O''Leary'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ public void testConstantStringWithTicks() {
+ helpTest(new Constant("'abc'"), "'''abc'''"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ public void testConstantStringWithMoreTicks() {
+ helpTest(new Constant("a'b'c"), "'a''b''c'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ public void testConstantStringWithDoubleTick() {
+ helpTest(new Constant("group=\"x\""), "'group=\"x\"'"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ public void testConstantBooleanTrue() {
+ helpTest(new Constant(Boolean.TRUE), "TRUE"); //$NON-NLS-1$
+ }
+
+ public void testConstantBooleanFalse() {
+ helpTest(new Constant(Boolean.FALSE), "FALSE"); //$NON-NLS-1$
+ }
+
+ 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() {
+ helpTest(new Constant(java.sql.Time.valueOf("5:00:00")), "{t'05:00:00'}"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ 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() {
+ ElementSymbol es = new ElementSymbol("elem"); //$NON-NLS-1$
+ helpTest(es, "elem"); //$NON-NLS-1$
+ }
+
+ 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() {
+ 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() {
+ ElementSymbol es = new ElementSymbol("vdb.m.g.elem", true); //$NON-NLS-1$
+ helpTest(es, "vdb.m.g.elem"); //$NON-NLS-1$
+ }
+
+ 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() {
+ ExpressionSymbol expr = new ExpressionSymbol("abc", new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
+ helpTest(expr, "'abc'"); //$NON-NLS-1$
+ }
+
+ 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() {
+ Function func = new Function("now", new Expression[] {}); //$NON-NLS-1$
+ helpTest(func, "now()"); //$NON-NLS-1$
+ }
+
+ 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() {
+ Function func1 = new Function("power", new Expression[] { //$NON-NLS-1$
+ new Constant(new Integer(5)),
+ new Constant(new Integer(3)) });
+ Function func2 = new Function("power", new Expression[] { //$NON-NLS-1$
+ func1,
+ new Constant(new Integer(3)) });
+ Function func3 = new Function("+", new Expression[] { //$NON-NLS-1$
+ new Constant(new Integer(1000)),
+ func2 });
+ helpTest(func3, "(1000 + power(power(5, 3), 3))"); //$NON-NLS-1$
+ }
+
+ public void testFunction5() {
+ Function func1 = new Function("concat", new Expression[] { //$NON-NLS-1$
+ new ElementSymbol("elem2"), //$NON-NLS-1$
+ null });
+ Function func2 = new Function("concat", new Expression[] { //$NON-NLS-1$
+ new ElementSymbol("elem1"), //$NON-NLS-1$
+ func1 });
+ helpTest(func2, "concat(elem1, concat(elem2, <undefined>))"); //$NON-NLS-1$
+ }
+
+ 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$
+ });
+ helpTest(func, "convert('5', integer)"); //$NON-NLS-1$
+ }
+
+ public void testConvertFunction2() {
+ Function func = new Function("convert", new Expression[] { //$NON-NLS-1$
+ null,
+ new Constant("integer") //$NON-NLS-1$
+ });
+ helpTest(func, "convert(<undefined>, integer)"); //$NON-NLS-1$
+ }
+
+ public void testConvertFunction3() {
+ Function func = new Function("convert", new Expression[] { //$NON-NLS-1$
+ new Constant(null),
+ new Constant("integer") //$NON-NLS-1$
+ });
+ helpTest(func, "convert(null, integer)"); //$NON-NLS-1$
+ }
+
+ public void testConvertFunction4() {
+ Function func = new Function("convert", new Expression[] { //$NON-NLS-1$
+ new Constant("abc"), //$NON-NLS-1$
+ null
+ });
+ helpTest(func, "convert('abc', <undefined>)"); //$NON-NLS-1$
+ }
+
+ public void testConvertFunction5() {
+ Function func = new Function("convert", null); //$NON-NLS-1$
+ helpTest(func, "convert()"); //$NON-NLS-1$
+ }
+
+ public void testConvertFunction6() {
+ Function func = new Function("convert", new Expression[0]); //$NON-NLS-1$
+ helpTest(func, "convert()"); //$NON-NLS-1$
+ }
+
+ 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() {
+ Function func = new Function("cast", new Expression[] { //$NON-NLS-1$
+ new Constant("5"), //$NON-NLS-1$
+ new Constant("integer") //$NON-NLS-1$
+ });
+ helpTest(func, "cast('5' AS integer)"); //$NON-NLS-1$
+ }
+
+ public void testCastFunction2() {
+ Function func = new Function("cast", new Expression[] { //$NON-NLS-1$
+ null,
+ new Constant("integer") //$NON-NLS-1$
+ });
+ helpTest(func, "cast(<undefined> AS integer)"); //$NON-NLS-1$
+ }
+
+ public void testCastFunction3() {
+ Function func = new Function("cast", new Expression[] { //$NON-NLS-1$
+ new Constant(null),
+ new Constant("integer") //$NON-NLS-1$
+ });
+ helpTest(func, "cast(null AS integer)"); //$NON-NLS-1$
+ }
+
+ public void testCastFunction4() {
+ Function func = new Function("cast", new Expression[] { //$NON-NLS-1$
+ new Constant("abc"), //$NON-NLS-1$
+ null
+ });
+ helpTest(func, "cast('abc' AS <undefined>)"); //$NON-NLS-1$
+ }
+
+ 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() {
+ GroupSymbol gs = new GroupSymbol("g"); //$NON-NLS-1$
+ helpTest(gs, "g"); //$NON-NLS-1$
+ }
+
+ 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() {
+ GroupSymbol gs = new GroupSymbol("vdb.g"); //$NON-NLS-1$
+ helpTest(gs, "vdb.g"); //$NON-NLS-1$
+ }
+
+ 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() {
+ 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() {
+ 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() {
+ StoredProcedure proc = new StoredProcedure();
+ proc.setProcedureName("myproc"); //$NON-NLS-1$
+ helpTest(proc, "EXEC myproc()"); //$NON-NLS-1$
+ }
+
+ public void testExecInputParam() {
+ StoredProcedure proc = new StoredProcedure();
+ proc.setProcedureName("myproc"); //$NON-NLS-1$
+ SPParameter param = new SPParameter(1, new Reference(0));
+ proc.setParameter(param);
+ helpTest(proc, "EXEC myproc(?)"); //$NON-NLS-1$
+ }
+
+ public void testExecInputOutputParam() {
+ StoredProcedure proc = new StoredProcedure();
+ proc.setProcedureName("myproc"); //$NON-NLS-1$
+ SPParameter param1 = new SPParameter(1, new Constant(new Integer(5)));
+ param1.setParameterType(ParameterInfo.IN);
+ proc.setParameter(param1);
+
+ SPParameter param2 = new SPParameter(2, ParameterInfo.OUT, "x"); //$NON-NLS-1$
+ proc.setParameter(param2);
+
+ helpTest(proc, "EXEC myproc(5)"); //$NON-NLS-1$
+ }
+
+ public void testExecOutputInputParam() {
+ StoredProcedure proc = new StoredProcedure();
+ proc.setProcedureName("myproc"); //$NON-NLS-1$
+
+ SPParameter param2 = new SPParameter(2, ParameterInfo.OUT, "x"); //$NON-NLS-1$
+ proc.setParameter(param2);
+
+ SPParameter param1 = new SPParameter(1, new Constant(new Integer(5)));
+ param1.setParameterType(ParameterInfo.IN);
+ proc.setParameter(param1);
+
+ helpTest(proc, "EXEC myproc(5)"); //$NON-NLS-1$
+ }
+
+ public void testExecReturnParam() {
+ StoredProcedure proc = new StoredProcedure();
+ proc.setProcedureName("myproc"); //$NON-NLS-1$
+
+ SPParameter param = new SPParameter(1, ParameterInfo.RETURN_VALUE, "ret"); //$NON-NLS-1$
+ proc.setParameter(param);
+ helpTest(proc, "EXEC myproc()"); //$NON-NLS-1$
+ }
+
+ public void testExecNamedParam() {
+ StoredProcedure proc = new StoredProcedure();
+ proc.setDisplayNamedParameters(true);
+ proc.setProcedureName("myproc"); //$NON-NLS-1$
+ SPParameter param = new SPParameter(1, new Reference(0));
+ param.setName("p1");//$NON-NLS-1$
+ proc.setParameter(param);
+ helpTest(proc, "EXEC myproc(p1 => ?)"); //$NON-NLS-1$
+ }
+
+ public void testExecNamedParams() {
+ StoredProcedure proc = new StoredProcedure();
+ proc.setDisplayNamedParameters(true);
+ proc.setProcedureName("myproc"); //$NON-NLS-1$
+ SPParameter param = new SPParameter(1, new Reference(0));
+ param.setName("p1");//$NON-NLS-1$
+ proc.setParameter(param);
+ SPParameter param2 = new SPParameter(2, new Reference(0));
+ param2.setName("p2");//$NON-NLS-1$
+ proc.setParameter(param2);
+ helpTest(proc, "EXEC myproc(p1 => ?, p2 => ?)"); //$NON-NLS-1$
+ }
+
+ /**
+ * Test when a parameter's name is a reserved word.
+ * (Note: parameters should always have short names, not
+ * multiple period-delimited name components.)
+ *
+ * @since 4.3
+ */
+ public void testExecNamedParamsReservedWord() {
+ StoredProcedure proc = new StoredProcedure();
+ proc.setDisplayNamedParameters(true);
+ proc.setProcedureName("myproc"); //$NON-NLS-1$
+ SPParameter param = new SPParameter(1, new Reference(0));
+ param.setName("in");//$NON-NLS-1$
+ proc.setParameter(param);
+ SPParameter param2 = new SPParameter(2, new Reference(0));
+ param2.setName("in2");//$NON-NLS-1$
+ proc.setParameter(param2);
+ helpTest(proc, "EXEC myproc(\"in\" => ?, in2 => ?)"); //$NON-NLS-1$
+ }
+
+ // Test methods for Update Procedure Language Objects
+
+ 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() {
+ RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
+ helpTest(errStmt, "ERROR 'My Error';"); //$NON-NLS-1$
+ }
+
+ public void testRaiseErrorStatementWithExpression() {
+ RaiseErrorStatement errStmt = new RaiseErrorStatement(new ElementSymbol("a")); //$NON-NLS-1$
+ helpTest(errStmt, "ERROR a;"); //$NON-NLS-1$
+ }
+
+ 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() {
+ Query q1 = new Query();
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("x")); //$NON-NLS-1$
+ q1.setSelect(select);
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+ q1.setFrom(from);
+
+ AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), q1); //$NON-NLS-1$
+ helpTest(assigStmt, "a = (SELECT x FROM g);"); //$NON-NLS-1$
+ }
+
+ 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$
+ List elmnts = new ArrayList(3);
+ elmnts.add(sy1);
+ elmnts.add(sy2);
+ elmnts.add(sy3);
+ CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.COMPARE_EQ, elmnts);
+ helpTest(cs, "= CRITERIA ON (a, b, c)"); //$NON-NLS-1$
+ }
+
+ 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$
+ List elmnts = new ArrayList(3);
+ elmnts.add(sy1);
+ elmnts.add(sy2);
+ elmnts.add(sy3);
+ CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
+ helpTest(cs, "LIKE CRITERIA ON (x, y, z)"); //$NON-NLS-1$
+ }
+
+ 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$
+ List elmnts = new ArrayList(3);
+ elmnts.add(sy1);
+ elmnts.add(sy2);
+ elmnts.add(sy3);
+ CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.BETWEEN, elmnts);
+ helpTest(cs, "BETWEEN CRITERIA ON (x, y, z)"); //$NON-NLS-1$
+ }
+
+ 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$
+ List elmnts = new ArrayList(3);
+ elmnts.add(sy1);
+ elmnts.add(sy2);
+ elmnts.add(sy3);
+ CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
+ helpTest(new HasCriteria(cs), "HAS LIKE CRITERIA ON (x, y, z)"); //$NON-NLS-1$
+ }
+
+ 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$
+ List elmnts = new ArrayList(3);
+ elmnts.add(sy1);
+ elmnts.add(sy2);
+ elmnts.add(sy3);
+ CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
+ helpTest(new HasCriteria(cs), "HAS LIKE CRITERIA ON (x, y, z)"); //$NON-NLS-1$
+ }
+
+ 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$
+ List elmnts = new ArrayList(3);
+ elmnts.add(sy1);
+ elmnts.add(sy2);
+ elmnts.add(sy3);
+ CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.BETWEEN, elmnts);
+ helpTest(new HasCriteria(cs), "HAS BETWEEN CRITERIA ON (x, y, z)"); //$NON-NLS-1$
+ }
+
+ public void testCommandStatement1() {
+ Query q1 = new Query();
+ Select select = new Select();
+ select.addSymbol(new ElementSymbol("x")); //$NON-NLS-1$
+ q1.setSelect(select);
+ From from = new From();
+ from.addGroup(new GroupSymbol("g")); //$NON-NLS-1$
+ q1.setFrom(from);
+
+ CommandStatement cmdStmt = new CommandStatement(q1);
+ helpTest(cmdStmt, "SELECT x FROM g;"); //$NON-NLS-1$
+ }
+
+ 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() {
+ Delete d1 = new Delete();
+ d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
+ CommandStatement cmdStmt = new CommandStatement(d1);
+ AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), new Constant(new Integer(1))); //$NON-NLS-1$
+ RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
+ Block b = new Block();
+ b.addStatement(cmdStmt);
+ b.addStatement(assigStmt);
+ b.addStatement(errStmt);
+ helpTest(b, "BEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND"); //$NON-NLS-1$
+ }
+
+ public void testBlock2() {
+ // construct If statement
+
+ Delete d1 = new Delete();
+ d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
+ CommandStatement cmdStmt = new CommandStatement(d1);
+ Block ifblock = new Block(cmdStmt);
+ // construct If criteria
+ ElementSymbol sy1 = new ElementSymbol("x"); //$NON-NLS-1$
+ List elmnts = new ArrayList(1);
+ elmnts.add(sy1);
+ CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
+ Criteria crit = new HasCriteria(cs);
+ IfStatement ifStmt = new IfStatement(crit, ifblock);
+
+ // other statements
+ RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
+ Block b = new Block();
+ b.addStatement(cmdStmt);
+ b.addStatement(ifStmt);
+ b.addStatement(errStmt);
+
+ 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() {
+ // construct If block
+ Delete d1 = new Delete();
+ d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
+ CommandStatement cmdStmt = new CommandStatement(d1);
+ AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), new Constant(new Integer(1))); //$NON-NLS-1$
+ RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
+ Block ifblock = new Block();
+ ifblock.addStatement(cmdStmt);
+ ifblock.addStatement(assigStmt);
+ ifblock.addStatement(errStmt);
+
+ // construct If criteria
+ ElementSymbol sy1 = new ElementSymbol("x"); //$NON-NLS-1$
+ List elmnts = new ArrayList(1);
+ elmnts.add(sy1);
+ CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
+ Criteria crit = new HasCriteria(cs);
+
+ IfStatement ifStmt = new IfStatement(crit, ifblock);
+ helpTest(ifStmt, "IF(HAS LIKE CRITERIA ON (x))\nBEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND"); //$NON-NLS-1$
+ }
+
+ public void testIfStatement2() {
+ // construct If block
+ Delete d1 = new Delete();
+ d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
+ CommandStatement cmdStmt = new CommandStatement(d1);
+ Block ifblock = new Block(cmdStmt);
+
+ // construct If criteria
+ ElementSymbol sy1 = new ElementSymbol("x"); //$NON-NLS-1$
+ List elmnts = new ArrayList(1);
+ elmnts.add(sy1);
+ CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
+ Criteria crit = new HasCriteria(cs);
+
+ IfStatement ifStmt = new IfStatement(crit, ifblock);
+ helpTest(ifStmt, "IF(HAS LIKE CRITERIA ON (x))\nBEGIN\nDELETE FROM g;\nEND"); //$NON-NLS-1$
+ }
+
+ public void testIfStatement3() {
+ // construct If block
+ Delete d1 = new Delete();
+ d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
+ CommandStatement cmdStmt = new CommandStatement(d1);
+ AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), new Constant(new Integer(1))); //$NON-NLS-1$
+ RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
+ Block ifblock = new Block();
+ ifblock.addStatement(cmdStmt);
+ ifblock.addStatement(assigStmt);
+ ifblock.addStatement(errStmt);
+
+ // construct If criteria
+ ElementSymbol sy1 = new ElementSymbol("x"); //$NON-NLS-1$
+ List elmnts = new ArrayList(1);
+ elmnts.add(sy1);
+ CriteriaSelector cs = new CriteriaSelector(CriteriaSelector.LIKE, elmnts);
+ Criteria crit = new HasCriteria(cs);
+
+ Block elseblock = new Block();
+ elseblock.addStatement(cmdStmt);
+
+ IfStatement ifStmt = new IfStatement(crit, ifblock, elseblock);
+ 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() {
+ Delete d1 = new Delete();
+ d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
+ CommandStatement cmdStmt = new CommandStatement(d1);
+ AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), new Constant(new Integer(1))); //$NON-NLS-1$
+ RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
+ Block b = new Block();
+ b.addStatement(cmdStmt);
+ b.addStatement(assigStmt);
+ b.addStatement(errStmt);
+ CreateUpdateProcedureCommand cup = new CreateUpdateProcedureCommand(b);
+ helpTest(cup, "CREATE PROCEDURE\nBEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND"); //$NON-NLS-1$
+ }
+
+ public void testCreateUpdateProcedure2() {
+ Delete d1 = new Delete();
+ d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
+ CommandStatement cmdStmt = new CommandStatement(d1);
+ AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), new Constant(new Integer(1))); //$NON-NLS-1$
+ RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
+ Block b = new Block();
+ b.addStatement(cmdStmt);
+ b.addStatement(assigStmt);
+ b.addStatement(errStmt);
+ CreateUpdateProcedureCommand cup = new CreateUpdateProcedureCommand(b);
+ helpTest(cup, "CREATE PROCEDURE\nBEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND"); //$NON-NLS-1$
+ }
+
+ public void testCreateUpdateProcedure3() {
+ Delete d1 = new Delete();
+ d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
+ CommandStatement cmdStmt = new CommandStatement(d1);
+ AssignmentStatement assigStmt = new AssignmentStatement(new ElementSymbol("a"), new Constant(new Integer(1))); //$NON-NLS-1$
+ RaiseErrorStatement errStmt = new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
+ Block b = new Block();
+ b.addStatement(cmdStmt);
+ b.addStatement(assigStmt);
+ b.addStatement(errStmt);
+ CreateUpdateProcedureCommand cup = new CreateUpdateProcedureCommand(b);
+ helpTest(cup, "CREATE PROCEDURE\nBEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND"); //$NON-NLS-1$
+ }
+
+ public void testSubqueryCompareCriteria1() {
+
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ ElementSymbol expr = new ElementSymbol("e2"); //$NON-NLS-1$
+
+ SubqueryCompareCriteria scc = new SubqueryCompareCriteria(expr, q1, SubqueryCompareCriteria.EQ, SubqueryCompareCriteria.ANY);
+
+ helpTest(scc, "e2 = ANY (SELECT e1 FROM m.g1)"); //$NON-NLS-1$
+ }
+
+ public void testSubqueryCompareCriteria2() {
+
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ ElementSymbol expr = new ElementSymbol("e2"); //$NON-NLS-1$
+
+ SubqueryCompareCriteria scc = new SubqueryCompareCriteria(expr, q1, SubqueryCompareCriteria.LE, SubqueryCompareCriteria.SOME);
+
+ helpTest(scc, "e2 <= SOME (SELECT e1 FROM m.g1)"); //$NON-NLS-1$
+ }
+
+ public void testExistsCriteria1() {
+
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ ExistsCriteria ec = new ExistsCriteria(q1);
+
+ helpTest(ec, "EXISTS (SELECT e1 FROM m.g1)"); //$NON-NLS-1$
+ }
+
+ public void testDynamicCommand() {
+ List symbols = new ArrayList();
+
+ ElementSymbol a1 = new ElementSymbol("a1"); //$NON-NLS-1$
+ a1.setType(DataTypeManager.DefaultDataClasses.STRING);
+ symbols.add(a1);
+
+ DynamicCommand obj = new DynamicCommand();
+ Expression sql = new Constant("SELECT a1 FROM g WHERE a2 = 5"); //$NON-NLS-1$
+
+ obj.setSql(sql);
+ obj.setAsColumns(symbols);
+ obj.setAsClauseSet(true);
+ obj.setIntoGroup(new GroupSymbol("#g")); //$NON-NLS-1$
+
+ helpTest(obj, "EXECUTE 'SELECT a1 FROM g WHERE a2 = 5' AS a1 string INTO #g"); //$NON-NLS-1$
+ }
+
+ public void testScalarSubquery() {
+
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ ScalarSubquery obj = new ScalarSubquery(q1);
+
+ helpTest(obj, "(SELECT e1 FROM m.g1)"); //$NON-NLS-1$
+ }
+
+ public void testNewSubqueryObjects(){
+
+ Select s1 = new Select();
+ s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ From f1 = new From();
+ f1.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+ q1.setFrom(f1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
+ s2.addSymbol(new ExpressionSymbol("blargh", new ScalarSubquery(q1))); //$NON-NLS-1$
+ From f2 = new From();
+ f2.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
+ Criteria left = new SubqueryCompareCriteria(new ElementSymbol("e3"), q1, SubqueryCompareCriteria.GE, SubqueryCompareCriteria.ANY); //$NON-NLS-1$
+ Criteria right = new ExistsCriteria(q1);
+ Criteria outer = new CompoundCriteria(CompoundCriteria.AND, left, right);
+ Query q2 = new Query();
+ q2.setSelect(s2);
+ q2.setFrom(f2);
+ q2.setCriteria(outer);
+
+ 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() {
+ helpTest(TestCaseExpression.example(2),
+ "CASE x WHEN 'a' THEN 0 WHEN 'b' THEN 1 ELSE 9999 END"); //$NON-NLS-1$
+ }
+
+ 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() {
+ 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() {
+ 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() {
+ helpTest(TestSearchedCaseExpression.example(2),
+ "CASE WHEN x = 0 THEN 0 WHEN x = 1 THEN 1 ELSE 9999 END"); //$NON-NLS-1$
+
+ }
+
+ public void testSearchedCaseExpression2() {
+ SearchedCaseExpression example = TestSearchedCaseExpression.example(2);
+ example.setElseExpression(null);
+ helpTest(example,
+ "CASE WHEN x = 0 THEN 0 WHEN x = 1 THEN 1 END"); //$NON-NLS-1$
+
+ }
+
+ /**
+ * For some reason this test was outputting
+ * SELECT 'A' AS FOO UNION SELECT 'A' AS FOO
+ */
+ public void testSetQueryUnionOfLiteralsCase3102() {
+
+ String expected = "SELECT 'A' AS FOO UNION SELECT 'B' AS FOO"; //$NON-NLS-1$
+
+ Select s1 = new Select();
+ s1.addSymbol(new AliasSymbol("FOO", new ExpressionSymbol("xxx", new Constant("A")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new AliasSymbol("FOO", new ExpressionSymbol("xxx", new Constant("B")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+
+ SetQuery sq = new SetQuery(Operation.UNION, false, q1, q2);
+
+ helpTest(sq, expected);
+ }
+
+ /**
+ * For some reason this test was outputting
+ * SELECT 'A' AS FOO UNION SELECT 'A' AS FOO
+ * Same as above except that ExpressionSymbols' internal names (which aren't visible
+ * in the query) are different
+ */
+ public void testSetQueryUnionOfLiteralsCase3102a() {
+
+ String expected = "SELECT 'A' AS FOO UNION SELECT 'B' AS FOO"; //$NON-NLS-1$
+
+ Select s1 = new Select();
+ s1.addSymbol(new AliasSymbol("FOO", new ExpressionSymbol("xxx", new Constant("A")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Query q1 = new Query();
+ q1.setSelect(s1);
+
+ Select s2 = new Select();
+ s2.addSymbol(new AliasSymbol("FOO", new ExpressionSymbol("yyy", new Constant("B")))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Query q2 = new Query();
+ q2.setSelect(s2);
+
+ SetQuery sq = new SetQuery(Operation.UNION, false, q1, q2);
+
+ helpTest(sq, expected);
+ }
+
+ public void testLimit() {
+ Query query = new Query();
+ Select select = new Select(Arrays.asList(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(query, "SELECT * FROM a LIMIT 100"); //$NON-NLS-1$
+ }
+
+ public void testLimitWithOffset() {
+ Query query = new Query();
+ Select select = new Select(Arrays.asList(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(query, "SELECT * FROM a LIMIT 50, 100"); //$NON-NLS-1$
+ }
+
+ 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, 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 {
+ 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, 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 {
+ Command command = QueryParser.getQueryParser().parseCommand("select pm1.g1.e1 as a from pm1.g1 order by a"); //$NON-NLS-1$
+ 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 {
+ Command command = QueryParser.getQueryParser().parseCommand("select pm1.g1.e1 as a from pm1.g1 order by 1"); //$NON-NLS-1$
+ QueryResolver.resolveCommand(command, RealMetadataFactory.example1Cached());
+ helpTest(command, "SELECT pm1.g1.e1 AS a FROM pm1.g1 ORDER BY 1"); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFacade.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFacade.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFacade.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFactory.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/FakeMetadataObject.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/unittest/FakeMetadataObject.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/FakeMetadataObject.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/FakeMetadataStore.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/unittest/FakeMetadataStore.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/FakeMetadataStore.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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);
- }
-
-}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,671 +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.List;
-
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.metadata.Column;
-import org.teiid.metadata.ColumnSet;
-import org.teiid.metadata.ForeignKey;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.FunctionParameter;
-import org.teiid.metadata.KeyRecord;
-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.metadata.ProcedureParameter.Type;
-import org.teiid.query.function.FunctionTree;
-import org.teiid.query.function.UDFSource;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.metadata.CompositeMetadataStore;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TransformationMetadata;
-import org.teiid.query.sql.lang.SPParameter;
-
- at SuppressWarnings("nls")
-public class RealMetadataFactory {
-
- private static TransformationMetadata CACHED_BQT = exampleBQT();
-
- private RealMetadataFactory() { }
-
- public static TransformationMetadata exampleBQTCached() {
- return CACHED_BQT;
- }
- public static MetadataStore exampleBQTStore() {
- MetadataStore metadataStore = new MetadataStore();
-
- Schema bqt1 = createPhysicalModel("BQT1", metadataStore); //$NON-NLS-1$
- Schema bqt2 = createPhysicalModel("BQT2", metadataStore); //$NON-NLS-1$
- Schema bqt3 = createPhysicalModel("BQT3", metadataStore); //$NON-NLS-1$
- Schema lob = createPhysicalModel("LOB", metadataStore); //$NON-NLS-1$
- Schema vqt = createVirtualModel("VQT", metadataStore); //$NON-NLS-1$
- Schema bvqt = createVirtualModel("BQT_V", metadataStore); //$NON-NLS-1$
- Schema bvqt2 = createVirtualModel("BQT2_V", metadataStore); //$NON-NLS-1$
-
- // Create physical groups
- Table bqt1SmallA = createPhysicalGroup("SmallA", bqt1); //$NON-NLS-1$
- Table bqt1SmallB = createPhysicalGroup("SmallB", bqt1); //$NON-NLS-1$
- Table bqt1MediumA = createPhysicalGroup("MediumA", bqt1); //$NON-NLS-1$
- Table bqt1MediumB = createPhysicalGroup("MediumB", bqt1); //$NON-NLS-1$
- Table bqt2SmallA = createPhysicalGroup("SmallA", bqt2); //$NON-NLS-1$
- Table bqt2SmallB = createPhysicalGroup("SmallB", bqt2); //$NON-NLS-1$
- Table bqt2MediumA = createPhysicalGroup("MediumA", bqt2); //$NON-NLS-1$
- Table bqt2MediumB = createPhysicalGroup("MediumB", bqt2); //$NON-NLS-1$
- Table bqt3SmallA = createPhysicalGroup("SmallA", bqt3); //$NON-NLS-1$
- Table bqt3SmallB = createPhysicalGroup("SmallB", bqt3); //$NON-NLS-1$
- Table bqt3MediumA = createPhysicalGroup("MediumA", bqt3); //$NON-NLS-1$
- Table bqt3MediumB = createPhysicalGroup("MediumB", bqt3); //$NON-NLS-1$
- Table lobTable = createPhysicalGroup("LobTbl", lob); //$NON-NLS-1$
- Table library = createPhysicalGroup("LOB_TESTING_ONE", lob); //$NON-NLS-1$
-
- createElements( library, new String[] { "CLOB_COLUMN", "BLOB_COLUMN", "KEY_EMULATOR" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- new String[] { DataTypeManager.DefaultDataTypes.CLOB, DataTypeManager.DefaultDataTypes.BLOB, DataTypeManager.DefaultDataTypes.INTEGER });
-
- // Create virtual groups
- QueryNode vqtn1 = new QueryNode("SELECT * FROM BQT1.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg1 = createUpdatableVirtualGroup("SmallA", vqt, vqtn1); //$NON-NLS-1$
-
- QueryNode vqtn2 = new QueryNode("SELECT Concat(stringKey, stringNum) as a12345 FROM BQT1.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg2 = createUpdatableVirtualGroup("SmallB", vqt, vqtn2); //$NON-NLS-1$
-
- // Case 2589
- QueryNode vqtn2589 = new QueryNode("SELECT * FROM BQT1.SmallA WHERE StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg2589 = createVirtualGroup("SmallA_2589", vqt, vqtn2589); //$NON-NLS-1$
-
- QueryNode vqtn2589a = new QueryNode("SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.IntKey = SmallB.IntKey WHERE SmallA.StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg2589a = createVirtualGroup("SmallA_2589a", vqt, vqtn2589a); //$NON-NLS-1$
-
- QueryNode vqtn2589b = new QueryNode("SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE SmallA.StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg2589b = createVirtualGroup("SmallA_2589b", vqt, vqtn2589b); //$NON-NLS-1$
-
- QueryNode vqtn2589c = new QueryNode("SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE concat(SmallA.StringNum, SmallB.StringNum) = '1010'"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg2589c = createVirtualGroup("SmallA_2589c", vqt, vqtn2589c); //$NON-NLS-1$
-
- QueryNode vqtn2589d = new QueryNode("SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE SmallA.StringNum = '10' AND SmallA.IntNum = 10"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg2589d = createVirtualGroup("SmallA_2589d", vqt, vqtn2589d); //$NON-NLS-1$
-
- QueryNode vqtn2589f = new QueryNode("SELECT * FROM VQT.SmallA_2589"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg2589f = createVirtualGroup("SmallA_2589f", vqt, vqtn2589f); //$NON-NLS-1$
-
- QueryNode vqtn2589g = new QueryNode("SELECT * FROM SmallA_2589b"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg2589g = createVirtualGroup("SmallA_2589g", vqt, vqtn2589g); //$NON-NLS-1$
-
- QueryNode vqtn2589h = new QueryNode("SELECT VQT.SmallA_2589.* FROM VQT.SmallA_2589 INNER JOIN BQT1.SmallB ON VQT.SmallA_2589.StringKey = SmallB.StringKey"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg2589h = createVirtualGroup("SmallA_2589h", vqt, vqtn2589h); //$NON-NLS-1$
-
- QueryNode vqtn2589i = new QueryNode("SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE SmallA.StringNum = '10' AND SmallB.StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg2589i = createVirtualGroup("SmallA_2589i", vqt, vqtn2589i); //$NON-NLS-1$
-
- // defect 15355
- QueryNode vqtn15355 = new QueryNode("SELECT convert(IntKey, string) as StringKey, BigIntegerValue FROM BQT1.SmallA UNION SELECT StringKey, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg15355 = createVirtualGroup("Defect15355", vqt, vqtn15355); //$NON-NLS-1$
- QueryNode vqtn15355a = new QueryNode("SELECT StringKey, StringNum, BigIntegerValue FROM BQT1.SmallA UNION SELECT StringKey, StringNum, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg15355a = createVirtualGroup("Defect15355a", vqt, vqtn15355a); //$NON-NLS-1$
- QueryNode vqtn15355b = new QueryNode("SELECT convert(IntKey, string) as IntKey, BigIntegerValue FROM BQT1.SmallA UNION SELECT StringKey, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vqtg15355b = createVirtualGroup("Defect15355b", vqt, vqtn15355b); //$NON-NLS-1$
-
- QueryNode bvqtn1 = new QueryNode("SELECT a.* FROM BQT1.SMALLA AS a WHERE a.INTNUM = (SELECT MIN(b.INTNUM) FROM BQT1.SMALLA AS b WHERE b.INTKEY = a.IntKey ) OPTION MAKEDEP a"); //$NON-NLS-1$ //$NON-NLS-2$
- Table bvqtg1 = createUpdatableVirtualGroup("BQT_V", bvqt, bvqtn1); //$NON-NLS-1$
- QueryNode bvqt2n1 = new QueryNode("SELECT BQT2.SmallA.* FROM BQT2.SmallA, BQT_V.BQT_V WHERE BQT2.SmallA.IntKey = BQT_V.BQT_V.IntKey"); //$NON-NLS-1$ //$NON-NLS-2$
- Table bvqt2g1 = createUpdatableVirtualGroup("BQT2_V", bvqt2, bvqt2n1); //$NON-NLS-1$
-
- // Create physical elements
- String[] elemNames = new String[] {
- "IntKey", "StringKey", //$NON-NLS-1$ //$NON-NLS-2$
- "IntNum", "StringNum", //$NON-NLS-1$ //$NON-NLS-2$
- "FloatNum", "LongNum", //$NON-NLS-1$ //$NON-NLS-2$
- "DoubleNum", "ByteNum", //$NON-NLS-1$ //$NON-NLS-2$
- "DateValue", "TimeValue", //$NON-NLS-1$ //$NON-NLS-2$
- "TimestampValue", "BooleanValue", //$NON-NLS-1$ //$NON-NLS-2$
- "CharValue", "ShortValue", //$NON-NLS-1$ //$NON-NLS-2$
- "BigIntegerValue", "BigDecimalValue", //$NON-NLS-1$ //$NON-NLS-2$
- "ObjectValue" }; //$NON-NLS-1$
- String[] elemTypes = new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.FLOAT, DataTypeManager.DefaultDataTypes.LONG,
- DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.BYTE,
- DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME,
- DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.DefaultDataTypes.BOOLEAN,
- DataTypeManager.DefaultDataTypes.CHAR, DataTypeManager.DefaultDataTypes.SHORT,
- DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.BIG_DECIMAL,
- DataTypeManager.DefaultDataTypes.OBJECT };
-
- List<Column> bqt1SmallAe = createElements(bqt1SmallA, elemNames, elemTypes);
- bqt1SmallAe.get(1).setNativeType("char"); //$NON-NLS-1$
- createElements(bqt1SmallB, elemNames, elemTypes);
- createElements(bqt1MediumA, elemNames, elemTypes);
- createElements(bqt1MediumB, elemNames, elemTypes);
- createElements(bqt2SmallA, elemNames, elemTypes);
- createElements(bqt2SmallB, elemNames, elemTypes);
- createElements(bqt2MediumA, elemNames, elemTypes);
- createElements(bqt2MediumB, elemNames, elemTypes);
- createElements(bqt3SmallA, elemNames, elemTypes);
- createElements(bqt3SmallB, elemNames, elemTypes);
- createElements(bqt3MediumA, elemNames, elemTypes);
- createElements(bqt3MediumB, elemNames, elemTypes);
- createElements(lobTable, new String[] {"ClobValue"}, new String[] {DataTypeManager.DefaultDataTypes.CLOB}); //$NON-NLS-1$
-
- // Create virtual elements
- createElements(vqtg1, elemNames, elemTypes);
- createElements(vqtg2, new String[] {"a12345"}, new String[] {DataTypeManager.DefaultDataTypes.STRING}); //$NON-NLS-1$
- createElements(vqtg15355, new String[] {"StringKey", "BigIntegerValue"}, new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_INTEGER}); //$NON-NLS-1$ //$NON-NLS-2$
- createElements(vqtg15355a, new String[] {"StringKey", "StringNum", "BigIntegerValue"}, new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_INTEGER}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- createElements(vqtg15355b, new String[] {"IntKey", "BigIntegerValue"}, new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_INTEGER}); //$NON-NLS-1$ //$NON-NLS-2$
- createElements(vqtg2589, elemNames, elemTypes);
- createElements(vqtg2589a, elemNames, elemTypes);
- createElements(vqtg2589b, elemNames, elemTypes);
- createElements(vqtg2589c, elemNames, elemTypes);
- createElements(vqtg2589d, elemNames, elemTypes);
- createElements(vqtg2589f, elemNames, elemTypes);
- createElements(vqtg2589g, elemNames, elemTypes);
- createElements(vqtg2589h, elemNames, elemTypes);
- createElements(vqtg2589i, elemNames, elemTypes);
- createElements(bvqtg1, elemNames, elemTypes);
- createElements(bvqt2g1, elemNames, elemTypes);
-
- // Add stored procedure
- 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$
- 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$
- 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$
- 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$
-
- 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$
- spTest11.setResultSet(rs3);
-
- //add virtual stored procedures
- Schema mmspTest1 = createVirtualModel("mmspTest1", metadataStore); //$NON-NLS-1$
- ColumnSet<Procedure> vsprs1 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
- QueryNode vspqn1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT intkey FROM bqt1.smallA) AS intKeyCursor BEGIN x= intKeyCursor.intkey - 1; END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
- Procedure vsp1 = createVirtualProcedure("MMSP1", mmspTest1, null, vspqn1); //$NON-NLS-1$
- vsp1.setResultSet(vsprs1);
-
- ColumnSet<Procedure> vsprs2 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
- QueryNode vspqn2 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT intkey FROM bqt1.smallA) AS intKeyCursor1 BEGIN LOOP ON (SELECT intkey FROM bqt1.smallB) AS intKeyCursor2 BEGIN x= intKeyCursor1.intkey - intKeyCursor2.intkey; END END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
- Procedure vsp2 = createVirtualProcedure("MMSP2", mmspTest1, null, vspqn2); //$NON-NLS-1$
- vsp2.setResultSet(vsprs2);
-
- ColumnSet<Procedure> vsprs3 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
- QueryNode vspqn3 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT intkey FROM bqt1.smallA) AS intKeyCursor BEGIN x= intKeyCursor.intkey - 1; if(x = 25) BEGIN BREAK; END ELSE BEGIN CONTINUE; END END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
- Procedure vsp3 = createVirtualProcedure("MMSP3", mmspTest1, null, vspqn3); //$NON-NLS-1$
- vsp3.setResultSet(vsprs3);
-
- ColumnSet<Procedure> vsprs4 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
- QueryNode vspqn4 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x=0; WHILE(x < 50) BEGIN x= x + 1; if(x = 25) BEGIN BREAK; END ELSE BEGIN CONTINUE; END END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
- Procedure vsp4 = createVirtualProcedure("MMSP4", mmspTest1, null, vspqn4); //$NON-NLS-1$
- vsp4.setResultSet(vsprs4);
-
- ColumnSet<Procedure> vsprs5 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
- ProcedureParameter vsp5p1 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
- QueryNode vspqn5 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT 0; END"); //$NON-NLS-1$ //$NON-NLS-2$
- Procedure vsp5 = createVirtualProcedure("MMSP5", mmspTest1, Arrays.asList(vsp5p1), vspqn5); //$NON-NLS-1$
- vsp5.setResultSet(vsprs5);
-
- ColumnSet<Procedure> vsprs6 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
- ProcedureParameter vsp6p1 = createParameter("p1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
- QueryNode vspqn6 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT p1 as StringKey; END"); //$NON-NLS-1$ //$NON-NLS-2$
- Procedure vsp6 = createVirtualProcedure("MMSP6", mmspTest1, Arrays.asList(vsp6p1), vspqn6); //$NON-NLS-1$
- 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$
-
- 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$
- QueryNode vspqn7 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN declare integer x; x = exec spTest9(p1); declare integer y; exec spTest11(inkey=>x, outkey=>y); select convert(x, string) || y; END"); //$NON-NLS-1$ //$NON-NLS-2$
- Procedure vsp7 = createVirtualProcedure("TEIIDSP7", mmspTest1, Arrays.asList(vsp7p1), vspqn7); //$NON-NLS-1$
- vsp7.setResultSet(vsprs7);
-
- ProcedureParameter vsp8p1 = createParameter("r", ParameterInfo.RETURN_VALUE, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
- ProcedureParameter vsp8p2 = createParameter("p1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
- QueryNode vspqn8 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN r = p1; END"); //$NON-NLS-1$ //$NON-NLS-2$
- createVirtualProcedure("TEIIDSP8", mmspTest1, Arrays.asList(vsp8p1, vsp8p2), vspqn8); //$NON-NLS-1$
-
- ColumnSet<Procedure> vsprs9 = createResultSet("TEIIDSP9.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
- ProcedureParameter vsp9p1 = createParameter("r", ParameterInfo.RETURN_VALUE, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
- vsp9p1.setNullType(NullType.No_Nulls);
- ProcedureParameter vsp9p2 = createParameter("p1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
- ProcedureParameter vsp9p3 = createParameter("p2", ParameterInfo.OUT, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
- QueryNode vspqn9 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN if (p1 = 1) begin\n r = 1; end\n p2 = 10; select 'hello'; END"); //$NON-NLS-1$ //$NON-NLS-2$
- Procedure vsp9 = createVirtualProcedure("TEIIDSP9", mmspTest1, Arrays.asList(vsp9p1, vsp9p2, vsp9p3), vspqn9); //$NON-NLS-1$
- vsp9.setResultSet(vsprs9);
-
- // this is for the source added function
- bqt1.addFunction(new FunctionMethod("reverse", "reverse", "misc", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- new FunctionParameter[] {new FunctionParameter("columnName", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
- new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
- return metadataStore;
- }
-
- public static TransformationMetadata exampleBQT() {
- return createTransformationMetadata(exampleBQTStore(), "bqt");
- }
-
-
- public static TransformationMetadata createTransformationMetadata(MetadataStore metadataStore, String vdbName) {
- CompositeMetadataStore store = new CompositeMetadataStore(metadataStore);
- VDBMetaData vdbMetaData = new VDBMetaData();
- vdbMetaData.setName(vdbName); //$NON-NLS-1$
- vdbMetaData.setVersion(1);
- List<FunctionTree> udfs = new ArrayList<FunctionTree>();
- for (Schema schema : metadataStore.getSchemas().values()) {
- vdbMetaData.addModel(FakeMetadataFactory.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);
- }
-
- /**
- * Metadata for Materialized Views
- * @return
- * @since 4.2
- */
- public static QueryMetadataInterface exampleMaterializedView() {
- MetadataStore metadataStore = new MetadataStore();
- Schema virtModel = createVirtualModel("MatView", metadataStore); //$NON-NLS-1$
- Schema physModel = createPhysicalModel("MatTable", metadataStore); //$NON-NLS-1$
- Schema physModel_virtSrc = createPhysicalModel("MatSrc", metadataStore); //$NON-NLS-1$
-
- Table physTable = createPhysicalGroup("info", physModel); //$NON-NLS-1$
- createElements(physTable,
- new String[] { "e1", "e2", "e3"}, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-
- Table physGroup = createPhysicalGroup("MatTable", physModel); //$NON-NLS-1$
- createElements(physGroup,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING});
-
- Table physGroupStage = createPhysicalGroup("MatStage", physModel); //$NON-NLS-1$
- createElements(physGroupStage,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING});
-
- Table physGroup1 = createPhysicalGroup("MatTable1", physModel); //$NON-NLS-1$
- createElements(physGroup1,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING});
-
- Table physGroupStage1 = createPhysicalGroup("MatStage1", physModel); //$NON-NLS-1$
- createElements(physGroupStage,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING});
-
- Table physGroup_virtSrc = createPhysicalGroup("MatSrc", physModel_virtSrc); //$NON-NLS-1$
- createElements(physGroup_virtSrc,
- new String[] { "X" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING});
-
- QueryNode virtTrans = new QueryNode("SELECT x as e1 FROM MatSrc.MatSrc"); //$NON-NLS-1$ //$NON-NLS-2$
- Table virtGroup = createVirtualGroup("MatView", virtModel, virtTrans); //$NON-NLS-1$
- createElements(virtGroup,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING});
-
- virtGroup.setMaterialized(true);
- virtGroup.setMaterializedTable(physGroup);
- virtGroup.setMaterializedStageTable(physGroupStage);
-
- //add one virtual group that uses the materialized group in transformation with NOCACHE option
- QueryNode vTrans = new QueryNode("SELECT e1 FROM MatView.MatView option NOCACHE"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vGroup = createVirtualGroup("VGroup", virtModel, vTrans); //$NON-NLS-1$
- createElements(vGroup,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING});
-
- QueryNode virtTrans1 = new QueryNode("SELECT e1 FROM MatView.MatView where e1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
- Table virtGroup1 = createVirtualGroup("MatView1", virtModel, virtTrans1); //$NON-NLS-1$
- createElements(virtGroup1,
- new String[] { "e1" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING});
-
- virtGroup1.setMaterializedTable(physGroup1);
- virtGroup1.setMaterializedStageTable(physGroupStage1);
-
- QueryNode vTrans2 = new QueryNode("SELECT x FROM matsrc"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vGroup2 = createVirtualGroup("VGroup2", virtModel, vTrans2); //$NON-NLS-1$
- vGroup2.setMaterialized(true);
- createElements(vGroup2,
- new String[] { "x" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING});
-
- //covering index
- QueryNode vTrans3 = new QueryNode("SELECT x, 'z' || substring(x, 2) as y FROM matsrc"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vGroup3 = createVirtualGroup("VGroup3", virtModel, vTrans3); //$NON-NLS-1$
- vGroup3.setMaterialized(true);
- List<Column> vElements3 = createElements(vGroup3,
- new String[] { "x", "y" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
- createKey(KeyRecord.Type.Primary, "pk", vGroup3, vElements3.subList(0, 1));
- createKey(KeyRecord.Type.Index, "idx", vGroup3, vElements3.subList(1, 2));
-
- QueryNode vTrans4 = new QueryNode("/*+ cache(ttl:100) */ SELECT x FROM matsrc"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vGroup4 = createVirtualGroup("VGroup4", virtModel, vTrans4); //$NON-NLS-1$
- vGroup4.setMaterialized(true);
- createElements(vGroup4,
- new String[] { "x" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING});
-
- //non-covering index
- QueryNode vTrans5 = new QueryNode("SELECT x, 'z' || substring(x, 2) as y, 1 as z FROM matsrc"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vGroup5 = createVirtualGroup("VGroup5", virtModel, vTrans5); //$NON-NLS-1$
- vGroup5.setMaterialized(true);
- List<Column> vElements5 = createElements(vGroup5,
- new String[] { "x", "y", "z" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
-
- createKey(KeyRecord.Type.Primary, "pk", vGroup5, vElements5.subList(0, 1));
- createKey(KeyRecord.Type.Index, "idx", vGroup5, vElements5.subList(1, 2));
-
- //no pk
- QueryNode vTrans6 = new QueryNode("SELECT x, 'z' || substring(x, 2) as y FROM matsrc"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vGroup6 = createVirtualGroup("VGroup6", virtModel, vTrans6); //$NON-NLS-1$
- vGroup6.setMaterialized(true);
- List<Column> vElements6 = createElements(vGroup6,
- new String[] { "x", "y" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
- createKey(KeyRecord.Type.Index, "idx", vGroup6, vElements6.subList(1, 2));
-
- //non-covering index
- QueryNode vTrans7 = new QueryNode("SELECT '1', 'z' || substring(x, 2) as y, 1 as z FROM matsrc"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vGroup7 = createVirtualGroup("VGroup7", virtModel, vTrans7); //$NON-NLS-1$
- vGroup7.setMaterialized(true);
- List<Column> vElements7 = createElements(vGroup7,
- new String[] { "x", "y", "z" }, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
-
- createKey(KeyRecord.Type.Primary, "pk", vGroup7, vElements7.subList(1, 2));
-
- Schema sp = createVirtualModel("sp", metadataStore); //$NON-NLS-1$
- ColumnSet<Procedure> rs = createResultSet("sp1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
- ProcedureParameter param = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
- param.setNullType(NullType.Nullable);
- QueryNode sp1qn = new QueryNode("/*+ cache */ CREATE VIRTUAL PROCEDURE BEGIN SELECT x as StringKey from matsrc where x = param1; END"); //$NON-NLS-1$ //$NON-NLS-2$
- Procedure vsp5 = createVirtualProcedure("sp1", sp, Arrays.asList(param), sp1qn); //$NON-NLS-1$
- vsp5.setResultSet(rs);
-
- return createTransformationMetadata(metadataStore, "");
- }
-
- /**
- * 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 KeyRecord createKey(KeyRecord.Type type, String name, Table group, List<Column> elements) {
- KeyRecord key = new KeyRecord(type);
- key.setName(name);
- for (Column column : elements) {
- key.addColumn(column);
- }
- switch (type) {
- case Primary:
- group.setPrimaryKey(key);
- break;
- case Index:
- group.getIndexes().add(key);
- break;
- case Unique:
- group.getUniqueKeys().add(key);
- break;
- default:
- throw new AssertionError("TODO");
- }
- return key;
- }
-
- public static ForeignKey createForeignKey(String name, Table group, List<Column> elements, KeyRecord primaryKey) {
- ForeignKey key = new ForeignKey();
- key.setName(name);
- for (Column column : elements) {
- key.addColumn(column);
- }
- key.setPrimaryKey(primaryKey);
- group.getForeignKeys().add(key);
- return key;
- }
-
- /**
- * Create a physical model with default settings.
- */
- public static Schema createPhysicalModel(String name, MetadataStore metadataStore) {
- Schema schema = new Schema();
- schema.setName(name);
- metadataStore.addSchema(schema);
- return schema;
- }
-
- /**
- * Create a virtual model with default settings.
- */
- public static Schema createVirtualModel(String name, MetadataStore metadataStore) {
- Schema schema = new Schema();
- schema.setName(name);
- schema.setPhysical(false);
- metadataStore.addSchema(schema);
- return schema;
- }
-
- /**
- * 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 Table createPhysicalGroup(String name, Schema model, boolean fullyQualify) {
- Table table = new Table();
- table.setName(name);
- model.addTable(table);
- table.setSupportsUpdate(true);
- table.setNameInSource((fullyQualify || name.lastIndexOf(".") == -1)? name : name.substring(name.lastIndexOf(".") + 1)); //$NON-NLS-1$ //$NON-NLS-2$
- return table;
- }
-
- public static Table createPhysicalGroup(String name, Schema model) {
- return createPhysicalGroup(name, model, false);
- }
-
- /**
- * Create a virtual group with default settings.
- */
- public static Table createVirtualGroup(String name, Schema model, QueryNode plan) {
- Table table = new Table();
- table.setName(name);
- model.addTable(table);
- table.setVirtual(true);
- table.setSelectTransformation(plan.getQuery());
- return table;
- }
-
- /**
- * Create a virtual group that allows updates with default settings.
- */
- public static Table createUpdatableVirtualGroup(String name, Schema model, QueryNode plan) {
- return createUpdatableVirtualGroup(name, model, plan, null);
- }
-
- public static Table createUpdatableVirtualGroup(String name, Schema model, QueryNode plan, String updatePlan) {
- Table table = createVirtualGroup(name, model, plan);
- table.setUpdatePlan(updatePlan);
- table.setSupportsUpdate(true);
- return table;
- }
-
- public static Column createElement(String name, ColumnSet<?> group, String type) {
- Column column = new Column();
- column.setName(name);
- group.addColumn(column);
- column.setRuntimeType(type);
- if(type.equals(DataTypeManager.DefaultDataTypes.STRING)) {
- column.setSearchType(SearchType.Searchable);
- } else if (DataTypeManager.isNonComparable(type)){
- column.setSearchType(SearchType.Unsearchable);
- } else {
- column.setSearchType(SearchType.All_Except_Like);
- }
- column.setNullType(NullType.Nullable);
- column.setPosition(group.getColumns().size()); //1 based indexing
- column.setUpdatable(true);
- column.setLength(100);
- column.setNameInSource(name);
- return column;
- }
-
- /**
- * Create a set of elements in batch
- */
- public static List<Column> createElements(ColumnSet<?> group, String[] names, String[] types) {
- return createElementsWithDefaults(group, names, types, new String[names.length]);
- }
-
- /**
- * Create a set of elements in batch
- */
- public static List<Column> createElementsWithDefaults(ColumnSet<?> group, String[] names, String[] types, String[] defaults) {
- List<Column> elements = new ArrayList<Column>();
-
- for(int i=0; i<names.length; i++) {
- Column element = createElement(names[i], group, types[i]);
- element.setDefaultValue(defaults[i]);
- elements.add(element);
- }
-
- return elements;
- }
-
- /**
- * Create stored procedure parameter.
- */
- public static ProcedureParameter createParameter(String name, int direction, String type) {
- ProcedureParameter param = new ProcedureParameter();
- param.setName(name);
- switch (direction) {
- case SPParameter.IN:
- param.setType(Type.In);
- break;
- case SPParameter.INOUT:
- param.setType(Type.InOut);
- break;
- case SPParameter.OUT:
- param.setType(Type.Out);
- break;
- case SPParameter.RESULT_SET:
- throw new AssertionError("should not directly create a resultset param"); //$NON-NLS-1$
- case SPParameter.RETURN_VALUE:
- param.setType(Type.ReturnValue);
- break;
- }
- param.setRuntimeType(type);
- return param;
- }
-
- /**
- * 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
- * @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) {
- Procedure proc = new Procedure();
- proc.setName(name);
- if (params != null) {
- int index = 1;
- for (ProcedureParameter procedureParameter : params) {
- procedureParameter.setProcedure(proc);
- procedureParameter.setPosition(index++);
- }
- proc.setParameters(params);
- }
- model.addProcedure(proc);
- return proc;
- }
-
- /**
- * 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 Procedure createVirtualProcedure(String name, Schema model, List<ProcedureParameter> params, QueryNode queryPlan) {
- Procedure proc = createStoredProcedure(name, model, params, null);
- proc.setVirtual(true);
- proc.setQueryPlan(queryPlan.getQuery());
- return proc;
- }
-
- /**
- * Create a result set.
- */
- public static ColumnSet<Procedure> createResultSet(String name, String[] colNames, String[] colTypes) {
- ColumnSet<Procedure> rs = new ColumnSet<Procedure>();
- rs.setName(name);
- for(Column column : createElements(rs, colNames, colTypes)) {
- column.setParent(rs);
- }
- return rs;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,2729 @@
+/*
+ * 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.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;
+import org.teiid.metadata.FunctionMethod;
+import org.teiid.metadata.FunctionParameter;
+import org.teiid.metadata.KeyRecord;
+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.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;
+
+ at SuppressWarnings("nls")
+public class RealMetadataFactory {
+
+ 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();
+
+ Schema bqt1 = createPhysicalModel("BQT1", metadataStore); //$NON-NLS-1$
+ Schema bqt2 = createPhysicalModel("BQT2", metadataStore); //$NON-NLS-1$
+ Schema bqt3 = createPhysicalModel("BQT3", metadataStore); //$NON-NLS-1$
+ Schema lob = createPhysicalModel("LOB", metadataStore); //$NON-NLS-1$
+ Schema vqt = createVirtualModel("VQT", metadataStore); //$NON-NLS-1$
+ Schema bvqt = createVirtualModel("BQT_V", metadataStore); //$NON-NLS-1$
+ Schema bvqt2 = createVirtualModel("BQT2_V", metadataStore); //$NON-NLS-1$
+
+ // Create physical groups
+ Table bqt1SmallA = createPhysicalGroup("SmallA", bqt1); //$NON-NLS-1$
+ Table bqt1SmallB = createPhysicalGroup("SmallB", bqt1); //$NON-NLS-1$
+ Table bqt1MediumA = createPhysicalGroup("MediumA", bqt1); //$NON-NLS-1$
+ Table bqt1MediumB = createPhysicalGroup("MediumB", bqt1); //$NON-NLS-1$
+ Table bqt2SmallA = createPhysicalGroup("SmallA", bqt2); //$NON-NLS-1$
+ Table bqt2SmallB = createPhysicalGroup("SmallB", bqt2); //$NON-NLS-1$
+ Table bqt2MediumA = createPhysicalGroup("MediumA", bqt2); //$NON-NLS-1$
+ Table bqt2MediumB = createPhysicalGroup("MediumB", bqt2); //$NON-NLS-1$
+ Table bqt3SmallA = createPhysicalGroup("SmallA", bqt3); //$NON-NLS-1$
+ Table bqt3SmallB = createPhysicalGroup("SmallB", bqt3); //$NON-NLS-1$
+ Table bqt3MediumA = createPhysicalGroup("MediumA", bqt3); //$NON-NLS-1$
+ Table bqt3MediumB = createPhysicalGroup("MediumB", bqt3); //$NON-NLS-1$
+ Table lobTable = createPhysicalGroup("LobTbl", lob); //$NON-NLS-1$
+ Table library = createPhysicalGroup("LOB_TESTING_ONE", lob); //$NON-NLS-1$
+
+ createElements( library, new String[] { "CLOB_COLUMN", "BLOB_COLUMN", "KEY_EMULATOR" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ new String[] { DataTypeManager.DefaultDataTypes.CLOB, DataTypeManager.DefaultDataTypes.BLOB, DataTypeManager.DefaultDataTypes.INTEGER });
+
+ // Create virtual groups
+ QueryNode vqtn1 = new QueryNode("SELECT * FROM BQT1.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg1 = createUpdatableVirtualGroup("SmallA", vqt, vqtn1); //$NON-NLS-1$
+
+ QueryNode vqtn2 = new QueryNode("SELECT Concat(stringKey, stringNum) as a12345 FROM BQT1.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg2 = createUpdatableVirtualGroup("SmallB", vqt, vqtn2); //$NON-NLS-1$
+
+ // Case 2589
+ QueryNode vqtn2589 = new QueryNode("SELECT * FROM BQT1.SmallA WHERE StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg2589 = createVirtualGroup("SmallA_2589", vqt, vqtn2589); //$NON-NLS-1$
+
+ QueryNode vqtn2589a = new QueryNode("SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.IntKey = SmallB.IntKey WHERE SmallA.StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg2589a = createVirtualGroup("SmallA_2589a", vqt, vqtn2589a); //$NON-NLS-1$
+
+ QueryNode vqtn2589b = new QueryNode("SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE SmallA.StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg2589b = createVirtualGroup("SmallA_2589b", vqt, vqtn2589b); //$NON-NLS-1$
+
+ QueryNode vqtn2589c = new QueryNode("SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE concat(SmallA.StringNum, SmallB.StringNum) = '1010'"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg2589c = createVirtualGroup("SmallA_2589c", vqt, vqtn2589c); //$NON-NLS-1$
+
+ QueryNode vqtn2589d = new QueryNode("SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE SmallA.StringNum = '10' AND SmallA.IntNum = 10"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg2589d = createVirtualGroup("SmallA_2589d", vqt, vqtn2589d); //$NON-NLS-1$
+
+ QueryNode vqtn2589f = new QueryNode("SELECT * FROM VQT.SmallA_2589"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg2589f = createVirtualGroup("SmallA_2589f", vqt, vqtn2589f); //$NON-NLS-1$
+
+ QueryNode vqtn2589g = new QueryNode("SELECT * FROM SmallA_2589b"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg2589g = createVirtualGroup("SmallA_2589g", vqt, vqtn2589g); //$NON-NLS-1$
+
+ QueryNode vqtn2589h = new QueryNode("SELECT VQT.SmallA_2589.* FROM VQT.SmallA_2589 INNER JOIN BQT1.SmallB ON VQT.SmallA_2589.StringKey = SmallB.StringKey"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg2589h = createVirtualGroup("SmallA_2589h", vqt, vqtn2589h); //$NON-NLS-1$
+
+ QueryNode vqtn2589i = new QueryNode("SELECT BQT1.SmallA.* FROM BQT1.SmallA INNER JOIN BQT1.SmallB ON SmallA.StringKey = SmallB.StringKey WHERE SmallA.StringNum = '10' AND SmallB.StringNum = '10'"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg2589i = createVirtualGroup("SmallA_2589i", vqt, vqtn2589i); //$NON-NLS-1$
+
+ // defect 15355
+ QueryNode vqtn15355 = new QueryNode("SELECT convert(IntKey, string) as StringKey, BigIntegerValue FROM BQT1.SmallA UNION SELECT StringKey, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg15355 = createVirtualGroup("Defect15355", vqt, vqtn15355); //$NON-NLS-1$
+ QueryNode vqtn15355a = new QueryNode("SELECT StringKey, StringNum, BigIntegerValue FROM BQT1.SmallA UNION SELECT StringKey, StringNum, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg15355a = createVirtualGroup("Defect15355a", vqt, vqtn15355a); //$NON-NLS-1$
+ QueryNode vqtn15355b = new QueryNode("SELECT convert(IntKey, string) as IntKey, BigIntegerValue FROM BQT1.SmallA UNION SELECT StringKey, (SELECT BigIntegerValue FROM BQT3.SmallA WHERE BQT3.SmallA.BigIntegerValue = BQT2.SmallA.StringNum) FROM BQT2.SmallA"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vqtg15355b = createVirtualGroup("Defect15355b", vqt, vqtn15355b); //$NON-NLS-1$
+
+ QueryNode bvqtn1 = new QueryNode("SELECT a.* FROM BQT1.SMALLA AS a WHERE a.INTNUM = (SELECT MIN(b.INTNUM) FROM BQT1.SMALLA AS b WHERE b.INTKEY = a.IntKey ) OPTION MAKEDEP a"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table bvqtg1 = createUpdatableVirtualGroup("BQT_V", bvqt, bvqtn1); //$NON-NLS-1$
+ QueryNode bvqt2n1 = new QueryNode("SELECT BQT2.SmallA.* FROM BQT2.SmallA, BQT_V.BQT_V WHERE BQT2.SmallA.IntKey = BQT_V.BQT_V.IntKey"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table bvqt2g1 = createUpdatableVirtualGroup("BQT2_V", bvqt2, bvqt2n1); //$NON-NLS-1$
+
+ // Create physical elements
+ String[] elemNames = new String[] {
+ "IntKey", "StringKey", //$NON-NLS-1$ //$NON-NLS-2$
+ "IntNum", "StringNum", //$NON-NLS-1$ //$NON-NLS-2$
+ "FloatNum", "LongNum", //$NON-NLS-1$ //$NON-NLS-2$
+ "DoubleNum", "ByteNum", //$NON-NLS-1$ //$NON-NLS-2$
+ "DateValue", "TimeValue", //$NON-NLS-1$ //$NON-NLS-2$
+ "TimestampValue", "BooleanValue", //$NON-NLS-1$ //$NON-NLS-2$
+ "CharValue", "ShortValue", //$NON-NLS-1$ //$NON-NLS-2$
+ "BigIntegerValue", "BigDecimalValue", //$NON-NLS-1$ //$NON-NLS-2$
+ "ObjectValue" }; //$NON-NLS-1$
+ String[] elemTypes = new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.FLOAT, DataTypeManager.DefaultDataTypes.LONG,
+ DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.BYTE,
+ DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME,
+ DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.DefaultDataTypes.BOOLEAN,
+ DataTypeManager.DefaultDataTypes.CHAR, DataTypeManager.DefaultDataTypes.SHORT,
+ DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.BIG_DECIMAL,
+ DataTypeManager.DefaultDataTypes.OBJECT };
+
+ List<Column> bqt1SmallAe = createElements(bqt1SmallA, elemNames, elemTypes);
+ bqt1SmallAe.get(1).setNativeType("char"); //$NON-NLS-1$
+ createElements(bqt1SmallB, elemNames, elemTypes);
+ createElements(bqt1MediumA, elemNames, elemTypes);
+ createElements(bqt1MediumB, elemNames, elemTypes);
+ createElements(bqt2SmallA, elemNames, elemTypes);
+ createElements(bqt2SmallB, elemNames, elemTypes);
+ createElements(bqt2MediumA, elemNames, elemTypes);
+ createElements(bqt2MediumB, elemNames, elemTypes);
+ createElements(bqt3SmallA, elemNames, elemTypes);
+ createElements(bqt3SmallB, elemNames, elemTypes);
+ createElements(bqt3MediumA, elemNames, elemTypes);
+ createElements(bqt3MediumB, elemNames, elemTypes);
+ createElements(lobTable, new String[] {"ClobValue"}, new String[] {DataTypeManager.DefaultDataTypes.CLOB}); //$NON-NLS-1$
+
+ // Create virtual elements
+ createElements(vqtg1, elemNames, elemTypes);
+ createElements(vqtg2, new String[] {"a12345"}, new String[] {DataTypeManager.DefaultDataTypes.STRING}); //$NON-NLS-1$
+ createElements(vqtg15355, new String[] {"StringKey", "BigIntegerValue"}, new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_INTEGER}); //$NON-NLS-1$ //$NON-NLS-2$
+ createElements(vqtg15355a, new String[] {"StringKey", "StringNum", "BigIntegerValue"}, new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_INTEGER}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ createElements(vqtg15355b, new String[] {"IntKey", "BigIntegerValue"}, new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_INTEGER}); //$NON-NLS-1$ //$NON-NLS-2$
+ createElements(vqtg2589, elemNames, elemTypes);
+ createElements(vqtg2589a, elemNames, elemTypes);
+ createElements(vqtg2589b, elemNames, elemTypes);
+ createElements(vqtg2589c, elemNames, elemTypes);
+ createElements(vqtg2589d, elemNames, elemTypes);
+ createElements(vqtg2589f, elemNames, elemTypes);
+ createElements(vqtg2589g, elemNames, elemTypes);
+ createElements(vqtg2589h, elemNames, elemTypes);
+ createElements(vqtg2589i, elemNames, elemTypes);
+ createElements(bvqtg1, elemNames, elemTypes);
+ createElements(bvqt2g1, elemNames, elemTypes);
+
+ // Add stored procedure
+ 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)); //$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)); //$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)); //$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)); //$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)); //$NON-NLS-1$ //$NON-NLS-2$
+ spTest11.setResultSet(rs3);
+
+ //add virtual stored procedures
+ Schema mmspTest1 = createVirtualModel("mmspTest1", metadataStore); //$NON-NLS-1$
+ ColumnSet<Procedure> vsprs1 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+ QueryNode vspqn1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT intkey FROM bqt1.smallA) AS intKeyCursor BEGIN x= intKeyCursor.intkey - 1; END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+ Procedure vsp1 = createVirtualProcedure("MMSP1", mmspTest1, null, vspqn1); //$NON-NLS-1$
+ vsp1.setResultSet(vsprs1);
+
+ ColumnSet<Procedure> vsprs2 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+ QueryNode vspqn2 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT intkey FROM bqt1.smallA) AS intKeyCursor1 BEGIN LOOP ON (SELECT intkey FROM bqt1.smallB) AS intKeyCursor2 BEGIN x= intKeyCursor1.intkey - intKeyCursor2.intkey; END END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+ Procedure vsp2 = createVirtualProcedure("MMSP2", mmspTest1, null, vspqn2); //$NON-NLS-1$
+ vsp2.setResultSet(vsprs2);
+
+ ColumnSet<Procedure> vsprs3 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+ QueryNode vspqn3 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT intkey FROM bqt1.smallA) AS intKeyCursor BEGIN x= intKeyCursor.intkey - 1; if(x = 25) BEGIN BREAK; END ELSE BEGIN CONTINUE; END END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+ Procedure vsp3 = createVirtualProcedure("MMSP3", mmspTest1, null, vspqn3); //$NON-NLS-1$
+ vsp3.setResultSet(vsprs3);
+
+ ColumnSet<Procedure> vsprs4 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+ QueryNode vspqn4 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x=0; WHILE(x < 50) BEGIN x= x + 1; if(x = 25) BEGIN BREAK; END ELSE BEGIN CONTINUE; END END SELECT stringkey FROM bqt1.smalla where intkey=x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+ Procedure vsp4 = createVirtualProcedure("MMSP4", mmspTest1, null, vspqn4); //$NON-NLS-1$
+ vsp4.setResultSet(vsprs4);
+
+ ColumnSet<Procedure> vsprs5 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+ ProcedureParameter vsp5p1 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+ QueryNode vspqn5 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT 0; END"); //$NON-NLS-1$ //$NON-NLS-2$
+ Procedure vsp5 = createVirtualProcedure("MMSP5", mmspTest1, Arrays.asList(vsp5p1), vspqn5); //$NON-NLS-1$
+ vsp5.setResultSet(vsprs5);
+
+ ColumnSet<Procedure> vsprs6 = createResultSet("mmspTest1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+ ProcedureParameter vsp6p1 = createParameter("p1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+ QueryNode vspqn6 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT p1 as StringKey; END"); //$NON-NLS-1$ //$NON-NLS-2$
+ Procedure vsp6 = createVirtualProcedure("MMSP6", mmspTest1, Arrays.asList(vsp6p1), vspqn6); //$NON-NLS-1$
+ vsp6.setResultSet(vsprs6);
+
+ createStoredProcedure("spRetOut", pm4, Arrays.asList(createParameter("ret", ParameterInfo.RETURN_VALUE, DataTypeManager.DefaultDataTypes.INTEGER),
+ 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$
+ QueryNode vspqn7 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN declare integer x; x = exec spTest9(p1); declare integer y; exec spTest11(inkey=>x, outkey=>y); select convert(x, string) || y; END"); //$NON-NLS-1$ //$NON-NLS-2$
+ Procedure vsp7 = createVirtualProcedure("TEIIDSP7", mmspTest1, Arrays.asList(vsp7p1), vspqn7); //$NON-NLS-1$
+ vsp7.setResultSet(vsprs7);
+
+ ProcedureParameter vsp8p1 = createParameter("r", ParameterInfo.RETURN_VALUE, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+ ProcedureParameter vsp8p2 = createParameter("p1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+ QueryNode vspqn8 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN r = p1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+ createVirtualProcedure("TEIIDSP8", mmspTest1, Arrays.asList(vsp8p1, vsp8p2), vspqn8); //$NON-NLS-1$
+
+ ColumnSet<Procedure> vsprs9 = createResultSet("TEIIDSP9.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+ ProcedureParameter vsp9p1 = createParameter("r", ParameterInfo.RETURN_VALUE, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+ vsp9p1.setNullType(NullType.No_Nulls);
+ ProcedureParameter vsp9p2 = createParameter("p1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+ ProcedureParameter vsp9p3 = createParameter("p2", ParameterInfo.OUT, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+ QueryNode vspqn9 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN if (p1 = 1) begin\n r = 1; end\n p2 = 10; select 'hello'; END"); //$NON-NLS-1$ //$NON-NLS-2$
+ Procedure vsp9 = createVirtualProcedure("TEIIDSP9", mmspTest1, Arrays.asList(vsp9p1, vsp9p2, vsp9p3), vspqn9); //$NON-NLS-1$
+ vsp9.setResultSet(vsprs9);
+
+ // this is for the source added function
+ bqt1.addFunction(new FunctionMethod("reverse", "reverse", "misc", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ new FunctionParameter[] {new FunctionParameter("columnName", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
+ new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
+
+ return metadataStore;
+ }
+
+ public static TransformationMetadata exampleBQT() {
+ return createTransformationMetadata(exampleBQTStore(), "bqt");
+ }
+
+ 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(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, SFM.getSystemFunctions(), udfs);
+ }
+
+ /**
+ * Metadata for Materialized Views
+ * @return
+ * @since 4.2
+ */
+ public static QueryMetadataInterface exampleMaterializedView() {
+ MetadataStore metadataStore = new MetadataStore();
+ Schema virtModel = createVirtualModel("MatView", metadataStore); //$NON-NLS-1$
+ Schema physModel = createPhysicalModel("MatTable", metadataStore); //$NON-NLS-1$
+ Schema physModel_virtSrc = createPhysicalModel("MatSrc", metadataStore); //$NON-NLS-1$
+
+ Table physTable = createPhysicalGroup("info", physModel); //$NON-NLS-1$
+ createElements(physTable,
+ new String[] { "e1", "e2", "e3"}, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+
+ Table physGroup = createPhysicalGroup("MatTable", physModel); //$NON-NLS-1$
+ createElements(physGroup,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING});
+
+ Table physGroupStage = createPhysicalGroup("MatStage", physModel); //$NON-NLS-1$
+ createElements(physGroupStage,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING});
+
+ Table physGroup1 = createPhysicalGroup("MatTable1", physModel); //$NON-NLS-1$
+ createElements(physGroup1,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING});
+
+ Table physGroupStage1 = createPhysicalGroup("MatStage1", physModel); //$NON-NLS-1$
+ createElements(physGroupStage,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING});
+
+ Table physGroup_virtSrc = createPhysicalGroup("MatSrc", physModel_virtSrc); //$NON-NLS-1$
+ createElements(physGroup_virtSrc,
+ new String[] { "X" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING});
+
+ QueryNode virtTrans = new QueryNode("SELECT x as e1 FROM MatSrc.MatSrc"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table virtGroup = createVirtualGroup("MatView", virtModel, virtTrans); //$NON-NLS-1$
+ createElements(virtGroup,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING});
+
+ virtGroup.setMaterialized(true);
+ virtGroup.setMaterializedTable(physGroup);
+ virtGroup.setMaterializedStageTable(physGroupStage);
+
+ //add one virtual group that uses the materialized group in transformation with NOCACHE option
+ QueryNode vTrans = new QueryNode("SELECT e1 FROM MatView.MatView option NOCACHE"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vGroup = createVirtualGroup("VGroup", virtModel, vTrans); //$NON-NLS-1$
+ createElements(vGroup,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING});
+
+ QueryNode virtTrans1 = new QueryNode("SELECT e1 FROM MatView.MatView where e1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table virtGroup1 = createVirtualGroup("MatView1", virtModel, virtTrans1); //$NON-NLS-1$
+ createElements(virtGroup1,
+ new String[] { "e1" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING});
+
+ virtGroup1.setMaterializedTable(physGroup1);
+ virtGroup1.setMaterializedStageTable(physGroupStage1);
+
+ QueryNode vTrans2 = new QueryNode("SELECT x FROM matsrc"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vGroup2 = createVirtualGroup("VGroup2", virtModel, vTrans2); //$NON-NLS-1$
+ vGroup2.setMaterialized(true);
+ createElements(vGroup2,
+ new String[] { "x" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING});
+
+ //covering index
+ QueryNode vTrans3 = new QueryNode("SELECT x, 'z' || substring(x, 2) as y FROM matsrc"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vGroup3 = createVirtualGroup("VGroup3", virtModel, vTrans3); //$NON-NLS-1$
+ vGroup3.setMaterialized(true);
+ List<Column> vElements3 = createElements(vGroup3,
+ new String[] { "x", "y" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+ createKey(KeyRecord.Type.Primary, "pk", vGroup3, vElements3.subList(0, 1));
+ createKey(KeyRecord.Type.Index, "idx", vGroup3, vElements3.subList(1, 2));
+
+ QueryNode vTrans4 = new QueryNode("/*+ cache(ttl:100) */ SELECT x FROM matsrc"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vGroup4 = createVirtualGroup("VGroup4", virtModel, vTrans4); //$NON-NLS-1$
+ vGroup4.setMaterialized(true);
+ createElements(vGroup4,
+ new String[] { "x" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING});
+
+ //non-covering index
+ QueryNode vTrans5 = new QueryNode("SELECT x, 'z' || substring(x, 2) as y, 1 as z FROM matsrc"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vGroup5 = createVirtualGroup("VGroup5", virtModel, vTrans5); //$NON-NLS-1$
+ vGroup5.setMaterialized(true);
+ List<Column> vElements5 = createElements(vGroup5,
+ new String[] { "x", "y", "z" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
+
+ createKey(KeyRecord.Type.Primary, "pk", vGroup5, vElements5.subList(0, 1));
+ createKey(KeyRecord.Type.Index, "idx", vGroup5, vElements5.subList(1, 2));
+
+ //no pk
+ QueryNode vTrans6 = new QueryNode("SELECT x, 'z' || substring(x, 2) as y FROM matsrc"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vGroup6 = createVirtualGroup("VGroup6", virtModel, vTrans6); //$NON-NLS-1$
+ vGroup6.setMaterialized(true);
+ List<Column> vElements6 = createElements(vGroup6,
+ new String[] { "x", "y" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+ createKey(KeyRecord.Type.Index, "idx", vGroup6, vElements6.subList(1, 2));
+
+ //non-covering index
+ QueryNode vTrans7 = new QueryNode("SELECT '1', 'z' || substring(x, 2) as y, 1 as z FROM matsrc"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vGroup7 = createVirtualGroup("VGroup7", virtModel, vTrans7); //$NON-NLS-1$
+ vGroup7.setMaterialized(true);
+ List<Column> vElements7 = createElements(vGroup7,
+ new String[] { "x", "y", "z" }, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
+
+ createKey(KeyRecord.Type.Primary, "pk", vGroup7, vElements7.subList(1, 2));
+
+ Schema sp = createVirtualModel("sp", metadataStore); //$NON-NLS-1$
+ ColumnSet<Procedure> rs = createResultSet("sp1.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+ ProcedureParameter param = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+ param.setNullType(NullType.Nullable);
+ QueryNode sp1qn = new QueryNode("/*+ cache */ CREATE VIRTUAL PROCEDURE BEGIN SELECT x as StringKey from matsrc where x = param1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+ Procedure vsp5 = createVirtualProcedure("sp1", sp, Arrays.asList(param), sp1qn); //$NON-NLS-1$
+ vsp5.setResultSet(rs);
+
+ 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$
+ Procedure sq16 = 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);
+
+ Procedure sp3 = 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
+ Procedure sp5 = 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.
+ * @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 KeyRecord createKey(KeyRecord.Type type, String name, Table group, List<Column> elements) {
+ KeyRecord key = new KeyRecord(type);
+ key.setName(name);
+ for (Column column : elements) {
+ key.addColumn(column);
+ }
+ switch (type) {
+ case Primary:
+ group.setPrimaryKey(key);
+ break;
+ case Index:
+ group.getIndexes().add(key);
+ break;
+ case Unique:
+ group.getUniqueKeys().add(key);
+ break;
+ case AccessPattern:
+ group.getAccessPatterns().add(key);
+ break;
+ default:
+ throw new AssertionError("TODO");
+ }
+ return key;
+ }
+
+ public static ForeignKey createForeignKey(String name, Table group, List<Column> elements, KeyRecord primaryKey) {
+ ForeignKey key = new ForeignKey();
+ key.setName(name);
+ for (Column column : elements) {
+ key.addColumn(column);
+ }
+ key.setPrimaryKey(primaryKey);
+ group.getForeignKeys().add(key);
+ return key;
+ }
+
+ /**
+ * Create a physical model with default settings.
+ */
+ public static Schema createPhysicalModel(String name, MetadataStore metadataStore) {
+ Schema schema = new Schema();
+ schema.setName(name);
+ metadataStore.addSchema(schema);
+ return schema;
+ }
+
+ /**
+ * Create a virtual model with default settings.
+ */
+ public static Schema createVirtualModel(String name, MetadataStore metadataStore) {
+ Schema schema = new Schema();
+ schema.setName(name);
+ schema.setPhysical(false);
+ metadataStore.addSchema(schema);
+ return schema;
+ }
+
+ /**
+ * 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 Table createPhysicalGroup(String name, Schema model, boolean fullyQualify) {
+ Table table = new Table();
+ table.setName(name);
+ 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;
+ }
+
+ public static Table createPhysicalGroup(String name, Schema model) {
+ return createPhysicalGroup(name, model, false);
+ }
+
+ /**
+ * Create a virtual group with default settings.
+ */
+ public static Table createVirtualGroup(String name, Schema model, QueryNode plan) {
+ Table table = new Table();
+ 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.
+ */
+ public static Table createUpdatableVirtualGroup(String name, Schema model, QueryNode plan) {
+ return createUpdatableVirtualGroup(name, model, plan, null);
+ }
+
+ public static Table createUpdatableVirtualGroup(String name, Schema model, QueryNode plan, String updatePlan) {
+ Table table = createVirtualGroup(name, model, plan);
+ table.setUpdatePlan(updatePlan);
+ table.setSupportsUpdate(true);
+ return table;
+ }
+
+ public static Column createElement(String name, ColumnSet<?> group, String type) {
+ Column column = new Column();
+ column.setName(name);
+ group.addColumn(column);
+ column.setRuntimeType(type);
+ if(type.equals(DataTypeManager.DefaultDataTypes.STRING)) {
+ column.setSearchType(SearchType.Searchable);
+ } else if (DataTypeManager.isNonComparable(type)){
+ column.setSearchType(SearchType.Unsearchable);
+ } else {
+ column.setSearchType(SearchType.All_Except_Like);
+ }
+ column.setNullType(NullType.Nullable);
+ column.setPosition(group.getColumns().size()); //1 based indexing
+ column.setUpdatable(true);
+ column.setLength(100);
+ column.setNameInSource(name);
+ return column;
+ }
+
+ /**
+ * Create a set of elements in batch
+ */
+ public static List<Column> createElements(ColumnSet<?> group, String[] names, String[] types) {
+ return createElementsWithDefaults(group, names, types, new String[names.length]);
+ }
+
+ /**
+ * Create a set of elements in batch
+ */
+ public static List<Column> createElementsWithDefaults(ColumnSet<?> group, String[] names, String[] types, String[] defaults) {
+ List<Column> elements = new ArrayList<Column>();
+
+ for(int i=0; i<names.length; i++) {
+ Column element = createElement(names[i], group, types[i]);
+ element.setDefaultValue(defaults[i]);
+ elements.add(element);
+ }
+
+ return elements;
+ }
+
+ /**
+ * Create stored procedure parameter.
+ */
+ public static ProcedureParameter createParameter(String name, int direction, String type) {
+ ProcedureParameter param = new ProcedureParameter();
+ param.setName(name);
+ switch (direction) {
+ case SPParameter.IN:
+ param.setType(Type.In);
+ break;
+ case SPParameter.INOUT:
+ param.setType(Type.InOut);
+ break;
+ case SPParameter.OUT:
+ param.setType(Type.Out);
+ break;
+ case SPParameter.RESULT_SET:
+ throw new AssertionError("should not directly create a resultset param"); //$NON-NLS-1$
+ case SPParameter.RETURN_VALUE:
+ param.setType(Type.ReturnValue);
+ break;
+ }
+ param.setRuntimeType(type);
+ return param;
+ }
+
+ /**
+ * 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 Procedure createStoredProcedure(String name, Schema model, List<ProcedureParameter> params) {
+ Procedure proc = new Procedure();
+ proc.setName(name);
+ if (params != null) {
+ int index = 1;
+ for (ProcedureParameter procedureParameter : params) {
+ procedureParameter.setProcedure(proc);
+ procedureParameter.setPosition(index++);
+ }
+ proc.setParameters(params);
+ }
+ model.addProcedure(proc);
+ return proc;
+ }
+
+ /**
+ * 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 Procedure createVirtualProcedure(String name, Schema model, List<ProcedureParameter> params, QueryNode queryPlan) {
+ Procedure proc = createStoredProcedure(name, model, params);
+ proc.setVirtual(true);
+ proc.setQueryPlan(queryPlan.getQuery());
+ return proc;
+ }
+
+ /**
+ * Create a result set.
+ */
+ public static ColumnSet<Procedure> createResultSet(String name, String[] colNames, String[] colTypes) {
+ ColumnSet<Procedure> rs = new ColumnSet<Procedure>();
+ rs.setName(name);
+ for(Column column : createElements(rs, colNames, colTypes)) {
+ column.setParent(rs);
+ }
+ 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");
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestUpdateValidator.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/validator/TestUpdateValidator.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestUpdateValidator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,346 +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 static org.junit.Assert.*;
-
-import java.util.Collections;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryParserException;
-import org.teiid.api.exception.query.QueryResolverException;
-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.ColumnSet;
-import org.teiid.metadata.KeyRecord;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.metadata.Procedure;
-import org.teiid.metadata.Schema;
-import org.teiid.metadata.Table;
-import org.teiid.metadata.BaseColumn.NullType;
-import org.teiid.metadata.KeyRecord.Type;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.metadata.TransformationMetadata;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.unittest.RealMetadataFactory;
-import org.teiid.query.validator.UpdateValidator.UpdateInfo;
-import org.teiid.query.validator.UpdateValidator.UpdateType;
-
- at SuppressWarnings("nls")
-public class TestUpdateValidator {
-
- private UpdateValidator helpTest(String sql, TransformationMetadata md, boolean shouldFail) {
- return helpTest(sql, md, shouldFail, shouldFail, shouldFail);
- }
-
- private UpdateValidator helpTest(String sql, TransformationMetadata md, boolean failInsert, boolean failUpdate, boolean failDelete) {
- try {
- String vGroup = "gx";
- Command command = createView(sql, md, vGroup);
-
- UpdateValidator uv = new UpdateValidator(md, UpdateType.INHERENT, UpdateType.INHERENT, UpdateType.INHERENT);
- GroupSymbol gs = new GroupSymbol(vGroup);
- ResolverUtil.resolveGroup(gs, md);
- uv.validate(command, ResolverUtil.resolveElementsInGroup(gs, md));
- UpdateInfo info = uv.getUpdateInfo();
- assertEquals(uv.getReport().getFailureMessage(), failInsert, info.isInsertValidationError());
- assertEquals(uv.getReport().getFailureMessage(), failUpdate, info.isUpdateValidationError());
- assertEquals(uv.getReport().getFailureMessage(), failDelete, info.isDeleteValidationError());
- return uv;
- } catch (TeiidException e) {
- throw new RuntimeException(e);
- }
- }
-
- public static Command createView(String sql, TransformationMetadata md, String vGroup)
- throws QueryParserException, QueryResolverException,
- TeiidComponentException {
- QueryNode vm1g1n1 = new QueryNode(sql);
- Table vm1g1 = RealMetadataFactory.createUpdatableVirtualGroup(vGroup, md.getMetadataStore().getSchema("VM1"), vm1g1n1);
-
- Command command = QueryParser.getQueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(command, md);
-
- List<SingleElementSymbol> symbols = command.getProjectedSymbols();
- String[] names = new String[symbols.size()];
- String[] types = new String[symbols.size()];
- int i = 0;
- for (SingleElementSymbol singleElementSymbol : symbols) {
- names[i] = singleElementSymbol.getShortName();
- types[i++] = DataTypeManager.getDataTypeName(singleElementSymbol.getType());
- }
-
- RealMetadataFactory.createElements(vm1g1, names, types);
- return command;
- }
-
- public static TransformationMetadata example1() {
- return example1(true);
- }
-
- public static TransformationMetadata example1(boolean allUpdatable) {
- 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$
- Table pm1g2 = RealMetadataFactory.createPhysicalGroup("g2", pm1); //$NON-NLS-1$
- Table pm1g3 = RealMetadataFactory.createPhysicalGroup("g3", pm1); //$NON-NLS-1$
-
- // Create physical elements
- List<Column> pm1g1e = 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 });
- if (!allUpdatable) {
- pm1g1e.get(0).setUpdatable(false);
- }
-
- KeyRecord pk = RealMetadataFactory.createKey(Type.Primary, "pk", pm1g1, pm1g1e.subList(0, 1));
-
- List<Column> pm1g2e = 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 });
-
- RealMetadataFactory.createKey(Type.Primary, "pk", pm1g2, pm1g1e.subList(1, 2));
- RealMetadataFactory.createForeignKey("fk", pm1g2, pm1g2e.subList(0, 1), pk);
-
- List<Column> pm1g3e = 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 });
- pm1g3e.get(0).setNullType(NullType.No_Nulls);
- pm1g3e.get(0).setDefaultValue(null);
-
- pm1g3e.get(1).setNullType(NullType.No_Nulls);
- pm1g3e.get(1).setAutoIncremented(true);
- pm1g3e.get(1).setDefaultValue(null);
-
- pm1g3e.get(2).setNullType(NullType.No_Nulls);
- pm1g3e.get(2).setDefaultValue("xyz"); //$NON-NLS-1$
-
- // Create virtual groups
- QueryNode vm1g1n1 = new QueryNode("SELECT e1 as a, e2 FROM pm1.g1 WHERE e3 > 5"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vm1g1 = RealMetadataFactory.createUpdatableVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
- QueryNode vm1g2n1 = new QueryNode("SELECT e1, e2, e3, e4 FROM pm1.g2 WHERE e3 > 5"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vm1g2 = RealMetadataFactory.createUpdatableVirtualGroup("g2", vm1, vm1g2n1); //$NON-NLS-1$
- QueryNode vm1g3n1 = new QueryNode("SELECT e1, e3 FROM pm1.g3"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vm1g3 = RealMetadataFactory.createUpdatableVirtualGroup("g3", vm1, vm1g3n1); //$NON-NLS-1$
- QueryNode vm1g4n1 = new QueryNode("SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vm1g4 = RealMetadataFactory.createUpdatableVirtualGroup("g4", vm1, vm1g4n1); //$NON-NLS-1$
- QueryNode vm1g5n1 = new QueryNode("SELECT e2, e3 FROM pm1.g3"); //$NON-NLS-1$ //$NON-NLS-2$
- Table vm1g5 = RealMetadataFactory.createVirtualGroup("g5", vm1, vm1g5n1); //$NON-NLS-1$
-
- // Create virtual elements
- RealMetadataFactory.createElements(vm1g1,
- new String[] { "a", "e2"}, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
- 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 });
- RealMetadataFactory.createElements(vm1g3,
- new String[] { "e1", "e2"}, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, });
- RealMetadataFactory.createElements(vm1g4,
- new String[] { "e1", "e3"}, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BOOLEAN });
- RealMetadataFactory.createElements(vm1g5,
- new String[] { "e2","e3"}, //$NON-NLS-1$ //$NON-NLS-2$
- new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN });
-
- // 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$
- sq1.setResultSet(rs1);
- // Create the facade from the store
- return RealMetadataFactory.createTransformationMetadata(metadataStore, "example");
- }
-
- //actual tests
- @Test public void testCreateInsertCommand(){
- helpTest("select e1 as a, e2 from pm1.g1 where e4 > 5",
- example1(), false); //$NON-NLS-1$
- }
-
- @Test public void testCreateInsertCommand2(){ //put a constant in select statement
- helpTest("select e1 as a, 5 from pm1.g1 where e4 > 5",
- example1(), false); //$NON-NLS-1$
- }
-
- @Test public void testCreateInsertCommand3(){
- helpTest("select * from pm1.g2 where e4 > 5",
- example1(), false); //$NON-NLS-1$
- }
-
- @Test public void testCreateInsertCommand4(){ //test group alias
- helpTest("select * from pm1.g2 as g_alias",
- example1(), false); //$NON-NLS-1$
- }
-
- @Test public void testCreateInsertCommand5(){
- helpTest("select e1 as a, e2 from pm1.g1 as g_alias where e4 > 5",
- example1(), false); //$NON-NLS-1$
- }
-
- @Test public void testCreateUpdateCommand(){
- helpTest("select e1 as a, e2 from pm1.g1 where e4 > 5",
- example1(), false); //$NON-NLS-1$
- }
-
- @Test public void testCreateDeleteCommand(){
- helpTest("select e1 as a, e2 from pm1.g1 where e4 > 5",
- example1(), false); //$NON-NLS-1$
- }
-
- @Test public void testCreateInsertCommand1(){
- helpTest("SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2",
- example1(), true);
- }
-
- @Test public void testCreateInsertCommand14(){
- helpTest("SELECT pm1.g2.e1 FROM pm1.g1, pm1.g2 where g1.e1 = g2.e1",
- example1(), false);
- }
-
- @Test public void testCreateInsertCommand2_fail(){
- helpTest("SELECT CONCAT(pm1.g1.e1, convert(pm1.g2.e1, string)) as x FROM pm1.g1, pm1.g2",
- example1(), true);
- }
-
- @Test public void testCreateInsertCommand3_fail(){
- helpTest("SELECT e1 FROM pm1.g1 UNION SELECT e1 FROM pm1.g2",
- example1(), true);
- }
-
- @Test public void testCreateInsertCommand4_fail(){
- helpTest("SELECT COUNT(*) FROM pm1.g1",
- example1(), true);
- }
-
- @Test public void testCreateInsertCommand5_fail(){
- helpTest("SELECT * FROM pm1.g1 GROUP BY e1",
- example1(), true);
- }
-
- @Test public void testCreateInsertCommand6_fail(){
- helpTest("EXEC pm1.sq1()",
- example1(), true);
- }
-
- @Test public void testCreateInsertCommand7_fail(){
- helpTest("INSERT INTO pm1.g1 (e1) VALUES ('x')",
- example1(), true);
- }
-
- @Test public void testCreateInsertCommand8_fail(){
- helpTest("UPDATE pm1.g1 SET e1='x'",
- example1(), true);
- }
-
- @Test public void testCreateInsertCommand9_fail(){
- helpTest("DELETE FROM pm1.g1",
- example1(), true);
- }
-
- @Test public void testCreateInsertCommand10_fail(){
- helpTest("SELECT COUNT(*) FROM pm1.g1",
- example1(), true);
- }
-
- @Test public void testCreateInsertCommand11_fail(){
- helpTest("SELECT COUNT(e1) as x FROM pm1.g1",
- example1(), true);
- }
-
- @Test public void testCreateInsertCommand12_fail(){
- helpTest("SELECT * FROM (EXEC pm1.sq1()) AS a",
- example1(), true);
- }
-
- @Test public void testCreateInsertCommand13_fail(){
- helpTest("SELECT 1",
- example1(), true);
- }
-
- @Test public void testRequiredElements1() {
- helpTest("SELECT e1, e2 FROM pm1.g3",
- example1(), false); //$NON-NLS-1$
- }
-
- @Test public void testRequiredElements2() {
- helpTest("SELECT e1, e3 FROM pm1.g3",
- example1(), false); //$NON-NLS-1$
- }
-
- @Test public void testRequiredElements3() {
- helpTest("SELECT e2, e3 FROM pm1.g3",
- example1(), true, false, false);
- }
-
- @Test public void testNonUpdateableElements() {
- helpTest("select e1 as a, e2 from pm1.g1 where e4 > 5",
- example1(false), false); //$NON-NLS-1$
- }
-
- @Test public void testNonUpdateableElements2() {
- helpTest("SELECT e1, e2 FROM pm1.g1",
- example1(false), false); //$NON-NLS-1$
- }
-
- @Test public void testSelectDistinct() {
- helpTest("SELECT distinct e1, e2 FROM pm1.g1",
- example1(), true); //$NON-NLS-1$
- }
-
- @Test public void testNonUpdatable() {
- helpTest("SELECT e2 FROM vm1.g5",
- example1(), true); //$NON-NLS-1$
- }
-
- @Test public void testAnsiJoin() {
- helpTest("SELECT g1.e1, x.e2 FROM pm1.g2 x inner join pm1.g1 on (x.e1 = g1.e1)",
- example1(), false); //$NON-NLS-1$
- }
-
- @Test public void testUnionAll() {
- helpTest("SELECT g1.e1, x.e2 FROM pm1.g2 x inner join pm1.g1 on (x.e1 = g1.e1) union all select pm1.g2.e1, pm1.g2.e2 from pm1.g2",
- example1(), true, false, false); //$NON-NLS-1$
- }
-
- @Test public void testParitionedUnionAll() {
- helpTest("SELECT g1.e1, x.e2 FROM pm1.g2 x inner join pm1.g1 on (x.e1 = g1.e1) where x.e2 in (1, 2) union all select pm1.g2.e1, pm1.g2.e2 from pm1.g2 where pm1.g2.e2 in (3, 4)",
- example1(), false, false, false); //$NON-NLS-1$
- }
-
-}
-
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestUpdateValidator.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/validator/TestUpdateValidator.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestUpdateValidator.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestUpdateValidator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,346 @@
+/*
+ * 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 static org.junit.Assert.*;
+
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.api.exception.query.QueryParserException;
+import org.teiid.api.exception.query.QueryResolverException;
+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.ColumnSet;
+import org.teiid.metadata.KeyRecord;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.metadata.BaseColumn.NullType;
+import org.teiid.metadata.KeyRecord.Type;
+import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.validator.UpdateValidator.UpdateInfo;
+import org.teiid.query.validator.UpdateValidator.UpdateType;
+
+ at SuppressWarnings("nls")
+public class TestUpdateValidator {
+
+ private UpdateValidator helpTest(String sql, TransformationMetadata md, boolean shouldFail) {
+ return helpTest(sql, md, shouldFail, shouldFail, shouldFail);
+ }
+
+ private UpdateValidator helpTest(String sql, TransformationMetadata md, boolean failInsert, boolean failUpdate, boolean failDelete) {
+ try {
+ String vGroup = "gx";
+ Command command = createView(sql, md, vGroup);
+
+ UpdateValidator uv = new UpdateValidator(md, UpdateType.INHERENT, UpdateType.INHERENT, UpdateType.INHERENT);
+ GroupSymbol gs = new GroupSymbol(vGroup);
+ ResolverUtil.resolveGroup(gs, md);
+ uv.validate(command, ResolverUtil.resolveElementsInGroup(gs, md));
+ UpdateInfo info = uv.getUpdateInfo();
+ assertEquals(uv.getReport().getFailureMessage(), failInsert, info.isInsertValidationError());
+ assertEquals(uv.getReport().getFailureMessage(), failUpdate, info.isUpdateValidationError());
+ assertEquals(uv.getReport().getFailureMessage(), failDelete, info.isDeleteValidationError());
+ return uv;
+ } catch (TeiidException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static Command createView(String sql, TransformationMetadata md, String vGroup)
+ throws QueryParserException, QueryResolverException,
+ TeiidComponentException {
+ QueryNode vm1g1n1 = new QueryNode(sql);
+ Table vm1g1 = RealMetadataFactory.createUpdatableVirtualGroup(vGroup, md.getMetadataStore().getSchema("VM1"), vm1g1n1);
+
+ Command command = QueryParser.getQueryParser().parseCommand(sql);
+ QueryResolver.resolveCommand(command, md);
+
+ List<SingleElementSymbol> symbols = command.getProjectedSymbols();
+ String[] names = new String[symbols.size()];
+ String[] types = new String[symbols.size()];
+ int i = 0;
+ for (SingleElementSymbol singleElementSymbol : symbols) {
+ names[i] = singleElementSymbol.getShortName();
+ types[i++] = DataTypeManager.getDataTypeName(singleElementSymbol.getType());
+ }
+
+ RealMetadataFactory.createElements(vm1g1, names, types);
+ return command;
+ }
+
+ public static TransformationMetadata example1() {
+ return example1(true);
+ }
+
+ public static TransformationMetadata example1(boolean allUpdatable) {
+ 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$
+ Table pm1g2 = RealMetadataFactory.createPhysicalGroup("g2", pm1); //$NON-NLS-1$
+ Table pm1g3 = RealMetadataFactory.createPhysicalGroup("g3", pm1); //$NON-NLS-1$
+
+ // Create physical elements
+ List<Column> pm1g1e = 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 });
+ if (!allUpdatable) {
+ pm1g1e.get(0).setUpdatable(false);
+ }
+
+ KeyRecord pk = RealMetadataFactory.createKey(Type.Primary, "pk", pm1g1, pm1g1e.subList(0, 1));
+
+ List<Column> pm1g2e = 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 });
+
+ RealMetadataFactory.createKey(Type.Primary, "pk", pm1g2, pm1g1e.subList(1, 2));
+ RealMetadataFactory.createForeignKey("fk", pm1g2, pm1g2e.subList(0, 1), pk);
+
+ List<Column> pm1g3e = 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 });
+ pm1g3e.get(0).setNullType(NullType.No_Nulls);
+ pm1g3e.get(0).setDefaultValue(null);
+
+ pm1g3e.get(1).setNullType(NullType.No_Nulls);
+ pm1g3e.get(1).setAutoIncremented(true);
+ pm1g3e.get(1).setDefaultValue(null);
+
+ pm1g3e.get(2).setNullType(NullType.No_Nulls);
+ pm1g3e.get(2).setDefaultValue("xyz"); //$NON-NLS-1$
+
+ // Create virtual groups
+ QueryNode vm1g1n1 = new QueryNode("SELECT e1 as a, e2 FROM pm1.g1 WHERE e3 > 5"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vm1g1 = RealMetadataFactory.createUpdatableVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
+ QueryNode vm1g2n1 = new QueryNode("SELECT e1, e2, e3, e4 FROM pm1.g2 WHERE e3 > 5"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vm1g2 = RealMetadataFactory.createUpdatableVirtualGroup("g2", vm1, vm1g2n1); //$NON-NLS-1$
+ QueryNode vm1g3n1 = new QueryNode("SELECT e1, e3 FROM pm1.g3"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vm1g3 = RealMetadataFactory.createUpdatableVirtualGroup("g3", vm1, vm1g3n1); //$NON-NLS-1$
+ QueryNode vm1g4n1 = new QueryNode("SELECT e1, e2 FROM pm1.g3"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vm1g4 = RealMetadataFactory.createUpdatableVirtualGroup("g4", vm1, vm1g4n1); //$NON-NLS-1$
+ QueryNode vm1g5n1 = new QueryNode("SELECT e2, e3 FROM pm1.g3"); //$NON-NLS-1$ //$NON-NLS-2$
+ Table vm1g5 = RealMetadataFactory.createVirtualGroup("g5", vm1, vm1g5n1); //$NON-NLS-1$
+
+ // Create virtual elements
+ RealMetadataFactory.createElements(vm1g1,
+ new String[] { "a", "e2"}, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
+ 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 });
+ RealMetadataFactory.createElements(vm1g3,
+ new String[] { "e1", "e2"}, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, });
+ RealMetadataFactory.createElements(vm1g4,
+ new String[] { "e1", "e3"}, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BOOLEAN });
+ RealMetadataFactory.createElements(vm1g5,
+ new String[] { "e2","e3"}, //$NON-NLS-1$ //$NON-NLS-2$
+ new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN });
+
+ // 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("sq1", pm1, Collections.EMPTY_LIST, sq1n1); //$NON-NLS-1$
+ sq1.setResultSet(rs1);
+ // Create the facade from the store
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "example");
+ }
+
+ //actual tests
+ @Test public void testCreateInsertCommand(){
+ helpTest("select e1 as a, e2 from pm1.g1 where e4 > 5",
+ example1(), false); //$NON-NLS-1$
+ }
+
+ @Test public void testCreateInsertCommand2(){ //put a constant in select statement
+ helpTest("select e1 as a, 5 from pm1.g1 where e4 > 5",
+ example1(), false); //$NON-NLS-1$
+ }
+
+ @Test public void testCreateInsertCommand3(){
+ helpTest("select * from pm1.g2 where e4 > 5",
+ example1(), false); //$NON-NLS-1$
+ }
+
+ @Test public void testCreateInsertCommand4(){ //test group alias
+ helpTest("select * from pm1.g2 as g_alias",
+ example1(), false); //$NON-NLS-1$
+ }
+
+ @Test public void testCreateInsertCommand5(){
+ helpTest("select e1 as a, e2 from pm1.g1 as g_alias where e4 > 5",
+ example1(), false); //$NON-NLS-1$
+ }
+
+ @Test public void testCreateUpdateCommand(){
+ helpTest("select e1 as a, e2 from pm1.g1 where e4 > 5",
+ example1(), false); //$NON-NLS-1$
+ }
+
+ @Test public void testCreateDeleteCommand(){
+ helpTest("select e1 as a, e2 from pm1.g1 where e4 > 5",
+ example1(), false); //$NON-NLS-1$
+ }
+
+ @Test public void testCreateInsertCommand1(){
+ helpTest("SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2",
+ example1(), true);
+ }
+
+ @Test public void testCreateInsertCommand14(){
+ helpTest("SELECT pm1.g2.e1 FROM pm1.g1, pm1.g2 where g1.e1 = g2.e1",
+ example1(), false);
+ }
+
+ @Test public void testCreateInsertCommand2_fail(){
+ helpTest("SELECT CONCAT(pm1.g1.e1, convert(pm1.g2.e1, string)) as x FROM pm1.g1, pm1.g2",
+ example1(), true);
+ }
+
+ @Test public void testCreateInsertCommand3_fail(){
+ helpTest("SELECT e1 FROM pm1.g1 UNION SELECT e1 FROM pm1.g2",
+ example1(), true);
+ }
+
+ @Test public void testCreateInsertCommand4_fail(){
+ helpTest("SELECT COUNT(*) FROM pm1.g1",
+ example1(), true);
+ }
+
+ @Test public void testCreateInsertCommand5_fail(){
+ helpTest("SELECT * FROM pm1.g1 GROUP BY e1",
+ example1(), true);
+ }
+
+ @Test public void testCreateInsertCommand6_fail(){
+ helpTest("EXEC pm1.sq1()",
+ example1(), true);
+ }
+
+ @Test public void testCreateInsertCommand7_fail(){
+ helpTest("INSERT INTO pm1.g1 (e1) VALUES ('x')",
+ example1(), true);
+ }
+
+ @Test public void testCreateInsertCommand8_fail(){
+ helpTest("UPDATE pm1.g1 SET e1='x'",
+ example1(), true);
+ }
+
+ @Test public void testCreateInsertCommand9_fail(){
+ helpTest("DELETE FROM pm1.g1",
+ example1(), true);
+ }
+
+ @Test public void testCreateInsertCommand10_fail(){
+ helpTest("SELECT COUNT(*) FROM pm1.g1",
+ example1(), true);
+ }
+
+ @Test public void testCreateInsertCommand11_fail(){
+ helpTest("SELECT COUNT(e1) as x FROM pm1.g1",
+ example1(), true);
+ }
+
+ @Test public void testCreateInsertCommand12_fail(){
+ helpTest("SELECT * FROM (EXEC pm1.sq1()) AS a",
+ example1(), true);
+ }
+
+ @Test public void testCreateInsertCommand13_fail(){
+ helpTest("SELECT 1",
+ example1(), true);
+ }
+
+ @Test public void testRequiredElements1() {
+ helpTest("SELECT e1, e2 FROM pm1.g3",
+ example1(), false); //$NON-NLS-1$
+ }
+
+ @Test public void testRequiredElements2() {
+ helpTest("SELECT e1, e3 FROM pm1.g3",
+ example1(), false); //$NON-NLS-1$
+ }
+
+ @Test public void testRequiredElements3() {
+ helpTest("SELECT e2, e3 FROM pm1.g3",
+ example1(), true, false, false);
+ }
+
+ @Test public void testNonUpdateableElements() {
+ helpTest("select e1 as a, e2 from pm1.g1 where e4 > 5",
+ example1(false), false); //$NON-NLS-1$
+ }
+
+ @Test public void testNonUpdateableElements2() {
+ helpTest("SELECT e1, e2 FROM pm1.g1",
+ example1(false), false); //$NON-NLS-1$
+ }
+
+ @Test public void testSelectDistinct() {
+ helpTest("SELECT distinct e1, e2 FROM pm1.g1",
+ example1(), true); //$NON-NLS-1$
+ }
+
+ @Test public void testNonUpdatable() {
+ helpTest("SELECT e2 FROM vm1.g5",
+ example1(), true); //$NON-NLS-1$
+ }
+
+ @Test public void testAnsiJoin() {
+ helpTest("SELECT g1.e1, x.e2 FROM pm1.g2 x inner join pm1.g1 on (x.e1 = g1.e1)",
+ example1(), false); //$NON-NLS-1$
+ }
+
+ @Test public void testUnionAll() {
+ helpTest("SELECT g1.e1, x.e2 FROM pm1.g2 x inner join pm1.g1 on (x.e1 = g1.e1) union all select pm1.g2.e1, pm1.g2.e2 from pm1.g2",
+ example1(), true, false, false); //$NON-NLS-1$
+ }
+
+ @Test public void testParitionedUnionAll() {
+ helpTest("SELECT g1.e1, x.e2 FROM pm1.g2 x inner join pm1.g1 on (x.e1 = g1.e1) where x.e2 in (1, 2) union all select pm1.g2.e1, pm1.g2.e2 from pm1.g2 where pm1.g2.e2 in (3, 4)",
+ example1(), false, false, false); //$NON-NLS-1$
+ }
+
+}
+
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/validator/TestValidator.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,1902 +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 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 org.junit.Ignore;
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryResolverException;
-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.TeiidRuntimeException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.dqp.internal.process.multisource.MultiSourceMetadataWrapper;
-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.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.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;
-
- at SuppressWarnings("nls")
-public class TestValidator {
-
- public static FakeMetadataFacade exampleMetadata() {
- // 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);
-
- 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);
-
- 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$
-
- // 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,
- 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,
- 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);
-
- // Create virtual documents
- MappingDocument doc = new MappingDocument(false);
- MappingElement complexRoot = doc.addChildElement(new MappingElement("a0")); //$NON-NLS-1$
-
- MappingElement sourceNode = complexRoot.addChildElement(new MappingElement("a1")); //$NON-NLS-1$
- sourceNode.setSource("test.group"); //$NON-NLS-1$
- sourceNode.addChildElement(new MappingElement("a2", "test.group.e1")); //$NON-NLS-1$ //$NON-NLS-2$
- 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$
- 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);
- }
-
- public FakeMetadataFacade exampleMetadata1() {
- // 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 elemObj3 = FakeMetadataFactory.createElement("test.group.e3", groupObj, DataTypeManager.DefaultDataTypes.STRING, 3); //$NON-NLS-1$
-
- elemObj0.putProperty(FakeMetadataObject.Props.NULL, Boolean.FALSE);
- elemObj0.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.FALSE);
-
- elemObj1.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
- elemObj1.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.TRUE);
-
- elemObj2.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
- elemObj2.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.FALSE);
-
- // 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);
- }
-
- /**
- * Group has element with type object
- * @return FakeMetadataFacade
- */
- public static FakeMetadataFacade exampleMetadata2() {
- // Create metadata objects
- FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test"); //$NON-NLS-1$
- FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj); //$NON-NLS-1$
-
- List elements = FakeMetadataFactory.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,
- DataTypeManager.DefaultDataTypes.STRING,
- DataTypeManager.DefaultDataTypes.OBJECT,
- DataTypeManager.DefaultDataTypes.BLOB,
- DataTypeManager.DefaultDataTypes.CLOB,
- DataTypeManager.DefaultDataTypes.XML,
- });
-
- // set up validator metadata
- FakeMetadataStore store = new FakeMetadataStore();
- store.addObject(modelObj);
- store.addObject(groupObj);
- store.addObjects(elements);
- return new FakeMetadataFacade(store);
- }
-
- public static FakeMetadataFacade exampleMetadata3() {
- // 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$
-
- 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$
-
- // set up validator metadata
- FakeMetadataStore store = new FakeMetadataStore();
- store.addObject(modelObj);
- store.addObject(groupObj);
- store.addObject(elemObj0);
- store.addObject(elemObj1);
- return new FakeMetadataFacade(store);
- }
-
- public static FakeMetadataFacade exampleMetadata4() {
- // 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$
- 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);
- elements.add(vElemObj0);
- elements.add(vElemObj1);
- FakeMetadataObject vGroupAp1 = FakeMetadataFactory.createAccessPattern("vTest.vGroup.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);
- elements.add(vElemObj20);
- elements.add(vElemObj21);
- FakeMetadataObject vGroup2Ap1 = FakeMetadataFactory.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);
- }
-
- // ################################## TEST HELPERS ################################
-
- static Command helpResolve(String sql, QueryMetadataInterface metadata) {
- Command command = null;
-
- try {
- command = QueryParser.getQueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(command, metadata);
- } catch(Exception e) {
- throw new TeiidRuntimeException(e);
- }
-
- return command;
- }
-
- static Command helpResolve(String sql, GroupSymbol container, int type, QueryMetadataInterface metadata) {
- Command command = null;
-
- try {
- command = QueryParser.getQueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(command, container, type, metadata);
- } catch(Exception e) {
- throw new TeiidRuntimeException(e);
- }
-
- return command;
- }
-
- static ValidatorReport helpValidate(String sql, String[] expectedStringArray, QueryMetadataInterface metadata) {
- Command command = helpResolve(sql, metadata);
-
- return helpRunValidator(command, expectedStringArray, metadata);
- }
-
- public static ValidatorReport helpRunValidator(Command command, String[] expectedStringArray, QueryMetadataInterface metadata) {
- try {
- ValidatorReport report = Validator.validate(command, metadata);
-
- examineReport(command, expectedStringArray, report);
- return report;
- } catch(TeiidException e) {
- throw new TeiidRuntimeException(e);
- }
- }
-
- private static void examineReport(Object command,
- String[] expectedStringArray, ValidatorReport report) {
- // Get invalid objects from report
- Collection actualObjs = new ArrayList();
- report.collectInvalidObjects(actualObjs);
-
- // Compare expected and actual objects
- Set<String> expectedStrings = new HashSet(Arrays.asList(expectedStringArray));
- Set<String> actualStrings = new HashSet<String>();
- Iterator objIter = actualObjs.iterator();
- while(objIter.hasNext()) {
- LanguageObject obj = (LanguageObject) objIter.next();
- actualStrings.add(SQLStringVisitor.getSQLString(obj));
- }
-
- if(expectedStrings.size() == 0 && actualStrings.size() > 0) {
- fail("Expected no failures but got some: " + report.getFailureMessage()); //$NON-NLS-1$
- } else if(actualStrings.size() == 0 && expectedStrings.size() > 0) {
- fail("Expected some failures but got none for sql = " + command); //$NON-NLS-1$
- } else {
- assertEquals("Expected and actual sets of strings are not the same: ", expectedStrings, actualStrings); //$NON-NLS-1$
- }
- }
-
- private void helpValidateProcedure(String procedure, String userUpdateStr, String procedureType) {
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
-
- try {
- validateProcedure(userUpdateStr, metadata);
- } catch(TeiidException e) {
- throw new TeiidRuntimeException(e);
- }
- }
-
- private void validateProcedure(String userUpdateStr,
- QueryMetadataInterface metadata) throws QueryResolverException,
- QueryMetadataException, TeiidComponentException,
- QueryValidatorException {
- ProcedureContainer command = (ProcedureContainer)helpResolve(userUpdateStr, metadata);
-
- Command proc = QueryResolver.expandCommand(command, metadata, AnalysisRecord.createNonRecordingRecord());
-
- ValidatorReport report = Validator.validate(proc, metadata);
- if(report.hasItems()) {
- throw new QueryValidatorException(report.getFailureMessage());
- }
-
- report = Validator.validate(command, metadata);
- if(report.hasItems()) {
- throw new QueryValidatorException(report.getFailureMessage());
- }
- }
-
- private void helpFailProcedure(String procedure, String userUpdateStr, String procedureType) {
-
- QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
-
- try {
- validateProcedure(userUpdateStr, metadata);
- fail("Expected failures for " + procedure);
- } catch (QueryValidatorException e) {
- } catch(TeiidException e) {
- throw new RuntimeException(e);
- }
- }
-
- // ################################## ACTUAL TESTS ################################
-
-
- @Test public void testSelectStarWhereNoElementsAreNotSelectable() {
- helpValidate("SELECT * FROM pm1.g5", new String[] {"SELECT * FROM pm1.g5"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateSelect1() {
- helpValidate("SELECT e1, e2 FROM test.group", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateSelect2() {
- helpValidate("SELECT e2 FROM test.group", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testValidateCompare1() {
- helpValidate("SELECT e2 FROM vTest.vMap WHERE e2 = 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testValidateCompare4() {
- helpValidate("SELECT e3 FROM vTest.vMap WHERE e3 LIKE 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testValidateCompare6() {
- helpValidate("SELECT e0 FROM vTest.vMap WHERE e0 BETWEEN 1000 AND 2000", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testValidateCompareInHaving2() {
- helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 IS NULL", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testValidateCompareInHaving3() {
- helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 IN ('a')", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testValidateCompareInHaving4() {
- helpValidate("SELECT e3 FROM vTest.vMap GROUP BY e3 HAVING e3 LIKE 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testValidateCompareInHaving5() {
- helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 BETWEEN 1000 AND 2000", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testInvalidAggregate1() {
- helpValidate("SELECT SUM(e3) FROM test.group GROUP BY e2", new String[] {"SUM(e3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testInvalidAggregate2() {
- helpValidate("SELECT e3 FROM test.group GROUP BY e2", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testInvalidAggregate3() {
- helpValidate("SELECT SUM(e2) FROM test.group GROUP BY e2", new String[] {"SUM(e2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testInvalidAggregate4() {
- helpValidate("SELECT AVG(e2) FROM test.group GROUP BY e2", new String[] {"AVG(e2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @Test public void testValidAggregate1() {
- helpValidate("SELECT (e2 + 1) * 2 frOM pm1.g1 GROUP BY e2 + 1", new String[] {}, FakeMetadataFactory.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$
- }
-
- @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());
- }
- @Test public void testInvalidHaving1() {
- helpValidate("SELECT e3 FROM test.group HAVING e3 > 0", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testInvalidHaving2() {
- helpValidate("SELECT e3 FROM test.group HAVING concat(e3,'a') > 0", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testNestedAggregateInHaving() {
- helpValidate("SELECT e0 FROM test.group GROUP BY e0 HAVING SUM(COUNT(e0)) > 0", new String[] {"COUNT(e0)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testNestedAggregateInSelect() {
- helpValidate("SELECT SUM(COUNT(e0)) FROM test.group GROUP BY e0", new String[] {"COUNT(e0)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @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$
- }
-
- @Test public void testValidateFunctionInGroupBy() {
- helpValidate("SELECT SUM(e2) FROM pm1.g1 GROUP BY (e2 + 1)", new String[] {}, FakeMetadataFactory.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$
- }
-
- @Test public void testInvalidConstantInGroupBy() {
- helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY 1", new String[] { "1" }, FakeMetadataFactory.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$
- }
-
- @Test public void testValidateObjectType1() {
- helpValidate("SELECT DISTINCT * FROM test.group", new String[] {"test.\"group\".e2", "test.\"group\".e3", "test.\"group\".e4", "test.\"group\".e5"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- }
-
- @Test public void testValidateObjectType2() {
- helpValidate("SELECT * FROM test.group ORDER BY e1, e2", new String[] {"e2"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateObjectType3() {
- helpValidate("SELECT e2 AS x FROM test.group ORDER BY x", new String[] {"x"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateNonComparableType() {
- helpValidate("SELECT e3 FROM test.group ORDER BY e3", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateNonComparableType1() {
- helpValidate("SELECT e3 FROM test.group union SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateNonComparableType2() {
- helpValidate("SELECT e3 FROM test.group GROUP BY e3", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateNonComparableType3() {
- helpValidate("SELECT e3 FROM test.group intersect SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateNonComparableType4() {
- helpValidate("SELECT e3 FROM test.group except SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @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$
- }
-
- @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$
- }
-
- @Test public void testInsert1() {
- helpValidate("INSERT INTO test.group (e0) VALUES (null)", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // non-null, no-default elements not left
- @Test public void testInsert4() throws Exception {
- QueryMetadataInterface metadata = exampleMetadata1();
-
- Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e0) VALUES (2)"); //$NON-NLS-1$
-
- QueryResolver.resolveCommand(command, metadata);
-
- helpRunValidator(command, new String[] {}, metadata);
- }
-
- // non-null, no-default elements left
- @Test public void testInsert5() throws Exception {
- QueryMetadataInterface metadata = exampleMetadata1();
-
- Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e1, e2) VALUES ('x', 'y')"); //$NON-NLS-1$
- QueryResolver.resolveCommand(command, metadata);
-
- helpRunValidator(command, new String[] {"test.\"group\".e0"}, metadata); //$NON-NLS-1$
- }
-
- @Test public void testValidateInsertElements1() throws Exception {
- QueryMetadataInterface metadata = exampleMetadata();
-
- Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group2 (e0, e1, e2) VALUES (5, 'x', 'y')"); //$NON-NLS-1$
- QueryResolver.resolveCommand(command, metadata);
-
- helpRunValidator(command, new String[] {"e2", "e0"}, metadata); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateInsertElements2() throws Exception {
- QueryMetadataInterface metadata = exampleMetadata();
-
- Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group2 (e1) VALUES ('y')"); //$NON-NLS-1$
-
- QueryResolver.resolveCommand(command, metadata);
-
- helpRunValidator(command, new String[] {}, metadata);
- }
-
- @Test public void testValidateInsertElements3_autoIncNotRequired() throws Exception {
- helpValidate("INSERT INTO test.group (e0) VALUES (1)", new String[] {}, exampleMetadata3()); //$NON-NLS-1$
- }
-
- @Test public void testUpdate1() {
- helpValidate("UPDATE test.group SET e0=null", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testUpdate2() {
- helpValidate("UPDATE test.group SET e0=1, e0=2", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateUpdateElements1() throws Exception {
- QueryMetadataInterface metadata = exampleMetadata();
-
- Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group2 SET e0 = 5, e1 = 'x', e2 = 'y'"); //$NON-NLS-1$
- QueryResolver.resolveCommand(command, metadata);
-
- helpRunValidator(command, new String[] {"e2", "e0"}, metadata); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateUpdateElements2() throws Exception {
- QueryMetadataInterface metadata = exampleMetadata();
-
- Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group2 SET e1 = 'x'"); //$NON-NLS-1$
- QueryResolver.resolveCommand(command, metadata);
-
- helpRunValidator(command, new String[] {}, metadata);
- }
- @Test public void testXMLQuery1() {
- helpValidate("SELECT * FROM vm1.doc1", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testXMLQuery2() {
- helpValidate("SELECT * FROM vm1.doc1 where a2='x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testXMLQuery3() {
- helpValidate("SELECT * FROM vm1.doc1 order by a2", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testXMLQuery6() {
- helpValidate("SELECT * FROM vm1.doc1 UNION SELECT * FROM vm1.doc1", new String[] {"\"xml\"", "SELECT * FROM vm1.doc1 UNION SELECT * FROM vm1.doc1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Test public void testXMLQueryWithLimit() {
- helpValidate("SELECT * FROM vm1.doc1 limit 1", new String[] {"SELECT * FROM vm1.doc1 LIMIT 1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** test rowlimit function is valid */
- @Test public void testXMLQueryRowLimit() {
- helpValidate("SELECT * FROM vm1.doc1 where 2 = RowLimit(a2)", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- /** rowlimit function operand must be nonnegative integer */
- @Test public void testXMLQueryRowLimit1() {
- helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)=-1", new String[] {"RowLimit(a2) = -1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimit function operand must be nonnegative integer */
- @Test public void testXMLQueryRowLimit2() {
- helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)='x'", new String[] {"RowLimit(a2) = 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimit function cannot be nested within another function (this test inserts an implicit type conversion) */
- @Test public void testXMLQueryRowLimitNested() {
- helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)=a2", new String[] {"RowLimit(a2) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimit function cannot be nested within another function */
- @Test public void testXMLQueryRowLimitNested2() {
- helpValidate("SELECT * FROM vm1.doc1 where convert(RowLimit(a2), string)=a2", new String[] {"convert(RowLimit(a2), string) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimit function operand must be nonnegative integer */
- @Test public void testXMLQueryRowLimit3a() {
- helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2) = convert(a2, integer)", new String[] {"RowLimit(a2) = convert(a2, integer)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimit function operand must be nonnegative integer */
- @Test public void testXMLQueryRowLimit3b() {
- helpValidate("SELECT * FROM vm1.doc1 where convert(a2, integer) = RowLimit(a2)", new String[] {"convert(a2, integer) = RowLimit(a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimit function arg must be an element symbol */
- @Test public void testXMLQueryRowLimit4() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit('x') = 3", new String[] {"rowlimit('x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimit function arg must be an element symbol */
- @Test public void testXMLQueryRowLimit5() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit(concat(a2, 'x')) = 3", new String[] {"rowlimit(concat(a2, 'x'))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimit function arg must be a single conjunct */
- @Test public void testXMLQueryRowLimitConjunct() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 OR a2 = 'x'", new String[] {"(rowlimit(a2) = 3) OR (a2 = 'x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimit function arg must be a single conjunct */
- @Test public void testXMLQueryRowLimitCompound() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND a2 = 'x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- /** rowlimit function arg must be a single conjunct */
- @Test public void testXMLQueryRowLimitCompound2() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND concat(a2, 'y') = 'xy'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- /** rowlimit function arg must be a single conjunct */
- @Test public void testXMLQueryRowLimitCompound3() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND (concat(a2, 'y') = 'xy' OR concat(a2, 'y') = 'zy')", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- /** each rowlimit function arg must be a single conjunct */
- @Test public void testXMLQueryRowLimitCompound4() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND rowlimit(c2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- /**
- * It doesn't make sense to use rowlimit twice on same element, but can't be
- * invalidated here (could be two different elements but in the same
- * mapping class - needs to be caught in XMLPlanner)
- */
- @Test public void testXMLQueryRowLimitCompound5() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND rowlimit(a2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testXMLQueryRowLimitInvalidCriteria() {
- helpValidate("SELECT * FROM vm1.doc1 where not(rowlimit(a2) = 3)", new String[] {"NOT (rowlimit(a2) = 3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitInvalidCriteria2() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IN (3)", new String[] {"rowlimit(a2) IN (3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitInvalidCriteria3() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) LIKE 'x'", new String[] {"rowlimit(a2) LIKE 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitInvalidCriteria4() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IS NULL", new String[] {"rowlimit(a2) IS NULL"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitInvalidCriteria5() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IN (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimit(a2) IN (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitInvalidCriteria6() {
- helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE WHEN rowlimit(a2) = 2 THEN 2 END", new String[] {"2 = CASE WHEN rowlimit(a2) = 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitInvalidCriteria6a() {
- helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE rowlimit(a2) WHEN 2 THEN 2 END", new String[] {"2 = CASE rowlimit(a2) WHEN 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitInvalidCriteria7() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) BETWEEN 2 AND 3", new String[] {"rowlimit(a2) BETWEEN 2 AND 3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitInvalidCriteria8() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = ANY (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimit(a2) = ANY (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** using rowlimit pseudo-function in non-XML query is invalid */
- @Test public void testNonXMLQueryRowLimit() {
- helpValidate("SELECT e2 FROM vTest.vMap WHERE rowlimit(e1) = 2", new String[] {"rowlimit(e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** test rowlimitexception function is valid */
- @Test public void testXMLQueryRowLimitException() {
- helpValidate("SELECT * FROM vm1.doc1 where 2 = RowLimitException(a2)", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- /** rowlimitexception function operand must be nonnegative integer */
- @Test public void testXMLQueryRowLimitException1() {
- helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)=-1", new String[] {"RowLimitException(a2) = -1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimitexception function operand must be nonnegative integer */
- @Test public void testXMLQueryRowLimitException2() {
- helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)='x'", new String[] {"RowLimitException(a2) = 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimitexception function cannot be nested within another function (this test inserts an implicit type conversion) */
- @Test public void testXMLQueryRowLimitExceptionNested() {
- helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)=a2", new String[] {"RowLimitException(a2) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimitexception function cannot be nested within another function */
- @Test public void testXMLQueryRowLimitExceptionNested2() {
- helpValidate("SELECT * FROM vm1.doc1 where convert(RowLimitException(a2), string)=a2", new String[] {"convert(RowLimitException(a2), string) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimitexception function operand must be nonnegative integer */
- @Test public void testXMLQueryRowLimitException3a() {
- helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2) = convert(a2, integer)", new String[] {"RowLimitException(a2) = convert(a2, integer)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimitexception function operand must be nonnegative integer */
- @Test public void testXMLQueryRowLimitException3b() {
- helpValidate("SELECT * FROM vm1.doc1 where convert(a2, integer) = RowLimitException(a2)", new String[] {"convert(a2, integer) = RowLimitException(a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimitexception function arg must be an element symbol */
- @Test public void testXMLQueryRowLimitException4() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception('x') = 3", new String[] {"rowlimitexception('x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimitexception function arg must be an element symbol */
- @Test public void testXMLQueryRowLimitException5() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(concat(a2, 'x')) = 3", new String[] {"rowlimitexception(concat(a2, 'x'))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimitexception function arg must be a single conjunct */
- @Test public void testXMLQueryRowLimitExceptionConjunct() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 OR a2 = 'x'", new String[] {"(rowlimitexception(a2) = 3) OR (a2 = 'x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** rowlimitexception function arg must be a single conjunct */
- @Test public void testXMLQueryRowLimitExceptionCompound() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND a2 = 'x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- /** rowlimitexception function arg must be a single conjunct */
- @Test public void testXMLQueryRowLimitExceptionCompound2() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND concat(a2, 'y') = 'xy'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- /** rowlimitexception function arg must be a single conjunct */
- @Test public void testXMLQueryRowLimitExceptionCompound3() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND (concat(a2, 'y') = 'xy' OR concat(a2, 'y') = 'zy')", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- /** each rowlimitexception function arg must be a single conjunct */
- @Test public void testXMLQueryRowLimitExceptionCompound4() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND rowlimitexception(c2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- /**
- * It doesn't make sense to use rowlimitexception twice on same element, but can't be
- * invalidated here (could be two different elements but in the same
- * mapping class - needs to be caught in XMLPlanner)
- */
- @Test public void testXMLQueryRowLimitExceptionCompound5() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND rowlimitexception(a2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testXMLQueryRowLimitExceptionInvalidCriteria() {
- helpValidate("SELECT * FROM vm1.doc1 where not(rowlimitexception(a2) = 3)", new String[] {"NOT (rowlimitexception(a2) = 3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitExceptionInvalidCriteria2() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IN (3)", new String[] {"rowlimitexception(a2) IN (3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitExceptionInvalidCriteria3() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) LIKE 'x'", new String[] {"rowlimitexception(a2) LIKE 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitExceptionInvalidCriteria4() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IS NULL", new String[] {"rowlimitexception(a2) IS NULL"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitExceptionInvalidCriteria5() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IN (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimitexception(a2) IN (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitExceptionInvalidCriteria6() {
- helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE WHEN rowlimitexception(a2) = 2 THEN 2 END", new String[] {"2 = CASE WHEN rowlimitexception(a2) = 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitExceptionInvalidCriteria6a() {
- helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE rowlimitexception(a2) WHEN 2 THEN 2 END", new String[] {"2 = CASE rowlimitexception(a2) WHEN 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitExceptionInvalidCriteria7() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) BETWEEN 2 AND 3", new String[] {"rowlimitexception(a2) BETWEEN 2 AND 3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testXMLQueryRowLimitExceptionInvalidCriteria8() {
- helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = ANY (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimitexception(a2) = ANY (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** using rowlimit pseudo-function in non-XML query is invalid */
- @Test public void testNonXMLQueryRowLimitException() {
- helpValidate("SELECT e2 FROM vTest.vMap WHERE rowlimitexception(e1) = 2", new String[] {"rowlimitexception(e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /** using context pseudo-function in non-XML query is invalid */
- @Test public void testNonXMLQueryContextOperator() {
- helpValidate("SELECT e2 FROM vTest.vMap WHERE context(e1, e1) = 2", new String[] {"context(e1, e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateSubquery1() {
- helpValidate("SELECT e2 FROM (SELECT e2 FROM vTest.vMap WHERE e2 = 'a') AS x", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testValidateSubquery2() {
- helpValidate("SELECT e2 FROM (SELECT e3 FROM vTest.vMap) AS x, vTest.vMap WHERE e2 = 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testValidateSubquery3() {
- helpValidate("SELECT * FROM pm1.g1, (EXEC pm1.sq1( )) AS alias", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
- }
-
- @Test public void testValidateUnionWithSubquery() {
- helpValidate("SELECT e2 FROM test.group2 union all SELECT e3 FROM test.group union all select * from (SELECT e1 FROM test.group) as subquery1", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateExistsSubquery() {
- helpValidate("SELECT e2 FROM test.group2 WHERE EXISTS (SELECT e2 FROM vTest.vMap WHERE e2 = 'a')", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testValidateScalarSubquery() {
- helpValidate("SELECT e2, (SELECT e1 FROM vTest.vMap WHERE e2 = '3') FROM test.group2", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateAnyCompareSubquery() {
- helpValidate("SELECT e2 FROM test.group2 WHERE e1 < ANY (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateAllCompareSubquery() {
- helpValidate("SELECT e2 FROM test.group2 WHERE e1 = ALL (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateSomeCompareSubquery() {
- helpValidate("SELECT e2 FROM test.group2 WHERE e1 <= SOME (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateCompareSubquery() {
- helpValidate("SELECT e2 FROM test.group2 WHERE e1 >= (SELECT e1 FROM test.group WHERE e1 = 1)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateInClauseSubquery() {
- helpValidate("SELECT e2 FROM test.group2 WHERE e1 IN (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateExec1() {
- helpValidate("EXEC pm1.sq1()", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
- }
-
- // valid variable declared
- @Test public void testCreateUpdateProcedure4() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpValidateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // validating criteria selector(on HAS CRITERIA), elements on it should be virtual group elements
- @Test public void testCreateUpdateProcedure5() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(HAS CRITERIA ON (vm1.g1.E1, vm1.g1.e1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpValidateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // validating Translate CRITERIA, elements on it should be virtual group elements
- @Test public void testCreateUpdateProcedure7() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpValidateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // ROWS_UPDATED not assigned
- @Test public void testCreateUpdateProcedure8() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1);\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // validating AssignmentStatement, more than one project symbol on the
- // command
- @Test public void testCreateUpdateProcedure11() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2, pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // validating AssignmentStatement, more than one project symbol on the
- // command
- @Test public void testCreateUpdateProcedure12() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = Select pm1.g1.e2, pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // TranslateCriteria on criteria of the if statement
- @Test public void testCreateUpdateProcedure13() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "if(TRANSLATE CRITERIA ON (vm1.g1.e1) WITH (vm1.g1.e1 = 1))\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpValidateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // INPUT ised in command
- @Test public void testCreateUpdateProcedure16() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "INSERT into pm1.g1 (pm1.g1.e1) values (INPUT.e1);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpValidateProcedure(procedure, userUpdateStr,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- // elements on with should be on ON
- @Test public void testCreateUpdateProcedure17() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e1) WITH (e1 = 20, e2 = 30);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- // failure, aggregate function in query transform
- @Ignore
- @Test public void testCreateUpdateProcedure18() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA ON (e3);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- // failure, aggregate function in query transform
- @Ignore
- @Test public void testCreateUpdateProcedure18a() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA ON (e3);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- 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);
- }
-
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- // failure, translated criteria elements not present on groups of command
- @Test public void testCreateUpdateProcedure19() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE = CRITERIA ON (x, y);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y= 1"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- @Test public void testCreateUpdateProcedure20() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (y = e2+1);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y= 1"; //$NON-NLS-1$
-
- helpValidateProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- @Test public void testCreateUpdateProcedure25() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE > CRITERIA ON (y);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y > 1"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- @Test public void testCreateUpdateProcedure26() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (e3 = e2+1);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where e3 > 1"; //$NON-NLS-1$
-
- helpValidateProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
- @Test public void testCreateUpdateProcedure27() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE LIKE CRITERIA WITH (y = e2+1);\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
- helpValidateProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // using aggregate function within a procedure - defect #8394
- @Test public void testCreateUpdateProcedure31() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE string MaxTran;\n"; //$NON-NLS-1$
- procedure = procedure + "MaxTran = SELECT MAX(e1) FROM pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
- helpValidateProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- // assigning null values to known datatype variable
- @Test public void testCreateUpdateProcedure32() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE string var;\n"; //$NON-NLS-1$
- procedure = procedure + "var = null;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
- helpValidateProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testDefect13643() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
- procedure = procedure + "LOOP ON (SELECT * FROM pm1.g1) AS myCursor\n"; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "var1 = SELECT COUNT(*) FROM myCursor;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testValidHaving() {
- helpValidate(
- "SELECT intnum " + //$NON-NLS-1$
- "FROM bqt1.smalla " + //$NON-NLS-1$
- "GROUP BY intnum " + //$NON-NLS-1$
- "HAVING SUM(floatnum) > 1", //$NON-NLS-1$
- new String[] { }, FakeMetadataFactory.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());
- }
-
- @Test public void testVirtualProcedure(){
- helpValidate("EXEC pm1.vsp1()", new String[] { }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
- }
-
- @Test public void testSelectWithNoFrom() {
- helpValidate("SELECT 5", new String[] {}, exampleMetadata()); //$NON-NLS-1$
- }
-
- @Test public void testSelectIntoTempGroup() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
- helpValidateProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- /**
- * Defect 24346
- */
- @Test public void testInvalidSelectIntoTempGroup() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g2;\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1, e2, e3 INTO #myTempTable FROM pm1.g2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- /**
- * Defect 24346 with type mismatch
- */
- @Test public void testInvalidSelectIntoTempGroup1() {
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "create local temporary table #myTempTable (e1 integer);\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1 INTO #myTempTable FROM pm1.g2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
-
- @Test public void testSelectIntoPhysicalGroup() {
- helpValidate("SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2", new String[] { }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
-
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
- helpValidateProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testSelectIntoPhysicalGroupNotUpdateable_Defect16857() {
- helpValidate("SELECT e0, e1, e2 INTO test.group3 FROM test.group2", new String[] {"test.group3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testSelectIntoElementsNotUpdateable() {
- helpValidate("SELECT e0, e1, e2 INTO test.group2 FROM test.group3", new String[] {"test.group2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @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$
-
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @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$
-
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @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$
-
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testSelectIntoWithStar() {
- helpResolve("SELECT * INTO pm1.g1 FROM pm1.g2", FakeMetadataFactory.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$
-
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
- helpFailProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testSelectIntoVirtualGroup() {
- helpValidate("SELECT e1, e2, e3, e4 INTO vm1.g1 FROM pm1.g2", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
-
- String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
- procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
- procedure = procedure + "SELECT e1, e2, e3, e4 INTO vm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
- procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
- procedure = procedure + "END\n"; //$NON-NLS-1$
-
- String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
- helpValidateProcedure(procedure, userQuery,
- FakeMetadataObject.Props.UPDATE_PROCEDURE);
- }
-
- @Test public void testVirtualProcedure2(){
- helpValidate("EXEC pm1.vsp13()", new String[] { }, FakeMetadataFactory.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$
- }
-
- @Test public void testNonEmbeddedSubcommand_defect11000() {
- helpValidate("SELECT e0 FROM vTest.vGroup", new String[0], exampleMetadata()); //$NON-NLS-1$
- }
-
- @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$
- 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();
-
- Command command = new QueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(command, metadata);
-
- // Validate
- ValidatorReport report = Validator.validate(command, metadata);
- assertEquals(0, report.getItems().size());
- }
-
- @Test public void testDefect9917() throws Exception{
- QueryMetadataInterface metadata = FakeMetadataFactory.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{
- QueryResolver.resolveCommand(command, metadata);
- fail("Did not get exception"); //$NON-NLS-1$
- }catch(QueryResolverException e){
- //expected
- }
-
- sql = "SELECT lookup('pm1.g1a', 'e1', 'e2', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
- command = new QueryParser().parseCommand(sql);
- try{
- QueryResolver.resolveCommand(command, metadata);
- fail("Did not get exception"); //$NON-NLS-1$
- }catch(QueryResolverException e){
- //expected
- }
- }
-
- @Test public void testLookupKeyElementComparable() throws Exception {
- QueryMetadataInterface metadata = exampleMetadata2();
- String sql = "SELECT lookup('test.group', 'e2', 'e3', convert(e2, blob)) AS x FROM test.group"; //$NON-NLS-1$
- Command command = QueryParser.getQueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(command, metadata);
-
- ValidatorReport report = Validator.validate(command, metadata);
- assertEquals("Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used as LOOKUP key columns: test.\"group\".e3.", report.toString()); //$NON-NLS-1$
- }
-
- @Test public void testDefect12107() throws Exception{
- QueryMetadataInterface metadata = FakeMetadataFactory.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$
- command = helpResolve(sql, metadata);
- ValidatorReport report = Validator.validate(command, metadata);
- assertEquals("The aggregate function SUM cannot be used with non-numeric expressions: SUM(DISTINCT lookup('pm1.g1', 'e3', 'e2', e2))", report.toString()); //$NON-NLS-1$
- }
-
- private ValidatorReport helpValidateInModeler(String procName, String procSql, QueryMetadataInterface metadata) throws Exception {
- Command command = new QueryParser().parseCommand(procSql);
-
- GroupSymbol group = new GroupSymbol(procName);
- QueryResolver.resolveCommand(command, group, Command.TYPE_STORED_PROCEDURE, metadata);
-
- // Validate
- return Validator.validate(command, metadata);
- }
-
- @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();
-
- // Validate
- ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata); //$NON-NLS-1$
- assertEquals(1, report.getItems().size());
- assertEquals("Wrong number of elements being SELECTed INTO the target table. Expected 4 elements, but was 1.", report.toString()); //$NON-NLS-1$
- }
-
- @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();
-
- // Validate
- ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata); //$NON-NLS-1$
- assertEquals(1, report.getItems().size());
- assertEquals("Elements cannot appear more than once in a SET or USING clause. The following elements are duplicated: [DVARS.id]", report.toString()); //$NON-NLS-1$
- }
-
- @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();
-
- // Validate
- ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata); //$NON-NLS-1$
- assertEquals(0, report.getItems().size());
- }
-
- @Test public void testDefect12533() {
- 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();
-
- // Validate
- helpValidate(sql, new String[] {"BQT1.SmallA.ObjectValue = BQT2.SmallB.ObjectValue"}, metadata); //$NON-NLS-1$
- }
-
- @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();
-
- // 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 testDefect14886() throws Exception{
- String sql = "CREATE VIRTUAL PROCEDURE BEGIN END"; //$NON-NLS-1$
- QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-
- Command command = new QueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(command, metadata);
-
- // Validate
- ValidatorReport report = Validator.validate(command, metadata);
- // Validate
- assertEquals(0, report.getItems().size());
- }
-
- @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);
-
- Command command = new QueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(command, metadata);
-
- // Validate
- ValidatorReport report = Validator.validate(command, metadata);
- // Validate
- assertEquals(0, report.getItems().size());
- }
-
- @Test public void testMakeNotDep() {
- helpValidate("select group2.e1, group3.e2 from group2, group3 WHERE group2.e0 = group3.e0 OPTION MAKENOTDEP group2, group3", new String[0], exampleMetadata()); //$NON-NLS-1$
- }
- @Test public void testInvalidMakeNotDep() {
- helpValidate("select group2.e1, group3.e2 from group2, group3 WHERE group2.e0 = group3.e0 OPTION MAKEDEP group2 MAKENOTDEP group2, group3", new String[] {"OPTION MAKEDEP group2 MAKENOTDEP group2, group3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testInvalidLimit() {
- helpValidate("SELECT * FROM pm1.g1 LIMIT -5", new String[] {"LIMIT -5"}, FakeMetadataFactory.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$
- }
-
- /**
- * Test case 4237. This test simulates the way the modeler transformation
- * panel uses the query resolver and validator to validate a transformation for
- * a virtual procedure. The modeler has to supply external metadata for the
- * virtual procedure group and parameter names (simulated in this test).
- *
- * This virtual procedure calls a physical stored procedure directly.
- */
- @Test public void testCase4237() {
-
- FakeMetadataFacade 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);
- helpRunValidator(command, new String[0], metadata);
- }
-
- /**
- * This test was already working before the case was logged, due for some reason
- * to the exec() statement being inside an inline view. This is a control test.
- */
- @Test public void testCase4237InlineView() {
-
- FakeMetadataFacade 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);
- helpRunValidator(command, new String[0], metadata);
- }
-
- /**
- * Create fake metadata for this case. Need a physical stored procedure and
- * 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$
-
- 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$
- 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);
- }
-
- @Test public void testSelectIntoWithNull() {
- helpValidate("SELECT null, null, null, null INTO pm1.g1 FROM pm1.g2", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
- }
-
- @Test public void testCreateWithNonSortablePrimaryKey() {
- QueryMetadataInterface metadata = FakeMetadataFactory.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());
- }
-
- @Test public void testDropNonTemporary() {
- QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
- Command command = helpResolve("drop table pm1.g1", metadata); //$NON-NLS-1$
- helpRunValidator(command, new String[] {command.toString()}, FakeMetadataFactory.example1Cached());
- }
-
- @Test public void testNestedContexts() {
- helpValidate("SELECT * FROM vm1.doc1 where context(a0, context(a0, a2))='x'", new String[] {"context(a0, context(a0, a2))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidContextElement() {
- helpValidate("SELECT * FROM vm1.doc1 where context(1, a2)='x'", new String[] {"context(1, a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testInsertIntoVirtualWithQuery() throws Exception {
- QueryMetadataInterface metadata = FakeMetadataFactory.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());
- }
-
- @Test public void testDynamicIntoDeclaredTemp() throws Exception {
- StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE ") //$NON-NLS-1$
- .append("BEGIN\n") //$NON-NLS-1$
- .append("CREATE LOCAL TEMPORARY TABLE x (column1 string);") //$NON-NLS-1$
- .append("execute string 'SELECT e1 FROM pm1.g2' as e1 string INTO x;\n") //$NON-NLS-1$
- .append("select column1 from x;\n") //$NON-NLS-1$
- .append("END\n"); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-
- // Validate
- ValidatorReport report = helpValidateInModeler("pm1.vsp36", procedure.toString(), metadata); //$NON-NLS-1$
- assertEquals(report.toString(), 0, report.getItems().size());
- }
-
- @Test public void testVariablesGroupSelect() {
- String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
- procedure += "BEGIN\n"; //$NON-NLS-1$
- procedure += "DECLARE integer VARIABLES.var1 = 1;\n"; //$NON-NLS-1$
- procedure += "select * from variables;\n"; //$NON-NLS-1$
- procedure += "END\n"; //$NON-NLS-1$
-
- QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-
- Command command = helpResolve(procedure, metadata);
- helpRunValidator(command, new String[] {"variables"}, metadata); //$NON-NLS-1$
- }
-
- @Test public void testClobEquals() {
- TestValidator.helpValidate("SELECT * FROM test.group where e4 = '1'", new String[] {"e4 = '1'"}, TestValidator.exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Should not fail since the update changing set is not really criteria
- */
- @Test public void testUpdateWithClob() {
- TestValidator.helpValidate("update test.group set e4 = ?", new String[] {}, TestValidator.exampleMetadata2()); //$NON-NLS-1$
- }
-
- @Test public void testBlobLessThan() {
- TestValidator.helpValidate("SELECT * FROM test.group where e3 < ?", new String[] {"e3 < ?"}, TestValidator.exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateCompare2() {
- helpValidate("SELECT e2 FROM test.group WHERE e4 IS NULL", new String[] {}, exampleMetadata2()); //$NON-NLS-1$
- }
-
- @Test public void testValidateCompare3() {
- helpValidate("SELECT e2 FROM test.group WHERE e4 IN ('a')", new String[] {"e4 IN ('a')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateCompare5() {
- helpValidate("SELECT e2 FROM test.group WHERE e4 BETWEEN '1' AND '2'", new String[] {"e4 BETWEEN '1' AND '2'"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateCompareInHaving1() {
- helpValidate("SELECT e1 FROM test.group GROUP BY e1 HAVING convert(e1, clob) = 'a'", new String[] {"convert(e1, clob) = 'a'"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateNoExpressionName() {
- helpValidate("SELECT xmlelement(name a, xmlattributes('1'))", new String[] {"XMLATTRIBUTES('1')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @Test public void testValidateNoExpressionName1() {
- helpValidate("SELECT xmlforest('1')", new String[] {"XMLFOREST('1')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- @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());
- }
-
- @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());
- }
-
- @Test public void testTextTableNegativeWidth() {
- helpValidate("SELECT * from texttable(null columns x string width -1) as x", new String[] {"TEXTTABLE(null COLUMNS x string WIDTH -1) AS x"}, RealMetadataFactory.exampleBQTCached());
- }
-
- @Test public void testTextTableNoWidth() {
- helpValidate("SELECT * from texttable(null columns x string width 1, y integer) as x", new String[] {"TEXTTABLE(null COLUMNS x string WIDTH 1, y integer) AS x"}, RealMetadataFactory.exampleBQTCached());
- }
-
- @Test public void testTextTableInvalidDelimiter() {
- 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 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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @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());
- }
-
- @Test public void testXMLTablePassingContextType() {
- helpValidate("select * from pm1.g1, xmltable('/' passing 2) as x", new String[] {"XMLTABLE('/' PASSING 2) AS x"}, FakeMetadataFactory.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());
- }
-
- @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());
- }
-
- @Test public void testXMLQueryPassingContextType() {
- helpValidate("select xmlquery('/' passing 2)", new String[] {"XMLQUERY('/' PASSING 2)"}, FakeMetadataFactory.example1Cached());
- }
-
- @Test public void testQueryString() {
- helpValidate("select querystring('/', '1')", new String[] {"QUERYSTRING('/', '1')"}, FakeMetadataFactory.example1Cached());
- }
-
- @Test public void testXmlNameValidation() throws Exception {
- helpValidate("select xmlelement(\":\")", new String[] {"XMLELEMENT(NAME \":\")"}, FakeMetadataFactory.example1Cached());
- }
-
- @Test public void testXmlParse() throws Exception {
- helpValidate("select xmlparse(content e2) from pm1.g1", new String[] {"XMLPARSE(CONTENT e2)"}, FakeMetadataFactory.example1Cached());
- }
-
- @Test public void testDecode() throws Exception {
- helpValidate("select to_bytes(e1, '?') from pm1.g1", new String[] {"to_bytes(e1, '?')"}, FakeMetadataFactory.example1Cached());
- }
-
- @Test public void testValidateXMLAGG() {
- helpValidate("SELECT XMLAGG(e1) from pm1.g1", new String[] {"XMLAGG(e1)"}, FakeMetadataFactory.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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @Test public void testInvalidIntoSubquery4() throws Exception {
- StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE\n") //$NON-NLS-1$
- .append("BEGIN\n") //$NON-NLS-1$
- .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();
-
- // Validate
- ValidatorReport report = helpValidateInModeler("pm1.vsp36", procedure.toString(), metadata); //$NON-NLS-1$
- examineReport(procedure, new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, report);
- }
-
- @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$
- 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$
- }
-
- @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$
- }
-
- @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$
- }
-
- @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$
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java (from rev 3218, trunk/engine/src/test/java/org/teiid/query/validator/TestValidator.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,1843 @@
+/*
+ * 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 static org.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryResolverException;
+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.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;
+import org.teiid.query.sql.lang.Command;
+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.RealMetadataFactory;
+
+ at SuppressWarnings("nls")
+public class TestValidator {
+
+ public static TransformationMetadata exampleMetadata() {
+ MetadataStore metadataStore = new MetadataStore();
+ // Create metadata objects
+ 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);
+
+ 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);
+
+ 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$
+ 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$
+ 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 });
+ 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);
+ MappingElement complexRoot = doc.addChildElement(new MappingElement("a0")); //$NON-NLS-1$
+
+ MappingElement sourceNode = complexRoot.addChildElement(new MappingElement("a1")); //$NON-NLS-1$
+ sourceNode.setSource("test.group"); //$NON-NLS-1$
+ sourceNode.addChildElement(new MappingElement("a2", "test.group.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+ 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$
+
+ 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 });
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "example");
+ }
+
+ public TransformationMetadata exampleMetadata1() {
+ MetadataStore metadataStore = new MetadataStore();
+ // Create metadata objects
+ Schema modelObj = RealMetadataFactory.createPhysicalModel("test", 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$
+ 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.setNullType(NullType.No_Nulls);
+
+ elemObj1.setNullType(NullType.Nullable);
+ elemObj1.setDefaultValue(Boolean.TRUE.toString());
+
+ elemObj2.setNullType(NullType.Nullable);
+ elemObj2.setDefaultValue(Boolean.FALSE.toString());
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "example1");
+ }
+
+ /**
+ * Group has element with type object
+ * @return QueryMetadataInterface
+ */
+ public static TransformationMetadata exampleMetadata2() {
+ MetadataStore metadataStore = new MetadataStore();
+ // Create metadata objects
+ Schema modelObj = RealMetadataFactory.createPhysicalModel("test", metadataStore); //$NON-NLS-1$
+ Table groupObj = RealMetadataFactory.createPhysicalGroup("group", modelObj); //$NON-NLS-1$
+
+ 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,
+ DataTypeManager.DefaultDataTypes.STRING,
+ DataTypeManager.DefaultDataTypes.OBJECT,
+ DataTypeManager.DefaultDataTypes.BLOB,
+ DataTypeManager.DefaultDataTypes.CLOB,
+ DataTypeManager.DefaultDataTypes.XML,
+ });
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "example2");
+ }
+
+ public static TransformationMetadata exampleMetadata3() {
+ MetadataStore metadataStore = new MetadataStore();
+ // Create metadata objects
+ 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$
+ Column elemObj1 = RealMetadataFactory.createElement("e1", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$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$
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "example3");
+ }
+
+ public static TransformationMetadata exampleMetadata4() {
+ MetadataStore metadataStore = new MetadataStore();
+ // Create metadata objects
+ 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$
+ 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);
+ RealMetadataFactory.createAccessPattern("ap1", vGroupObj, elements); //e1 //$NON-NLS-1$
+
+ QueryNode vNode2 = new QueryNode("SELECT * FROM vTest.vGroup"); //$NON-NLS-1$ //$NON-NLS-2$
+ 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);
+ RealMetadataFactory.createAccessPattern("vTest.vGroup2.ap1", vGroupObj2, elements); //e1 //$NON-NLS-1$
+
+ return RealMetadataFactory.createTransformationMetadata(metadataStore, "example4");
+ }
+
+ // ################################## TEST HELPERS ################################
+
+ static Command helpResolve(String sql, QueryMetadataInterface metadata) {
+ Command command = null;
+
+ try {
+ command = QueryParser.getQueryParser().parseCommand(sql);
+ QueryResolver.resolveCommand(command, metadata);
+ } catch(Exception e) {
+ throw new TeiidRuntimeException(e);
+ }
+
+ return command;
+ }
+
+ static Command helpResolve(String sql, GroupSymbol container, int type, QueryMetadataInterface metadata) {
+ Command command = null;
+
+ try {
+ command = QueryParser.getQueryParser().parseCommand(sql);
+ QueryResolver.resolveCommand(command, container, type, metadata);
+ } catch(Exception e) {
+ throw new TeiidRuntimeException(e);
+ }
+
+ return command;
+ }
+
+ static ValidatorReport helpValidate(String sql, String[] expectedStringArray, QueryMetadataInterface metadata) {
+ Command command = helpResolve(sql, metadata);
+
+ return helpRunValidator(command, expectedStringArray, metadata);
+ }
+
+ public static ValidatorReport helpRunValidator(Command command, String[] expectedStringArray, QueryMetadataInterface metadata) {
+ try {
+ ValidatorReport report = Validator.validate(command, metadata);
+
+ examineReport(command, expectedStringArray, report);
+ return report;
+ } catch(TeiidException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+
+ private static void examineReport(Object command,
+ String[] expectedStringArray, ValidatorReport report) {
+ // Get invalid objects from report
+ Collection<LanguageObject> actualObjs = new ArrayList<LanguageObject>();
+ report.collectInvalidObjects(actualObjs);
+
+ // Compare expected and actual objects
+ Set<String> expectedStrings = new HashSet<String>(Arrays.asList(expectedStringArray));
+ Set<String> actualStrings = new HashSet<String>();
+ for (LanguageObject obj : actualObjs) {
+ actualStrings.add(SQLStringVisitor.getSQLString(obj));
+ }
+
+ if(expectedStrings.size() == 0 && actualStrings.size() > 0) {
+ fail("Expected no failures but got some: " + report.getFailureMessage()); //$NON-NLS-1$
+ } else if(actualStrings.size() == 0 && expectedStrings.size() > 0) {
+ fail("Expected some failures but got none for sql = " + command); //$NON-NLS-1$
+ } else {
+ assertEquals("Expected and actual sets of strings are not the same: ", expectedStrings, actualStrings); //$NON-NLS-1$
+ }
+ }
+
+ private void helpValidateProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType) {
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(procedureType, procedure);
+
+ try {
+ validateProcedure(userUpdateStr, metadata);
+ } catch(TeiidException e) {
+ throw new TeiidRuntimeException(e);
+ }
+ }
+
+ private void validateProcedure(String userUpdateStr,
+ QueryMetadataInterface metadata) throws QueryResolverException,
+ QueryMetadataException, TeiidComponentException,
+ QueryValidatorException {
+ ProcedureContainer command = (ProcedureContainer)helpResolve(userUpdateStr, metadata);
+
+ Command proc = QueryResolver.expandCommand(command, metadata, AnalysisRecord.createNonRecordingRecord());
+
+ ValidatorReport report = Validator.validate(proc, metadata);
+ if(report.hasItems()) {
+ throw new QueryValidatorException(report.getFailureMessage());
+ }
+
+ report = Validator.validate(command, metadata);
+ if(report.hasItems()) {
+ throw new QueryValidatorException(report.getFailureMessage());
+ }
+ }
+
+ private void helpFailProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType) {
+
+ QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(procedureType, procedure);
+
+ try {
+ validateProcedure(userUpdateStr, metadata);
+ fail("Expected failures for " + procedure);
+ } catch (QueryValidatorException e) {
+ } catch(TeiidException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ // ################################## ACTUAL TESTS ################################
+
+
+ @Test public void testSelectStarWhereNoElementsAreNotSelectable() {
+ helpValidate("SELECT * FROM pm1.g5", new String[] {"SELECT * FROM pm1.g5"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateSelect1() {
+ helpValidate("SELECT e1, e2 FROM test.group", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateSelect2() {
+ helpValidate("SELECT e2 FROM test.group", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testValidateCompare1() {
+ helpValidate("SELECT e2 FROM vTest.vMap WHERE e2 = 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testValidateCompare4() {
+ helpValidate("SELECT e3 FROM vTest.vMap WHERE e3 LIKE 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testValidateCompare6() {
+ helpValidate("SELECT e0 FROM vTest.vMap WHERE e0 BETWEEN 1000 AND 2000", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testValidateCompareInHaving2() {
+ helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 IS NULL", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testValidateCompareInHaving3() {
+ helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 IN ('a')", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testValidateCompareInHaving4() {
+ helpValidate("SELECT e3 FROM vTest.vMap GROUP BY e3 HAVING e3 LIKE 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testValidateCompareInHaving5() {
+ helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 BETWEEN 1000 AND 2000", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testInvalidAggregate1() {
+ helpValidate("SELECT SUM(e3) FROM test.group GROUP BY e2", new String[] {"SUM(e3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInvalidAggregate2() {
+ helpValidate("SELECT e3 FROM test.group GROUP BY e2", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInvalidAggregate3() {
+ helpValidate("SELECT SUM(e2) FROM test.group GROUP BY e2", new String[] {"SUM(e2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInvalidAggregate4() {
+ helpValidate("SELECT AVG(e2) FROM test.group GROUP BY e2", new String[] {"AVG(e2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInvalidAggregate5() {
+ 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"}, 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"}, 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)"}, 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)"}, 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"}, 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[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testValidAggregate2() {
+ 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[] {}, RealMetadataFactory.exampleBQTCached());
+ }
+ @Test public void testInvalidHaving1() {
+ helpValidate("SELECT e3 FROM test.group HAVING e3 > 0", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInvalidHaving2() {
+ helpValidate("SELECT e3 FROM test.group HAVING concat(e3,'a') > 0", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testNestedAggregateInHaving() {
+ helpValidate("SELECT e0 FROM test.group GROUP BY e0 HAVING SUM(COUNT(e0)) > 0", new String[] {"COUNT(e0)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testNestedAggregateInSelect() {
+ helpValidate("SELECT SUM(COUNT(e0)) FROM test.group GROUP BY e0", new String[] {"COUNT(e0)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateCaseInGroupBy() {
+ 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[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testInvalidScalarSubqueryInGroupBy() {
+ 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" }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInvalidReferenceInGroupBy() {
+ helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY ?", new String[] { "?" }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateObjectType1() {
+ helpValidate("SELECT DISTINCT * FROM test.group", new String[] {"test.\"group\".e2", "test.\"group\".e3", "test.\"group\".e4", "test.\"group\".e5"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ }
+
+ @Test public void testValidateObjectType2() {
+ helpValidate("SELECT * FROM test.group ORDER BY e1, e2", new String[] {"e2"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateObjectType3() {
+ helpValidate("SELECT e2 AS x FROM test.group ORDER BY x", new String[] {"x"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateNonComparableType() {
+ helpValidate("SELECT e3 FROM test.group ORDER BY e3", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateNonComparableType1() {
+ helpValidate("SELECT e3 FROM test.group union SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateNonComparableType2() {
+ helpValidate("SELECT e3 FROM test.group GROUP BY e3", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateNonComparableType3() {
+ helpValidate("SELECT e3 FROM test.group intersect SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateNonComparableType4() {
+ helpValidate("SELECT e3 FROM test.group except SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @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"}, 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"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInsert1() {
+ helpValidate("INSERT INTO test.group (e0) VALUES (null)", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ // non-null, no-default elements not left
+ @Test public void testInsert4() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata1();
+
+ Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e0) VALUES (2)"); //$NON-NLS-1$
+
+ QueryResolver.resolveCommand(command, metadata);
+
+ helpRunValidator(command, new String[] {}, metadata);
+ }
+
+ // non-null, no-default elements left
+ @Test public void testInsert5() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata1();
+
+ Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e1, e2) VALUES ('x', 'y')"); //$NON-NLS-1$
+ QueryResolver.resolveCommand(command, metadata);
+
+ helpRunValidator(command, new String[] {"test.\"group\".e0"}, metadata); //$NON-NLS-1$
+ }
+
+ @Test public void testValidateInsertElements1() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata();
+
+ Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group2 (e0, e1, e2) VALUES (5, 'x', 'y')"); //$NON-NLS-1$
+ QueryResolver.resolveCommand(command, metadata);
+
+ helpRunValidator(command, new String[] {"e2", "e0"}, metadata); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateInsertElements2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata();
+
+ Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group2 (e1) VALUES ('y')"); //$NON-NLS-1$
+
+ QueryResolver.resolveCommand(command, metadata);
+
+ helpRunValidator(command, new String[] {}, metadata);
+ }
+
+ @Test public void testValidateInsertElements3_autoIncNotRequired() throws Exception {
+ helpValidate("INSERT INTO test.group (e0) VALUES (1)", new String[] {}, exampleMetadata3()); //$NON-NLS-1$
+ }
+
+ @Test public void testUpdate1() {
+ helpValidate("UPDATE test.group SET e0=null", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testUpdate2() {
+ helpValidate("UPDATE test.group SET e0=1, e0=2", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateUpdateElements1() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata();
+
+ Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group2 SET e0 = 5, e1 = 'x', e2 = 'y'"); //$NON-NLS-1$
+ QueryResolver.resolveCommand(command, metadata);
+
+ helpRunValidator(command, new String[] {"e2", "e0"}, metadata); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateUpdateElements2() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata();
+
+ Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group2 SET e1 = 'x'"); //$NON-NLS-1$
+ QueryResolver.resolveCommand(command, metadata);
+
+ helpRunValidator(command, new String[] {}, metadata);
+ }
+ @Test public void testXMLQuery1() {
+ helpValidate("SELECT * FROM vm1.doc1", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLQuery2() {
+ helpValidate("SELECT * FROM vm1.doc1 where a2='x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLQuery3() {
+ helpValidate("SELECT * FROM vm1.doc1 order by a2", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLQuery6() {
+ helpValidate("SELECT * FROM vm1.doc1 UNION SELECT * FROM vm1.doc1", new String[] {"\"xml\"", "SELECT * FROM vm1.doc1 UNION SELECT * FROM vm1.doc1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ @Test public void testXMLQueryWithLimit() {
+ helpValidate("SELECT * FROM vm1.doc1 limit 1", new String[] {"SELECT * FROM vm1.doc1 LIMIT 1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** test rowlimit function is valid */
+ @Test public void testXMLQueryRowLimit() {
+ helpValidate("SELECT * FROM vm1.doc1 where 2 = RowLimit(a2)", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ /** rowlimit function operand must be nonnegative integer */
+ @Test public void testXMLQueryRowLimit1() {
+ helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)=-1", new String[] {"RowLimit(a2) = -1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimit function operand must be nonnegative integer */
+ @Test public void testXMLQueryRowLimit2() {
+ helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)='x'", new String[] {"RowLimit(a2) = 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimit function cannot be nested within another function (this test inserts an implicit type conversion) */
+ @Test public void testXMLQueryRowLimitNested() {
+ helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)=a2", new String[] {"RowLimit(a2) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimit function cannot be nested within another function */
+ @Test public void testXMLQueryRowLimitNested2() {
+ helpValidate("SELECT * FROM vm1.doc1 where convert(RowLimit(a2), string)=a2", new String[] {"convert(RowLimit(a2), string) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimit function operand must be nonnegative integer */
+ @Test public void testXMLQueryRowLimit3a() {
+ helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2) = convert(a2, integer)", new String[] {"RowLimit(a2) = convert(a2, integer)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimit function operand must be nonnegative integer */
+ @Test public void testXMLQueryRowLimit3b() {
+ helpValidate("SELECT * FROM vm1.doc1 where convert(a2, integer) = RowLimit(a2)", new String[] {"convert(a2, integer) = RowLimit(a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimit function arg must be an element symbol */
+ @Test public void testXMLQueryRowLimit4() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit('x') = 3", new String[] {"rowlimit('x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimit function arg must be an element symbol */
+ @Test public void testXMLQueryRowLimit5() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit(concat(a2, 'x')) = 3", new String[] {"rowlimit(concat(a2, 'x'))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimit function arg must be a single conjunct */
+ @Test public void testXMLQueryRowLimitConjunct() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 OR a2 = 'x'", new String[] {"(rowlimit(a2) = 3) OR (a2 = 'x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimit function arg must be a single conjunct */
+ @Test public void testXMLQueryRowLimitCompound() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND a2 = 'x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ /** rowlimit function arg must be a single conjunct */
+ @Test public void testXMLQueryRowLimitCompound2() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND concat(a2, 'y') = 'xy'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ /** rowlimit function arg must be a single conjunct */
+ @Test public void testXMLQueryRowLimitCompound3() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND (concat(a2, 'y') = 'xy' OR concat(a2, 'y') = 'zy')", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ /** each rowlimit function arg must be a single conjunct */
+ @Test public void testXMLQueryRowLimitCompound4() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND rowlimit(c2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ /**
+ * It doesn't make sense to use rowlimit twice on same element, but can't be
+ * invalidated here (could be two different elements but in the same
+ * mapping class - needs to be caught in XMLPlanner)
+ */
+ @Test public void testXMLQueryRowLimitCompound5() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND rowlimit(a2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLQueryRowLimitInvalidCriteria() {
+ helpValidate("SELECT * FROM vm1.doc1 where not(rowlimit(a2) = 3)", new String[] {"NOT (rowlimit(a2) = 3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitInvalidCriteria2() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IN (3)", new String[] {"rowlimit(a2) IN (3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitInvalidCriteria3() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) LIKE 'x'", new String[] {"rowlimit(a2) LIKE 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitInvalidCriteria4() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IS NULL", new String[] {"rowlimit(a2) IS NULL"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitInvalidCriteria5() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IN (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimit(a2) IN (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitInvalidCriteria6() {
+ helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE WHEN rowlimit(a2) = 2 THEN 2 END", new String[] {"2 = CASE WHEN rowlimit(a2) = 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitInvalidCriteria6a() {
+ helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE rowlimit(a2) WHEN 2 THEN 2 END", new String[] {"2 = CASE rowlimit(a2) WHEN 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitInvalidCriteria7() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) BETWEEN 2 AND 3", new String[] {"rowlimit(a2) BETWEEN 2 AND 3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitInvalidCriteria8() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = ANY (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimit(a2) = ANY (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** using rowlimit pseudo-function in non-XML query is invalid */
+ @Test public void testNonXMLQueryRowLimit() {
+ helpValidate("SELECT e2 FROM vTest.vMap WHERE rowlimit(e1) = 2", new String[] {"rowlimit(e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** test rowlimitexception function is valid */
+ @Test public void testXMLQueryRowLimitException() {
+ helpValidate("SELECT * FROM vm1.doc1 where 2 = RowLimitException(a2)", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ /** rowlimitexception function operand must be nonnegative integer */
+ @Test public void testXMLQueryRowLimitException1() {
+ helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)=-1", new String[] {"RowLimitException(a2) = -1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimitexception function operand must be nonnegative integer */
+ @Test public void testXMLQueryRowLimitException2() {
+ helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)='x'", new String[] {"RowLimitException(a2) = 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimitexception function cannot be nested within another function (this test inserts an implicit type conversion) */
+ @Test public void testXMLQueryRowLimitExceptionNested() {
+ helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)=a2", new String[] {"RowLimitException(a2) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimitexception function cannot be nested within another function */
+ @Test public void testXMLQueryRowLimitExceptionNested2() {
+ helpValidate("SELECT * FROM vm1.doc1 where convert(RowLimitException(a2), string)=a2", new String[] {"convert(RowLimitException(a2), string) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimitexception function operand must be nonnegative integer */
+ @Test public void testXMLQueryRowLimitException3a() {
+ helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2) = convert(a2, integer)", new String[] {"RowLimitException(a2) = convert(a2, integer)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimitexception function operand must be nonnegative integer */
+ @Test public void testXMLQueryRowLimitException3b() {
+ helpValidate("SELECT * FROM vm1.doc1 where convert(a2, integer) = RowLimitException(a2)", new String[] {"convert(a2, integer) = RowLimitException(a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimitexception function arg must be an element symbol */
+ @Test public void testXMLQueryRowLimitException4() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception('x') = 3", new String[] {"rowlimitexception('x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimitexception function arg must be an element symbol */
+ @Test public void testXMLQueryRowLimitException5() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(concat(a2, 'x')) = 3", new String[] {"rowlimitexception(concat(a2, 'x'))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimitexception function arg must be a single conjunct */
+ @Test public void testXMLQueryRowLimitExceptionConjunct() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 OR a2 = 'x'", new String[] {"(rowlimitexception(a2) = 3) OR (a2 = 'x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** rowlimitexception function arg must be a single conjunct */
+ @Test public void testXMLQueryRowLimitExceptionCompound() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND a2 = 'x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ /** rowlimitexception function arg must be a single conjunct */
+ @Test public void testXMLQueryRowLimitExceptionCompound2() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND concat(a2, 'y') = 'xy'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ /** rowlimitexception function arg must be a single conjunct */
+ @Test public void testXMLQueryRowLimitExceptionCompound3() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND (concat(a2, 'y') = 'xy' OR concat(a2, 'y') = 'zy')", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ /** each rowlimitexception function arg must be a single conjunct */
+ @Test public void testXMLQueryRowLimitExceptionCompound4() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND rowlimitexception(c2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ /**
+ * It doesn't make sense to use rowlimitexception twice on same element, but can't be
+ * invalidated here (could be two different elements but in the same
+ * mapping class - needs to be caught in XMLPlanner)
+ */
+ @Test public void testXMLQueryRowLimitExceptionCompound5() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND rowlimitexception(a2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testXMLQueryRowLimitExceptionInvalidCriteria() {
+ helpValidate("SELECT * FROM vm1.doc1 where not(rowlimitexception(a2) = 3)", new String[] {"NOT (rowlimitexception(a2) = 3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitExceptionInvalidCriteria2() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IN (3)", new String[] {"rowlimitexception(a2) IN (3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitExceptionInvalidCriteria3() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) LIKE 'x'", new String[] {"rowlimitexception(a2) LIKE 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitExceptionInvalidCriteria4() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IS NULL", new String[] {"rowlimitexception(a2) IS NULL"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitExceptionInvalidCriteria5() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IN (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimitexception(a2) IN (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitExceptionInvalidCriteria6() {
+ helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE WHEN rowlimitexception(a2) = 2 THEN 2 END", new String[] {"2 = CASE WHEN rowlimitexception(a2) = 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitExceptionInvalidCriteria6a() {
+ helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE rowlimitexception(a2) WHEN 2 THEN 2 END", new String[] {"2 = CASE rowlimitexception(a2) WHEN 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitExceptionInvalidCriteria7() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) BETWEEN 2 AND 3", new String[] {"rowlimitexception(a2) BETWEEN 2 AND 3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testXMLQueryRowLimitExceptionInvalidCriteria8() {
+ helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = ANY (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimitexception(a2) = ANY (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** using rowlimit pseudo-function in non-XML query is invalid */
+ @Test public void testNonXMLQueryRowLimitException() {
+ helpValidate("SELECT e2 FROM vTest.vMap WHERE rowlimitexception(e1) = 2", new String[] {"rowlimitexception(e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /** using context pseudo-function in non-XML query is invalid */
+ @Test public void testNonXMLQueryContextOperator() {
+ helpValidate("SELECT e2 FROM vTest.vMap WHERE context(e1, e1) = 2", new String[] {"context(e1, e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateSubquery1() {
+ helpValidate("SELECT e2 FROM (SELECT e2 FROM vTest.vMap WHERE e2 = 'a') AS x", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testValidateSubquery2() {
+ helpValidate("SELECT e2 FROM (SELECT e3 FROM vTest.vMap) AS x, vTest.vMap WHERE e2 = 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testValidateSubquery3() {
+ helpValidate("SELECT * FROM pm1.g1, (EXEC pm1.sq1( )) AS alias", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testValidateUnionWithSubquery() {
+ helpValidate("SELECT e2 FROM test.group2 union all SELECT e3 FROM test.group union all select * from (SELECT e1 FROM test.group) as subquery1", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateExistsSubquery() {
+ helpValidate("SELECT e2 FROM test.group2 WHERE EXISTS (SELECT e2 FROM vTest.vMap WHERE e2 = 'a')", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testValidateScalarSubquery() {
+ helpValidate("SELECT e2, (SELECT e1 FROM vTest.vMap WHERE e2 = '3') FROM test.group2", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateAnyCompareSubquery() {
+ helpValidate("SELECT e2 FROM test.group2 WHERE e1 < ANY (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateAllCompareSubquery() {
+ helpValidate("SELECT e2 FROM test.group2 WHERE e1 = ALL (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateSomeCompareSubquery() {
+ helpValidate("SELECT e2 FROM test.group2 WHERE e1 <= SOME (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateCompareSubquery() {
+ helpValidate("SELECT e2 FROM test.group2 WHERE e1 >= (SELECT e1 FROM test.group WHERE e1 = 1)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateInClauseSubquery() {
+ helpValidate("SELECT e2 FROM test.group2 WHERE e1 IN (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateExec1() {
+ helpValidate("EXEC pm1.sq1()", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ // valid variable declared
+ @Test public void testCreateUpdateProcedure4() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpValidateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // validating criteria selector(on HAS CRITERIA), elements on it should be virtual group elements
+ @Test public void testCreateUpdateProcedure5() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(HAS CRITERIA ON (vm1.g1.E1, vm1.g1.e1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpValidateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // validating Translate CRITERIA, elements on it should be virtual group elements
+ @Test public void testCreateUpdateProcedure7() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, vm1.g1.e1 = 2);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpValidateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // ROWS_UPDATED not assigned
+ @Test public void testCreateUpdateProcedure8() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1);\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // validating AssignmentStatement, more than one project symbol on the
+ // command
+ @Test public void testCreateUpdateProcedure11() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2, pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // validating AssignmentStatement, more than one project symbol on the
+ // command
+ @Test public void testCreateUpdateProcedure12() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = Select pm1.g1.e2, pm1.g1.e1 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // TranslateCriteria on criteria of the if statement
+ @Test public void testCreateUpdateProcedure13() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "if(TRANSLATE CRITERIA ON (vm1.g1.e1) WITH (vm1.g1.e1 = 1))\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpValidateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // INPUT ised in command
+ @Test public void testCreateUpdateProcedure16() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "INSERT into pm1.g1 (pm1.g1.e1) values (INPUT.e1);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpValidateProcedure(procedure, userUpdateStr,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ // elements on with should be on ON
+ @Test public void testCreateUpdateProcedure17() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e1) WITH (e1 = 20, e2 = 30);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ // failure, aggregate function in query transform
+ @Ignore
+ @Test public void testCreateUpdateProcedure18() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA ON (e3);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ // failure, aggregate function in query transform
+ @Ignore
+ @Test public void testCreateUpdateProcedure18a() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA ON (e3);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y like '%a' and e3= 1"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ // failure, translated criteria elements not present on groups of command
+ @Test public void testCreateUpdateProcedure19() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE = CRITERIA ON (x, y);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y= 1"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ @Test public void testCreateUpdateProcedure20() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (y = e2+1);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y= 1"; //$NON-NLS-1$
+
+ helpValidateProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ @Test public void testCreateUpdateProcedure25() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE > CRITERIA ON (y);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y > 1"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ @Test public void testCreateUpdateProcedure26() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (e3 = e2+1);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where e3 > 1"; //$NON-NLS-1$
+
+ helpValidateProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+ @Test public void testCreateUpdateProcedure27() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE LIKE CRITERIA WITH (y = e2+1);\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+ helpValidateProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // using aggregate function within a procedure - defect #8394
+ @Test public void testCreateUpdateProcedure31() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE string MaxTran;\n"; //$NON-NLS-1$
+ procedure = procedure + "MaxTran = SELECT MAX(e1) FROM pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+ helpValidateProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ // assigning null values to known datatype variable
+ @Test public void testCreateUpdateProcedure32() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE string var;\n"; //$NON-NLS-1$
+ procedure = procedure + "var = null;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED =0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+ helpValidateProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testDefect13643() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+ procedure = procedure + "LOOP ON (SELECT * FROM pm1.g1) AS myCursor\n"; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "var1 = SELECT COUNT(*) FROM myCursor;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testValidHaving() {
+ helpValidate(
+ "SELECT intnum " + //$NON-NLS-1$
+ "FROM bqt1.smalla " + //$NON-NLS-1$
+ "GROUP BY intnum " + //$NON-NLS-1$
+ "HAVING SUM(floatnum) > 1", //$NON-NLS-1$
+ 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[] {}, RealMetadataFactory.exampleBQTCached());
+ }
+
+ @Test public void testVirtualProcedure(){
+ helpValidate("EXEC pm1.vsp1()", new String[] { }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testSelectWithNoFrom() {
+ helpValidate("SELECT 5", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @Test public void testSelectIntoTempGroup() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+ helpValidateProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ /**
+ * Defect 24346
+ */
+ @Test public void testInvalidSelectIntoTempGroup() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g2;\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT e1, e2, e3 INTO #myTempTable FROM pm1.g2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ /**
+ * Defect 24346 with type mismatch
+ */
+ @Test public void testInvalidSelectIntoTempGroup1() {
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "create local temporary table #myTempTable (e1 integer);\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT e1 INTO #myTempTable FROM pm1.g2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+
+ @Test public void testSelectIntoPhysicalGroup() {
+ 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$
+ procedure = procedure + "SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+ helpValidateProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testSelectIntoPhysicalGroupNotUpdateable_Defect16857() {
+ helpValidate("SELECT e0, e1, e2 INTO test.group3 FROM test.group2", new String[] {"test.group3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testSelectIntoElementsNotUpdateable() {
+ helpValidate("SELECT e0, e1, e2 INTO test.group2 FROM test.group3", new String[] {"test.group2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @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"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userQuery,
+ 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"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userQuery,
+ 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"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testSelectIntoWithStar() {
+ 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"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+
+ String procedure = "CREATE PROCEDURE "; //$NON-NLS-1$
+ procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+ procedure = procedure + "SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+ helpFailProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testSelectIntoVirtualGroup() {
+ 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$
+ procedure = procedure + "SELECT e1, e2, e3, e4 INTO vm1.g1 FROM pm1.g2;\n"; //$NON-NLS-1$
+ procedure = procedure + "ROWS_UPDATED = 0;\n"; //$NON-NLS-1$
+ procedure = procedure + "END\n"; //$NON-NLS-1$
+
+ String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+ helpValidateProcedure(procedure, userQuery,
+ Table.TriggerEvent.UPDATE);
+ }
+
+ @Test public void testVirtualProcedure2(){
+ 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[] { }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testNonEmbeddedSubcommand_defect11000() {
+ helpValidate("SELECT e0 FROM vTest.vGroup", new String[0], exampleMetadata()); //$NON-NLS-1$
+ }
+
+ @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"}, 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 = RealMetadataFactory.example1Cached();
+
+ Command command = new QueryParser().parseCommand(sql);
+ QueryResolver.resolveCommand(command, metadata);
+
+ // Validate
+ ValidatorReport report = Validator.validate(command, metadata);
+ assertEquals(0, report.getItems().size());
+ }
+
+ @Test public void testDefect9917() throws Exception{
+ 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{
+ QueryResolver.resolveCommand(command, metadata);
+ fail("Did not get exception"); //$NON-NLS-1$
+ }catch(QueryResolverException e){
+ //expected
+ }
+
+ sql = "SELECT lookup('pm1.g1a', 'e1', 'e2', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
+ command = new QueryParser().parseCommand(sql);
+ try{
+ QueryResolver.resolveCommand(command, metadata);
+ fail("Did not get exception"); //$NON-NLS-1$
+ }catch(QueryResolverException e){
+ //expected
+ }
+ }
+
+ @Test public void testLookupKeyElementComparable() throws Exception {
+ QueryMetadataInterface metadata = exampleMetadata2();
+ String sql = "SELECT lookup('test.group', 'e2', 'e3', convert(e2, blob)) AS x FROM test.group"; //$NON-NLS-1$
+ Command command = QueryParser.getQueryParser().parseCommand(sql);
+ QueryResolver.resolveCommand(command, metadata);
+
+ ValidatorReport report = Validator.validate(command, metadata);
+ assertEquals("Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used as LOOKUP key columns: test.\"group\".e3.", report.toString()); //$NON-NLS-1$
+ }
+
+ @Test public void testDefect12107() throws Exception{
+ 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$
+ command = helpResolve(sql, metadata);
+ ValidatorReport report = Validator.validate(command, metadata);
+ assertEquals("The aggregate function SUM cannot be used with non-numeric expressions: SUM(DISTINCT lookup('pm1.g1', 'e3', 'e2', e2))", report.toString()); //$NON-NLS-1$
+ }
+
+ private ValidatorReport helpValidateInModeler(String procName, String procSql, QueryMetadataInterface metadata) throws Exception {
+ Command command = new QueryParser().parseCommand(procSql);
+
+ GroupSymbol group = new GroupSymbol(procName);
+ QueryResolver.resolveCommand(command, group, Command.TYPE_STORED_PROCEDURE, metadata);
+
+ // Validate
+ return Validator.validate(command, metadata);
+ }
+
+ @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 = RealMetadataFactory.example1Cached();
+
+ // Validate
+ ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata); //$NON-NLS-1$
+ assertEquals(1, report.getItems().size());
+ assertEquals("Wrong number of elements being SELECTed INTO the target table. Expected 4 elements, but was 1.", report.toString()); //$NON-NLS-1$
+ }
+
+ @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 = RealMetadataFactory.example1Cached();
+
+ // Validate
+ ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata); //$NON-NLS-1$
+ assertEquals(1, report.getItems().size());
+ assertEquals("Elements cannot appear more than once in a SET or USING clause. The following elements are duplicated: [DVARS.id]", report.toString()); //$NON-NLS-1$
+ }
+
+ @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 = RealMetadataFactory.example1Cached();
+
+ // Validate
+ ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata); //$NON-NLS-1$
+ assertEquals(0, report.getItems().size());
+ }
+
+ @Test public void testDefect12533() {
+ 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 = RealMetadataFactory.exampleBQTCached();
+
+ // Validate
+ helpValidate(sql, new String[] {"BQT1.SmallA.ObjectValue = BQT2.SmallB.ObjectValue"}, metadata); //$NON-NLS-1$
+ }
+
+ @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 = 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 testDefect14886() throws Exception{
+ String sql = "CREATE VIRTUAL PROCEDURE BEGIN END"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ Command command = new QueryParser().parseCommand(sql);
+ QueryResolver.resolveCommand(command, metadata);
+
+ // Validate
+ ValidatorReport report = Validator.validate(command, metadata);
+ // Validate
+ assertEquals(0, report.getItems().size());
+ }
+
+ @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$
+ 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);
+
+ // Validate
+ ValidatorReport report = Validator.validate(command, metadata);
+ // Validate
+ assertEquals(0, report.getItems().size());
+ }
+
+ @Test public void testMakeNotDep() {
+ helpValidate("select group2.e1, group3.e2 from group2, group3 WHERE group2.e0 = group3.e0 OPTION MAKENOTDEP group2, group3", new String[0], exampleMetadata()); //$NON-NLS-1$
+ }
+ @Test public void testInvalidMakeNotDep() {
+ helpValidate("select group2.e1, group3.e2 from group2, group3 WHERE group2.e0 = group3.e0 OPTION MAKEDEP group2 MAKENOTDEP group2, group3", new String[] {"OPTION MAKEDEP group2 MAKENOTDEP group2, group3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInvalidLimit() {
+ 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"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Test case 4237. This test simulates the way the modeler transformation
+ * panel uses the query resolver and validator to validate a transformation for
+ * a virtual procedure. The modeler has to supply external metadata for the
+ * virtual procedure group and parameter names (simulated in this test).
+ *
+ * This virtual procedure calls a physical stored procedure directly.
+ */
+ @Test public void testCase4237() {
+
+ 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);
+ helpRunValidator(command, new String[0], metadata);
+ }
+
+ /**
+ * This test was already working before the case was logged, due for some reason
+ * to the exec() statement being inside an inline view. This is a control test.
+ */
+ @Test public void testCase4237InlineView() {
+
+ 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);
+ helpRunValidator(command, new String[0], metadata);
+ }
+
+ /**
+ * Create fake metadata for this case. Need a physical stored procedure and
+ * a virtual stored procedure which calls the physical one.
+ * @return
+ */
+ 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);
+
+ 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$
+ 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[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
+ }
+
+ @Test public void testCreateWithNonSortablePrimaryKey() {
+ 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"}, RealMetadataFactory.example1Cached());
+ }
+
+ @Test public void testDropNonTemporary() {
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+ Command command = helpResolve("drop table pm1.g1", metadata); //$NON-NLS-1$
+ helpRunValidator(command, new String[] {command.toString()}, RealMetadataFactory.example1Cached());
+ }
+
+ @Test public void testNestedContexts() {
+ helpValidate("SELECT * FROM vm1.doc1 where context(a0, context(a0, a2))='x'", new String[] {"context(a0, context(a0, a2))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidContextElement() {
+ helpValidate("SELECT * FROM vm1.doc1 where context(1, a2)='x'", new String[] {"context(1, a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInsertIntoVirtualWithQuery() throws Exception {
+ 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());
+ }
+
+ @Test public void testDynamicIntoDeclaredTemp() throws Exception {
+ StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE ") //$NON-NLS-1$
+ .append("BEGIN\n") //$NON-NLS-1$
+ .append("CREATE LOCAL TEMPORARY TABLE x (column1 string);") //$NON-NLS-1$
+ .append("execute string 'SELECT e1 FROM pm1.g2' as e1 string INTO x;\n") //$NON-NLS-1$
+ .append("select column1 from x;\n") //$NON-NLS-1$
+ .append("END\n"); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ // Validate
+ ValidatorReport report = helpValidateInModeler("pm1.vsp36", procedure.toString(), metadata); //$NON-NLS-1$
+ assertEquals(report.toString(), 0, report.getItems().size());
+ }
+
+ @Test public void testVariablesGroupSelect() {
+ String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
+ procedure += "BEGIN\n"; //$NON-NLS-1$
+ procedure += "DECLARE integer VARIABLES.var1 = 1;\n"; //$NON-NLS-1$
+ procedure += "select * from variables;\n"; //$NON-NLS-1$
+ procedure += "END\n"; //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+
+ Command command = helpResolve(procedure, metadata);
+ helpRunValidator(command, new String[] {"variables"}, metadata); //$NON-NLS-1$
+ }
+
+ @Test public void testClobEquals() {
+ TestValidator.helpValidate("SELECT * FROM test.group where e4 = '1'", new String[] {"e4 = '1'"}, TestValidator.exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Should not fail since the update changing set is not really criteria
+ */
+ @Test public void testUpdateWithClob() {
+ TestValidator.helpValidate("update test.group set e4 = ?", new String[] {}, TestValidator.exampleMetadata2()); //$NON-NLS-1$
+ }
+
+ @Test public void testBlobLessThan() {
+ TestValidator.helpValidate("SELECT * FROM test.group where e3 < ?", new String[] {"e3 < ?"}, TestValidator.exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateCompare2() {
+ helpValidate("SELECT e2 FROM test.group WHERE e4 IS NULL", new String[] {}, exampleMetadata2()); //$NON-NLS-1$
+ }
+
+ @Test public void testValidateCompare3() {
+ helpValidate("SELECT e2 FROM test.group WHERE e4 IN ('a')", new String[] {"e4 IN ('a')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateCompare5() {
+ helpValidate("SELECT e2 FROM test.group WHERE e4 BETWEEN '1' AND '2'", new String[] {"e4 BETWEEN '1' AND '2'"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateCompareInHaving1() {
+ helpValidate("SELECT e1 FROM test.group GROUP BY e1 HAVING convert(e1, clob) = 'a'", new String[] {"convert(e1, clob) = 'a'"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateNoExpressionName() {
+ helpValidate("SELECT xmlelement(name a, xmlattributes('1'))", new String[] {"XMLATTRIBUTES('1')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateNoExpressionName1() {
+ helpValidate("SELECT xmlforest('1')", new String[] {"XMLFOREST('1')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @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[] {}, 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\"]')"}, RealMetadataFactory.exampleBQTCached());
+ }
+
+ @Test public void testTextTableNegativeWidth() {
+ helpValidate("SELECT * from texttable(null columns x string width -1) as x", new String[] {"TEXTTABLE(null COLUMNS x string WIDTH -1) AS x"}, RealMetadataFactory.exampleBQTCached());
+ }
+
+ @Test public void testTextTableNoWidth() {
+ helpValidate("SELECT * from texttable(null columns x string width 1, y integer) as x", new String[] {"TEXTTABLE(null COLUMNS x string WIDTH 1, y integer) AS x"}, RealMetadataFactory.exampleBQTCached());
+ }
+
+ @Test public void testTextTableInvalidDelimiter() {
+ 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 testXMLNamespaces() {
+ 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)"}, 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"}, 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"}, RealMetadataFactory.example1Cached());
+ }
+
+ @Test public void testXMLTablePassingContextType() {
+ 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"}, 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"}, RealMetadataFactory.example1Cached());
+ }
+
+ @Test public void testXMLQueryPassingContextType() {
+ helpValidate("select xmlquery('/' passing 2)", new String[] {"XMLQUERY('/' PASSING 2)"}, RealMetadataFactory.example1Cached());
+ }
+
+ @Test public void testQueryString() {
+ helpValidate("select querystring('/', '1')", new String[] {"QUERYSTRING('/', '1')"}, RealMetadataFactory.example1Cached());
+ }
+
+ @Test public void testXmlNameValidation() throws Exception {
+ 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)"}, RealMetadataFactory.example1Cached());
+ }
+
+ @Test public void testDecode() throws Exception {
+ 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)"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testValidateBooleanAgg() {
+ 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)"}, 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'"}, 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'"}, 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'"}, 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'"}, 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'"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testInvalidIntoSubquery4() throws Exception {
+ StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE\n") //$NON-NLS-1$
+ .append("BEGIN\n") //$NON-NLS-1$
+ .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 = RealMetadataFactory.example1Cached();
+
+ // Validate
+ ValidatorReport report = helpValidateInModeler("pm1.vsp36", procedure.toString(), metadata); //$NON-NLS-1$
+ examineReport(procedure, new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, report);
+ }
+
+ @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(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(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)"}, 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)"}, 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(RealMetadataFactory.exampleMultiBinding(), models)); //$NON-NLS-1$
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/resources/text/cdm_dos_win.txt
===================================================================
--- trunk/engine/src/test/resources/text/cdm_dos_win.txt 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/resources/text/cdm_dos_win.txt 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,52 +0,0 @@
- 000183USD07/26/200107/26/2004 000183 USD 07/26/2001 07/26/2004 10000000.00 Summit 195205NY 0.005450 0.000000 MCREDCLN
- 000184USD07/26/200107/26/2004 000184 USD 07/26/2001 07/26/2004 10000000.00 Summit 195219NY 0.005450 0.000000 NYBDUMMY
- 000185USD07/26/200107/26/2004 000185 USD 07/26/2001 07/26/2004 10000000.00 Summit 195233NY 0.009700 0.000000 MCREDCLN
- 000186USD07/26/200107/26/2004 000186 USD 07/26/2001 07/26/2004 10000000.00 Summit 195234NY 0.009700 0.000000 NYBDUMMY
- 000258AUSD12/12/200209/15/2005 000258 USD 12/12/2002 09/15/2005 10000000.00 Summit 247299N 0.011500 0.000000 DCC2
- 000259AUSD01/17/200303/20/2005 000259 USD 01/17/2003 03/20/2005 10000000.00 Summit 247300N 0.011000 0.000000 DCC2
- 000273USD04/25/200307/07/2006 000273 USD 04/25/2003 07/07/2006 5000000.00 Summit 258123NY 0.008000 0.000000 LTINV
- 000276AUSD05/10/200306/20/2008 000276 USD 05/10/2003 06/20/2008 10000000.00 Summit 260100N 0.033000 0.000000 DCC2
- 000277AUSD05/10/200306/20/2008 000277 USD 05/10/2003 06/20/2008 5000000.00 Summit 260101N 0.006500 0.000000 DCC2
- 000278AUSD05/13/200306/20/2008 000278 USD 05/13/2003 06/20/2008 5000000.00 Summit 260102N 0.033000 0.000000 DCC2
- 000279AUSD05/14/200306/20/2008 000279 USD 05/14/2003 06/20/2008 5000000.00 Summit 260131N 0.033000 0.000000 DCC2
- 000280USD06/11/200307/07/2006 000280 USD 06/11/2003 07/07/2006 5000000.00 Summit 264602NY 0.008900 0.000000 LTINV
- 000289AUSD07/03/200309/20/2008 000289 USD 07/03/2003 09/20/2008 5000000.00 Summit 265496NY 0.004400 0.000000 LTINV
- 000292USD07/19/200309/20/2008 000292 USD 07/19/2003 09/20/2008 5000000.00 Summit 271005NY 0.005000 0.000000 LTINV
- 000350USD01/28/200403/20/2009 000350 USD 01/28/2004 03/20/2009 10000000.00 Summit 314996N 0.005200 0.000000 DCC2
- 000354USD03/10/200403/10/2007 000354 USD 03/10/2004 03/10/2007 9324082.77 Summit 318622NY 0.037500 0.000000 LTTRSCDS
- 000357USD03/16/200403/16/2007 000357 USD 03/16/2004 03/16/2007 9924050.62 Summit 318638NY 0.030000 0.000000 LTTRSCDS
- 000359USD03/09/200403/09/2007 000359 USD 03/09/2004 03/09/2007 9329349.59 Summit 318641NY 0.027500 0.000000 LTTRSCDS
- 000360USD03/18/200403/18/2007 000360 USD 03/18/2004 03/18/2007 232935.47 Summit 318642NY 0.032500 0.000000 LTTRSCDS
- 000352USD04/08/200404/08/2007 000352 USD 04/08/2004 04/08/2007 9788013.59 Summit 318643NY 0.032500 0.000000 LTTRSCDS
- 000353USD03/04/200403/04/2007 000353 USD 03/04/2004 03/04/2007 809831.58 Summit 318644NY 0.032500 0.000000 LTTRSCDS
- 000353USD03/04/200403/04/2007 000353 USD 03/04/2004 03/04/2007 705882.35 Summit 325357NY 0.032500 0.000000 LTTRSCDS
- 000353USD03/04/200403/04/2007 000353 USD 03/04/2004 03/04/2007 156623.38 Summit 325358NY 0.032500 0.000000 LTTRSCDS
- 000353USD03/04/200403/04/2007 000353 USD 03/04/2004 03/04/2007 278643.02 Summit 325363NY 0.032500 0.000000 LTTRSCDS
- 000353USD03/04/200403/04/2007 000353 USD 03/04/2004 03/04/2007 711809.48 Summit 325364NY 0.032500 0.000000 LTTRSCDS
- 000359USD03/09/200403/09/2007 000359 USD 03/09/2004 03/09/2007 76890.25 Summit 325366NY 0.027500 0.000000 LTTRSCDS
- 000360USD03/18/200403/18/2007 000360 USD 03/18/2004 03/18/2007 1049811.00 Summit 329001NY 0.032500 0.000000 LTTRSCDS
- 000360USD03/18/200403/18/2007 000360 USD 03/18/2004 03/18/2007 414407.12 Summit 329002NY 0.032500 0.000000 LTTRSCDS
- 000360USD03/18/200403/18/2007 000360 USD 03/18/2004 03/18/2007 1204408.30 Summit 329003NY 0.032500 0.000000 LTTRSCDS
- 000360USD03/18/200403/18/2007 000360 USD 03/18/2004 03/18/2007 1058626.60 Summit 329004NY 0.032500 0.000000 LTTRSCDS
- 000362USD04/12/200404/12/2007 000362 USD 04/12/2004 04/12/2007 194934.82 Summit 331567NY 0.040000 0.000000 LTTRSCDS
- 000362USD04/12/200404/12/2007 000362 USD 04/12/2004 04/12/2007 131062.23 Summit 335678NY 0.040000 0.000000 LTTRSCDS
- 000362USD04/12/200404/12/2007 000362 USD 04/12/2004 04/12/2007 1094136.66 Summit 335679NY 0.040000 0.000000 LTTRSCDS
- 000362USD04/12/200404/12/2007 000362 USD 04/12/2004 04/12/2007 2785075.14 Summit 335680NY 0.040000 0.000000 LTTRSCDS
- 000362USD04/12/200404/12/2007 000362 USD 04/12/2004 04/12/2007 2785075.14 Summit 335681NY 0.040000 0.000000 LTTRSCDS
- 000362USD04/12/200404/12/2007 000362 USD 04/12/2004 04/12/2007 2984009.08 Summit 335682NY 0.040000 0.000000 LTTRSCDS
- 000363USD05/03/200405/03/2007 000363 USD 05/03/2004 05/03/2007 10000000.00 Summit 338242NY 0.025000 0.000000 LTTRSCDS
- 000364USD05/17/200405/17/2007 000364 USD 05/17/2004 05/17/2007 5000000.00 Summit 338820NY 0.032500 0.000000 LTTRSCDS
- 000365USD05/07/200406/20/2009 000365 USD 05/07/2004 06/20/2009 5000000.00 Summit 340411N 0.004800 0.000000 DCC2
- 000099USD12/06/199912/06/2004 000099 USD 12/06/1999 12/06/2004 200000000.00 Summit 340805NY 0.000000 0.000000 PCTRSCDS
- 000129USD04/03/200010/01/2008 000129 USD 04/03/2000 10/01/2008 200000000.00 Summit 340834NY 0.000000 0.000000 PCTRSCDS
- 000148USD09/12/200012/19/2005 000148 USD 09/12/2000 12/19/2005 573667.12 Summit 340844NY 0.000000 0.000000 PCTRSCDS
- 000149USD09/12/200012/19/2005 000149 USD 09/12/2000 12/19/2005 2118155.52 Summit 340847NY 0.000000 0.000000 PCTRSCDS
- 000150USD09/12/200012/19/2005 000150 USD 09/12/2000 12/19/2005 4986491.88 Summit 340848NY 0.000000 0.000000 PCTRSCDS
- 000366USD05/06/200405/06/2007 000366 USD 05/06/2004 05/06/2007 3058823.53 Summit 341369NY 0.030000 0.000000 LTTRSCDS
- 000367USD05/06/200405/06/2007 000367 USD 05/06/2004 05/06/2007 6941176.47 Summit 341377NY 0.030000 0.000000 LTTRSCDS
- 000213USD02/11/200202/11/2007 000213 USD 02/11/2002 02/11/2007 8000000.00 Summit 343117NY 0.056500 0.000000 CNA2
- 000272USD03/05/200301/31/2005 000272 USD 03/05/2003 01/31/2005 28000000.00 Summit 343123NY 0.006000 0.000000 CNA2
- 000333USD11/13/200311/20/2004 000333 USD 11/13/2003 11/20/2004 25000000.00 Summit 343151NY 0.003800 0.000000 CNA2
- 000368USD05/24/200405/24/2007 000368 USD 05/24/2004 05/24/2007 10000000.00 Summit 343169NY 0.025000 0.000000 LTTRSCDS
- 000168USD12/18/200001/31/2006 000168 USD 12/18/2000 01/31/2006 672096851.46 Summit 344846NY 0.000000 0.000000 ASGCGD
- 000369USD05/20/200405/20/2007 000369 USD 05/20/2004 05/20/2007 10000000.00 Summit 344851NY 0.032500 0.000000 LTTRSCDS
Copied: tags/teiid-parent-7.5.0.Alpha1/engine/src/test/resources/text/cdm_dos_win.txt (from rev 3218, trunk/engine/src/test/resources/text/cdm_dos_win.txt)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/engine/src/test/resources/text/cdm_dos_win.txt (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/engine/src/test/resources/text/cdm_dos_win.txt 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,52 @@
+ 000183USD07/26/200107/26/2004 000183 USD 07/26/2001 07/26/2004 10000000.00 Summit 195205NY 0.005450 0.000000 MCREDCLN
+ 000184USD07/26/200107/26/2004 000184 USD 07/26/2001 07/26/2004 10000000.00 Summit 195219NY 0.005450 0.000000 NYBDUMMY
+ 000185USD07/26/200107/26/2004 000185 USD 07/26/2001 07/26/2004 10000000.00 Summit 195233NY 0.009700 0.000000 MCREDCLN
+ 000186USD07/26/200107/26/2004 000186 USD 07/26/2001 07/26/2004 10000000.00 Summit 195234NY 0.009700 0.000000 NYBDUMMY
+ 000258AUSD12/12/200209/15/2005 000258 USD 12/12/2002 09/15/2005 10000000.00 Summit 247299N 0.011500 0.000000 DCC2
+ 000259AUSD01/17/200303/20/2005 000259 USD 01/17/2003 03/20/2005 10000000.00 Summit 247300N 0.011000 0.000000 DCC2
+ 000273USD04/25/200307/07/2006 000273 USD 04/25/2003 07/07/2006 5000000.00 Summit 258123NY 0.008000 0.000000 LTINV
+ 000276AUSD05/10/200306/20/2008 000276 USD 05/10/2003 06/20/2008 10000000.00 Summit 260100N 0.033000 0.000000 DCC2
+ 000277AUSD05/10/200306/20/2008 000277 USD 05/10/2003 06/20/2008 5000000.00 Summit 260101N 0.006500 0.000000 DCC2
+ 000278AUSD05/13/200306/20/2008 000278 USD 05/13/2003 06/20/2008 5000000.00 Summit 260102N 0.033000 0.000000 DCC2
+ 000279AUSD05/14/200306/20/2008 000279 USD 05/14/2003 06/20/2008 5000000.00 Summit 260131N 0.033000 0.000000 DCC2
+ 000280USD06/11/200307/07/2006 000280 USD 06/11/2003 07/07/2006 5000000.00 Summit 264602NY 0.008900 0.000000 LTINV
+ 000289AUSD07/03/200309/20/2008 000289 USD 07/03/2003 09/20/2008 5000000.00 Summit 265496NY 0.004400 0.000000 LTINV
+ 000292USD07/19/200309/20/2008 000292 USD 07/19/2003 09/20/2008 5000000.00 Summit 271005NY 0.005000 0.000000 LTINV
+ 000350USD01/28/200403/20/2009 000350 USD 01/28/2004 03/20/2009 10000000.00 Summit 314996N 0.005200 0.000000 DCC2
+ 000354USD03/10/200403/10/2007 000354 USD 03/10/2004 03/10/2007 9324082.77 Summit 318622NY 0.037500 0.000000 LTTRSCDS
+ 000357USD03/16/200403/16/2007 000357 USD 03/16/2004 03/16/2007 9924050.62 Summit 318638NY 0.030000 0.000000 LTTRSCDS
+ 000359USD03/09/200403/09/2007 000359 USD 03/09/2004 03/09/2007 9329349.59 Summit 318641NY 0.027500 0.000000 LTTRSCDS
+ 000360USD03/18/200403/18/2007 000360 USD 03/18/2004 03/18/2007 232935.47 Summit 318642NY 0.032500 0.000000 LTTRSCDS
+ 000352USD04/08/200404/08/2007 000352 USD 04/08/2004 04/08/2007 9788013.59 Summit 318643NY 0.032500 0.000000 LTTRSCDS
+ 000353USD03/04/200403/04/2007 000353 USD 03/04/2004 03/04/2007 809831.58 Summit 318644NY 0.032500 0.000000 LTTRSCDS
+ 000353USD03/04/200403/04/2007 000353 USD 03/04/2004 03/04/2007 705882.35 Summit 325357NY 0.032500 0.000000 LTTRSCDS
+ 000353USD03/04/200403/04/2007 000353 USD 03/04/2004 03/04/2007 156623.38 Summit 325358NY 0.032500 0.000000 LTTRSCDS
+ 000353USD03/04/200403/04/2007 000353 USD 03/04/2004 03/04/2007 278643.02 Summit 325363NY 0.032500 0.000000 LTTRSCDS
+ 000353USD03/04/200403/04/2007 000353 USD 03/04/2004 03/04/2007 711809.48 Summit 325364NY 0.032500 0.000000 LTTRSCDS
+ 000359USD03/09/200403/09/2007 000359 USD 03/09/2004 03/09/2007 76890.25 Summit 325366NY 0.027500 0.000000 LTTRSCDS
+ 000360USD03/18/200403/18/2007 000360 USD 03/18/2004 03/18/2007 1049811.00 Summit 329001NY 0.032500 0.000000 LTTRSCDS
+ 000360USD03/18/200403/18/2007 000360 USD 03/18/2004 03/18/2007 414407.12 Summit 329002NY 0.032500 0.000000 LTTRSCDS
+ 000360USD03/18/200403/18/2007 000360 USD 03/18/2004 03/18/2007 1204408.30 Summit 329003NY 0.032500 0.000000 LTTRSCDS
+ 000360USD03/18/200403/18/2007 000360 USD 03/18/2004 03/18/2007 1058626.60 Summit 329004NY 0.032500 0.000000 LTTRSCDS
+ 000362USD04/12/200404/12/2007 000362 USD 04/12/2004 04/12/2007 194934.82 Summit 331567NY 0.040000 0.000000 LTTRSCDS
+ 000362USD04/12/200404/12/2007 000362 USD 04/12/2004 04/12/2007 131062.23 Summit 335678NY 0.040000 0.000000 LTTRSCDS
+ 000362USD04/12/200404/12/2007 000362 USD 04/12/2004 04/12/2007 1094136.66 Summit 335679NY 0.040000 0.000000 LTTRSCDS
+ 000362USD04/12/200404/12/2007 000362 USD 04/12/2004 04/12/2007 2785075.14 Summit 335680NY 0.040000 0.000000 LTTRSCDS
+ 000362USD04/12/200404/12/2007 000362 USD 04/12/2004 04/12/2007 2785075.14 Summit 335681NY 0.040000 0.000000 LTTRSCDS
+ 000362USD04/12/200404/12/2007 000362 USD 04/12/2004 04/12/2007 2984009.08 Summit 335682NY 0.040000 0.000000 LTTRSCDS
+ 000363USD05/03/200405/03/2007 000363 USD 05/03/2004 05/03/2007 10000000.00 Summit 338242NY 0.025000 0.000000 LTTRSCDS
+ 000364USD05/17/200405/17/2007 000364 USD 05/17/2004 05/17/2007 5000000.00 Summit 338820NY 0.032500 0.000000 LTTRSCDS
+ 000365USD05/07/200406/20/2009 000365 USD 05/07/2004 06/20/2009 5000000.00 Summit 340411N 0.004800 0.000000 DCC2
+ 000099USD12/06/199912/06/2004 000099 USD 12/06/1999 12/06/2004 200000000.00 Summit 340805NY 0.000000 0.000000 PCTRSCDS
+ 000129USD04/03/200010/01/2008 000129 USD 04/03/2000 10/01/2008 200000000.00 Summit 340834NY 0.000000 0.000000 PCTRSCDS
+ 000148USD09/12/200012/19/2005 000148 USD 09/12/2000 12/19/2005 573667.12 Summit 340844NY 0.000000 0.000000 PCTRSCDS
+ 000149USD09/12/200012/19/2005 000149 USD 09/12/2000 12/19/2005 2118155.52 Summit 340847NY 0.000000 0.000000 PCTRSCDS
+ 000150USD09/12/200012/19/2005 000150 USD 09/12/2000 12/19/2005 4986491.88 Summit 340848NY 0.000000 0.000000 PCTRSCDS
+ 000366USD05/06/200405/06/2007 000366 USD 05/06/2004 05/06/2007 3058823.53 Summit 341369NY 0.030000 0.000000 LTTRSCDS
+ 000367USD05/06/200405/06/2007 000367 USD 05/06/2004 05/06/2007 6941176.47 Summit 341377NY 0.030000 0.000000 LTTRSCDS
+ 000213USD02/11/200202/11/2007 000213 USD 02/11/2002 02/11/2007 8000000.00 Summit 343117NY 0.056500 0.000000 CNA2
+ 000272USD03/05/200301/31/2005 000272 USD 03/05/2003 01/31/2005 28000000.00 Summit 343123NY 0.006000 0.000000 CNA2
+ 000333USD11/13/200311/20/2004 000333 USD 11/13/2003 11/20/2004 25000000.00 Summit 343151NY 0.003800 0.000000 CNA2
+ 000368USD05/24/200405/24/2007 000368 USD 05/24/2004 05/24/2007 10000000.00 Summit 343169NY 0.025000 0.000000 LTTRSCDS
+ 000168USD12/18/200001/31/2006 000168 USD 12/18/2000 01/31/2006 672096851.46 Summit 344846NY 0.000000 0.000000 ASGCGD
+ 000369USD05/20/200405/20/2007 000369 USD 05/20/2004 05/20/2007 10000000.00 Summit 344851NY 0.032500 0.000000 LTTRSCDS
Deleted: tags/teiid-parent-7.5.0.Alpha1/hibernate-dialect/pom.xml
===================================================================
--- trunk/hibernate-dialect/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/hibernate-dialect/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,18 +0,0 @@
-<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-hibernate-dialect</artifactId>
- <name>Hibernate Dialect</name>
- <description>Teiid Hibernate Dialect</description>
- <dependencies>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-core</artifactId>
- <version>3.5.2-Final</version>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/hibernate-dialect/pom.xml (from rev 3220, trunk/hibernate-dialect/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/hibernate-dialect/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/hibernate-dialect/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,18 @@
+<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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>teiid-hibernate-dialect</artifactId>
+ <name>Hibernate Dialect</name>
+ <description>Teiid Hibernate Dialect</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-core</artifactId>
+ <version>3.5.2-Final</version>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/jboss-integration/pom.xml
===================================================================
--- trunk/jboss-integration/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/jboss-integration/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,146 +0,0 @@
-<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>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-jboss-integration</artifactId>
- <name>teiid-jboss-integration</name>
- <description>JBoss specific integration layer for teiid</description>
-
- <dependencies>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-runtime</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-cache-jbosscache</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jboss-reflect</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.man</groupId>
- <artifactId>jboss-managed</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.integration</groupId>
- <artifactId>jboss-profileservice-spi</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.jbossas</groupId>
- <artifactId>jboss-as-connector</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.microcontainer</groupId>
- <artifactId>jboss-aop-mc-int</artifactId>
- <version>2.0.6.GA</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.security</groupId>
- <artifactId>jbosssx</artifactId>
- <version>2.0.3.SP1</version>
- <scope>provided</scope>
- </dependency>
- <!-- these for just running profile service remotely -->
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.naming</groupId>
- <artifactId>jnp-client</artifactId>
- <version>5.0.3.GA</version>
- <scope>test</scope>
- </dependency>
-<!--
- <dependency>
- <groupId>org.jboss.aop</groupId>
- <artifactId>jboss-aop</artifactId>
- <classifier>client</classifier>
- <version>2.1.1.GA</version>
- <scope>test</scope>
- </dependency>
--->
-
- <dependency>
- <groupId>org.jboss.remoting</groupId>
- <artifactId>jboss-remoting</artifactId>
- <version>2.5.1</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.aspects</groupId>
- <artifactId>jboss-security-aspects</artifactId>
- <version>1.0.0.GA</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.aspects</groupId>
- <artifactId>jboss-remoting-aspects</artifactId>
- <version>1.0.1.GA</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>oswego-concurrent</groupId>
- <artifactId>concurrent</artifactId>
- <version>1.3.4-jboss-update1</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.jbossas</groupId>
- <artifactId>jboss-as-server</artifactId>
- <version>5.1.0.GA</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.jbossas</groupId>
- <artifactId>jboss-as-profileservice</artifactId>
- <version>5.1.0.GA</version>
- <scope>test</scope>
- </dependency>
-
- </dependencies>
-
-</project>
Copied: tags/teiid-parent-7.5.0.Alpha1/jboss-integration/pom.xml (from rev 3220, trunk/jboss-integration/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/jboss-integration/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/jboss-integration/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,146 @@
+<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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-jboss-integration</artifactId>
+ <name>teiid-jboss-integration</name>
+ <description>JBoss specific integration layer for teiid</description>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-runtime</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-cache-jbosscache</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jboss-reflect</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.man</groupId>
+ <artifactId>jboss-managed</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.integration</groupId>
+ <artifactId>jboss-profileservice-spi</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.jbossas</groupId>
+ <artifactId>jboss-as-connector</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.microcontainer</groupId>
+ <artifactId>jboss-aop-mc-int</artifactId>
+ <version>2.0.6.GA</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.security</groupId>
+ <artifactId>jbosssx</artifactId>
+ <version>2.0.3.SP1</version>
+ <scope>provided</scope>
+ </dependency>
+ <!-- these for just running profile service remotely -->
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.naming</groupId>
+ <artifactId>jnp-client</artifactId>
+ <version>5.0.3.GA</version>
+ <scope>test</scope>
+ </dependency>
+<!--
+ <dependency>
+ <groupId>org.jboss.aop</groupId>
+ <artifactId>jboss-aop</artifactId>
+ <classifier>client</classifier>
+ <version>2.1.1.GA</version>
+ <scope>test</scope>
+ </dependency>
+-->
+
+ <dependency>
+ <groupId>org.jboss.remoting</groupId>
+ <artifactId>jboss-remoting</artifactId>
+ <version>2.5.1</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.aspects</groupId>
+ <artifactId>jboss-security-aspects</artifactId>
+ <version>1.0.0.GA</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.aspects</groupId>
+ <artifactId>jboss-remoting-aspects</artifactId>
+ <version>1.0.1.GA</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>oswego-concurrent</groupId>
+ <artifactId>concurrent</artifactId>
+ <version>1.3.4-jboss-update1</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.jbossas</groupId>
+ <artifactId>jboss-as-server</artifactId>
+ <version>5.1.0.GA</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.jbossas</groupId>
+ <artifactId>jboss-as-profileservice</artifactId>
+ <version>5.1.0.GA</version>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+
+</project>
Deleted: tags/teiid-parent-7.5.0.Alpha1/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,812 +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.jboss.deployers;
-
-import java.io.Serializable;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.SQLException;
-import java.sql.SQLXML;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.resource.spi.XATerminator;
-import javax.resource.spi.work.WorkManager;
-import javax.security.auth.login.LoginException;
-import javax.transaction.TransactionManager;
-
-import org.jboss.managed.api.ManagedOperation.Impact;
-import org.jboss.managed.api.annotation.ManagementComponent;
-import org.jboss.managed.api.annotation.ManagementObject;
-import org.jboss.managed.api.annotation.ManagementOperation;
-import org.jboss.managed.api.annotation.ManagementParameter;
-import org.jboss.managed.api.annotation.ManagementProperties;
-import org.jboss.managed.api.annotation.ManagementProperty;
-import org.jboss.managed.api.annotation.ViewUse;
-import org.jboss.profileservice.spi.ProfileService;
-import org.jboss.util.naming.Util;
-import org.teiid.adminapi.Admin;
-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.CacheStatisticsMetadata;
-import org.teiid.adminapi.impl.DQPManagement;
-import org.teiid.adminapi.impl.RequestMetadata;
-import org.teiid.adminapi.impl.SessionMetadata;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.adminapi.impl.WorkerPoolStatisticsMetadata;
-import org.teiid.adminapi.jboss.AdminProvider;
-import org.teiid.cache.CacheFactory;
-import org.teiid.client.DQP;
-import org.teiid.client.RequestMessage;
-import org.teiid.client.ResultsMessage;
-import org.teiid.client.security.ILogon;
-import org.teiid.client.security.InvalidSessionException;
-import org.teiid.client.util.ExceptionUtil;
-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.LRUCache;
-import org.teiid.deployers.VDBLifeCycleListener;
-import org.teiid.deployers.VDBRepository;
-import org.teiid.deployers.VDBStatusChecker;
-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;
-import org.teiid.dqp.service.TransactionService;
-import org.teiid.events.EventDistributor;
-import org.teiid.events.EventDistributorFactory;
-import org.teiid.jboss.IntegrationPlugin;
-import org.teiid.logging.Log4jListener;
-import org.teiid.logging.LogConstants;
-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;
-import org.teiid.metadata.MetadataRepository;
-import org.teiid.metadata.Procedure;
-import org.teiid.metadata.Schema;
-import org.teiid.metadata.Table;
-import org.teiid.metadata.TableStats;
-import org.teiid.metadata.Table.TriggerEvent;
-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.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;
-
-
- at ManagementObject(name="RuntimeEngineDeployer", isRuntime=true, componentType=@ManagementComponent(type="teiid",subtype="dqp"), properties=ManagementProperties.EXPLICIT)
-public class RuntimeEngineDeployer extends DQPConfiguration implements DQPManagement, Serializable , ClientServiceRegistry, EventDistributor, EventDistributorFactory {
- private static final long serialVersionUID = -4676205340262775388L;
-
- private transient SocketConfiguration jdbcSocketConfiguration;
- private transient SocketConfiguration adminSocketConfiguration;
- private transient SocketConfiguration odbcSocketConfiguration;
- private transient SocketListener jdbcSocket;
- private transient SocketListener adminSocket;
- private transient SocketListener odbcSocket;
- private transient TransactionServerImpl transactionServerImpl = new TransactionServerImpl();
-
- private transient DQPCore dqpCore = new DQPCore();
- private transient SessionService sessionService;
- private transient ILogon logon;
- private transient Admin admin;
- private transient ClientServiceRegistryImpl csr = new ClientServiceRegistryImpl();
- private transient VDBRepository vdbRepository;
- private transient VDBStatusChecker vdbStatusChecker;
-
- private transient ProfileService profileService;
- private transient String jndiName;
-
- private String eventDistributorName;
- private transient EventDistributor eventDistributor;
-
- public RuntimeEngineDeployer() {
- // TODO: this does not belong here
- LogManager.setLogListener(new Log4jListener());
- }
-
- @Override
- public <T> T getClientService(Class<T> iface)
- throws ComponentNotFoundException {
- return this.csr.getClientService(iface);
- }
-
- @Override
- public SecurityHelper getSecurityHelper() {
- return this.csr.getSecurityHelper();
- }
-
- public void start() {
- dqpCore.setTransactionService((TransactionService)LogManager.createLoggingProxy(LogConstants.CTX_TXN_LOG, transactionServerImpl, new Class[] {TransactionService.class}, MessageLevel.DETAIL));
-
- if (this.eventDistributorName != null) {
- try {
- InitialContext ic = new InitialContext();
- this.eventDistributor = (EventDistributor) ic.lookup(this.eventDistributorName);
- } catch (NamingException ne) {
- //log at a detail level since we may not be in the all profile
- LogManager.logDetail(LogConstants.CTX_RUNTIME, ne, IntegrationPlugin.Util.getString("jndi_failed", new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
- }
- }
- this.dqpCore.start(this);
- this.dqpCore.getDataTierManager().setEventDistributor(this.eventDistributor);
- // create the necessary services
- createClientServices();
-
- int offset = 0;
- String portBinding = System.getProperty("jboss.service.binding.set"); //$NON-NLS-1$
- if (portBinding != null && portBinding.startsWith("ports-")) { //$NON-NLS-1$
- if (portBinding.equals("ports-default")) { //$NON-NLS-1$
- offset = 0;
- }
- else {
- try {
- offset = Integer.parseInt(portBinding.substring(portBinding.length()-2))*100;
- } catch (NumberFormatException e) {
- offset = 0;
- }
- }
- }
-
- this.csr.registerClientService(ILogon.class, logon, LogConstants.CTX_SECURITY);
- DQP dqpProxy = proxyService(DQP.class, this.dqpCore, LogConstants.CTX_DQP);
- this.csr.registerClientService(DQP.class, dqpProxy, LogConstants.CTX_DQP);
- Admin adminProxy = proxyService(Admin.class, admin, LogConstants.CTX_ADMIN_API);
- this.csr.registerClientService(Admin.class, adminProxy, LogConstants.CTX_ADMIN_API);
-
- ClientServiceRegistryImpl jdbcCsr = new ClientServiceRegistryImpl();
- jdbcCsr.registerClientService(ILogon.class, logon, LogConstants.CTX_SECURITY);
- jdbcCsr.registerClientService(DQP.class, dqpProxy, LogConstants.CTX_DQP);
-
- if (this.jdbcSocketConfiguration.getEnabled()) {
- this.jdbcSocket = new SocketListener(this.jdbcSocketConfiguration, jdbcCsr, this.dqpCore.getBufferManager(), offset);
- LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_enabled","Teiid JDBC = ",(this.jdbcSocketConfiguration.getSSLConfiguration().isSslEnabled()?"mms://":"mm://")+this.jdbcSocketConfiguration.getHostAddress().getHostName()+":"+(this.jdbcSocketConfiguration.getPortNumber()+offset))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- } else {
- LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_not_enabled", "jdbc connections")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- ClientServiceRegistryImpl adminCsr = new ClientServiceRegistryImpl(Type.Admin);
- adminCsr.registerClientService(ILogon.class, logon, LogConstants.CTX_SECURITY);
- adminCsr.registerClientService(Admin.class, adminProxy, LogConstants.CTX_ADMIN_API);
-
- if (this.adminSocketConfiguration.getEnabled()) {
- this.adminSocket = new SocketListener(this.adminSocketConfiguration, adminCsr, this.dqpCore.getBufferManager(), offset);
- LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_enabled","Teiid Admin", (this.adminSocketConfiguration.getSSLConfiguration().isSslEnabled()?"mms://":"mm://")+this.adminSocketConfiguration.getHostAddress().getHostName()+":"+(this.adminSocketConfiguration.getPortNumber()+offset))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
- } else {
- LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_not_enabled", "admin connections")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (this.odbcSocketConfiguration.getEnabled()) {
- this.vdbRepository.odbcEnabled();
- this.odbcSocket = new ODBCSocketListener(this.odbcSocketConfiguration, this.dqpCore.getBufferManager(), offset, getMaxODBCLobSizeAllowed());
- 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$
- }
-
- LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("engine_started", getRuntimeVersion(), new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
- if (jndiName != null) {
- final InitialContext ic ;
- try {
- ic = new InitialContext() ;
- Util.bind(ic, jndiName, this) ;
- } catch (final NamingException ne) {
- // Add jndi_failed to bundle
- LogManager.logError(LogConstants.CTX_RUNTIME, ne, IntegrationPlugin.Util.getString("jndi_failed", new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
- }
- }
-
- // add vdb life cycle listeners
- this.vdbRepository.addListener(new VDBLifeCycleListener() {
-
- private Set<VDBKey> recentlyRemoved = Collections.newSetFromMap(new LRUCache<VDBKey, Boolean>(10000));
-
- @Override
- public void removed(String name, int version) {
- recentlyRemoved.add(new VDBKey(name, version));
- }
-
- @Override
- public void added(String name, int version) {
- if (!recentlyRemoved.remove(new VDBKey(name, version))) {
- return;
- }
- // terminate all the previous sessions
- try {
- Collection<SessionMetadata> sessions = sessionService.getActiveSessions();
- for (SessionMetadata session:sessions) {
- if (name.equalsIgnoreCase(session.getVDBName()) && version == session.getVDBVersion()){
- sessionService.terminateSession(session.getSessionId(), null);
- }
- }
- } catch (SessionServiceException e) {
- //ignore
- }
-
- // dump the caches.
- dqpCore.clearCache(Cache.PREPARED_PLAN_CACHE.toString(), name, version);
- dqpCore.clearCache(Cache.QUERY_SERVICE_RESULT_SET_CACHE.toString(), name, version);
- }
- });
- }
-
- public void stop() {
- if (jndiName != null) {
- final InitialContext ic ;
- try {
- ic = new InitialContext() ;
- Util.unbind(ic, jndiName) ;
- } catch (final NamingException ne) {
- }
- }
-
- try {
- this.dqpCore.stop();
- } catch(TeiidRuntimeException e) {
- // this bean is already shutdown
- }
-
- // Stop socket transport(s)
- if (this.jdbcSocket != null) {
- this.jdbcSocket.stop();
- this.jdbcSocket = null;
- }
-
- if (this.adminSocket != null) {
- this.adminSocket.stop();
- this.adminSocket = null;
- }
-
- if (this.odbcSocket != null) {
- this.odbcSocket.stop();
- this.odbcSocket = null;
- }
- LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("engine_stopped", new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
- }
-
- private void createClientServices() {
- this.logon = new LogonImpl(this.sessionService, "teiid-cluster"); //$NON-NLS-1$
- if (profileService != null) {
- this.admin = AdminProvider.getLocal(profileService, vdbStatusChecker);
- } else {
- try {
- this.admin = AdminProvider.getLocal(vdbStatusChecker);
- } catch (AdminComponentException e) {
- throw new TeiidRuntimeException(e.getCause());
- }
- }
- }
-
- /**
- * Creates an proxy to validate the incoming session
- */
- private <T> T proxyService(final Class<T> iface, final T instance, String context) {
-
- return iface.cast(Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {iface}, new LogManager.LoggingProxy(instance, context, MessageLevel.TRACE) {
-
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- Throwable exception = null;
- try {
- sessionService.validateSession(DQPWorkContext.getWorkContext().getSessionId());
- return super.invoke(proxy, method, args);
- } catch (InvocationTargetException e) {
- exception = e.getTargetException();
- } catch(Throwable t){
- exception = t;
- }
- throw ExceptionUtil.convertException(method, exception);
- }
- }));
- }
-
- public void setJdbcSocketConfiguration(SocketConfiguration socketConfig) {
- this.jdbcSocketConfiguration = socketConfig;
- }
-
- public void setAdminSocketConfiguration(SocketConfiguration socketConfig) {
- this.adminSocketConfiguration = socketConfig;
- }
-
- public void setOdbcSocketConfiguration(SocketConfiguration socketConfig) {
- this.odbcSocketConfiguration = socketConfig;
- }
-
- public void setXATerminator(XATerminator xaTerminator){
- this.transactionServerImpl.setXaTerminator(xaTerminator);
- }
-
- public void setTransactionManager(TransactionManager transactionManager) {
- this.transactionServerImpl.setTransactionManager(transactionManager);
- }
-
- public void setWorkManager(WorkManager mgr) {
- this.transactionServerImpl.setWorkManager(mgr);
- }
-
- public void setSessionService(SessionService service) {
- this.sessionService = service;
- service.setDqp(this.dqpCore);
- }
-
- public void setBufferService(BufferService service) {
- this.dqpCore.setBufferService(service);
- }
-
- public void setSecurityHelper(SecurityHelper helper) {
- this.csr.setSecurityHelper(helper);
- }
-
- public void setVDBRepository(VDBRepository repo) {
- this.vdbRepository = repo;
- }
-
- public void setVDBStatusChecker(VDBStatusChecker vdbStatusChecker) {
- this.vdbStatusChecker = vdbStatusChecker;
- }
-
- public void setProfileService(final ProfileService profileService) {
- this.profileService = profileService ;
- }
-
- public void setJndiName(final String jndiName) {
- this.jndiName = jndiName ;
- }
-
- @Override
- @ManagementOperation(description="Requests for perticular session", impact=Impact.ReadOnly,params={@ManagementParameter(name="sessionId",description="The session Identifier")})
- public List<RequestMetadata> getRequestsForSession(String sessionId) {
- return this.dqpCore.getRequestsForSession(sessionId);
- }
-
- @Override
- @ManagementOperation(description="Requests using a certain VDB", impact=Impact.ReadOnly,params={@ManagementParameter(name="vdbName",description="VDB Name"), @ManagementParameter(name="vdbVersion",description="VDB Version")})
- public List<RequestMetadata> getRequestsUsingVDB(String vdbName, int vdbVersion) throws AdminException {
- List<RequestMetadata> requests = new ArrayList<RequestMetadata>();
- try {
- Collection<SessionMetadata> sessions = this.sessionService.getActiveSessions();
- for (SessionMetadata session:sessions) {
- if (session.getVDBName().equals(vdbName) && session.getVDBVersion() == vdbVersion) {
- requests.addAll(this.dqpCore.getRequestsForSession(session.getSessionId()));
- }
- }
- } catch (SessionServiceException e) {
- throw new AdminComponentException(e);
- }
- return requests;
- }
-
-
- @Override
- @ManagementOperation(description="Active requests", impact=Impact.ReadOnly)
- public List<RequestMetadata> getRequests() {
- return this.dqpCore.getRequests();
- }
-
- @Override
- @ManagementOperation(description="Long running requests", impact=Impact.ReadOnly)
- public List<RequestMetadata> getLongRunningRequests() {
- return this.dqpCore.getLongRunningRequests();
- }
-
-
- @Override
- @ManagementOperation(description="Get thread statistics worker pool", impact=Impact.ReadOnly,params={@ManagementParameter(name="identifier",description="Get thread statistics worker pool")})
- public WorkerPoolStatisticsMetadata getWorkerPoolStatistics(){
- return this.dqpCore.getWorkerPoolStatistics();
- }
-
- @Override
- @ManagementOperation(description="Terminate a Session",params={@ManagementParameter(name="terminateeId",description="The session to be terminated")})
- public void terminateSession(String terminateeId) {
- this.sessionService.terminateSession(terminateeId, DQPWorkContext.getWorkContext().getSessionId());
- }
-
- @Override
- @ManagementOperation(description="Cancel a Request",params={@ManagementParameter(name="sessionId",description="The session Identifier"), @ManagementParameter(name="executionId",description="The Execution Identifier")})
- public boolean cancelRequest(String sessionId, long executionId) throws AdminException {
- try {
- return this.dqpCore.cancelRequest(sessionId, executionId);
- } catch (TeiidComponentException e) {
- throw new AdminComponentException(e);
- }
- }
-
- @Override
- @ManagementOperation(description="Get Cache types in the system", impact=Impact.ReadOnly)
- public Collection<String> getCacheTypes(){
- return this.dqpCore.getCacheTypes();
- }
-
- @Override
- @ManagementOperation(description="Clear the caches in the system", impact=Impact.ReadOnly)
- public void clearCache(String cacheType) {
- this.dqpCore.clearCache(cacheType);
- }
-
- @Override
- @ManagementOperation(description="Clear the caches in the system for a VDB", params={@ManagementParameter(name="cacheType",description="Type of Cache"), @ManagementParameter(name="vdbName",description="VDB Name"), at ManagementParameter(name="version",description="VDB Version")}, impact=Impact.ReadOnly)
- public void clearCache(String cacheType, String vdbName, int version) {
- this.dqpCore.clearCache(cacheType, vdbName, version);
- }
-
- @Override
- @ManagementOperation(description="Get the cache statistics", impact=Impact.ReadOnly)
- public CacheStatisticsMetadata getCacheStatistics(String cacheType) {
- return this.dqpCore.getCacheStatistics(cacheType);
- }
-
- @Override
- @ManagementOperation(description="Active sessions", impact=Impact.ReadOnly)
- public Collection<SessionMetadata> getActiveSessions() throws AdminException {
- try {
- return this.sessionService.getActiveSessions();
- } catch (SessionServiceException e) {
- throw new AdminComponentException(e);
- }
- }
-
- @Override
- @ManagementProperty(description="Active session count", use={ViewUse.STATISTIC}, readOnly=true)
- public int getActiveSessionsCount() throws AdminException{
- try {
- return this.sessionService.getActiveSessionsCount();
- } catch (SessionServiceException e) {
- throw new AdminComponentException(e);
- }
- }
-
- @Override
- @ManagementOperation(description="Active Transactions", impact=Impact.ReadOnly)
- public Collection<org.teiid.adminapi.Transaction> getTransactions() {
- return this.dqpCore.getTransactions();
- }
-
- @Override
- @ManagementOperation(description="Terminate the transaction", impact=Impact.ReadOnly)
- public void terminateTransaction(String xid) throws AdminException {
- this.dqpCore.terminateTransaction(xid);
- }
-
- @Override
- @ManagementOperation(description="Merge Two VDBs",params={@ManagementParameter(name="sourceVDBName"), at ManagementParameter(name="sourceVDBName"), @ManagementParameter(name="targetVDBName"), @ManagementParameter(name="targetVDBVersion")})
- public void mergeVDBs(String sourceVDBName, int sourceVDBVersion,
- String targetVDBName, int targetVDBVersion) throws AdminException {
- this.vdbRepository.mergeVDBs(sourceVDBName, sourceVDBVersion, targetVDBName, targetVDBVersion);
- }
-
- public void setCacheFactory(CacheFactory factory) {
- this.dqpCore.setCacheFactory(factory);
- }
-
- @Override
- @ManagementOperation(description="Execute a sql query", params={@ManagementParameter(name="vdbName"), at ManagementParameter(name="vdbVersion"), @ManagementParameter(name="command"), @ManagementParameter(name="timoutInMilli")})
- 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, false); //$NON-NLS-1$
- } catch (SessionServiceException e1) {
- throw new AdminProcessingException(e1);
- } catch (LoginException e1) {
- throw new AdminProcessingException(e1);
- }
-
- final long requestID = 0L;
-
- DQPWorkContext context = new DQPWorkContext();
- context.setSession(session);
-
- try {
- return context.runInContext(new Callable<List<List>>() {
- @Override
- public List<List> call() throws Exception {
- ArrayList<List> results = new ArrayList<List>();
-
- long start = System.currentTimeMillis();
- RequestMessage request = new RequestMessage(command);
- 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);
-
- if (rm.getException() != null) {
- throw new AdminProcessingException(rm.getException());
- }
-
- if (rm.isUpdateResult()) {
- results.addAll(new ArrayList(Arrays.asList("update count"))); //$NON-NLS-1$
- results.addAll(Arrays.asList(rm.getResults()));
- }
- else {
- results.addAll(new ArrayList(Arrays.asList(rm.getColumnNames())));
- results.addAll(Arrays.asList(fixResults(rm.getResults())));
-
- while (rm.getFinalRow() == -1 || rm.getLastRow() < rm.getFinalRow()) {
- long elapsed = System.currentTimeMillis() - start;
- message = dqpCore.processCursorRequest(requestID, rm.getLastRow()+1, 1024);
- rm = message.get(timoutInMilli-elapsed, TimeUnit.MILLISECONDS);
- results.addAll(Arrays.asList(fixResults(rm.getResults())));
- }
- }
-
- long elapsed = System.currentTimeMillis() - start;
- ResultsFuture<?> response = dqpCore.closeRequest(requestID);
- response.get(timoutInMilli-elapsed, TimeUnit.MILLISECONDS);
- return results;
- }
- });
- } catch (Throwable t) {
- throw new AdminProcessingException(t);
- } finally {
- try {
- sessionService.closeSession(session.getSessionId());
- } catch (InvalidSessionException e) { //ignore
- }
- }
- }
-
- /**
- * Managed Object framework has bug that does not currently allow
- * sending a NULL in the Collection Value, so sending literal string "null".
- * If you send them as Array Value, the MO is packaged as composite object and would like
- * all the elements in array to be same type which is not the case with results.
- */
- List[] fixResults(List[] rows) throws SQLException {
- List[] newResults = new List[rows.length];
-
- for(int i = 0; i < rows.length; i++) {
- List row = rows[i];
- ArrayList<Object> newRow = new ArrayList<Object>();
- for (Object col:row) {
- if (col == null) {
- newRow.add("null"); //$NON-NLS-1$
- }
- else {
- if (col instanceof Number || col instanceof String || col instanceof Character) {
- newRow.add(col);
- }
- else if (col instanceof Blob) {
- newRow.add("blob"); //$NON-NLS-1$
- }
- else if (col instanceof Clob) {
- newRow.add("clob"); //$NON-NLS-1$
- }
- else if (col instanceof SQLXML) {
- SQLXML xml = (SQLXML)col;
- newRow.add(xml.getString());
- }
- else {
- newRow.add(col.toString());
- }
- }
- }
- newResults[i] = newRow;
- }
- return newResults;
- }
-
- public String getEventDistributorName() {
- return eventDistributorName;
- }
-
- public void setEventDistributorName(String eventDistributorName) {
- this.eventDistributorName = eventDistributorName;
- }
-
- @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$
- }
- }
-
- @Override
- public void dataModification(String vdbName, int vdbVersion, String schema,
- String... tableNames) {
- updateModified(true, vdbName, vdbVersion, schema, tableNames);
- }
-
- private void updateModified(boolean data, String vdbName, int vdbVersion, String schema,
- String... objectNames) {
- Schema s = getSchema(vdbName, vdbVersion, schema);
- if (s == null) {
- return;
- }
- long ts = System.currentTimeMillis();
- for (String name:objectNames) {
- Table table = s.getTables().get(name);
- if (table == null) {
- continue;
- }
- if (data) {
- table.setLastDataModification(ts);
- } else {
- table.setLastModified(ts);
- }
- }
- }
-
- @Override
- public void setColumnStats(String vdbName, int vdbVersion,
- String schemaName, String tableName, String columnName,
- ColumnStats stats) {
- Table t = getTable(vdbName, vdbVersion, schemaName, tableName);
- if (t == null) {
- return;
- }
- for (Column c : t.getColumns()) {
- if (c.getName().equalsIgnoreCase(columnName)) {
- c.setColumnStats(stats);
- t.setLastModified(System.currentTimeMillis());
- break;
- }
- }
- }
-
- @Override
- public void setTableStats(String vdbName, int vdbVersion,
- String schemaName, String tableName, TableStats stats) {
- Table t = getTable(vdbName, vdbVersion, schemaName, tableName);
- if (t == null) {
- return;
- }
- t.setTableStats(stats);
- t.setLastModified(System.currentTimeMillis());
- }
-
- private Table getTable(String vdbName, int vdbVersion, String schemaName,
- String tableName) {
- Schema s = getSchema(vdbName, vdbVersion, schemaName);
- if (s == null) {
- return null;
- }
- return s.getTables().get(tableName.toUpperCase());
- }
-
- private Schema getSchema(String vdbName, int vdbVersion, String schemaName) {
- VDBMetaData vdb = this.vdbRepository.getVDB(vdbName, vdbVersion);
- if (vdb == null) {
- return null;
- }
- TransformationMetadata tm = vdb.getAttachment(TransformationMetadata.class);
- if (tm == null) {
- return null;
- }
- return tm.getMetadataStore().getSchemas().get(schemaName.toUpperCase());
- }
-
- @Override
- public void setInsteadOfTriggerDefinition(String vdbName, int vdbVersion,
- String schema, String viewName, TriggerEvent triggerEvent,
- String triggerDefinition, Boolean enabled) {
- Table t = getTable(vdbName, vdbVersion, schema, viewName);
- if (t == null) {
- return;
- }
- DdlPlan.alterInsteadOfTrigger(this.vdbRepository.getVDB(vdbName, vdbVersion), t, triggerDefinition, enabled, triggerEvent);
- }
-
- @Override
- public void setProcedureDefinition(String vdbName, int vdbVersion,
- String schema, String procName, String definition) {
- Schema s = getSchema(vdbName, vdbVersion, schema);
- if (s == null) {
- return;
- }
- Procedure p = s.getProcedures().get(procName.toUpperCase());
- if (p == null) {
- return;
- }
- DdlPlan.alterProcedureDefinition(this.vdbRepository.getVDB(vdbName, vdbVersion), p, definition);
- }
-
- @Override
- public void setViewDefinition(String vdbName, int vdbVersion,
- String schema, String viewName, String definition) {
- Table t = getTable(vdbName, vdbVersion, schema, viewName);
- if (t == null) {
- return;
- }
- DdlPlan.alterView(this.vdbRepository.getVDB(vdbName, vdbVersion), t, definition);
- }
-
- @Override
- public void setProperty(String vdbName, int vdbVersion, String uuid,
- String name, String value) {
- VDBMetaData vdb = this.vdbRepository.getVDB(vdbName, vdbVersion);
- if (vdb == null) {
- return;
- }
- TransformationMetadata tm = vdb.getAttachment(TransformationMetadata.class);
- if (tm == null) {
- return;
- }
- AbstractMetadataRecord record = DataTierManagerImpl.getByUuid(tm.getMetadataStore(), uuid);
- if (record != null) {
- record.setProperty(name, value);
- }
- }
-
- @Override
- public EventDistributor getEventDistributor() {
- if (this.eventDistributor != null) {
- return eventDistributor;
- }
- return this;
- }
-
- @Override
- public MetadataRepository getMetadataRepository() {
- return this.vdbRepository.getMetadataRepository();
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java (from rev 3218, trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,819 @@
+/*
+ * 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.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;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import javax.resource.spi.XATerminator;
+import javax.resource.spi.work.WorkManager;
+import javax.security.auth.login.LoginException;
+import javax.transaction.TransactionManager;
+
+import org.jboss.managed.api.ManagedOperation.Impact;
+import org.jboss.managed.api.annotation.ManagementComponent;
+import org.jboss.managed.api.annotation.ManagementObject;
+import org.jboss.managed.api.annotation.ManagementOperation;
+import org.jboss.managed.api.annotation.ManagementParameter;
+import org.jboss.managed.api.annotation.ManagementProperties;
+import org.jboss.managed.api.annotation.ManagementProperty;
+import org.jboss.managed.api.annotation.ViewUse;
+import org.jboss.profileservice.spi.ProfileService;
+import org.jboss.util.naming.Util;
+import org.teiid.adminapi.Admin;
+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.CacheStatisticsMetadata;
+import org.teiid.adminapi.impl.DQPManagement;
+import org.teiid.adminapi.impl.RequestMetadata;
+import org.teiid.adminapi.impl.SessionMetadata;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.adminapi.impl.WorkerPoolStatisticsMetadata;
+import org.teiid.adminapi.jboss.AdminProvider;
+import org.teiid.cache.CacheFactory;
+import org.teiid.client.DQP;
+import org.teiid.client.RequestMessage;
+import org.teiid.client.ResultsMessage;
+import org.teiid.client.security.ILogon;
+import org.teiid.client.security.InvalidSessionException;
+import org.teiid.client.util.ExceptionUtil;
+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.LRUCache;
+import org.teiid.deployers.VDBLifeCycleListener;
+import org.teiid.deployers.VDBRepository;
+import org.teiid.deployers.VDBStatusChecker;
+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;
+import org.teiid.dqp.service.TransactionService;
+import org.teiid.events.EventDistributor;
+import org.teiid.events.EventDistributorFactory;
+import org.teiid.jboss.IntegrationPlugin;
+import org.teiid.logging.Log4jListener;
+import org.teiid.logging.LogConstants;
+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;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.metadata.TableStats;
+import org.teiid.metadata.Table.TriggerEvent;
+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.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;
+
+
+ at ManagementObject(name="RuntimeEngineDeployer", isRuntime=true, componentType=@ManagementComponent(type="teiid",subtype="dqp"), properties=ManagementProperties.EXPLICIT)
+public class RuntimeEngineDeployer extends DQPConfiguration implements DQPManagement, Serializable , ClientServiceRegistry, EventDistributor, EventDistributorFactory {
+ private static final long serialVersionUID = -4676205340262775388L;
+
+ private transient SocketConfiguration jdbcSocketConfiguration;
+ private transient SocketConfiguration adminSocketConfiguration;
+ private transient SocketConfiguration odbcSocketConfiguration;
+ private transient SocketListener jdbcSocket;
+ private transient SocketListener adminSocket;
+ private transient SocketListener odbcSocket;
+ private transient TransactionServerImpl transactionServerImpl = new TransactionServerImpl();
+
+ private transient DQPCore dqpCore = new DQPCore();
+ private transient SessionService sessionService;
+ private transient ILogon logon;
+ private transient Admin admin;
+ private transient ClientServiceRegistryImpl csr = new ClientServiceRegistryImpl();
+ private transient VDBRepository vdbRepository;
+ private transient VDBStatusChecker vdbStatusChecker;
+
+ private transient ProfileService profileService;
+ private transient String jndiName;
+
+ private String eventDistributorName;
+ private transient EventDistributor eventDistributor;
+ private transient EventDistributor eventDistributorProxy;
+
+ public RuntimeEngineDeployer() {
+ // TODO: this does not belong here
+ LogManager.setLogListener(new Log4jListener());
+ }
+
+ @Override
+ public <T> T getClientService(Class<T> iface)
+ throws ComponentNotFoundException {
+ return this.csr.getClientService(iface);
+ }
+
+ @Override
+ public SecurityHelper getSecurityHelper() {
+ return this.csr.getSecurityHelper();
+ }
+
+ public void start() {
+ dqpCore.setTransactionService((TransactionService)LogManager.createLoggingProxy(LogConstants.CTX_TXN_LOG, transactionServerImpl, new Class[] {TransactionService.class}, MessageLevel.DETAIL));
+
+ if (this.eventDistributorName != null) {
+ try {
+ InitialContext ic = new InitialContext();
+ this.eventDistributor = (EventDistributor) ic.lookup(this.eventDistributorName);
+ } catch (NamingException ne) {
+ //log at a detail level since we may not be in the all profile
+ 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.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();
+
+ int offset = 0;
+ String portBinding = System.getProperty("jboss.service.binding.set"); //$NON-NLS-1$
+ if (portBinding != null && portBinding.startsWith("ports-")) { //$NON-NLS-1$
+ if (portBinding.equals("ports-default")) { //$NON-NLS-1$
+ offset = 0;
+ }
+ else {
+ try {
+ offset = Integer.parseInt(portBinding.substring(portBinding.length()-2))*100;
+ } catch (NumberFormatException e) {
+ offset = 0;
+ }
+ }
+ }
+
+ this.csr.registerClientService(ILogon.class, logon, LogConstants.CTX_SECURITY);
+ DQP dqpProxy = proxyService(DQP.class, this.dqpCore, LogConstants.CTX_DQP);
+ this.csr.registerClientService(DQP.class, dqpProxy, LogConstants.CTX_DQP);
+ Admin adminProxy = proxyService(Admin.class, admin, LogConstants.CTX_ADMIN_API);
+ this.csr.registerClientService(Admin.class, adminProxy, LogConstants.CTX_ADMIN_API);
+
+ ClientServiceRegistryImpl jdbcCsr = new ClientServiceRegistryImpl();
+ jdbcCsr.registerClientService(ILogon.class, logon, LogConstants.CTX_SECURITY);
+ jdbcCsr.registerClientService(DQP.class, dqpProxy, LogConstants.CTX_DQP);
+
+ if (this.jdbcSocketConfiguration.getEnabled()) {
+ this.jdbcSocket = new SocketListener(this.jdbcSocketConfiguration, jdbcCsr, this.dqpCore.getBufferManager(), offset);
+ LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_enabled","Teiid JDBC = ",(this.jdbcSocketConfiguration.getSSLConfiguration().isSslEnabled()?"mms://":"mm://")+this.jdbcSocketConfiguration.getHostAddress().getHostName()+":"+(this.jdbcSocketConfiguration.getPortNumber()+offset))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ } else {
+ LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_not_enabled", "jdbc connections")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ ClientServiceRegistryImpl adminCsr = new ClientServiceRegistryImpl(Type.Admin);
+ adminCsr.registerClientService(ILogon.class, logon, LogConstants.CTX_SECURITY);
+ adminCsr.registerClientService(Admin.class, adminProxy, LogConstants.CTX_ADMIN_API);
+
+ if (this.adminSocketConfiguration.getEnabled()) {
+ this.adminSocket = new SocketListener(this.adminSocketConfiguration, adminCsr, this.dqpCore.getBufferManager(), offset);
+ LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_enabled","Teiid Admin", (this.adminSocketConfiguration.getSSLConfiguration().isSslEnabled()?"mms://":"mm://")+this.adminSocketConfiguration.getHostAddress().getHostName()+":"+(this.adminSocketConfiguration.getPortNumber()+offset))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ } else {
+ LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("socket_not_enabled", "admin connections")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ if (this.odbcSocketConfiguration.getEnabled()) {
+ this.vdbRepository.odbcEnabled();
+ this.odbcSocket = new ODBCSocketListener(this.odbcSocketConfiguration, this.dqpCore.getBufferManager(), offset, getMaxODBCLobSizeAllowed());
+ 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$
+ }
+
+ LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("engine_started", getRuntimeVersion(), new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
+ if (jndiName != null) {
+ final InitialContext ic ;
+ try {
+ ic = new InitialContext() ;
+ Util.bind(ic, jndiName, this) ;
+ } catch (final NamingException ne) {
+ // Add jndi_failed to bundle
+ LogManager.logError(LogConstants.CTX_RUNTIME, ne, IntegrationPlugin.Util.getString("jndi_failed", new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
+ }
+ }
+
+ // add vdb life cycle listeners
+ this.vdbRepository.addListener(new VDBLifeCycleListener() {
+
+ private Set<VDBKey> recentlyRemoved = Collections.newSetFromMap(new LRUCache<VDBKey, Boolean>(10000));
+
+ @Override
+ public void removed(String name, int version) {
+ recentlyRemoved.add(new VDBKey(name, version));
+ }
+
+ @Override
+ public void added(String name, int version) {
+ if (!recentlyRemoved.remove(new VDBKey(name, version))) {
+ return;
+ }
+ // terminate all the previous sessions
+ try {
+ Collection<SessionMetadata> sessions = sessionService.getActiveSessions();
+ for (SessionMetadata session:sessions) {
+ if (name.equalsIgnoreCase(session.getVDBName()) && version == session.getVDBVersion()){
+ sessionService.terminateSession(session.getSessionId(), null);
+ }
+ }
+ } catch (SessionServiceException e) {
+ //ignore
+ }
+
+ // dump the caches.
+ dqpCore.clearCache(Cache.PREPARED_PLAN_CACHE.toString(), name, version);
+ dqpCore.clearCache(Cache.QUERY_SERVICE_RESULT_SET_CACHE.toString(), name, version);
+ }
+ });
+ }
+
+ public void stop() {
+ if (jndiName != null) {
+ final InitialContext ic ;
+ try {
+ ic = new InitialContext() ;
+ Util.unbind(ic, jndiName) ;
+ } catch (final NamingException ne) {
+ }
+ }
+
+ try {
+ this.dqpCore.stop();
+ } catch(TeiidRuntimeException e) {
+ // this bean is already shutdown
+ }
+
+ // Stop socket transport(s)
+ if (this.jdbcSocket != null) {
+ this.jdbcSocket.stop();
+ this.jdbcSocket = null;
+ }
+
+ if (this.adminSocket != null) {
+ this.adminSocket.stop();
+ this.adminSocket = null;
+ }
+
+ if (this.odbcSocket != null) {
+ this.odbcSocket.stop();
+ this.odbcSocket = null;
+ }
+ LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("engine_stopped", new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
+ }
+
+ private void createClientServices() {
+ this.logon = new LogonImpl(this.sessionService, "teiid-cluster"); //$NON-NLS-1$
+ if (profileService != null) {
+ this.admin = AdminProvider.getLocal(profileService, vdbStatusChecker);
+ } else {
+ try {
+ this.admin = AdminProvider.getLocal(vdbStatusChecker);
+ } catch (AdminComponentException e) {
+ throw new TeiidRuntimeException(e.getCause());
+ }
+ }
+ }
+
+ /**
+ * Creates an proxy to validate the incoming session
+ */
+ private <T> T proxyService(final Class<T> iface, final T instance, String context) {
+
+ return iface.cast(Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {iface}, new LogManager.LoggingProxy(instance, context, MessageLevel.TRACE) {
+
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ Throwable exception = null;
+ try {
+ sessionService.validateSession(DQPWorkContext.getWorkContext().getSessionId());
+ return super.invoke(proxy, method, args);
+ } catch (InvocationTargetException e) {
+ exception = e.getTargetException();
+ } catch(Throwable t){
+ exception = t;
+ }
+ throw ExceptionUtil.convertException(method, exception);
+ }
+ }));
+ }
+
+ public void setJdbcSocketConfiguration(SocketConfiguration socketConfig) {
+ this.jdbcSocketConfiguration = socketConfig;
+ }
+
+ public void setAdminSocketConfiguration(SocketConfiguration socketConfig) {
+ this.adminSocketConfiguration = socketConfig;
+ }
+
+ public void setOdbcSocketConfiguration(SocketConfiguration socketConfig) {
+ this.odbcSocketConfiguration = socketConfig;
+ }
+
+ public void setXATerminator(XATerminator xaTerminator){
+ this.transactionServerImpl.setXaTerminator(xaTerminator);
+ }
+
+ public void setTransactionManager(TransactionManager transactionManager) {
+ this.transactionServerImpl.setTransactionManager(transactionManager);
+ }
+
+ public void setWorkManager(WorkManager mgr) {
+ this.transactionServerImpl.setWorkManager(mgr);
+ }
+
+ public void setSessionService(SessionService service) {
+ this.sessionService = service;
+ service.setDqp(this.dqpCore);
+ }
+
+ public void setBufferService(BufferService service) {
+ this.dqpCore.setBufferService(service);
+ }
+
+ public void setSecurityHelper(SecurityHelper helper) {
+ this.csr.setSecurityHelper(helper);
+ }
+
+ public void setVDBRepository(VDBRepository repo) {
+ this.vdbRepository = repo;
+ }
+
+ public void setVDBStatusChecker(VDBStatusChecker vdbStatusChecker) {
+ this.vdbStatusChecker = vdbStatusChecker;
+ }
+
+ public void setProfileService(final ProfileService profileService) {
+ this.profileService = profileService ;
+ }
+
+ public void setJndiName(final String jndiName) {
+ this.jndiName = jndiName ;
+ }
+
+ @Override
+ @ManagementOperation(description="Requests for perticular session", impact=Impact.ReadOnly,params={@ManagementParameter(name="sessionId",description="The session Identifier")})
+ public List<RequestMetadata> getRequestsForSession(String sessionId) {
+ return this.dqpCore.getRequestsForSession(sessionId);
+ }
+
+ @Override
+ @ManagementOperation(description="Requests using a certain VDB", impact=Impact.ReadOnly,params={@ManagementParameter(name="vdbName",description="VDB Name"), @ManagementParameter(name="vdbVersion",description="VDB Version")})
+ public List<RequestMetadata> getRequestsUsingVDB(String vdbName, int vdbVersion) throws AdminException {
+ List<RequestMetadata> requests = new ArrayList<RequestMetadata>();
+ try {
+ Collection<SessionMetadata> sessions = this.sessionService.getActiveSessions();
+ for (SessionMetadata session:sessions) {
+ if (session.getVDBName().equals(vdbName) && session.getVDBVersion() == vdbVersion) {
+ requests.addAll(this.dqpCore.getRequestsForSession(session.getSessionId()));
+ }
+ }
+ } catch (SessionServiceException e) {
+ throw new AdminComponentException(e);
+ }
+ return requests;
+ }
+
+
+ @Override
+ @ManagementOperation(description="Active requests", impact=Impact.ReadOnly)
+ public List<RequestMetadata> getRequests() {
+ return this.dqpCore.getRequests();
+ }
+
+ @Override
+ @ManagementOperation(description="Long running requests", impact=Impact.ReadOnly)
+ public List<RequestMetadata> getLongRunningRequests() {
+ return this.dqpCore.getLongRunningRequests();
+ }
+
+
+ @Override
+ @ManagementOperation(description="Get thread statistics worker pool", impact=Impact.ReadOnly,params={@ManagementParameter(name="identifier",description="Get thread statistics worker pool")})
+ public WorkerPoolStatisticsMetadata getWorkerPoolStatistics(){
+ return this.dqpCore.getWorkerPoolStatistics();
+ }
+
+ @Override
+ @ManagementOperation(description="Terminate a Session",params={@ManagementParameter(name="terminateeId",description="The session to be terminated")})
+ public void terminateSession(String terminateeId) {
+ this.sessionService.terminateSession(terminateeId, DQPWorkContext.getWorkContext().getSessionId());
+ }
+
+ @Override
+ @ManagementOperation(description="Cancel a Request",params={@ManagementParameter(name="sessionId",description="The session Identifier"), @ManagementParameter(name="executionId",description="The Execution Identifier")})
+ public boolean cancelRequest(String sessionId, long executionId) throws AdminException {
+ try {
+ return this.dqpCore.cancelRequest(sessionId, executionId);
+ } catch (TeiidComponentException e) {
+ throw new AdminComponentException(e);
+ }
+ }
+
+ @Override
+ @ManagementOperation(description="Get Cache types in the system", impact=Impact.ReadOnly)
+ public Collection<String> getCacheTypes(){
+ return this.dqpCore.getCacheTypes();
+ }
+
+ @Override
+ @ManagementOperation(description="Clear the caches in the system", impact=Impact.ReadOnly)
+ public void clearCache(String cacheType) {
+ this.dqpCore.clearCache(cacheType);
+ }
+
+ @Override
+ @ManagementOperation(description="Clear the caches in the system for a VDB", params={@ManagementParameter(name="cacheType",description="Type of Cache"), @ManagementParameter(name="vdbName",description="VDB Name"), at ManagementParameter(name="version",description="VDB Version")}, impact=Impact.ReadOnly)
+ public void clearCache(String cacheType, String vdbName, int version) {
+ this.dqpCore.clearCache(cacheType, vdbName, version);
+ }
+
+ @Override
+ @ManagementOperation(description="Get the cache statistics", impact=Impact.ReadOnly)
+ public CacheStatisticsMetadata getCacheStatistics(String cacheType) {
+ return this.dqpCore.getCacheStatistics(cacheType);
+ }
+
+ @Override
+ @ManagementOperation(description="Active sessions", impact=Impact.ReadOnly)
+ public Collection<SessionMetadata> getActiveSessions() throws AdminException {
+ try {
+ return this.sessionService.getActiveSessions();
+ } catch (SessionServiceException e) {
+ throw new AdminComponentException(e);
+ }
+ }
+
+ @Override
+ @ManagementProperty(description="Active session count", use={ViewUse.STATISTIC}, readOnly=true)
+ public int getActiveSessionsCount() throws AdminException{
+ try {
+ return this.sessionService.getActiveSessionsCount();
+ } catch (SessionServiceException e) {
+ throw new AdminComponentException(e);
+ }
+ }
+
+ @Override
+ @ManagementOperation(description="Active Transactions", impact=Impact.ReadOnly)
+ public Collection<org.teiid.adminapi.Transaction> getTransactions() {
+ return this.dqpCore.getTransactions();
+ }
+
+ @Override
+ @ManagementOperation(description="Terminate the transaction", impact=Impact.ReadOnly)
+ public void terminateTransaction(String xid) throws AdminException {
+ this.dqpCore.terminateTransaction(xid);
+ }
+
+ @Override
+ @ManagementOperation(description="Merge Two VDBs",params={@ManagementParameter(name="sourceVDBName"), at ManagementParameter(name="sourceVDBName"), @ManagementParameter(name="targetVDBName"), @ManagementParameter(name="targetVDBVersion")})
+ public void mergeVDBs(String sourceVDBName, int sourceVDBVersion,
+ String targetVDBName, int targetVDBVersion) throws AdminException {
+ this.vdbRepository.mergeVDBs(sourceVDBName, sourceVDBVersion, targetVDBName, targetVDBVersion);
+ }
+
+ public void setCacheFactory(CacheFactory factory) {
+ this.dqpCore.setCacheFactory(factory);
+ }
+
+ @Override
+ @ManagementOperation(description="Execute a sql query", params={@ManagementParameter(name="vdbName"), at ManagementParameter(name="vdbVersion"), @ManagementParameter(name="command"), @ManagementParameter(name="timoutInMilli")})
+ 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, false); //$NON-NLS-1$
+ } catch (SessionServiceException e1) {
+ throw new AdminProcessingException(e1);
+ } catch (LoginException e1) {
+ throw new AdminProcessingException(e1);
+ }
+
+ final long requestID = 0L;
+
+ DQPWorkContext context = new DQPWorkContext();
+ context.setSession(session);
+
+ try {
+ return context.runInContext(new Callable<List<List>>() {
+ @Override
+ public List<List> call() throws Exception {
+ ArrayList<List> results = new ArrayList<List>();
+
+ long start = System.currentTimeMillis();
+ RequestMessage request = new RequestMessage(command);
+ 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);
+
+ if (rm.getException() != null) {
+ throw new AdminProcessingException(rm.getException());
+ }
+
+ if (rm.isUpdateResult()) {
+ results.addAll(new ArrayList(Arrays.asList("update count"))); //$NON-NLS-1$
+ results.addAll(Arrays.asList(rm.getResults()));
+ }
+ else {
+ results.addAll(new ArrayList(Arrays.asList(rm.getColumnNames())));
+ results.addAll(Arrays.asList(fixResults(rm.getResults())));
+
+ while (rm.getFinalRow() == -1 || rm.getLastRow() < rm.getFinalRow()) {
+ long elapsed = System.currentTimeMillis() - start;
+ message = dqpCore.processCursorRequest(requestID, rm.getLastRow()+1, 1024);
+ rm = message.get(timoutInMilli-elapsed, TimeUnit.MILLISECONDS);
+ results.addAll(Arrays.asList(fixResults(rm.getResults())));
+ }
+ }
+
+ long elapsed = System.currentTimeMillis() - start;
+ ResultsFuture<?> response = dqpCore.closeRequest(requestID);
+ response.get(timoutInMilli-elapsed, TimeUnit.MILLISECONDS);
+ return results;
+ }
+ });
+ } catch (Throwable t) {
+ throw new AdminProcessingException(t);
+ } finally {
+ try {
+ sessionService.closeSession(session.getSessionId());
+ } catch (InvalidSessionException e) { //ignore
+ }
+ }
+ }
+
+ /**
+ * Managed Object framework has bug that does not currently allow
+ * sending a NULL in the Collection Value, so sending literal string "null".
+ * If you send them as Array Value, the MO is packaged as composite object and would like
+ * all the elements in array to be same type which is not the case with results.
+ */
+ List[] fixResults(List[] rows) throws SQLException {
+ List[] newResults = new List[rows.length];
+
+ for(int i = 0; i < rows.length; i++) {
+ List row = rows[i];
+ ArrayList<Object> newRow = new ArrayList<Object>();
+ for (Object col:row) {
+ if (col == null) {
+ newRow.add("null"); //$NON-NLS-1$
+ }
+ else {
+ if (col instanceof Number || col instanceof String || col instanceof Character) {
+ newRow.add(col);
+ }
+ else if (col instanceof Blob) {
+ newRow.add("blob"); //$NON-NLS-1$
+ }
+ else if (col instanceof Clob) {
+ newRow.add("clob"); //$NON-NLS-1$
+ }
+ else if (col instanceof SQLXML) {
+ SQLXML xml = (SQLXML)col;
+ newRow.add(xml.getString());
+ }
+ else {
+ newRow.add(col.toString());
+ }
+ }
+ }
+ newResults[i] = newRow;
+ }
+ return newResults;
+ }
+
+ public String getEventDistributorName() {
+ return eventDistributorName;
+ }
+
+ public void setEventDistributorName(String eventDistributorName) {
+ this.eventDistributorName = eventDistributorName;
+ }
+
+ @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$
+ }
+ }
+
+ @Override
+ public void dataModification(String vdbName, int vdbVersion, String schema,
+ String... tableNames) {
+ updateModified(true, vdbName, vdbVersion, schema, tableNames);
+ }
+
+ private void updateModified(boolean data, String vdbName, int vdbVersion, String schema,
+ String... objectNames) {
+ Schema s = getSchema(vdbName, vdbVersion, schema);
+ if (s == null) {
+ return;
+ }
+ long ts = System.currentTimeMillis();
+ for (String name:objectNames) {
+ Table table = s.getTables().get(name.toUpperCase());
+ if (table == null) {
+ continue;
+ }
+ if (data) {
+ table.setLastDataModification(ts);
+ } else {
+ table.setLastModified(ts);
+ }
+ }
+ }
+
+ @Override
+ public void setColumnStats(String vdbName, int vdbVersion,
+ String schemaName, String tableName, String columnName,
+ ColumnStats stats) {
+ Table t = getTable(vdbName, vdbVersion, schemaName, tableName);
+ if (t == null) {
+ return;
+ }
+ for (Column c : t.getColumns()) {
+ if (c.getName().equalsIgnoreCase(columnName)) {
+ c.setColumnStats(stats);
+ t.setLastModified(System.currentTimeMillis());
+ break;
+ }
+ }
+ }
+
+ @Override
+ public void setTableStats(String vdbName, int vdbVersion,
+ String schemaName, String tableName, TableStats stats) {
+ Table t = getTable(vdbName, vdbVersion, schemaName, tableName);
+ if (t == null) {
+ return;
+ }
+ t.setTableStats(stats);
+ t.setLastModified(System.currentTimeMillis());
+ }
+
+ private Table getTable(String vdbName, int vdbVersion, String schemaName,
+ String tableName) {
+ Schema s = getSchema(vdbName, vdbVersion, schemaName);
+ if (s == null) {
+ return null;
+ }
+ return s.getTables().get(tableName.toUpperCase());
+ }
+
+ private Schema getSchema(String vdbName, int vdbVersion, String schemaName) {
+ VDBMetaData vdb = this.vdbRepository.getVDB(vdbName, vdbVersion);
+ if (vdb == null) {
+ return null;
+ }
+ TransformationMetadata tm = vdb.getAttachment(TransformationMetadata.class);
+ if (tm == null) {
+ return null;
+ }
+ return tm.getMetadataStore().getSchemas().get(schemaName.toUpperCase());
+ }
+
+ @Override
+ public void setInsteadOfTriggerDefinition(String vdbName, int vdbVersion,
+ String schema, String viewName, TriggerEvent triggerEvent,
+ String triggerDefinition, Boolean enabled) {
+ Table t = getTable(vdbName, vdbVersion, schema, viewName);
+ if (t == null) {
+ return;
+ }
+ DdlPlan.alterInsteadOfTrigger(this.vdbRepository.getVDB(vdbName, vdbVersion), t, triggerDefinition, enabled, triggerEvent);
+ }
+
+ @Override
+ public void setProcedureDefinition(String vdbName, int vdbVersion,
+ String schema, String procName, String definition) {
+ Schema s = getSchema(vdbName, vdbVersion, schema);
+ if (s == null) {
+ return;
+ }
+ Procedure p = s.getProcedures().get(procName.toUpperCase());
+ if (p == null) {
+ return;
+ }
+ DdlPlan.alterProcedureDefinition(this.vdbRepository.getVDB(vdbName, vdbVersion), p, definition);
+ }
+
+ @Override
+ public void setViewDefinition(String vdbName, int vdbVersion,
+ String schema, String viewName, String definition) {
+ Table t = getTable(vdbName, vdbVersion, schema, viewName);
+ if (t == null) {
+ return;
+ }
+ DdlPlan.alterView(this.vdbRepository.getVDB(vdbName, vdbVersion), t, definition);
+ }
+
+ @Override
+ public void setProperty(String vdbName, int vdbVersion, String uuid,
+ String name, String value) {
+ VDBMetaData vdb = this.vdbRepository.getVDB(vdbName, vdbVersion);
+ if (vdb == null) {
+ return;
+ }
+ TransformationMetadata tm = vdb.getAttachment(TransformationMetadata.class);
+ if (tm == null) {
+ return;
+ }
+ AbstractMetadataRecord record = DataTierManagerImpl.getByUuid(tm.getMetadataStore(), uuid);
+ if (record != null) {
+ record.setProperty(name, value);
+ }
+ }
+
+ @Override
+ public EventDistributor getEventDistributor() {
+ return this.eventDistributorProxy;
+ }
+
+}
Property changes on: tags/teiid-parent-7.5.0.Alpha1/metadata
___________________________________________________________________
Deleted: svn:mergeinfo
-
Deleted: tags/teiid-parent-7.5.0.Alpha1/metadata/pom.xml
===================================================================
--- trunk/metadata/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/metadata/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,69 +0,0 @@
-<?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-metadata</artifactId>
- <name>Metadata</name>
- <description>Provides vdb metadata from index files.</description>
-
- <dependencies>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <type>test-jar</type>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-engine</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-engine</artifactId>
- <type>test-jar</type>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jboss-vfs</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.man</groupId>
- <artifactId>jboss-managed</artifactId>
- </dependency>
-
- </dependencies>
-
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/metadata/pom.xml (from rev 3220, trunk/metadata/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/metadata/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/metadata/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,69 @@
+<?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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>teiid-metadata</artifactId>
+ <name>Metadata</name>
+ <description>Provides vdb metadata from index files.</description>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <type>test-jar</type>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-engine</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-engine</artifactId>
+ <type>test-jar</type>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jboss-vfs</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.man</groupId>
+ <artifactId>jboss-managed</artifactId>
+ </dependency>
+
+ </dependencies>
+
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/api/TranslationUtility.java
===================================================================
--- trunk/metadata/src/test/java/org/teiid/cdk/api/TranslationUtility.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/api/TranslationUtility.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,111 +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.cdk.api;
-
-import java.io.IOException;
-import java.net.URL;
-import java.util.Collection;
-
-import org.teiid.cdk.CommandBuilder;
-import org.teiid.dqp.internal.datamgr.RuntimeMetadataImpl;
-import org.teiid.language.Command;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.RuntimeMetadata;
-import org.teiid.metadata.index.VDBMetadataFactory;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.function.FunctionTree;
-import org.teiid.query.function.SystemFunctionManager;
-import org.teiid.query.function.UDFSource;
-import org.teiid.query.metadata.BasicQueryMetadataWrapper;
-import org.teiid.query.metadata.QueryMetadataInterface;
-
-
-/**
- * <p>This translation utility can be used to translate sql strings into
- * Connector API language interfaces for testing purposes. The utility
- * requires a metadata .vdb file in order to resolve references in
- * the SQL.</p>
- *
- * <p>This utility class can also be used to obtain a RuntimeMetadata
- * implementation based on the VDB file, which is sometimes handy when writing
- * unit tests.</p>
- */
-public class TranslationUtility {
-
- private QueryMetadataInterface metadata;
-
- /**
- * 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);
- }
-
- public TranslationUtility(URL url) {
- try {
- metadata = VDBMetadataFactory.getVDBMetadata(url, null);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- public TranslationUtility(QueryMetadataInterface metadata) {
- this.metadata = metadata;
- }
-
- public Command parseCommand(String sql, boolean generateAliases, boolean supportsGroupAliases) {
- CommandBuilder commandBuilder = new CommandBuilder(metadata);
- return commandBuilder.getCommand(sql, generateAliases, supportsGroupAliases);
- }
-
- /**
- * Parse a SQL command and return an ICommand object.
- * @param sql
- * @return Command using the language interfaces
- */
- public Command parseCommand(String sql) {
- CommandBuilder commandBuilder = new CommandBuilder(metadata);
- return commandBuilder.getCommand(sql);
- }
-
- /**
- * Create a RuntimeMetadata that can be used for testing a connector.
- * This RuntimeMetadata instance will be backed by the metadata from the vdbFile
- * this translation utility instance was created with.
- * @return RuntimeMetadata for testing
- */
- public RuntimeMetadata createRuntimeMetadata() {
- return new RuntimeMetadataImpl(metadata);
- }
-
- 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$
- }
- };
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/api/TranslationUtility.java (from rev 3218, trunk/metadata/src/test/java/org/teiid/cdk/api/TranslationUtility.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/api/TranslationUtility.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/api/TranslationUtility.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,123 @@
+/*
+ * 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.cdk.api;
+
+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;
+import org.teiid.language.Command;
+import org.teiid.metadata.FunctionMethod;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.metadata.index.VDBMetadataFactory;
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.function.FunctionTree;
+import org.teiid.query.function.SystemFunctionManager;
+import org.teiid.query.function.UDFSource;
+import org.teiid.query.metadata.BasicQueryMetadataWrapper;
+import org.teiid.query.metadata.QueryMetadataInterface;
+
+
+/**
+ * <p>This translation utility can be used to translate sql strings into
+ * Connector API language interfaces for testing purposes. The utility
+ * requires a metadata .vdb file in order to resolve references in
+ * the SQL.</p>
+ *
+ * <p>This utility class can also be used to obtain a RuntimeMetadata
+ * implementation based on the VDB file, which is sometimes handy when writing
+ * unit tests.</p>
+ */
+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) {
+ 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) {
+ try {
+ initWrapper(VDBMetadataFactory.getVDBMetadata(url, null));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public TranslationUtility(QueryMetadataInterface metadata) {
+ initWrapper(metadata);
+ }
+
+ public Command parseCommand(String sql, boolean generateAliases, boolean supportsGroupAliases) {
+ CommandBuilder commandBuilder = new CommandBuilder(metadata);
+ return commandBuilder.getCommand(sql, generateAliases, supportsGroupAliases);
+ }
+
+ /**
+ * Parse a SQL command and return an ICommand object.
+ * @param sql
+ * @return Command using the language interfaces
+ */
+ public Command parseCommand(String sql) {
+ CommandBuilder commandBuilder = new CommandBuilder(metadata);
+ return commandBuilder.getCommand(sql);
+ }
+
+ /**
+ * Create a RuntimeMetadata that can be used for testing a connector.
+ * This RuntimeMetadata instance will be backed by the metadata from the vdbFile
+ * this translation utility instance was created with.
+ * @return RuntimeMetadata for testing
+ */
+ 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()]));
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/unittest/FakeTranslationFactory.java
===================================================================
--- trunk/metadata/src/test/java/org/teiid/cdk/unittest/FakeTranslationFactory.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/unittest/FakeTranslationFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.cdk.unittest;
-
-import org.teiid.cdk.api.TranslationUtility;
-import org.teiid.query.unittest.FakeMetadataFactory;
-
-
-public class FakeTranslationFactory {
-
- private static FakeTranslationFactory instance = new FakeTranslationFactory();
-
- public static FakeTranslationFactory getInstance() {
- return instance;
- }
-
- public TranslationUtility getBQTTranslationUtility() {
- return new TranslationUtility(FakeMetadataFactory.exampleBQTCached());
- }
-
- public TranslationUtility getYahooTranslationUtility() {
- return new TranslationUtility(FakeMetadataFactory.exampleYahoo());
- }
-
- public TranslationUtility getExampleTranslationUtility() {
- return new TranslationUtility(FakeMetadataFactory.example1Cached());
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/unittest/FakeTranslationFactory.java (from rev 3218, trunk/metadata/src/test/java/org/teiid/cdk/unittest/FakeTranslationFactory.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/unittest/FakeTranslationFactory.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/cdk/unittest/FakeTranslationFactory.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,94 @@
+/*
+ * 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.cdk.unittest;
+
+import java.util.List;
+
+import org.teiid.cdk.api.TranslationUtility;
+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();
+
+ public static FakeTranslationFactory getInstance() {
+ return instance;
+ }
+
+ public TranslationUtility getBQTTranslationUtility() {
+ return new TranslationUtility(RealMetadataFactory.exampleBQTCached());
+ }
+
+ public TranslationUtility getYahooTranslationUtility() {
+ 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(RealMetadataFactory.example1Cached());
+ }
+
+}
Copied: tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/metadata/index/TestStagingTable.java (from rev 3218, trunk/metadata/src/test/java/org/teiid/metadata/index/TestStagingTable.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/metadata/index/TestStagingTable.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/java/org/teiid/metadata/index/TestStagingTable.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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() + "/test.vdb");
+
+ assertEquals(1, tm.getXMLTempGroups(tm.getGroupID("doc.newxmldocument")).size());
+ }
+
+}
Copied: tags/teiid-parent-7.5.0.Alpha1/metadata/src/test/resources/test.vdb (from rev 3218, trunk/metadata/src/test/resources/test.vdb)
===================================================================
(Binary files differ)
Deleted: tags/teiid-parent-7.5.0.Alpha1/pom.xml
===================================================================
--- trunk/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,496 +0,0 @@
-<?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">
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-parent</artifactId>
- <packaging>pom</packaging>
- <name>Teiid</name>
- <version>7.5.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>
- </properties>
- <scm>
- <connection>scm:svn:https://anonsvn.jboss.org/repos/teiid/trunk</connection>
- <developerConnection>scm:svn:https://svn.jboss.org/repos/teiid/trunk</developerConnection>
- </scm>
- <licenses>
- <license>
- <name>GNU Lesser General Public License</name>
- <url>http://www.gnu.org/licenses/lgpl.html</url>
- <distribution>repo</distribution>
- <comments>A business-friendly OSS license</comments>
- </license>
- </licenses>
- <url>${site.url}</url>
- <developers>
- <developer>
- <name>Steve Hawkins</name>
- <id>steve</id>
- <email>shawkins at redhat.com</email>
- <organization>Red Hat</organization>
- <roles>
- <role>Project Lead</role>
- </roles>
- <timezone>-6</timezone>
- </developer>
- <developer>
- <name>Ramesh Reddy</name>
- <id>ramesh</id>
- <email>rareddy at redhat.com</email>
- <organization>Red Hat</organization>
- <roles>
- <role>Project Lead</role>
- </roles>
- <timezone>-6</timezone>
- </developer>
- <developer>
- <name>Van Halbert</name>
- <id>van</id>
- <email>vhalbert at redhat.com</email>
- <organization>Red Hat</organization>
- <roles>
- <role>Developer</role>
- </roles>
- <timezone>-6</timezone>
- </developer>
- <developer>
- <name>Ted Jones</name>
- <id>ted</id>
- <email>tejones at redhat.com</email>
- <organization>Red Hat</organization>
- <roles>
- <role>Developer</role>
- </roles>
- <timezone>-6</timezone>
- </developer>
- </developers>
- <profiles>
- <profile>
- <!--
- This profile is activated manually, as in "mvn ... -P release ..."
- -->
- <id>release</id>
- <modules>
- <module>documentation</module>
- <module>build</module>
- </modules>
- </profile>
- <profile>
- <!--
- This is to enable faster build for development time.
- -->
- <id>dev</id>
- <modules>
- <module>build</module>
- </modules>
- </profile>
- </profiles>
- <build>
- <!-- This section defines the default plugin settings inherited by child projects. -->
- <pluginManagement>
- <plugins>
- <!-- Fixes how test resources of a project can be used in projects dependent on it -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <version>2.2</version>
- </plugin>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <version>2.2-beta-6-m1-jboss</version>
- </plugin>
- </plugins>
- </pluginManagement>
- <plugins>
- <!-- Specify the compiler options and settings -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <source>1.6</source>
- <target>1.6</target>
- <showDeprecation>false</showDeprecation>
- <showWarnings>false</showWarnings>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <includes>
- <include>**/*TestCase.java</include>
- <include>**/*Test.java</include>
- <include>**/Test*.java</include>
- </includes>
- <excludes>
- <exclude>**/Abstract*TestCase.java</exclude>
- <!-- hack to prevent anonymous inner classes in Tests from being run as tests -->
- <include>**/Test*$*.java</include>
- </excludes>
- <systemProperties>
- <property>
- <name>user.dir</name>
- <value>${basedir}/target</value>
- </property>
- <property>
- <name>java.io.tmpdir</name>
- <value>${basedir}/target</value>
- </property>
- </systemProperties>
- </configuration>
- </plugin>
- <!--
- Build a test-jar for each project, so that src/test/* resources and classes can be used
- in other projects. Also customize how the jar files are assembled.
- -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>test-jar</goal>
- </goals>
- </execution>
- </executions>
- <configuration>
- <archive>
- <manifest>
- <addDefaultSpecificationEntries> true</addDefaultSpecificationEntries>
- <addDefaultImplementationEntries> true</addDefaultImplementationEntries>
- </manifest>
- <manifestEntries>
- <Implementation-URL>${pom.url}</Implementation-URL>
- </manifestEntries>
- </archive>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-source-plugin</artifactId>
- <executions>
- <execution>
- <id>attach-sources</id>
- <goals>
- <goal>jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <version>2.5</version>
- </plugin>
- </plugins>
- </build>
- <reporting>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-javadoc-plugin</artifactId>
- <configuration>
- <aggregate>true</aggregate>
- <maxmemory>512m</maxmemory>
- <excludePackageNames>*.internal</excludePackageNames>
- </configuration>
- </plugin>
- </plugins>
- </reporting>
- <repositories>
- <repository>
- <id>jboss-public-repository</id>
- <name>JBoss Public Maven Repository Group</name>
- <url>http://repository.jboss.org/nexus/content/groups/public/</url>
- </repository>
- </repositories>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.4</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-all</artifactId>
- <version>1.5</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <dependencyManagement>
- <dependencies>
- <!--
- Declare all dependency versions and default scopes here, but not optional.
- Each module should declare it's direct dependency and possibily overwrite scope/optional.
- -->
-
- <!-- Internal dependencies -->
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <type>test-jar</type>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <type>test-jar</type>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-console</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-console</artifactId>
- <type>test-jar</type>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- <type>test-jar</type>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-engine</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-engine</artifactId>
- <type>test-jar</type>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-metadata</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-metadata</artifactId>
- <type>test-jar</type>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-txn-jbossts</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-cache-jbosscache</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-jboss-integration</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-runtime</artifactId>
- <version>${project.version}</version>
- </dependency>
-
- <!-- External dependencies -->
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <version>1.5</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.transaction</groupId>
- <artifactId>jta</artifactId>
- <version>1.1</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.14</version>
- </dependency>
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.1</version>
- <exclusions>
- <exclusion>
- <groupId>logkit</groupId>
- <artifactId>logkit</artifactId>
- </exclusion>
- <exclusion>
- <groupId>avalon-framework</groupId>
- <artifactId>avalon-framework</artifactId>
- </exclusion>
- <exclusion>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>jgroups</groupId>
- <artifactId>jgroups</artifactId>
- <version>2.6.15.GA</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.cache</groupId>
- <artifactId>jbosscache-core</artifactId>
- <version>3.2.5.GA</version>
- <exclusions>
- <exclusion>
- <groupId>javax.transaction</groupId>
- <artifactId>jta</artifactId>
- </exclusion>
- <exclusion>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.jboss</groupId>
- <artifactId>jboss-common-core</artifactId>
- </exclusion>
- </exclusions>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.man</groupId>
- <artifactId>jboss-managed</artifactId>
- <version>2.1.0.SP1</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.man</groupId>
- <artifactId>jboss-metatype</artifactId>
- <version>2.1.0.SP1</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.integration</groupId>
- <artifactId>jboss-profileservice-spi</artifactId>
- <version>5.1.0.GA</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jboss-vfs</artifactId>
- <version>2.1.2.GA</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.deployers</groupId>
- <artifactId>jboss-deployers-vfs-spi</artifactId>
- <version>2.0.7.GA</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.deployers</groupId>
- <artifactId>jboss-deployers-vfs</artifactId>
- <version>2.0.7.GA</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.jbossas</groupId>
- <artifactId>jboss-as-connector</artifactId>
- <version>5.1.0.GA</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jboss-reflect</artifactId>
- <version>2.0.2.GA</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.remoting</groupId>
- <artifactId>jboss-remoting</artifactId>
- <version>2.5.1</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>net.sourceforge.saxon</groupId>
- <artifactId>saxon</artifactId>
- <version>9.1.0.8</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>
- </dependency>
- <dependency>
- <groupId>org.apache.ant</groupId>
- <artifactId>ant</artifactId>
- <version>${ant.version}</version>
- </dependency>
- <dependency>
- <groupId>com.googlecode.json-simple</groupId>
- <artifactId>json-simple</artifactId>
- <version>1.1</version>
- </dependency>
- </dependencies>
- </dependencyManagement>
- <modules>
- <module>common-core</module>
- <module>api</module>
- <module>client</module>
- <module>engine</module>
- <module>connectors</module>
- <module>console</module>
- <module>metadata</module>
- <module>runtime</module>
- <module>adminshell</module>
- <module>cache-jbosscache</module>
- <module>hibernate-dialect</module>
- <module>jboss-integration</module>
- <module>test-integration</module>
- <module>client-jdk15</module>
- </modules>
- <distributionManagement>
- <repository>
- <id>jboss-releases-repository</id>
- <name>JBoss Releases Repository</name>
- <url>https://repository.jboss.org/nexus/service/local/staging/deploy/maven2/</url>
- </repository>
- <snapshotRepository>
- <id>jboss-snapshots-repository</id>
- <name>JBoss Snapshots Repository</name>
- <url>https://repository.jboss.org/nexus/content/repositories/snapshots/</url>
- </snapshotRepository>
- </distributionManagement>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/pom.xml (from rev 3220, trunk/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,496 @@
+<?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">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-parent</artifactId>
+ <packaging>pom</packaging>
+ <name>Teiid</name>
+ <version>7.5.0.Alpha1</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>
+ </properties>
+ <scm>
+ <connection>scm:svn:https://anonsvn.jboss.org/repos/teiid/tags/teiid-parent-7.5.0.Alpha1</connection>
+ <developerConnection>scm:svn:https://svn.jboss.org/repos/teiid/tags/teiid-parent-7.5.0.Alpha1</developerConnection>
+ </scm>
+ <licenses>
+ <license>
+ <name>GNU Lesser General Public License</name>
+ <url>http://www.gnu.org/licenses/lgpl.html</url>
+ <distribution>repo</distribution>
+ <comments>A business-friendly OSS license</comments>
+ </license>
+ </licenses>
+ <url>${site.url}</url>
+ <developers>
+ <developer>
+ <name>Steve Hawkins</name>
+ <id>steve</id>
+ <email>shawkins at redhat.com</email>
+ <organization>Red Hat</organization>
+ <roles>
+ <role>Project Lead</role>
+ </roles>
+ <timezone>-6</timezone>
+ </developer>
+ <developer>
+ <name>Ramesh Reddy</name>
+ <id>ramesh</id>
+ <email>rareddy at redhat.com</email>
+ <organization>Red Hat</organization>
+ <roles>
+ <role>Project Lead</role>
+ </roles>
+ <timezone>-6</timezone>
+ </developer>
+ <developer>
+ <name>Van Halbert</name>
+ <id>van</id>
+ <email>vhalbert at redhat.com</email>
+ <organization>Red Hat</organization>
+ <roles>
+ <role>Developer</role>
+ </roles>
+ <timezone>-6</timezone>
+ </developer>
+ <developer>
+ <name>Ted Jones</name>
+ <id>ted</id>
+ <email>tejones at redhat.com</email>
+ <organization>Red Hat</organization>
+ <roles>
+ <role>Developer</role>
+ </roles>
+ <timezone>-6</timezone>
+ </developer>
+ </developers>
+ <profiles>
+ <profile>
+ <!--
+ This profile is activated manually, as in "mvn ... -P release ..."
+ -->
+ <id>release</id>
+ <modules>
+ <module>documentation</module>
+ <module>build</module>
+ </modules>
+ </profile>
+ <profile>
+ <!--
+ This is to enable faster build for development time.
+ -->
+ <id>dev</id>
+ <modules>
+ <module>build</module>
+ </modules>
+ </profile>
+ </profiles>
+ <build>
+ <!-- This section defines the default plugin settings inherited by child projects. -->
+ <pluginManagement>
+ <plugins>
+ <!-- Fixes how test resources of a project can be used in projects dependent on it -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <version>2.2</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>2.2-beta-6-m1-jboss</version>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ <plugins>
+ <!-- Specify the compiler options and settings -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ <showDeprecation>false</showDeprecation>
+ <showWarnings>false</showWarnings>
+ </configuration>
+ </plugin>
+ <plugin>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <includes>
+ <include>**/*TestCase.java</include>
+ <include>**/*Test.java</include>
+ <include>**/Test*.java</include>
+ </includes>
+ <excludes>
+ <exclude>**/Abstract*TestCase.java</exclude>
+ <!-- hack to prevent anonymous inner classes in Tests from being run as tests -->
+ <include>**/Test*$*.java</include>
+ </excludes>
+ <systemProperties>
+ <property>
+ <name>user.dir</name>
+ <value>${basedir}/target</value>
+ </property>
+ <property>
+ <name>java.io.tmpdir</name>
+ <value>${basedir}/target</value>
+ </property>
+ </systemProperties>
+ </configuration>
+ </plugin>
+ <!--
+ Build a test-jar for each project, so that src/test/* resources and classes can be used
+ in other projects. Also customize how the jar files are assembled.
+ -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>test-jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ <configuration>
+ <archive>
+ <manifest>
+ <addDefaultSpecificationEntries> true</addDefaultSpecificationEntries>
+ <addDefaultImplementationEntries> true</addDefaultImplementationEntries>
+ </manifest>
+ <manifestEntries>
+ <Implementation-URL>${pom.url}</Implementation-URL>
+ </manifestEntries>
+ </archive>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-source-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-sources</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <version>2.5</version>
+ </plugin>
+ </plugins>
+ </build>
+ <reporting>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <configuration>
+ <aggregate>true</aggregate>
+ <maxmemory>512m</maxmemory>
+ <excludePackageNames>*.internal</excludePackageNames>
+ </configuration>
+ </plugin>
+ </plugins>
+ </reporting>
+ <repositories>
+ <repository>
+ <id>jboss-public-repository</id>
+ <name>JBoss Public Maven Repository Group</name>
+ <url>http://repository.jboss.org/nexus/content/groups/public/</url>
+ </repository>
+ </repositories>
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.4</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <version>1.5</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+ <dependencyManagement>
+ <dependencies>
+ <!--
+ Declare all dependency versions and default scopes here, but not optional.
+ Each module should declare it's direct dependency and possibily overwrite scope/optional.
+ -->
+
+ <!-- Internal dependencies -->
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <type>test-jar</type>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <type>test-jar</type>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-console</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-console</artifactId>
+ <type>test-jar</type>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ <type>test-jar</type>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-engine</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-engine</artifactId>
+ <type>test-jar</type>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-metadata</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-metadata</artifactId>
+ <type>test-jar</type>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-txn-jbossts</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-cache-jbosscache</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-jboss-integration</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-runtime</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <!-- External dependencies -->
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <version>1.5</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.transaction</groupId>
+ <artifactId>jta</artifactId>
+ <version>1.1</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <version>1.2.14</version>
+ </dependency>
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ <version>1.1</version>
+ <exclusions>
+ <exclusion>
+ <groupId>logkit</groupId>
+ <artifactId>logkit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>avalon-framework</groupId>
+ <artifactId>avalon-framework</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>jgroups</groupId>
+ <artifactId>jgroups</artifactId>
+ <version>2.6.15.GA</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.cache</groupId>
+ <artifactId>jbosscache-core</artifactId>
+ <version>3.2.5.GA</version>
+ <exclusions>
+ <exclusion>
+ <groupId>javax.transaction</groupId>
+ <artifactId>jta</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.jboss</groupId>
+ <artifactId>jboss-common-core</artifactId>
+ </exclusion>
+ </exclusions>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.man</groupId>
+ <artifactId>jboss-managed</artifactId>
+ <version>2.1.0.SP1</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.man</groupId>
+ <artifactId>jboss-metatype</artifactId>
+ <version>2.1.0.SP1</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.integration</groupId>
+ <artifactId>jboss-profileservice-spi</artifactId>
+ <version>5.1.0.GA</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jboss-vfs</artifactId>
+ <version>2.1.2.GA</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.deployers</groupId>
+ <artifactId>jboss-deployers-vfs-spi</artifactId>
+ <version>2.0.7.GA</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.deployers</groupId>
+ <artifactId>jboss-deployers-vfs</artifactId>
+ <version>2.0.7.GA</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.jbossas</groupId>
+ <artifactId>jboss-as-connector</artifactId>
+ <version>5.1.0.GA</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jboss-reflect</artifactId>
+ <version>2.0.2.GA</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.remoting</groupId>
+ <artifactId>jboss-remoting</artifactId>
+ <version>2.5.1</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>net.sourceforge.saxon</groupId>
+ <artifactId>saxon</artifactId>
+ <version>9.1.0.8</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>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.ant</groupId>
+ <artifactId>ant</artifactId>
+ <version>${ant.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.googlecode.json-simple</groupId>
+ <artifactId>json-simple</artifactId>
+ <version>1.1</version>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+ <modules>
+ <module>common-core</module>
+ <module>api</module>
+ <module>client</module>
+ <module>engine</module>
+ <module>connectors</module>
+ <module>console</module>
+ <module>metadata</module>
+ <module>runtime</module>
+ <module>adminshell</module>
+ <module>cache-jbosscache</module>
+ <module>hibernate-dialect</module>
+ <module>jboss-integration</module>
+ <module>test-integration</module>
+ <module>client-jdk15</module>
+ </modules>
+ <distributionManagement>
+ <repository>
+ <id>jboss-releases-repository</id>
+ <name>JBoss Releases Repository</name>
+ <url>https://repository.jboss.org/nexus/service/local/staging/deploy/maven2/</url>
+ </repository>
+ <snapshotRepository>
+ <id>jboss-snapshots-repository</id>
+ <name>JBoss Snapshots Repository</name>
+ <url>https://repository.jboss.org/nexus/content/repositories/snapshots/</url>
+ </snapshotRepository>
+ </distributionManagement>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/runtime/pom.xml
===================================================================
--- trunk/runtime/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,94 +0,0 @@
-<?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>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-runtime</artifactId>
- <name>Runtime Engine</name>
- <description>Teiid Runtime Engine</description>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <type>test-jar</type>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-engine</artifactId>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-engine</artifactId>
- <type>test-jar</type>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-metadata</artifactId>
- </dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.netty</groupId>
- <artifactId>netty</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.cache</groupId>
- <artifactId>jbosscache-core</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss</groupId>
- <artifactId>jboss-vfs</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.deployers</groupId>
- <artifactId>jboss-deployers-vfs-spi</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.deployers</groupId>
- <artifactId>jboss-deployers-vfs</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.integration</groupId>
- <artifactId>jboss-profileservice-spi</artifactId>
- <scope>provided</scope>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/runtime/pom.xml (from rev 3220, trunk/runtime/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/runtime/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,94 @@
+<?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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-runtime</artifactId>
+ <name>Runtime Engine</name>
+ <description>Teiid Runtime Engine</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-engine</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-engine</artifactId>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-metadata</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.netty</groupId>
+ <artifactId>netty</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.cache</groupId>
+ <artifactId>jbosscache-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jboss-vfs</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.deployers</groupId>
+ <artifactId>jboss-deployers-vfs-spi</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.deployers</groupId>
+ <artifactId>jboss-deployers-vfs</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.integration</groupId>
+ <artifactId>jboss-profileservice-spi</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCClientRemote.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/odbc/ODBCClientRemote.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCClientRemote.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,113 +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.odbc;
-
-import java.sql.ParameterMetaData;
-import java.sql.ResultSetMetaData;
-import java.sql.Statement;
-import java.util.Properties;
-
-import org.teiid.client.util.ResultsFuture;
-import org.teiid.jdbc.ResultSetImpl;
-
-public interface ODBCClientRemote {
-
- void initialized(Properties props);
-
- void setEncoding(String value);
-
- // AuthenticationCleartextPassword (B)
- void useClearTextAuthentication();
-
- // AuthenticationOk (B)
- // BackendKeyData (B)
- // ParameterStatus (B)
- void authenticationSucess(int processId, int screctKey);
-
- // ParseComplete (B)
- void prepareCompleted(String preparedName);
-
- // ErrorResponse (B)
- void errorOccurred(String msg);
-
- // ErrorResponse (B)
- void errorOccurred(Throwable e);
-
- void terminated();
-
- // ParameterDescription (B)
- void sendParameterDescription(ParameterMetaData parameterMetaData, int[] paramType);
-
- // BindComplete (B)
- void bindComplete();
-
- // RowDescription (B)
- // NoData (B)
- void sendResultSetDescription(ResultSetMetaData metaData, Statement stmt);
-
- // DataRow (B)
- // CommandComplete (B)
- void sendResults(String sql, ResultSetImpl rs, ResultsFuture<Void> result, boolean describeRows);
-
- // CommandComplete (B)
- void sendUpdateCount(String sql, int updateCount);
-
- // ReadyForQuery (B)
- void ready(boolean inTransaction, boolean failedTransaction);
-
- void statementClosed();
-
- // EmptyQueryResponse (B)
- void emptyQueryReceived();
-
- void flush();
-
- // FunctionCallResponse (B)
- void functionCallResponse(byte[] data);
- void functionCallResponse(int data);
-
- void sslDenied();
-
- // unimplemented backend messages
-
- // AuthenticationKerberosV5 (B)
- // AuthenticationMD5Password (B)
- // AuthenticationSCMCredential (B)
- // AuthenticationGSS (B)
- // AuthenticationSSPI (B)
- // AuthenticationGSSContinue (B)
-
- // CloseComplete (B)
-
- // CopyData (F & B)
- // CopyDone (F & B)
- // CopyInResponse (B)
- // CopyOutResponse (B)
-
- // NoticeResponse (B)
- // NotificationResponse (B)
-
- // PortalSuspended (B)
-
-
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCClientRemote.java (from rev 3218, trunk/runtime/src/main/java/org/teiid/odbc/ODBCClientRemote.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCClientRemote.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCClientRemote.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,113 @@
+/*
+ * 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.ParameterMetaData;
+import java.sql.ResultSetMetaData;
+import java.sql.Statement;
+import java.util.Properties;
+
+import org.teiid.client.util.ResultsFuture;
+import org.teiid.jdbc.ResultSetImpl;
+
+public interface ODBCClientRemote {
+
+ void initialized(Properties props);
+
+ void setEncoding(String value);
+
+ // AuthenticationCleartextPassword (B)
+ void useClearTextAuthentication();
+
+ // AuthenticationOk (B)
+ // BackendKeyData (B)
+ // ParameterStatus (B)
+ void authenticationSucess(int processId, int screctKey);
+
+ // ParseComplete (B)
+ void prepareCompleted(String preparedName);
+
+ // ErrorResponse (B)
+ void errorOccurred(String msg);
+
+ // ErrorResponse (B)
+ void errorOccurred(Throwable e);
+
+ void terminated();
+
+ // ParameterDescription (B)
+ void sendParameterDescription(ParameterMetaData parameterMetaData, int[] paramType);
+
+ // BindComplete (B)
+ void bindComplete();
+
+ // RowDescription (B)
+ // NoData (B)
+ void sendResultSetDescription(ResultSetMetaData metaData, Statement stmt);
+
+ // DataRow (B)
+ // CommandComplete (B)
+ void sendResults(String sql, ResultSetImpl rs, ResultsFuture<Void> result, boolean describeRows);
+
+ // CommandComplete (B)
+ void sendUpdateCount(String sql, int updateCount);
+
+ // ReadyForQuery (B)
+ void ready(boolean inTransaction, boolean failedTransaction);
+
+ void statementClosed();
+
+ // EmptyQueryResponse (B)
+ void emptyQueryReceived();
+
+ void flush();
+
+ // FunctionCallResponse (B)
+ void functionCallResponse(byte[] data);
+ void functionCallResponse(int data);
+
+ void sendSslResponse();
+
+ // unimplemented backend messages
+
+ // AuthenticationKerberosV5 (B)
+ // AuthenticationMD5Password (B)
+ // AuthenticationSCMCredential (B)
+ // AuthenticationGSS (B)
+ // AuthenticationSSPI (B)
+ // AuthenticationGSSContinue (B)
+
+ // CloseComplete (B)
+
+ // CopyData (F & B)
+ // CopyDone (F & B)
+ // CopyInResponse (B)
+ // CopyOutResponse (B)
+
+ // NoticeResponse (B)
+ // NotificationResponse (B)
+
+ // PortalSuspended (B)
+
+
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCServerRemoteImpl.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/odbc/ODBCServerRemoteImpl.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCServerRemoteImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,814 +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.odbc;
-
-import java.io.IOException;
-import java.io.StringReader;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-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.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.StatementImpl;
-import org.teiid.jdbc.TeiidDriver;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.runtime.RuntimePlugin;
-import org.teiid.transport.ODBCClientInstance;
-
-/**
- * While executing the multiple prepared statements I see this bug currently
- * http://pgfoundry.org/tracker/?func=detail&atid=538&aid=1007690&group_id=1000125
- */
-public class ODBCServerRemoteImpl implements ODBCServerRemote {
-
- private static final String UNNAMED = "UNNAMED"; //$NON-NLS-1$
- private static Pattern setPattern = Pattern.compile("(SET|set)\\s+(\\w+)\\s+(TO|to)\\s+'(\\w+\\d*)'");//$NON-NLS-1$
-
- private static Pattern pkPattern = Pattern.compile("select ta.attname, ia.attnum, ic.relname, n.nspname, tc.relname " +//$NON-NLS-1$
- "from pg_catalog.pg_attribute ta, pg_catalog.pg_attribute ia, pg_catalog.pg_class tc, pg_catalog.pg_index i, " +//$NON-NLS-1$
- "pg_catalog.pg_namespace n, pg_catalog.pg_class ic where tc.relname = (E?(?:'[^']*')+) AND n.nspname = (E?(?:'[^']*')+).*" );//$NON-NLS-1$
-
- private static Pattern pkKeyPattern = Pattern.compile("select ta.attname, ia.attnum, ic.relname, n.nspname, NULL from " + //$NON-NLS-1$
- "pg_catalog.pg_attribute ta, pg_catalog.pg_attribute ia, pg_catalog.pg_class ic, pg_catalog.pg_index i, " + //$NON-NLS-1$
- "pg_catalog.pg_namespace n where ic.relname = (E?(?:'[^']*')+) AND n.nspname = (E?(?:'[^']*')+) .*"); //$NON-NLS-1$
-
- private Pattern fkPattern = Pattern.compile("select\\s+((?:'[^']*')+)::name as PKTABLE_CAT," + //$NON-NLS-1$
- "\\s+n2.nspname as PKTABLE_SCHEM," + //$NON-NLS-1$
- "\\s+c2.relname as PKTABLE_NAME," + //$NON-NLS-1$
- "\\s+a2.attname as PKCOLUMN_NAME," + //$NON-NLS-1$
- "\\s+((?:'[^']*')+)::name as FKTABLE_CAT," + //$NON-NLS-1$
- "\\s+n1.nspname as FKTABLE_SCHEM," + //$NON-NLS-1$
- "\\s+c1.relname as FKTABLE_NAME," + //$NON-NLS-1$
- "\\s+a1.attname as FKCOLUMN_NAME," + //$NON-NLS-1$
- "\\s+i::int2 as KEY_SEQ," + //$NON-NLS-1$
- "\\s+case ref.confupdtype" + //$NON-NLS-1$
- "\\s+when 'c' then (\\d)::int2" + //$NON-NLS-1$
- "\\s+when 'n' then (\\d)::int2" + //$NON-NLS-1$
- "\\s+when 'd' then (\\d)::int2" + //$NON-NLS-1$
- "\\s+when 'r' then (\\d)::int2" + //$NON-NLS-1$
- "\\s+else 3::int2" + //$NON-NLS-1$
- "\\s+end as UPDATE_RULE," + //$NON-NLS-1$
- "\\s+case ref.confdeltype" + //$NON-NLS-1$
- "\\s+when 'c' then (\\d)::int2" + //$NON-NLS-1$
- "\\s+when 'n' then (\\d)::int2" + //$NON-NLS-1$
- "\\s+when 'd' then (\\d)::int2" + //$NON-NLS-1$
- "\\s+when 'r' then (\\d)::int2" + //$NON-NLS-1$
- "\\s+else 3::int2" + //$NON-NLS-1$
- "\\s+end as DELETE_RULE," + //$NON-NLS-1$
- "\\s+ref.conname as FK_NAME," + //$NON-NLS-1$
- "\\s+cn.conname as PK_NAME," + //$NON-NLS-1$
- "\\s+case" + //$NON-NLS-1$
- "\\s+when ref.condeferrable then" + //$NON-NLS-1$
- "\\s+case" + //$NON-NLS-1$
- "\\s+when ref.condeferred then (\\d)::int2" + //$NON-NLS-1$
- "\\s+else (\\d)::int2" + //$NON-NLS-1$
- "\\s+end" + //$NON-NLS-1$
- "\\s+else (\\d)::int2" + //$NON-NLS-1$
- "\\s+end as DEFERRABLITY" + //$NON-NLS-1$
- "\\s+from" + //$NON-NLS-1$
- "\\s+\\(\\(\\(\\(\\(\\(\\( \\(select cn.oid, conrelid, conkey, confrelid, confkey," + //$NON-NLS-1$
- "\\s+generate_series\\(array_lower\\(conkey, 1\\), array_upper\\(conkey, 1\\)\\) as i," + //$NON-NLS-1$
- "\\s+confupdtype, confdeltype, conname," + //$NON-NLS-1$
- "\\s+condeferrable, condeferred" + //$NON-NLS-1$
- "\\s+from pg_catalog.pg_constraint cn," + //$NON-NLS-1$
- "\\s+pg_catalog.pg_class c," + //$NON-NLS-1$
- "\\s+pg_catalog.pg_namespace n" + //$NON-NLS-1$
- "\\s+where contype = 'f' " + //$NON-NLS-1$
- "\\s+and conrelid = c.oid" + //$NON-NLS-1$
- "\\s+and relname = (E?(?:'[^']*')+)" + //$NON-NLS-1$
- "\\s+and n.oid = c.relnamespace" + //$NON-NLS-1$
- "\\s+and n.nspname = (E?(?:'[^']*')+)" + //$NON-NLS-1$
- "\\s+\\) ref" + //$NON-NLS-1$
- "\\s+inner join pg_catalog.pg_class c1" + //$NON-NLS-1$
- "\\s+on c1.oid = ref.conrelid\\)" + //$NON-NLS-1$
- "\\s+inner join pg_catalog.pg_namespace n1" + //$NON-NLS-1$
- "\\s+on n1.oid = c1.relnamespace\\)" + //$NON-NLS-1$
- "\\s+inner join pg_catalog.pg_attribute a1" + //$NON-NLS-1$
- "\\s+on a1.attrelid = c1.oid" + //$NON-NLS-1$
- "\\s+and a1.attnum = conkey\\[i\\]\\)" + //$NON-NLS-1$
- "\\s+inner join pg_catalog.pg_class c2" + //$NON-NLS-1$
- "\\s+on c2.oid = ref.confrelid\\)" + //$NON-NLS-1$
- "\\s+inner join pg_catalog.pg_namespace n2" + //$NON-NLS-1$
- "\\s+on n2.oid = c2.relnamespace\\)" + //$NON-NLS-1$
- "\\s+inner join pg_catalog.pg_attribute a2" + //$NON-NLS-1$
- "\\s+on a2.attrelid = c2.oid" + //$NON-NLS-1$
- "\\s+and a2.attnum = confkey\\[i\\]\\)" + //$NON-NLS-1$
- "\\s+left outer join pg_catalog.pg_constraint cn" + //$NON-NLS-1$
- "\\s+on cn.conrelid = ref.confrelid" + //$NON-NLS-1$
- "\\s+and cn.contype = 'p'\\)" + //$NON-NLS-1$
- "\\s+order by ref.oid, ref.i"); //$NON-NLS-1$
-
- 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 TeiidDriver driver;
- private ODBCClientRemote client;
- private Properties props;
- private AuthenticationType authType;
- private ConnectionImpl connection;
- private boolean executing;
- private boolean errorOccurred;
-
- private volatile ResultsFuture<Boolean> executionFuture;
-
- // 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>());
-
- public ODBCServerRemoteImpl(ODBCClientInstance client, AuthenticationType authType, TeiidDriver driver) {
- this.driver = driver;
- this.client = client.getClient();
- this.authType = authType;
- }
-
- @Override
- public void initialize(Properties props) {
- this.props = props;
-
- this.client.initialized(this.props);
-
- if (this.authType.equals(AuthenticationType.CLEARTEXT)) {
- this.client.useClearTextAuthentication();
- }
- else if (this.authType.equals(AuthenticationType.MD5)) {
- // TODO: implement MD5 auth type
- }
- }
-
- @Override
- public void logon(String databaseName, String user, String password) {
- try {
- java.util.Properties info = new java.util.Properties();
- String url = "jdbc:teiid:"+databaseName+";ApplicationName=ODBC"; //$NON-NLS-1$ //$NON-NLS-2$
- info.put("user", user); //$NON-NLS-1$
- 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();
- while (keys.hasMoreElements()) {
- String key = (String)keys.nextElement();
- Statement stmt = this.connection.createStatement();
- stmt.execute("SET " + key + " '" + this.props.getProperty(key) + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- stmt.close();
- }
- this.client.authenticationSucess(hash, hash);
- ready();
- } catch (SQLException e) {
- errorOccurred(e);
- terminate();
- }
- }
-
- @Override
- public void prepare(String prepareName, String sql, int[] paramType) {
- if (this.connection != null) {
-
- if (prepareName == null || prepareName.length() == 0) {
- prepareName = UNNAMED;
- }
-
- if (sql != null) {
- String modfiedSQL = fixSQL(sql);
- try {
- // close if the name is already used or the unnamed prepare; otherwise
- // stmt is alive until session ends.
- Prepared previous = this.preparedMap.remove(prepareName);
- if (previous != null) {
- previous.stmt.close();
- }
-
- PreparedStatementImpl stmt = this.connection.prepareStatement(modfiedSQL);
- this.preparedMap.put(prepareName, new Prepared(prepareName, sql, stmt, paramType));
- this.client.prepareCompleted(prepareName);
- } catch (SQLException e) {
- errorOccurred(e);
- }
- }
- }
- else {
- errorOccurred(RuntimePlugin.Util.getString("no_active_connection")); //$NON-NLS-1$
- }
- }
-
- @Override
- public void bindParameters(String bindName, String prepareName, int paramCount, Object[] params, int resultCodeCount, int[] resultColumnFormat) {
- // An unnamed portal is destroyed at the end of the transaction, or as soon as
- // the next Bind statement specifying the unnamed portal as destination is issued.
- this.portalMap.remove(UNNAMED);
-
- if (prepareName == null || prepareName.length() == 0) {
- prepareName = UNNAMED;
- }
-
- Prepared previous = this.preparedMap.get(prepareName);
- if (previous == null) {
- errorOccurred(RuntimePlugin.Util.getString("bad_binding", prepareName)); //$NON-NLS-1$
- return;
- }
-
- if (bindName == null || bindName.length() == 0) {
- bindName = UNNAMED;
- }
-
- try {
- for (int i = 0; i < paramCount; i++) {
- previous.stmt.setObject(i+1, params[i]);
- }
- } catch (SQLException e) {
- errorOccurred(e);
- }
-
- this.portalMap.put(bindName, new Portal(bindName, prepareName, previous.sql, previous.stmt, resultColumnFormat));
- this.client.bindComplete();
- }
-
- @Override
- public void unsupportedOperation(String msg) {
- errorOccurred(msg);
- }
-
- @Override
- public void execute(String bindName, int maxRows) {
- if (beginExecution()) {
- errorOccurred("Awaiting asynch result"); //$NON-NLS-1$
- return;
- }
- if (bindName == null || bindName.length() == 0) {
- bindName = UNNAMED;
- }
-
- 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);
- }
- }
- }
-
- private String fixSQL(String sql) {
- String modified = modifySQL(sql);
- if (modified != null && !modified.equals(sql)) {
- LogManager.logDetail(LogConstants.CTX_ODBC, "Modified Query:", modified); //$NON-NLS-1$
- }
- return modified;
- }
-
- private String modifySQL(String sql) {
- String modified = sql;
- // select current_schema()
- // set client_encoding to 'WIN1252'
- if (sql == null) {
- return null;
- }
- // selects are coming with "select\t" so using a space after "select" does not always work
- if (StringUtil.startsWithIgnoreCase(sql, "select")) { //$NON-NLS-1$
- modified = sql.replace('\n', ' ');
-
- Matcher m = null;
- if ((m = pkPattern.matcher(modified)).matches()) {
- return new StringBuffer("SELECT k.Name AS attname, convert(Position, short) AS attnum, TableName AS relname, SchemaName AS nspname, TableName AS relname") //$NON-NLS-1$
- .append(" FROM SYS.KeyColumns k") //$NON-NLS-1$
- .append(" WHERE ") //$NON-NLS-1$
- .append(" UCASE(SchemaName)").append(" LIKE UCASE(").append(m.group(2)).append(")")//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- .append(" AND UCASE(TableName)") .append(" LIKE UCASE(").append(m.group(1)).append(")")//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- .append(" AND KeyType LIKE 'Primary'") //$NON-NLS-1$
- .append(" ORDER BY attnum").toString(); //$NON-NLS-1$
- }
- else if ((m = pkKeyPattern.matcher(modified)).matches()) {
- String tableName = m.group(1);
- if (tableName.endsWith("_pkey'")) { //$NON-NLS-1$
- tableName = tableName.substring(0, tableName.length()-6) + '\'';
- return "select ia.attname, ia.attnum, ic.relname, n.nspname, NULL "+ //$NON-NLS-1$
- "from pg_catalog.pg_attribute ia, pg_catalog.pg_class ic, pg_catalog.pg_namespace n, Sys.KeyColumns kc "+ //$NON-NLS-1$
- "where ic.relname = "+tableName+" AND n.nspname = "+m.group(2)+" AND "+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- "n.oid = ic.relnamespace AND ia.attrelid = ic.oid AND kc.SchemaName = n.nspname " +//$NON-NLS-1$
- "AND kc.TableName = ic.relname AND kc.KeyType = 'Primary' AND kc.Name = ia.attname order by ia.attnum";//$NON-NLS-1$
- }
- return "SELECT NULL, NULL, NULL, NULL, NULL FROM (SELECT 1) as X WHERE 0=1"; //$NON-NLS-1$
- }
- else if ((m = fkPattern.matcher(modified)).matches()){
- return "SELECT PKTABLE_CAT, PKTABLE_SCHEM, PKTABLE_NAME, PKCOLUMN_NAME, FKTABLE_CAT, FKTABLE_SCHEM, "+//$NON-NLS-1$
- "FKTABLE_NAME, FKCOLUMN_NAME, KEY_SEQ, UPDATE_RULE, DELETE_RULE, FK_NAME, PK_NAME, DEFERRABILITY "+//$NON-NLS-1$
- "FROM SYS.ReferenceKeyColumns WHERE PKTABLE_NAME LIKE "+m.group(14)+" and PKTABLE_SCHEM LIKE "+m.group(15);//$NON-NLS-1$ //$NON-NLS-2$
- }
- else if (modified.equalsIgnoreCase("select version()")) { //$NON-NLS-1$
- return "SELECT 'Teiid "+ApplicationInfo.getInstance().getReleaseNumber()+"'"; //$NON-NLS-1$ //$NON-NLS-2$
- }
- else if (modified.startsWith("SELECT name FROM master..sysdatabases")) { //$NON-NLS-1$
- return "SELECT 'Teiid'"; //$NON-NLS-1$
- }
- else if (modified.equalsIgnoreCase("select db_name() dbname")) { //$NON-NLS-1$
- return "SELECT current_database()"; //$NON-NLS-1$
- }
- else if (preparedAutoIncrement.matcher(modified).matches()) {
- return "SELECT 1 from matpg_relatt where attrelid = ? and attnum = ? and autoinc = true"; //$NON-NLS-1$
- }
- else {
- // since teiid can work with multiple schemas at a given time
- // this call resolution is ambiguous
- if (sql.equalsIgnoreCase("select current_schema()")) { //$NON-NLS-1$
- return "SELECT ''"; //$NON-NLS-1$
- }
- }
-
- }
- else if (sql.equalsIgnoreCase("show max_identifier_length")){ //$NON-NLS-1$
- return "select 63"; //$NON-NLS-1$
- }
- else {
- Matcher m = setPattern.matcher(sql);
- if (m.matches()) {
- return "SET " + m.group(2) + " " + m.group(4); //$NON-NLS-1$ //$NON-NLS-2$
- }
- else if (modified.equalsIgnoreCase("BEGIN")) { //$NON-NLS-1$
- return "START TRANSACTION"; //$NON-NLS-1$
- }
- 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;
- //these are somewhat dangerous
- modified = modified.replaceAll("::[A-Za-z0-9]*", " "); //$NON-NLS-1$ //$NON-NLS-2$
- modified = modified.replaceAll("'pg_toast'", "'SYS'"); //$NON-NLS-1$ //$NON-NLS-2$
- return modified;
- }
-
- @Override
- public void executeQuery(final String query) {
- if (beginExecution()) {
- this.client.errorOccurred("Awaiting asynch result"); //$NON-NLS-1$
- ready();
- return;
- }
- //46.2.3 Note that a simple Query message also destroys the unnamed portal.
- this.portalMap.remove(UNNAMED);
- this.preparedMap.remove(UNNAMED);
-
- if (query.trim().length() == 0) {
- this.client.emptyQueryReceived();
- ready();
- return;
- }
- QueryWorkItem r = new QueryWorkItem(query);
- r.run();
- }
-
- private boolean beginExecution() {
- if (this.executionFuture != null) {
- return true;
- }
- synchronized (this) {
- this.executing = true;
- }
- return false;
- }
-
- public boolean isExecuting() {
- return executing;
- }
-
- public boolean isErrorOccurred() {
- return errorOccurred;
- }
-
- @Override
- public void getParameterDescription(String prepareName) {
- if (prepareName == null || prepareName.length() == 0) {
- prepareName = UNNAMED;
- }
- Prepared query = this.preparedMap.get(prepareName);
- if (query == null) {
- errorOccurred(RuntimePlugin.Util.getString("no_stmt_found", prepareName)); //$NON-NLS-1$
- }
- else {
- try {
- this.client.sendParameterDescription(query.stmt.getParameterMetaData(), query.paramType);
- } catch (SQLException e) {
- errorOccurred(e);
- }
- }
- }
-
- private void errorOccurred(String error) {
- this.client.errorOccurred(error);
- synchronized (this) {
- this.errorOccurred = true;
- doneExecuting();
- }
- }
-
- private void errorOccurred(Throwable error) {
- this.client.errorOccurred(error);
- synchronized (this) {
- this.errorOccurred = true;
- doneExecuting();
- }
- }
-
- @Override
- public void getResultSetMetaDataDescription(String bindName) {
- if (bindName == null || bindName.length() == 0) {
- bindName = UNNAMED;
- }
- Portal query = this.portalMap.get(bindName);
- if (query == null) {
- errorOccurred(RuntimePlugin.Util.getString("not_bound", bindName)); //$NON-NLS-1$
- }
- else {
- try {
- this.client.sendResultSetDescription(query.stmt.getMetaData(), query.stmt);
- } catch (SQLException e) {
- errorOccurred(e);
- }
- }
- }
-
- @Override
- public void sync() {
- ready();
- }
-
- protected synchronized void doneExecuting() {
- executing = false;
- }
-
- private void ready() {
- boolean inTxn = false;
- boolean failedTxn = false;
- try {
- if (!this.connection.getAutoCommit()) {
- inTxn = true;
- }
- } catch (SQLException e) {
- failedTxn = true;
- }
- synchronized (this) {
- this.errorOccurred = false;
- }
- this.client.ready(inTxn, failedTxn);
- }
-
- @Override
- public void cancel() {
- // TODO Auto-generated method stub
- }
-
- @Override
- public void closeBoundStatement(String bindName) {
- if (bindName == null || bindName.length() == 0) {
- bindName = UNNAMED;
- }
- Portal query = this.portalMap.remove(bindName);
- if (query == null) {
- errorOccurred(RuntimePlugin.Util.getString("not_bound", bindName)); //$NON-NLS-1$
- }
- else {
- try {
- if (this.connection.getAutoCommit()) {
- // After checking the pg's client code I do not see it send a
- // close of the Prepare stmt as per the wire protocol, it only sends
- // bound close. Since it also have issue with
- // http://pgfoundry.org/tracker/?func=detail&atid=538&aid=1007690&group_id=1000125
- // treating the prepare and bound as same for now.
- closePreparedStatement(bindName);
- }
- } catch (SQLException e) {
- closePreparedStatement(bindName);
- }
- }
- }
-
- @Override
- public void closePreparedStatement(String preparedName) {
- if (preparedName == null || preparedName.length() == 0) {
- preparedName = UNNAMED;
- }
- Prepared query = this.preparedMap.remove(preparedName);
- if (query == null) {
- errorOccurred(RuntimePlugin.Util.getString("no_stmt_found", preparedName)); //$NON-NLS-1$
- }
- else {
- // Close all the bound messages off of this prepared
- // TODO: can there be more than one?
- this.portalMap.remove(preparedName);
-
- try {
- query.stmt.close();
- this.client.statementClosed();
- } catch (SQLException e) {
- errorOccurred(RuntimePlugin.Util.getString("error_closing_stmt", preparedName)); //$NON-NLS-1$
- }
- }
- }
-
- @Override
- public void terminate() {
-
- for (Portal p: this.portalMap.values()) {
- try {
- p.stmt.close();
- } catch (SQLException e) {
- //ignore
- }
- }
-
- for (Prepared p:this.preparedMap.values()) {
- try {
- p.stmt.close();
- } catch (SQLException e) {
- //ignore
- }
- }
-
- try {
- if (this.connection != null) {
- this.connection.close();
- }
- } catch (SQLException e) {
- //ignore
- }
- this.client.terminated();
- }
-
- @Override
- public void flush() {
- this.client.flush();
- }
-
- @Override
- public void functionCall(int oid) {
- errorOccurred(RuntimePlugin.Util.getString("lo_not_supported")); //$NON-NLS-1$
- }
-
- @Override
- public void sslRequest() {
- this.client.sslDenied();
- }
-
- private void setEncoding() {
- try {
- StatementImpl t = connection.createStatement();
- ResultSet rs = t.executeQuery("show client_encoding"); //$NON-NLS-1$
- if (rs.next()) {
- String encoding = rs.getString(1);
- if (encoding != null) {
- //this may be unnecessary
- this.client.setEncoding(encoding);
- }
- }
- } catch (Exception e) {
- //don't care
- }
- }
-
- 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));
- }
-
- @Override
- public void run() {
- try {
- if (modfiedSQL == null) {
- sql = reader.readStatement();
- modfiedSQL = fixSQL(sql);
- }
- while (modfiedSQL != 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;
- }
- }
- });
- return; //wait for the execution to finish
- } catch (SQLException e) {
- client.errorOccurred(e);
- break;
- }
- }
- } catch(IOException e) {
- client.errorOccurred(e);
- }
- doneExecuting();
- ready();
- }
-
- }
-
- /**
- * Represents a PostgreSQL Prepared object.
- */
- static class Prepared {
-
- public Prepared (String name, String sql, PreparedStatementImpl stmt, int[] paramType) {
- this.name = name;
- this.sql = sql;
- this.stmt = stmt;
- this.paramType = paramType;
- }
-
- /**
- * The object name.
- */
- String name;
-
- /**
- * The SQL statement.
- */
- String sql;
-
- /**
- * The prepared statement.
- */
- PreparedStatementImpl stmt;
-
- /**
- * The list of parameter types (if set).
- */
- int[] paramType;
- }
-
- /**
- * Represents a PostgreSQL Portal object.
- */
- static class Portal {
-
- public Portal(String name, String preparedName, String sql, PreparedStatementImpl stmt, int[] resultColumnformat) {
- this.name = name;
- this.preparedName = preparedName;
- this.sql = sql;
- this.stmt = stmt;
- this.resultColumnFormat = resultColumnformat;
- }
- /**
- * The portal name.
- */
- String name;
-
-
- String preparedName;
-
- /**
- * The SQL statement.
- */
- String sql;
-
- /**
- * The format used in the result set columns (if set).
- */
- int[] resultColumnFormat;
-
- /**
- * The prepared statement.
- */
- PreparedStatementImpl stmt;
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCServerRemoteImpl.java (from rev 3218, trunk/runtime/src/main/java/org/teiid/odbc/ODBCServerRemoteImpl.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCServerRemoteImpl.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/odbc/ODBCServerRemoteImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,814 @@
+/*
+ * 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.io.IOException;
+import java.io.StringReader;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashMap;
+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.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.StatementImpl;
+import org.teiid.jdbc.TeiidDriver;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.runtime.RuntimePlugin;
+import org.teiid.transport.ODBCClientInstance;
+
+/**
+ * While executing the multiple prepared statements I see this bug currently
+ * http://pgfoundry.org/tracker/?func=detail&atid=538&aid=1007690&group_id=1000125
+ */
+public class ODBCServerRemoteImpl implements ODBCServerRemote {
+
+ private static final String UNNAMED = "UNNAMED"; //$NON-NLS-1$
+ private static Pattern setPattern = Pattern.compile("(SET|set)\\s+(\\w+)\\s+(TO|to)\\s+'(\\w+\\d*)'");//$NON-NLS-1$
+
+ private static Pattern pkPattern = Pattern.compile("select ta.attname, ia.attnum, ic.relname, n.nspname, tc.relname " +//$NON-NLS-1$
+ "from pg_catalog.pg_attribute ta, pg_catalog.pg_attribute ia, pg_catalog.pg_class tc, pg_catalog.pg_index i, " +//$NON-NLS-1$
+ "pg_catalog.pg_namespace n, pg_catalog.pg_class ic where tc.relname = (E?(?:'[^']*')+) AND n.nspname = (E?(?:'[^']*')+).*" );//$NON-NLS-1$
+
+ private static Pattern pkKeyPattern = Pattern.compile("select ta.attname, ia.attnum, ic.relname, n.nspname, NULL from " + //$NON-NLS-1$
+ "pg_catalog.pg_attribute ta, pg_catalog.pg_attribute ia, pg_catalog.pg_class ic, pg_catalog.pg_index i, " + //$NON-NLS-1$
+ "pg_catalog.pg_namespace n where ic.relname = (E?(?:'[^']*')+) AND n.nspname = (E?(?:'[^']*')+) .*"); //$NON-NLS-1$
+
+ private Pattern fkPattern = Pattern.compile("select\\s+((?:'[^']*')+)::name as PKTABLE_CAT," + //$NON-NLS-1$
+ "\\s+n2.nspname as PKTABLE_SCHEM," + //$NON-NLS-1$
+ "\\s+c2.relname as PKTABLE_NAME," + //$NON-NLS-1$
+ "\\s+a2.attname as PKCOLUMN_NAME," + //$NON-NLS-1$
+ "\\s+((?:'[^']*')+)::name as FKTABLE_CAT," + //$NON-NLS-1$
+ "\\s+n1.nspname as FKTABLE_SCHEM," + //$NON-NLS-1$
+ "\\s+c1.relname as FKTABLE_NAME," + //$NON-NLS-1$
+ "\\s+a1.attname as FKCOLUMN_NAME," + //$NON-NLS-1$
+ "\\s+i::int2 as KEY_SEQ," + //$NON-NLS-1$
+ "\\s+case ref.confupdtype" + //$NON-NLS-1$
+ "\\s+when 'c' then (\\d)::int2" + //$NON-NLS-1$
+ "\\s+when 'n' then (\\d)::int2" + //$NON-NLS-1$
+ "\\s+when 'd' then (\\d)::int2" + //$NON-NLS-1$
+ "\\s+when 'r' then (\\d)::int2" + //$NON-NLS-1$
+ "\\s+else 3::int2" + //$NON-NLS-1$
+ "\\s+end as UPDATE_RULE," + //$NON-NLS-1$
+ "\\s+case ref.confdeltype" + //$NON-NLS-1$
+ "\\s+when 'c' then (\\d)::int2" + //$NON-NLS-1$
+ "\\s+when 'n' then (\\d)::int2" + //$NON-NLS-1$
+ "\\s+when 'd' then (\\d)::int2" + //$NON-NLS-1$
+ "\\s+when 'r' then (\\d)::int2" + //$NON-NLS-1$
+ "\\s+else 3::int2" + //$NON-NLS-1$
+ "\\s+end as DELETE_RULE," + //$NON-NLS-1$
+ "\\s+ref.conname as FK_NAME," + //$NON-NLS-1$
+ "\\s+cn.conname as PK_NAME," + //$NON-NLS-1$
+ "\\s+case" + //$NON-NLS-1$
+ "\\s+when ref.condeferrable then" + //$NON-NLS-1$
+ "\\s+case" + //$NON-NLS-1$
+ "\\s+when ref.condeferred then (\\d)::int2" + //$NON-NLS-1$
+ "\\s+else (\\d)::int2" + //$NON-NLS-1$
+ "\\s+end" + //$NON-NLS-1$
+ "\\s+else (\\d)::int2" + //$NON-NLS-1$
+ "\\s+end as DEFERRABLITY" + //$NON-NLS-1$
+ "\\s+from" + //$NON-NLS-1$
+ "\\s+\\(\\(\\(\\(\\(\\(\\( \\(select cn.oid, conrelid, conkey, confrelid, confkey," + //$NON-NLS-1$
+ "\\s+generate_series\\(array_lower\\(conkey, 1\\), array_upper\\(conkey, 1\\)\\) as i," + //$NON-NLS-1$
+ "\\s+confupdtype, confdeltype, conname," + //$NON-NLS-1$
+ "\\s+condeferrable, condeferred" + //$NON-NLS-1$
+ "\\s+from pg_catalog.pg_constraint cn," + //$NON-NLS-1$
+ "\\s+pg_catalog.pg_class c," + //$NON-NLS-1$
+ "\\s+pg_catalog.pg_namespace n" + //$NON-NLS-1$
+ "\\s+where contype = 'f' " + //$NON-NLS-1$
+ "\\s+and conrelid = c.oid" + //$NON-NLS-1$
+ "\\s+and relname = (E?(?:'[^']*')+)" + //$NON-NLS-1$
+ "\\s+and n.oid = c.relnamespace" + //$NON-NLS-1$
+ "\\s+and n.nspname = (E?(?:'[^']*')+)" + //$NON-NLS-1$
+ "\\s+\\) ref" + //$NON-NLS-1$
+ "\\s+inner join pg_catalog.pg_class c1" + //$NON-NLS-1$
+ "\\s+on c1.oid = ref.conrelid\\)" + //$NON-NLS-1$
+ "\\s+inner join pg_catalog.pg_namespace n1" + //$NON-NLS-1$
+ "\\s+on n1.oid = c1.relnamespace\\)" + //$NON-NLS-1$
+ "\\s+inner join pg_catalog.pg_attribute a1" + //$NON-NLS-1$
+ "\\s+on a1.attrelid = c1.oid" + //$NON-NLS-1$
+ "\\s+and a1.attnum = conkey\\[i\\]\\)" + //$NON-NLS-1$
+ "\\s+inner join pg_catalog.pg_class c2" + //$NON-NLS-1$
+ "\\s+on c2.oid = ref.confrelid\\)" + //$NON-NLS-1$
+ "\\s+inner join pg_catalog.pg_namespace n2" + //$NON-NLS-1$
+ "\\s+on n2.oid = c2.relnamespace\\)" + //$NON-NLS-1$
+ "\\s+inner join pg_catalog.pg_attribute a2" + //$NON-NLS-1$
+ "\\s+on a2.attrelid = c2.oid" + //$NON-NLS-1$
+ "\\s+and a2.attnum = confkey\\[i\\]\\)" + //$NON-NLS-1$
+ "\\s+left outer join pg_catalog.pg_constraint cn" + //$NON-NLS-1$
+ "\\s+on cn.conrelid = ref.confrelid" + //$NON-NLS-1$
+ "\\s+and cn.contype = 'p'\\)" + //$NON-NLS-1$
+ "\\s+order by ref.oid, ref.i"); //$NON-NLS-1$
+
+ 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 TeiidDriver driver;
+ private ODBCClientRemote client;
+ private Properties props;
+ private AuthenticationType authType;
+ private ConnectionImpl connection;
+ private boolean executing;
+ private boolean errorOccurred;
+
+ private volatile ResultsFuture<Boolean> executionFuture;
+
+ // 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>());
+
+ public ODBCServerRemoteImpl(ODBCClientInstance client, AuthenticationType authType, TeiidDriver driver) {
+ this.driver = driver;
+ this.client = client.getClient();
+ this.authType = authType;
+ }
+
+ @Override
+ public void initialize(Properties props) {
+ this.props = props;
+
+ this.client.initialized(this.props);
+
+ if (this.authType.equals(AuthenticationType.CLEARTEXT)) {
+ this.client.useClearTextAuthentication();
+ }
+ else if (this.authType.equals(AuthenticationType.MD5)) {
+ // TODO: implement MD5 auth type
+ }
+ }
+
+ @Override
+ public void logon(String databaseName, String user, String password) {
+ try {
+ java.util.Properties info = new java.util.Properties();
+ String url = "jdbc:teiid:"+databaseName+";ApplicationName=ODBC"; //$NON-NLS-1$ //$NON-NLS-2$
+ info.put("user", user); //$NON-NLS-1$
+ 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();
+ while (keys.hasMoreElements()) {
+ String key = (String)keys.nextElement();
+ Statement stmt = this.connection.createStatement();
+ stmt.execute("SET " + key + " '" + this.props.getProperty(key) + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ stmt.close();
+ }
+ this.client.authenticationSucess(hash, hash);
+ ready();
+ } catch (SQLException e) {
+ errorOccurred(e);
+ terminate();
+ }
+ }
+
+ @Override
+ public void prepare(String prepareName, String sql, int[] paramType) {
+ if (this.connection != null) {
+
+ if (prepareName == null || prepareName.length() == 0) {
+ prepareName = UNNAMED;
+ }
+
+ if (sql != null) {
+ String modfiedSQL = fixSQL(sql);
+ try {
+ // close if the name is already used or the unnamed prepare; otherwise
+ // stmt is alive until session ends.
+ Prepared previous = this.preparedMap.remove(prepareName);
+ if (previous != null) {
+ previous.stmt.close();
+ }
+
+ PreparedStatementImpl stmt = this.connection.prepareStatement(modfiedSQL);
+ this.preparedMap.put(prepareName, new Prepared(prepareName, sql, stmt, paramType));
+ this.client.prepareCompleted(prepareName);
+ } catch (SQLException e) {
+ errorOccurred(e);
+ }
+ }
+ }
+ else {
+ errorOccurred(RuntimePlugin.Util.getString("no_active_connection")); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ public void bindParameters(String bindName, String prepareName, int paramCount, Object[] params, int resultCodeCount, int[] resultColumnFormat) {
+ // An unnamed portal is destroyed at the end of the transaction, or as soon as
+ // the next Bind statement specifying the unnamed portal as destination is issued.
+ this.portalMap.remove(UNNAMED);
+
+ if (prepareName == null || prepareName.length() == 0) {
+ prepareName = UNNAMED;
+ }
+
+ Prepared previous = this.preparedMap.get(prepareName);
+ if (previous == null) {
+ errorOccurred(RuntimePlugin.Util.getString("bad_binding", prepareName)); //$NON-NLS-1$
+ return;
+ }
+
+ if (bindName == null || bindName.length() == 0) {
+ bindName = UNNAMED;
+ }
+
+ try {
+ for (int i = 0; i < paramCount; i++) {
+ previous.stmt.setObject(i+1, params[i]);
+ }
+ } catch (SQLException e) {
+ errorOccurred(e);
+ }
+
+ this.portalMap.put(bindName, new Portal(bindName, prepareName, previous.sql, previous.stmt, resultColumnFormat));
+ this.client.bindComplete();
+ }
+
+ @Override
+ public void unsupportedOperation(String msg) {
+ errorOccurred(msg);
+ }
+
+ @Override
+ public void execute(String bindName, int maxRows) {
+ if (beginExecution()) {
+ errorOccurred("Awaiting asynch result"); //$NON-NLS-1$
+ return;
+ }
+ if (bindName == null || bindName.length() == 0) {
+ bindName = UNNAMED;
+ }
+
+ 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);
+ }
+ }
+ }
+
+ private String fixSQL(String sql) {
+ String modified = modifySQL(sql);
+ if (modified != null && !modified.equals(sql)) {
+ LogManager.logDetail(LogConstants.CTX_ODBC, "Modified Query:", modified); //$NON-NLS-1$
+ }
+ return modified;
+ }
+
+ private String modifySQL(String sql) {
+ String modified = sql;
+ // select current_schema()
+ // set client_encoding to 'WIN1252'
+ if (sql == null) {
+ return null;
+ }
+ // selects are coming with "select\t" so using a space after "select" does not always work
+ if (StringUtil.startsWithIgnoreCase(sql, "select")) { //$NON-NLS-1$
+ modified = sql.replace('\n', ' ');
+
+ Matcher m = null;
+ if ((m = pkPattern.matcher(modified)).matches()) {
+ return new StringBuffer("SELECT k.Name AS attname, convert(Position, short) AS attnum, TableName AS relname, SchemaName AS nspname, TableName AS relname") //$NON-NLS-1$
+ .append(" FROM SYS.KeyColumns k") //$NON-NLS-1$
+ .append(" WHERE ") //$NON-NLS-1$
+ .append(" UCASE(SchemaName)").append(" LIKE UCASE(").append(m.group(2)).append(")")//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ .append(" AND UCASE(TableName)") .append(" LIKE UCASE(").append(m.group(1)).append(")")//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ .append(" AND KeyType LIKE 'Primary'") //$NON-NLS-1$
+ .append(" ORDER BY attnum").toString(); //$NON-NLS-1$
+ }
+ else if ((m = pkKeyPattern.matcher(modified)).matches()) {
+ String tableName = m.group(1);
+ if (tableName.endsWith("_pkey'")) { //$NON-NLS-1$
+ tableName = tableName.substring(0, tableName.length()-6) + '\'';
+ return "select ia.attname, ia.attnum, ic.relname, n.nspname, NULL "+ //$NON-NLS-1$
+ "from pg_catalog.pg_attribute ia, pg_catalog.pg_class ic, pg_catalog.pg_namespace n, Sys.KeyColumns kc "+ //$NON-NLS-1$
+ "where ic.relname = "+tableName+" AND n.nspname = "+m.group(2)+" AND "+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ "n.oid = ic.relnamespace AND ia.attrelid = ic.oid AND kc.SchemaName = n.nspname " +//$NON-NLS-1$
+ "AND kc.TableName = ic.relname AND kc.KeyType = 'Primary' AND kc.Name = ia.attname order by ia.attnum";//$NON-NLS-1$
+ }
+ return "SELECT NULL, NULL, NULL, NULL, NULL FROM (SELECT 1) as X WHERE 0=1"; //$NON-NLS-1$
+ }
+ else if ((m = fkPattern.matcher(modified)).matches()){
+ return "SELECT PKTABLE_CAT, PKTABLE_SCHEM, PKTABLE_NAME, PKCOLUMN_NAME, FKTABLE_CAT, FKTABLE_SCHEM, "+//$NON-NLS-1$
+ "FKTABLE_NAME, FKCOLUMN_NAME, KEY_SEQ, UPDATE_RULE, DELETE_RULE, FK_NAME, PK_NAME, DEFERRABILITY "+//$NON-NLS-1$
+ "FROM SYS.ReferenceKeyColumns WHERE PKTABLE_NAME LIKE "+m.group(14)+" and PKTABLE_SCHEM LIKE "+m.group(15);//$NON-NLS-1$ //$NON-NLS-2$
+ }
+ else if (modified.equalsIgnoreCase("select version()")) { //$NON-NLS-1$
+ return "SELECT 'Teiid "+ApplicationInfo.getInstance().getReleaseNumber()+"'"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ else if (modified.startsWith("SELECT name FROM master..sysdatabases")) { //$NON-NLS-1$
+ return "SELECT 'Teiid'"; //$NON-NLS-1$
+ }
+ else if (modified.equalsIgnoreCase("select db_name() dbname")) { //$NON-NLS-1$
+ return "SELECT current_database()"; //$NON-NLS-1$
+ }
+ else if (preparedAutoIncrement.matcher(modified).matches()) {
+ return "SELECT 1 from matpg_relatt where attrelid = ? and attnum = ? and autoinc = true"; //$NON-NLS-1$
+ }
+ else {
+ // since teiid can work with multiple schemas at a given time
+ // this call resolution is ambiguous
+ if (sql.equalsIgnoreCase("select current_schema()")) { //$NON-NLS-1$
+ return "SELECT ''"; //$NON-NLS-1$
+ }
+ }
+
+ }
+ else if (sql.equalsIgnoreCase("show max_identifier_length")){ //$NON-NLS-1$
+ return "select 63"; //$NON-NLS-1$
+ }
+ else {
+ Matcher m = setPattern.matcher(sql);
+ if (m.matches()) {
+ return "SET " + m.group(2) + " " + m.group(4); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ else if (modified.equalsIgnoreCase("BEGIN")) { //$NON-NLS-1$
+ return "START TRANSACTION"; //$NON-NLS-1$
+ }
+ 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;
+ //these are somewhat dangerous
+ modified = modified.replaceAll("::[A-Za-z0-9]*", " "); //$NON-NLS-1$ //$NON-NLS-2$
+ modified = modified.replaceAll("'pg_toast'", "'SYS'"); //$NON-NLS-1$ //$NON-NLS-2$
+ return modified;
+ }
+
+ @Override
+ public void executeQuery(final String query) {
+ if (beginExecution()) {
+ this.client.errorOccurred("Awaiting asynch result"); //$NON-NLS-1$
+ ready();
+ return;
+ }
+ //46.2.3 Note that a simple Query message also destroys the unnamed portal.
+ this.portalMap.remove(UNNAMED);
+ this.preparedMap.remove(UNNAMED);
+
+ if (query.trim().length() == 0) {
+ this.client.emptyQueryReceived();
+ ready();
+ return;
+ }
+ QueryWorkItem r = new QueryWorkItem(query);
+ r.run();
+ }
+
+ private boolean beginExecution() {
+ if (this.executionFuture != null) {
+ return true;
+ }
+ synchronized (this) {
+ this.executing = true;
+ }
+ return false;
+ }
+
+ public boolean isExecuting() {
+ return executing;
+ }
+
+ public boolean isErrorOccurred() {
+ return errorOccurred;
+ }
+
+ @Override
+ public void getParameterDescription(String prepareName) {
+ if (prepareName == null || prepareName.length() == 0) {
+ prepareName = UNNAMED;
+ }
+ Prepared query = this.preparedMap.get(prepareName);
+ if (query == null) {
+ errorOccurred(RuntimePlugin.Util.getString("no_stmt_found", prepareName)); //$NON-NLS-1$
+ }
+ else {
+ try {
+ this.client.sendParameterDescription(query.stmt.getParameterMetaData(), query.paramType);
+ } catch (SQLException e) {
+ errorOccurred(e);
+ }
+ }
+ }
+
+ private void errorOccurred(String error) {
+ this.client.errorOccurred(error);
+ synchronized (this) {
+ this.errorOccurred = true;
+ doneExecuting();
+ }
+ }
+
+ private void errorOccurred(Throwable error) {
+ this.client.errorOccurred(error);
+ synchronized (this) {
+ this.errorOccurred = true;
+ doneExecuting();
+ }
+ }
+
+ @Override
+ public void getResultSetMetaDataDescription(String bindName) {
+ if (bindName == null || bindName.length() == 0) {
+ bindName = UNNAMED;
+ }
+ Portal query = this.portalMap.get(bindName);
+ if (query == null) {
+ errorOccurred(RuntimePlugin.Util.getString("not_bound", bindName)); //$NON-NLS-1$
+ }
+ else {
+ try {
+ this.client.sendResultSetDescription(query.stmt.getMetaData(), query.stmt);
+ } catch (SQLException e) {
+ errorOccurred(e);
+ }
+ }
+ }
+
+ @Override
+ public void sync() {
+ ready();
+ }
+
+ protected synchronized void doneExecuting() {
+ executing = false;
+ }
+
+ private void ready() {
+ boolean inTxn = false;
+ boolean failedTxn = false;
+ try {
+ if (!this.connection.getAutoCommit()) {
+ inTxn = true;
+ }
+ } catch (SQLException e) {
+ failedTxn = true;
+ }
+ synchronized (this) {
+ this.errorOccurred = false;
+ }
+ this.client.ready(inTxn, failedTxn);
+ }
+
+ @Override
+ public void cancel() {
+ // TODO Auto-generated method stub
+ }
+
+ @Override
+ public void closeBoundStatement(String bindName) {
+ if (bindName == null || bindName.length() == 0) {
+ bindName = UNNAMED;
+ }
+ Portal query = this.portalMap.remove(bindName);
+ if (query == null) {
+ errorOccurred(RuntimePlugin.Util.getString("not_bound", bindName)); //$NON-NLS-1$
+ }
+ else {
+ try {
+ if (this.connection.getAutoCommit()) {
+ // After checking the pg's client code I do not see it send a
+ // close of the Prepare stmt as per the wire protocol, it only sends
+ // bound close. Since it also have issue with
+ // http://pgfoundry.org/tracker/?func=detail&atid=538&aid=1007690&group_id=1000125
+ // treating the prepare and bound as same for now.
+ closePreparedStatement(bindName);
+ }
+ } catch (SQLException e) {
+ closePreparedStatement(bindName);
+ }
+ }
+ }
+
+ @Override
+ public void closePreparedStatement(String preparedName) {
+ if (preparedName == null || preparedName.length() == 0) {
+ preparedName = UNNAMED;
+ }
+ Prepared query = this.preparedMap.remove(preparedName);
+ if (query == null) {
+ errorOccurred(RuntimePlugin.Util.getString("no_stmt_found", preparedName)); //$NON-NLS-1$
+ }
+ else {
+ // Close all the bound messages off of this prepared
+ // TODO: can there be more than one?
+ this.portalMap.remove(preparedName);
+
+ try {
+ query.stmt.close();
+ this.client.statementClosed();
+ } catch (SQLException e) {
+ errorOccurred(RuntimePlugin.Util.getString("error_closing_stmt", preparedName)); //$NON-NLS-1$
+ }
+ }
+ }
+
+ @Override
+ public void terminate() {
+
+ for (Portal p: this.portalMap.values()) {
+ try {
+ p.stmt.close();
+ } catch (SQLException e) {
+ //ignore
+ }
+ }
+
+ for (Prepared p:this.preparedMap.values()) {
+ try {
+ p.stmt.close();
+ } catch (SQLException e) {
+ //ignore
+ }
+ }
+
+ try {
+ if (this.connection != null) {
+ this.connection.close();
+ }
+ } catch (SQLException e) {
+ //ignore
+ }
+ this.client.terminated();
+ }
+
+ @Override
+ public void flush() {
+ this.client.flush();
+ }
+
+ @Override
+ public void functionCall(int oid) {
+ errorOccurred(RuntimePlugin.Util.getString("lo_not_supported")); //$NON-NLS-1$
+ }
+
+ @Override
+ public void sslRequest() {
+ this.client.sendSslResponse();
+ }
+
+ private void setEncoding() {
+ try {
+ StatementImpl t = connection.createStatement();
+ ResultSet rs = t.executeQuery("show client_encoding"); //$NON-NLS-1$
+ if (rs.next()) {
+ String encoding = rs.getString(1);
+ if (encoding != null) {
+ //this may be unnecessary
+ this.client.setEncoding(encoding);
+ }
+ }
+ } catch (Exception e) {
+ //don't care
+ }
+ }
+
+ 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));
+ }
+
+ @Override
+ public void run() {
+ try {
+ if (modfiedSQL == null) {
+ sql = reader.readStatement();
+ modfiedSQL = fixSQL(sql);
+ }
+ while (modfiedSQL != 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;
+ }
+ }
+ });
+ return; //wait for the execution to finish
+ } catch (SQLException e) {
+ client.errorOccurred(e);
+ break;
+ }
+ }
+ } catch(IOException e) {
+ client.errorOccurred(e);
+ }
+ doneExecuting();
+ ready();
+ }
+
+ }
+
+ /**
+ * Represents a PostgreSQL Prepared object.
+ */
+ static class Prepared {
+
+ public Prepared (String name, String sql, PreparedStatementImpl stmt, int[] paramType) {
+ this.name = name;
+ this.sql = sql;
+ this.stmt = stmt;
+ this.paramType = paramType;
+ }
+
+ /**
+ * The object name.
+ */
+ String name;
+
+ /**
+ * The SQL statement.
+ */
+ String sql;
+
+ /**
+ * The prepared statement.
+ */
+ PreparedStatementImpl stmt;
+
+ /**
+ * The list of parameter types (if set).
+ */
+ int[] paramType;
+ }
+
+ /**
+ * Represents a PostgreSQL Portal object.
+ */
+ static class Portal {
+
+ public Portal(String name, String preparedName, String sql, PreparedStatementImpl stmt, int[] resultColumnformat) {
+ this.name = name;
+ this.preparedName = preparedName;
+ this.sql = sql;
+ this.stmt = stmt;
+ this.resultColumnFormat = resultColumnformat;
+ }
+ /**
+ * The portal name.
+ */
+ String name;
+
+
+ String preparedName;
+
+ /**
+ * The SQL statement.
+ */
+ String sql;
+
+ /**
+ * The format used in the result set columns (if set).
+ */
+ int[] resultColumnFormat;
+
+ /**
+ * The prepared statement.
+ */
+ PreparedStatementImpl stmt;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,378 +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.services;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-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.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.jboss.managed.api.annotation.ManagementComponent;
-import org.jboss.managed.api.annotation.ManagementObject;
-import org.jboss.managed.api.annotation.ManagementProperties;
-import org.jboss.managed.api.annotation.ManagementProperty;
-import org.teiid.adminapi.VDB;
-import org.teiid.adminapi.VDB.ConnectionType;
-import org.teiid.adminapi.impl.SessionMetadata;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.client.security.InvalidSessionException;
-import org.teiid.client.security.SessionToken;
-import org.teiid.core.util.ArgCheck;
-import org.teiid.deployers.VDBRepository;
-import org.teiid.dqp.internal.process.DQPCore;
-import org.teiid.dqp.service.SessionService;
-import org.teiid.dqp.service.SessionServiceException;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.net.ServerConnection;
-import org.teiid.net.TeiidURL;
-import org.teiid.runtime.RuntimePlugin;
-import org.teiid.security.Credentials;
-import org.teiid.security.SecurityHelper;
-
-
-/**
- * This class serves as the primary implementation of the Session Service.
- */
- at ManagementObject(name="SessionService", componentType=@ManagementComponent(type="teiid",subtype="dqp"), properties=ManagementProperties.EXPLICIT)
-public class SessionServiceImpl implements SessionService {
- public static final String SECURITY_DOMAINS = "securitydomains"; //$NON-NLS-1$
-
- /*
- * Configuration state
- */
- private long sessionMaxLimit = DEFAULT_MAX_SESSIONS;
- private long sessionExpirationTimeLimit = DEFAULT_SESSION_EXPIRATION;
-
- /*
- * Injected state
- */
- private VDBRepository vdbRepository;
- private SecurityHelper securityHelper;
-
- private DQPCore dqp;
-
- private Map<String, SessionMetadata> sessionCache = new ConcurrentHashMap<String, SessionMetadata>();
- private Timer sessionMonitor = new Timer("SessionMonitor", true); //$NON-NLS-1$
- private LinkedList<String> securityDomains = new LinkedList<String>();
- private LinkedList<String> adminSecurityDomains = new LinkedList<String>();
-
-
- // -----------------------------------------------------------------------------------
- // S E R V I C E - R E L A T E D M E T H O D S
- // -----------------------------------------------------------------------------------
-
- private void monitorSessions() {
- long currentTime = System.currentTimeMillis();
- for (SessionMetadata info : sessionCache.values()) {
- try {
- if (!info.isEmbedded() && currentTime - info.getLastPingTime() > ServerConnection.PING_INTERVAL * 5) {
- LogManager.logInfo(LogConstants.CTX_SECURITY, RuntimePlugin.Util.getString( "SessionServiceImpl.keepaliveFailed", info.getSessionId())); //$NON-NLS-1$
- closeSession(info.getSessionId());
- } else if (sessionExpirationTimeLimit > 0 && currentTime - info.getCreatedTime() > sessionExpirationTimeLimit) {
- LogManager.logInfo(LogConstants.CTX_SECURITY, RuntimePlugin.Util.getString( "SessionServiceImpl.expireSession", info.getSessionId())); //$NON-NLS-1$
- closeSession(info.getSessionId());
- }
- } catch (Exception e) {
- LogManager.logDetail(LogConstants.CTX_SECURITY, e, "error running session monitor, unable to monitor:", info.getSessionId()); //$NON-NLS-1$
- }
- }
- }
-
- @Override
- public void closeSession(String sessionID) throws InvalidSessionException {
- LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"closeSession", sessionID}); //$NON-NLS-1$
- if (sessionID == null) {
- throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
- }
- SessionMetadata info = this.sessionCache.remove(sessionID);
- if (info == null) {
- throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
- }
- if (info.getVDBName() != null) {
- try {
- dqp.terminateSession(info.getSessionId());
- } catch (Exception e) {
- LogManager.logWarning(LogConstants.CTX_SECURITY,e,"Exception terminitating session"); //$NON-NLS-1$
- }
- }
-
- // try to log out of the context.
- try {
- LoginContext context = info.getLoginContext();
- if (context != null) {
- context.logout();
- }
- } catch (LoginException e) {
- LogManager.logWarning(LogConstants.CTX_SECURITY,e,"Exception terminitating session"); //$NON-NLS-1$
- }
- }
-
- @Override
- public SessionMetadata createSession(String userName, Credentials credentials, String applicationName, Properties properties, boolean adminConnection, boolean authenticate)
- throws LoginException, SessionServiceException {
- ArgCheck.isNotNull(applicationName);
- ArgCheck.isNotNull(properties);
-
- LoginContext loginContext = null;
- String securityDomain = "none"; //$NON-NLS-1$
- Object securityContext = null;
- List<String> domains = this.securityDomains;
- if (adminConnection) {
- domains = this.adminSecurityDomains;
- }
-
- // Validate VDB and version if logging on to server product...
- VDBMetaData vdb = null;
- String vdbName = properties.getProperty(TeiidURL.JDBC.VDB_NAME);
- if (vdbName != null) {
- String vdbVersion = properties.getProperty(TeiidURL.JDBC.VDB_VERSION);
- vdb = getActiveVDB(vdbName, vdbVersion);
- }
-
- if (sessionMaxLimit > 0 && getActiveSessionsCount() >= sessionMaxLimit) {
- throw new SessionServiceException(RuntimePlugin.Util.getString("SessionServiceImpl.reached_max_sessions", new Object[] {new Long(sessionMaxLimit)})); //$NON-NLS-1$
- }
-
- if (!domains.isEmpty() && authenticate) {
- // Authenticate user...
- // if not authenticated, this method throws exception
- boolean onlyAllowPassthrough = Boolean.valueOf(properties.getProperty(TeiidURL.CONNECTION.PASSTHROUGH_AUTHENTICATION, "false")); //$NON-NLS-1$
- TeiidLoginContext membership = authenticate(userName, credentials, applicationName, domains, this.securityHelper, onlyAllowPassthrough);
- loginContext = membership.getLoginContext();
- userName = membership.getUserName();
- securityDomain = membership.getSecurityDomain();
- securityContext = membership.getSecurityContext();
- }
-
- long creationTime = System.currentTimeMillis();
-
- // Return a new session info object
- SessionMetadata newSession = new SessionMetadata();
- newSession.setSessionToken(new SessionToken(userName));
- newSession.setSessionId(newSession.getSessionToken().getSessionID());
- newSession.setUserName(userName);
- newSession.setCreatedTime(creationTime);
- newSession.setApplicationName(applicationName);
- newSession.setClientHostName(properties.getProperty(TeiidURL.CONNECTION.CLIENT_HOSTNAME));
- newSession.setIPAddress(properties.getProperty(TeiidURL.CONNECTION.CLIENT_IP_ADDRESS));
- newSession.setSecurityDomain(securityDomain);
- if (vdb != null) {
- newSession.setVDBName(vdb.getName());
- newSession.setVDBVersion(vdb.getVersion());
- }
-
- // these are local no need for monitoring.
- newSession.setLoginContext(loginContext);
- 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$
- this.sessionCache.put(newSession.getSessionId(), newSession);
- return newSession;
- }
-
- VDBMetaData getActiveVDB(String vdbName, String vdbVersion) throws SessionServiceException {
- VDBMetaData vdb = null;
-
- // handle the situation when the version is part of the vdb name.
-
- int firstIndex = vdbName.indexOf('.');
- int lastIndex = vdbName.lastIndexOf('.');
- if (firstIndex != -1) {
- if (firstIndex != lastIndex || vdbVersion != null) {
- throw new SessionServiceException(RuntimePlugin.Util.getString("ambigious_name", vdbName, vdbVersion)); //$NON-NLS-1$
- }
- vdbVersion = vdbName.substring(firstIndex+1);
- vdbName = vdbName.substring(0, firstIndex);
- }
-
- try {
- if (vdbVersion == null) {
- vdbVersion = "latest"; //$NON-NLS-1$
- vdb = this.vdbRepository.getVDB(vdbName);
- }
- else {
- vdb = this.vdbRepository.getVDB(vdbName, Integer.parseInt(vdbVersion));
- }
- } catch (NumberFormatException e) {
- throw new SessionServiceException(e, RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._3", vdbVersion)); //$NON-NLS-1$
- }
-
- if (vdb == null) {
- throw new SessionServiceException(RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._1", vdbName, vdbVersion)); //$NON-NLS-1$
- }
-
- if (vdb.getStatus() != VDB.Status.ACTIVE) {
- throw new SessionServiceException(RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._2", vdbName, vdbVersion)); //$NON-NLS-1$
- }
- if (vdb.getConnectionType() == ConnectionType.NONE) {
- throw new SessionServiceException(RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._4", vdbName, vdbVersion)); //$NON-NLS-1$
- }
- return vdb;
- }
-
- protected TeiidLoginContext authenticate(String userName, Credentials credentials, String applicationName, List<String> domains, SecurityHelper helper, boolean onlyallowPassthrough)
- throws LoginException {
- TeiidLoginContext membership = new TeiidLoginContext(helper);
- membership.authenticateUser(userName, credentials, applicationName, domains, onlyallowPassthrough);
- return membership;
- }
-
- @Override
- public Collection<SessionMetadata> getActiveSessions() throws SessionServiceException {
- return new ArrayList<SessionMetadata>(this.sessionCache.values());
- }
-
- @Override
- public SessionMetadata getActiveSession(String sessionID) {
- return this.sessionCache.get(sessionID);
- }
-
- @Override
- public int getActiveSessionsCount() throws SessionServiceException{
- return this.sessionCache.size();
- }
-
- @Override
- public Collection<SessionMetadata> getSessionsLoggedInToVDB(String VDBName, int vdbVersion)
- throws SessionServiceException {
- if (VDBName == null || vdbVersion <= 0) {
- return Collections.emptyList();
- }
- ArrayList<SessionMetadata> results = new ArrayList<SessionMetadata>();
- for (SessionMetadata info : this.sessionCache.values()) {
- if (VDBName.equalsIgnoreCase(info.getVDBName()) && vdbVersion == info.getVDBVersion()) {
- results.add(info);
- }
- }
- return results;
- }
-
- @Override
- public void pingServer(String sessionID) throws InvalidSessionException {
- SessionMetadata info = getSessionInfo(sessionID);
- info.setLastPingTime(System.currentTimeMillis());
- this.sessionCache.put(sessionID, info);
- LogManager.logDetail(LogConstants.CTX_SECURITY, "Keep-alive ping received for session:", sessionID); //$NON-NLS-1$
- }
-
- @Override
- public boolean terminateSession(String terminatedSessionID, String adminSessionID) {
- Object[] params = {adminSessionID, terminatedSessionID};
- LogManager.logInfo(LogConstants.CTX_SECURITY, RuntimePlugin.Util.getString( "SessionServiceImpl.terminateSession", params)); //$NON-NLS-1$
- try {
- closeSession(terminatedSessionID);
- return true;
- } catch (InvalidSessionException e) {
- LogManager.logWarning(LogConstants.CTX_SECURITY,e,RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", new Object[] {e.getMessage()})); //$NON-NLS-1$
- return false;
- }
- }
-
- @Override
- public SessionMetadata validateSession(String sessionID) throws InvalidSessionException, SessionServiceException {
- SessionMetadata info = getSessionInfo(sessionID);
- return info;
- }
-
- private SessionMetadata getSessionInfo(String sessionID)
- throws InvalidSessionException {
- if (sessionID == null) {
- throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
- }
- SessionMetadata info = this.sessionCache.get(sessionID);
- if (info == null) {
- throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
- }
- return info;
- }
-
- @ManagementProperty (description="Maximum number of sessions allowed by the system (default 5000)")
- public long getSessionMaxLimit() {
- return this.sessionMaxLimit;
- }
-
- public void setSessionMaxLimit(long limit) {
- this.sessionMaxLimit = limit;
- }
-
- @ManagementProperty(description="Max allowed time before the session is terminated by the system, 0 indicates unlimited (default 0)")
- public long getSessionExpirationTimeLimit() {
- return this.sessionExpirationTimeLimit;
- }
-
- public void setSessionExpirationTimeLimit(long limit) {
- this.sessionExpirationTimeLimit = limit;
- }
-
- public void setSecurityDomains(String domainNameOrder) {
- if (domainNameOrder != null && domainNameOrder.trim().length()>0) {
- LogManager.logInfo(LogConstants.CTX_SECURITY, "Security Enabled: true"); //$NON-NLS-1$
-
- String[] domainNames = domainNameOrder.split(","); //$NON-NLS-1$
- for (String domainName : domainNames) {
- this.securityDomains.addLast(domainName);
- }
- }
- }
-
- public void setAdminSecurityDomain(String domain) {
- this.adminSecurityDomains.add(domain);
- LogManager.logInfo(LogConstants.CTX_SECURITY, "Admin Security Enabled: true"); //$NON-NLS-1$
- }
-
- public void start() {
- this.sessionMonitor.schedule(new TimerTask() {
- @Override
- public void run() {
- monitorSessions();
- }
- }, 0, ServerConnection.PING_INTERVAL * 5);
- }
-
- public void stop(){
- this.sessionMonitor.cancel();
- this.sessionCache.clear();
- }
-
- public void setVDBRepository(VDBRepository repo) {
- this.vdbRepository = repo;
- }
-
- public void setSecurityHelper(SecurityHelper securityHelper) {
- this.securityHelper = securityHelper;
- }
-
- public void setDqp(DQPCore dqp) {
- this.dqp = dqp;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java (from rev 3218, trunk/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,379 @@
+/*
+ * 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.services;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedList;
+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.login.LoginContext;
+import javax.security.auth.login.LoginException;
+
+import org.jboss.managed.api.annotation.ManagementComponent;
+import org.jboss.managed.api.annotation.ManagementObject;
+import org.jboss.managed.api.annotation.ManagementProperties;
+import org.jboss.managed.api.annotation.ManagementProperty;
+import org.teiid.adminapi.VDB;
+import org.teiid.adminapi.VDB.ConnectionType;
+import org.teiid.adminapi.impl.SessionMetadata;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.client.security.InvalidSessionException;
+import org.teiid.client.security.SessionToken;
+import org.teiid.core.util.ArgCheck;
+import org.teiid.deployers.VDBRepository;
+import org.teiid.dqp.internal.process.DQPCore;
+import org.teiid.dqp.service.SessionService;
+import org.teiid.dqp.service.SessionServiceException;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.net.ServerConnection;
+import org.teiid.net.TeiidURL;
+import org.teiid.runtime.RuntimePlugin;
+import org.teiid.security.Credentials;
+import org.teiid.security.SecurityHelper;
+
+
+/**
+ * This class serves as the primary implementation of the Session Service.
+ */
+ at ManagementObject(name="SessionService", componentType=@ManagementComponent(type="teiid",subtype="dqp"), properties=ManagementProperties.EXPLICIT)
+public class SessionServiceImpl implements SessionService {
+ public static final String SECURITY_DOMAINS = "securitydomains"; //$NON-NLS-1$
+
+ /*
+ * Configuration state
+ */
+ private long sessionMaxLimit = DEFAULT_MAX_SESSIONS;
+ private long sessionExpirationTimeLimit = DEFAULT_SESSION_EXPIRATION;
+
+ /*
+ * Injected state
+ */
+ private VDBRepository vdbRepository;
+ private SecurityHelper securityHelper;
+
+ private DQPCore dqp;
+
+ private Map<String, SessionMetadata> sessionCache = new ConcurrentHashMap<String, SessionMetadata>();
+ private Timer sessionMonitor = new Timer("SessionMonitor", true); //$NON-NLS-1$
+ private LinkedList<String> securityDomains = new LinkedList<String>();
+ private LinkedList<String> adminSecurityDomains = new LinkedList<String>();
+
+
+ // -----------------------------------------------------------------------------------
+ // S E R V I C E - R E L A T E D M E T H O D S
+ // -----------------------------------------------------------------------------------
+
+ private void monitorSessions() {
+ long currentTime = System.currentTimeMillis();
+ for (SessionMetadata info : sessionCache.values()) {
+ try {
+ if (!info.isEmbedded() && currentTime - info.getLastPingTime() > ServerConnection.PING_INTERVAL * 5) {
+ LogManager.logInfo(LogConstants.CTX_SECURITY, RuntimePlugin.Util.getString( "SessionServiceImpl.keepaliveFailed", info.getSessionId())); //$NON-NLS-1$
+ closeSession(info.getSessionId());
+ } else if (sessionExpirationTimeLimit > 0 && currentTime - info.getCreatedTime() > sessionExpirationTimeLimit) {
+ LogManager.logInfo(LogConstants.CTX_SECURITY, RuntimePlugin.Util.getString( "SessionServiceImpl.expireSession", info.getSessionId())); //$NON-NLS-1$
+ closeSession(info.getSessionId());
+ }
+ } catch (Exception e) {
+ LogManager.logDetail(LogConstants.CTX_SECURITY, e, "error running session monitor, unable to monitor:", info.getSessionId()); //$NON-NLS-1$
+ }
+ }
+ }
+
+ @Override
+ public void closeSession(String sessionID) throws InvalidSessionException {
+ LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"closeSession", sessionID}); //$NON-NLS-1$
+ if (sessionID == null) {
+ throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
+ }
+ SessionMetadata info = this.sessionCache.remove(sessionID);
+ if (info == null) {
+ throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
+ }
+ if (info.getVDBName() != null) {
+ try {
+ dqp.terminateSession(info.getSessionId());
+ } catch (Exception e) {
+ LogManager.logWarning(LogConstants.CTX_SECURITY,e,"Exception terminitating session"); //$NON-NLS-1$
+ }
+ }
+
+ // try to log out of the context.
+ try {
+ LoginContext context = info.getLoginContext();
+ if (context != null) {
+ context.logout();
+ }
+ } catch (LoginException e) {
+ LogManager.logWarning(LogConstants.CTX_SECURITY,e,"Exception terminitating session"); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ public SessionMetadata createSession(String userName, Credentials credentials, String applicationName, Properties properties, boolean adminConnection, boolean authenticate)
+ throws LoginException, SessionServiceException {
+ ArgCheck.isNotNull(applicationName);
+ ArgCheck.isNotNull(properties);
+
+ LoginContext loginContext = null;
+ String securityDomain = "none"; //$NON-NLS-1$
+ Object securityContext = null;
+ List<String> domains = this.securityDomains;
+ if (adminConnection) {
+ domains = this.adminSecurityDomains;
+ }
+
+ // Validate VDB and version if logging on to server product...
+ VDBMetaData vdb = null;
+ String vdbName = properties.getProperty(TeiidURL.JDBC.VDB_NAME);
+ if (vdbName != null) {
+ String vdbVersion = properties.getProperty(TeiidURL.JDBC.VDB_VERSION);
+ vdb = getActiveVDB(vdbName, vdbVersion);
+ }
+
+ if (sessionMaxLimit > 0 && getActiveSessionsCount() >= sessionMaxLimit) {
+ throw new SessionServiceException(RuntimePlugin.Util.getString("SessionServiceImpl.reached_max_sessions", new Object[] {new Long(sessionMaxLimit)})); //$NON-NLS-1$
+ }
+
+ if (!domains.isEmpty() && authenticate) {
+ // Authenticate user...
+ // if not authenticated, this method throws exception
+ boolean onlyAllowPassthrough = Boolean.valueOf(properties.getProperty(TeiidURL.CONNECTION.PASSTHROUGH_AUTHENTICATION, "false")); //$NON-NLS-1$
+ TeiidLoginContext membership = authenticate(userName, credentials, applicationName, domains, this.securityHelper, onlyAllowPassthrough);
+ loginContext = membership.getLoginContext();
+ userName = membership.getUserName();
+ securityDomain = membership.getSecurityDomain();
+ securityContext = membership.getSecurityContext();
+ }
+
+ long creationTime = System.currentTimeMillis();
+
+ // Return a new session info object
+ SessionMetadata newSession = new SessionMetadata();
+ newSession.setSessionToken(new SessionToken(userName));
+ newSession.setSessionId(newSession.getSessionToken().getSessionID());
+ newSession.setUserName(userName);
+ newSession.setCreatedTime(creationTime);
+ 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());
+ newSession.setVDBVersion(vdb.getVersion());
+ }
+
+ // these are local no need for monitoring.
+ newSession.setLoginContext(loginContext);
+ newSession.setSecurityContext(securityContext);
+ newSession.setVdb(vdb);
+ LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"Logon successful, created", newSession }); //$NON-NLS-1$
+ this.sessionCache.put(newSession.getSessionId(), newSession);
+ return newSession;
+ }
+
+ VDBMetaData getActiveVDB(String vdbName, String vdbVersion) throws SessionServiceException {
+ VDBMetaData vdb = null;
+
+ // handle the situation when the version is part of the vdb name.
+
+ int firstIndex = vdbName.indexOf('.');
+ int lastIndex = vdbName.lastIndexOf('.');
+ if (firstIndex != -1) {
+ if (firstIndex != lastIndex || vdbVersion != null) {
+ throw new SessionServiceException(RuntimePlugin.Util.getString("ambigious_name", vdbName, vdbVersion)); //$NON-NLS-1$
+ }
+ vdbVersion = vdbName.substring(firstIndex+1);
+ vdbName = vdbName.substring(0, firstIndex);
+ }
+
+ try {
+ if (vdbVersion == null) {
+ vdbVersion = "latest"; //$NON-NLS-1$
+ vdb = this.vdbRepository.getVDB(vdbName);
+ }
+ else {
+ vdb = this.vdbRepository.getVDB(vdbName, Integer.parseInt(vdbVersion));
+ }
+ } catch (NumberFormatException e) {
+ throw new SessionServiceException(e, RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._3", vdbVersion)); //$NON-NLS-1$
+ }
+
+ if (vdb == null) {
+ throw new SessionServiceException(RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._1", vdbName, vdbVersion)); //$NON-NLS-1$
+ }
+
+ if (vdb.getStatus() != VDB.Status.ACTIVE) {
+ throw new SessionServiceException(RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._2", vdbName, vdbVersion)); //$NON-NLS-1$
+ }
+ if (vdb.getConnectionType() == ConnectionType.NONE) {
+ throw new SessionServiceException(RuntimePlugin.Util.getString("VDBService.VDB_does_not_exist._4", vdbName, vdbVersion)); //$NON-NLS-1$
+ }
+ return vdb;
+ }
+
+ protected TeiidLoginContext authenticate(String userName, Credentials credentials, String applicationName, List<String> domains, SecurityHelper helper, boolean onlyallowPassthrough)
+ throws LoginException {
+ TeiidLoginContext membership = new TeiidLoginContext(helper);
+ membership.authenticateUser(userName, credentials, applicationName, domains, onlyallowPassthrough);
+ return membership;
+ }
+
+ @Override
+ public Collection<SessionMetadata> getActiveSessions() throws SessionServiceException {
+ return new ArrayList<SessionMetadata>(this.sessionCache.values());
+ }
+
+ @Override
+ public SessionMetadata getActiveSession(String sessionID) {
+ return this.sessionCache.get(sessionID);
+ }
+
+ @Override
+ public int getActiveSessionsCount() throws SessionServiceException{
+ return this.sessionCache.size();
+ }
+
+ @Override
+ public Collection<SessionMetadata> getSessionsLoggedInToVDB(String VDBName, int vdbVersion)
+ throws SessionServiceException {
+ if (VDBName == null || vdbVersion <= 0) {
+ return Collections.emptyList();
+ }
+ ArrayList<SessionMetadata> results = new ArrayList<SessionMetadata>();
+ for (SessionMetadata info : this.sessionCache.values()) {
+ if (VDBName.equalsIgnoreCase(info.getVDBName()) && vdbVersion == info.getVDBVersion()) {
+ results.add(info);
+ }
+ }
+ return results;
+ }
+
+ @Override
+ public void pingServer(String sessionID) throws InvalidSessionException {
+ SessionMetadata info = getSessionInfo(sessionID);
+ info.setLastPingTime(System.currentTimeMillis());
+ this.sessionCache.put(sessionID, info);
+ LogManager.logDetail(LogConstants.CTX_SECURITY, "Keep-alive ping received for session:", sessionID); //$NON-NLS-1$
+ }
+
+ @Override
+ public boolean terminateSession(String terminatedSessionID, String adminSessionID) {
+ Object[] params = {adminSessionID, terminatedSessionID};
+ LogManager.logInfo(LogConstants.CTX_SECURITY, RuntimePlugin.Util.getString( "SessionServiceImpl.terminateSession", params)); //$NON-NLS-1$
+ try {
+ closeSession(terminatedSessionID);
+ return true;
+ } catch (InvalidSessionException e) {
+ LogManager.logWarning(LogConstants.CTX_SECURITY,e,RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", new Object[] {e.getMessage()})); //$NON-NLS-1$
+ return false;
+ }
+ }
+
+ @Override
+ public SessionMetadata validateSession(String sessionID) throws InvalidSessionException, SessionServiceException {
+ SessionMetadata info = getSessionInfo(sessionID);
+ return info;
+ }
+
+ private SessionMetadata getSessionInfo(String sessionID)
+ throws InvalidSessionException {
+ if (sessionID == null) {
+ throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
+ }
+ SessionMetadata info = this.sessionCache.get(sessionID);
+ if (info == null) {
+ throw new InvalidSessionException(RuntimePlugin.Util.getString("SessionServiceImpl.invalid_session", sessionID)); //$NON-NLS-1$
+ }
+ return info;
+ }
+
+ @ManagementProperty (description="Maximum number of sessions allowed by the system (default 5000)")
+ public long getSessionMaxLimit() {
+ return this.sessionMaxLimit;
+ }
+
+ public void setSessionMaxLimit(long limit) {
+ this.sessionMaxLimit = limit;
+ }
+
+ @ManagementProperty(description="Max allowed time before the session is terminated by the system, 0 indicates unlimited (default 0)")
+ public long getSessionExpirationTimeLimit() {
+ return this.sessionExpirationTimeLimit;
+ }
+
+ public void setSessionExpirationTimeLimit(long limit) {
+ this.sessionExpirationTimeLimit = limit;
+ }
+
+ public void setSecurityDomains(String domainNameOrder) {
+ if (domainNameOrder != null && domainNameOrder.trim().length()>0) {
+ LogManager.logInfo(LogConstants.CTX_SECURITY, "Security Enabled: true"); //$NON-NLS-1$
+
+ String[] domainNames = domainNameOrder.split(","); //$NON-NLS-1$
+ for (String domainName : domainNames) {
+ this.securityDomains.addLast(domainName);
+ }
+ }
+ }
+
+ public void setAdminSecurityDomain(String domain) {
+ this.adminSecurityDomains.add(domain);
+ LogManager.logInfo(LogConstants.CTX_SECURITY, "Admin Security Enabled: true"); //$NON-NLS-1$
+ }
+
+ public void start() {
+ this.sessionMonitor.schedule(new TimerTask() {
+ @Override
+ public void run() {
+ monitorSessions();
+ }
+ }, 0, ServerConnection.PING_INTERVAL * 5);
+ }
+
+ public void stop(){
+ this.sessionMonitor.cancel();
+ this.sessionCache.clear();
+ }
+
+ public void setVDBRepository(VDBRepository repo) {
+ this.vdbRepository = repo;
+ }
+
+ public void setSecurityHelper(SecurityHelper securityHelper) {
+ this.securityHelper = securityHelper;
+ }
+
+ public void setDqp(DQPCore dqp) {
+ this.dqp = dqp;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,261 +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.services;
-
-import java.io.IOException;
-import java.security.Principal;
-import java.security.acl.Group;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-
-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.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.runtime.RuntimePlugin;
-import org.teiid.security.Credentials;
-import org.teiid.security.SecurityHelper;
-
-
-/**
- * This class serves as the primary implementation of the
- * Membership Service. Based on the security domains specified this class delegates the responsibility of
- * authenticating user to those security domains in the order they are defined.
- */
-public class TeiidLoginContext {
- public static final String AT = "@"; //$NON-NLS-1$
- private LoginContext loginContext;
- private String userName;
- private String securitydomain;
- private Object credentials;
- private SecurityHelper securityHelper;
-
- public TeiidLoginContext(SecurityHelper helper) {
- this.securityHelper = helper;
- }
-
- public void authenticateUser(String username, final Credentials credential,
- String applicationName, List<String> domains, boolean onlyallowPassthrough)
- throws LoginException {
-
- LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"authenticateUser", username, applicationName}); //$NON-NLS-1$
-
- final String baseUsername = getBaseUsername(username);
-
- if (onlyallowPassthrough) {
- for (String domain:getDomainsForUser(domains, username)) {
- Subject existing = this.securityHelper.getSubjectInContext(domain);
- if (existing != null) {
- this.userName = getUserName(existing)+AT+domain;
- this.securitydomain = domain;
- this.loginContext = createLoginContext(domain, existing);
- return;
- }
- }
- throw new LoginException(RuntimePlugin.Util.getString("no_passthrough_identity_found")); //$NON-NLS-1$
- }
-
-
- // If username specifies a domain (user at domain) only that domain is authenticated against.
- // If username specifies no domain, then all domains are tried in order.
- for (String domain:getDomainsForUser(domains, username)) {
-
- try {
- 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(baseUsername);
- } else if (callbacks[i] instanceof PasswordCallback) {
- PasswordCallback pc = (PasswordCallback)callbacks[i];
- char[] password = null;
- if (credential != null) {
- password = credential.getCredentialsAsCharArray();
- }
- pc.setPassword(password);
- credentials = password;
- } else {
- throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback"); //$NON-NLS-1$
- }
- }
- }
- };
-
- // this is the configured login for teiid
- this.loginContext = createLoginContext(domain,handler);
- this.loginContext.login();
- this.userName = baseUsername+AT+domain;
- this.securitydomain = domain;
- LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"Logon successful for \"", username, "\""}); //$NON-NLS-1$ //$NON-NLS-2$
- return;
- } catch (LoginException e) {
- LogManager.logDetail(LogConstants.CTX_SECURITY,e, e.getMessage());
- }
- }
- throw new LoginException(RuntimePlugin.Util.getString("SessionServiceImpl.The_username_0_and/or_password_are_incorrect", username )); //$NON-NLS-1$
- }
-
- private String getUserName(Subject subject) {
- Set<Principal> principals = subject.getPrincipals();
- for (Principal p:principals) {
- if (p instanceof Group) {
- continue;
- }
- return p.getName();
- }
- return null;
- }
-
- protected LoginContext createLoginContext(String domain, CallbackHandler handler) throws LoginException {
- return new LoginContext(domain, handler);
- }
-
- protected LoginContext createLoginContext(String domain, Subject subject) throws LoginException {
- return new LoginContext(domain, subject);
- }
-
- public LoginContext getLoginContext() {
- return this.loginContext;
- }
-
- public String getUserName() {
- return this.userName;
- }
-
- public String getSecurityDomain() {
- return this.securitydomain;
- }
-
- public Object getSecurityContext() {
- Object sc = null;
- if (this.loginContext != null) {
- sc = this.securityHelper.getSecurityContext(this.securitydomain);
- if ( sc == null){
- Subject subject = this.loginContext.getSubject();
- Principal principal = null;
- for(Principal p:subject.getPrincipals()) {
- if (this.userName.startsWith(p.getName())) {
- principal = p;
- break;
- }
- }
- return this.securityHelper.createSecurityContext(this.securitydomain, principal, credentials, subject);
- }
- }
- return sc;
- }
-
- static String getBaseUsername(String username) {
- if (username == null) {
- return username;
- }
-
- int index = getQualifierIndex(username);
-
- String result = username;
-
- if (index != -1) {
- result = username.substring(0, index);
- }
-
- //strip the escape character from the remaining ats
- return result.replaceAll("\\\\"+AT, AT); //$NON-NLS-1$
- }
-
- static String escapeName(String name) {
- if (name == null) {
- return name;
- }
-
- return name.replaceAll(AT, "\\\\"+AT); //$NON-NLS-1$
- }
-
- static String getDomainName(String username) {
- if (username == null) {
- return username;
- }
-
- int index = getQualifierIndex(username);
-
- if (index != -1) {
- return username.substring(index + 1);
- }
-
- return null;
- }
-
- static int getQualifierIndex(String username) {
- int index = username.length();
- while ((index = username.lastIndexOf(AT, --index)) != -1) {
- if (index > 0 && username.charAt(index - 1) != '\\') {
- return index;
- }
- }
-
- return -1;
- }
-
- private Collection<String> getDomainsForUser(List<String> domains, String username) {
- // If username is null, return all domains
- if (username == null) {
- return domains;
- }
-
- String domain = getDomainName(username);
-
- if (domain == null) {
- return domains;
- }
-
- // ------------------------------------------
- // Handle usernames having @ sign
- // ------------------------------------------
- String domainHolder = null;
- for (String d:domains) {
- if(d.equalsIgnoreCase(domain)) {
- domainHolder = d;
- break;
- }
- }
-
- if (domainHolder == null) {
- return Collections.emptyList();
- }
-
- LinkedList<String> result = new LinkedList<String>();
- result.add(domainHolder);
- return result;
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java (from rev 3218, trunk/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,260 @@
+/*
+ * 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.services;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+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.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.runtime.RuntimePlugin;
+import org.teiid.security.Credentials;
+import org.teiid.security.SecurityHelper;
+
+
+/**
+ * This class serves as the primary implementation of the
+ * Membership Service. Based on the security domains specified this class delegates the responsibility of
+ * authenticating user to those security domains in the order they are defined.
+ */
+public class TeiidLoginContext {
+ public static final String AT = "@"; //$NON-NLS-1$
+ private LoginContext loginContext;
+ private String userName;
+ private String securitydomain;
+ private Object credentials;
+ private SecurityHelper securityHelper;
+
+ public TeiidLoginContext(SecurityHelper helper) {
+ this.securityHelper = helper;
+ }
+
+ public void authenticateUser(String username, final Credentials credential,
+ String applicationName, List<String> domains, boolean onlyallowPassthrough)
+ throws LoginException {
+
+ LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"authenticateUser", username, applicationName}); //$NON-NLS-1$
+
+ final String baseUsername = getBaseUsername(username);
+
+ if (onlyallowPassthrough) {
+ for (String domain:getDomainsForUser(domains, username)) {
+ Subject existing = this.securityHelper.getSubjectInContext(domain);
+ if (existing != null) {
+ this.userName = getUserName(existing)+AT+domain;
+ this.securitydomain = domain;
+ this.loginContext = createLoginContext(domain, existing);
+ return;
+ }
+ }
+ throw new LoginException(RuntimePlugin.Util.getString("no_passthrough_identity_found")); //$NON-NLS-1$
+ }
+
+
+ // If username specifies a domain (user at domain) only that domain is authenticated against.
+ // If username specifies no domain, then all domains are tried in order.
+ for (String domain:getDomainsForUser(domains, username)) {
+
+ try {
+ 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(baseUsername);
+ } else if (callbacks[i] instanceof PasswordCallback) {
+ PasswordCallback pc = (PasswordCallback)callbacks[i];
+ char[] password = null;
+ if (credential != null) {
+ password = credential.getCredentialsAsCharArray();
+ }
+ pc.setPassword(password);
+ credentials = password;
+ } else {
+ throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback"); //$NON-NLS-1$
+ }
+ }
+ }
+ };
+
+ // this is the configured login for teiid
+ this.loginContext = createLoginContext(domain,handler);
+ this.loginContext.login();
+ this.userName = baseUsername+AT+domain;
+ this.securitydomain = domain;
+ return;
+ } catch (LoginException e) {
+ LogManager.logDetail(LogConstants.CTX_SECURITY,e, e.getMessage());
+ }
+ }
+ throw new LoginException(RuntimePlugin.Util.getString("SessionServiceImpl.The_username_0_and/or_password_are_incorrect", username )); //$NON-NLS-1$
+ }
+
+ private String getUserName(Subject subject) {
+ Set<Principal> principals = subject.getPrincipals();
+ for (Principal p:principals) {
+ if (p instanceof Group) {
+ continue;
+ }
+ return p.getName();
+ }
+ return null;
+ }
+
+ protected LoginContext createLoginContext(String domain, CallbackHandler handler) throws LoginException {
+ return new LoginContext(domain, handler);
+ }
+
+ protected LoginContext createLoginContext(String domain, Subject subject) throws LoginException {
+ return new LoginContext(domain, subject);
+ }
+
+ public LoginContext getLoginContext() {
+ return this.loginContext;
+ }
+
+ public String getUserName() {
+ return this.userName;
+ }
+
+ public String getSecurityDomain() {
+ return this.securitydomain;
+ }
+
+ public Object getSecurityContext() {
+ Object sc = null;
+ if (this.loginContext != null) {
+ sc = this.securityHelper.getSecurityContext(this.securitydomain);
+ if ( sc == null){
+ Subject subject = this.loginContext.getSubject();
+ Principal principal = null;
+ for(Principal p:subject.getPrincipals()) {
+ if (this.userName.startsWith(p.getName())) {
+ principal = p;
+ break;
+ }
+ }
+ return this.securityHelper.createSecurityContext(this.securitydomain, principal, credentials, subject);
+ }
+ }
+ return sc;
+ }
+
+ static String getBaseUsername(String username) {
+ if (username == null) {
+ return username;
+ }
+
+ int index = getQualifierIndex(username);
+
+ String result = username;
+
+ if (index != -1) {
+ result = username.substring(0, index);
+ }
+
+ //strip the escape character from the remaining ats
+ return result.replaceAll("\\\\"+AT, AT); //$NON-NLS-1$
+ }
+
+ static String escapeName(String name) {
+ if (name == null) {
+ return name;
+ }
+
+ return name.replaceAll(AT, "\\\\"+AT); //$NON-NLS-1$
+ }
+
+ static String getDomainName(String username) {
+ if (username == null) {
+ return username;
+ }
+
+ int index = getQualifierIndex(username);
+
+ if (index != -1) {
+ return username.substring(index + 1);
+ }
+
+ return null;
+ }
+
+ static int getQualifierIndex(String username) {
+ int index = username.length();
+ while ((index = username.lastIndexOf(AT, --index)) != -1) {
+ if (index > 0 && username.charAt(index - 1) != '\\') {
+ return index;
+ }
+ }
+
+ return -1;
+ }
+
+ private Collection<String> getDomainsForUser(List<String> domains, String username) {
+ // If username is null, return all domains
+ if (username == null) {
+ return domains;
+ }
+
+ String domain = getDomainName(username);
+
+ if (domain == null) {
+ return domains;
+ }
+
+ // ------------------------------------------
+ // Handle usernames having @ sign
+ // ------------------------------------------
+ String domainHolder = null;
+ for (String d:domains) {
+ if(d.equalsIgnoreCase(domain)) {
+ domainHolder = d;
+ break;
+ }
+ }
+
+ if (domainHolder == null) {
+ return Collections.emptyList();
+ }
+
+ LinkedList<String> result = new LinkedList<String>();
+ result.add(domainHolder);
+ return result;
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/LogonImpl.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/LogonImpl.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/LogonImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,151 +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.transport;
-
-import java.util.Collection;
-import java.util.Properties;
-
-import javax.security.auth.login.LoginException;
-
-import org.teiid.adminapi.impl.SessionMetadata;
-import org.teiid.client.security.ILogon;
-import org.teiid.client.security.InvalidSessionException;
-import org.teiid.client.security.LogonException;
-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;
-import org.teiid.dqp.service.SessionService;
-import org.teiid.dqp.service.SessionServiceException;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.net.CommunicationException;
-import org.teiid.net.TeiidURL;
-import org.teiid.security.Credentials;
-
-
-public class LogonImpl implements ILogon {
-
- private SessionService service;
- private String clusterName;
-
- public LogonImpl(SessionService service, String clusterName) {
- this.service = service;
- this.clusterName = clusterName;
- }
-
- public LogonResult logon(Properties connProps) throws LogonException,
- ComponentNotFoundException {
- DQPWorkContext workContext = DQPWorkContext.getWorkContext();
- SessionToken oldToken = workContext.getSessionToken();
- 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);
- // password may be null if using trustedToken to log on
- String password = connProps.getProperty(TeiidURL.CONNECTION.PASSWORD);
- Credentials credential = null;
- if (password != null) {
- credential = new Credentials(password.toCharArray());
- }
-
- boolean adminConnection = Boolean.parseBoolean(connProps.getProperty(TeiidURL.CONNECTION.ADMIN));
- try {
- SessionMetadata sessionInfo = service.createSession(user,credential, applicationName, connProps, adminConnection, true);
- updateDQPContext(sessionInfo);
- if (DQPWorkContext.getWorkContext().getClientAddress() == null) {
- sessionInfo.setEmbedded(true);
- }
- if (oldToken != null) {
- try {
- this.service.closeSession(oldToken.getSessionID());
- } catch (InvalidSessionException e) {
- }
- }
- return new LogonResult(sessionInfo.getSessionToken(), sessionInfo.getVDBName(), sessionInfo.getVDBVersion(), clusterName);
- } catch (LoginException e) {
- throw new LogonException(e.getMessage());
- } catch (SessionServiceException e) {
- throw new LogonException(e, e.getMessage());
- }
- }
-
- private String updateDQPContext(SessionMetadata s) {
- String sessionID = s.getSessionId();
-
- DQPWorkContext workContext = DQPWorkContext.getWorkContext();
- workContext.setSession(s);
- return sessionID;
- }
-
- public ResultsFuture<?> logoff() throws InvalidSessionException {
- this.service.closeSession(DQPWorkContext.getWorkContext().getSessionId());
- DQPWorkContext.getWorkContext().getSession().setSessionId(null);
- return ResultsFuture.NULL_FUTURE;
- }
-
- public ResultsFuture<?> ping() throws InvalidSessionException,TeiidComponentException {
- // ping is double used to alert the aliveness of the client, as well as check the server instance is
- // alive by socket server instance, so that they can be cached.
- String id = DQPWorkContext.getWorkContext().getSessionId();
- if (id != null) {
- this.service.pingServer(id);
- }
- LogManager.logTrace(LogConstants.CTX_SECURITY, "Ping", id); //$NON-NLS-1$
- return ResultsFuture.NULL_FUTURE;
- }
-
- @Override
- public ResultsFuture<?> ping(Collection<String> sessions)
- throws TeiidComponentException, CommunicationException {
- for (String string : sessions) {
- try {
- this.service.pingServer(string);
- } catch (InvalidSessionException e) {
- }
- }
- return ResultsFuture.NULL_FUTURE;
- }
-
- @Override
- public void assertIdentity(SessionToken checkSession) throws InvalidSessionException, TeiidComponentException {
- SessionMetadata sessionInfo = null;
- try {
- sessionInfo = this.service.validateSession(checkSession.getSessionID());
- } catch (SessionServiceException e) {
- throw new TeiidComponentException(e);
- }
-
- if (sessionInfo == null) {
- throw new InvalidSessionException();
- }
-
- SessionToken st = sessionInfo.getSessionToken();
- if (!st.equals(checkSession)) {
- throw new InvalidSessionException();
- }
- this.updateDQPContext(sessionInfo);
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/LogonImpl.java (from rev 3218, trunk/runtime/src/main/java/org/teiid/transport/LogonImpl.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/LogonImpl.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/LogonImpl.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,151 @@
+/*
+ * 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.transport;
+
+import java.util.Collection;
+import java.util.Properties;
+
+import javax.security.auth.login.LoginException;
+
+import org.teiid.adminapi.impl.SessionMetadata;
+import org.teiid.client.security.ILogon;
+import org.teiid.client.security.InvalidSessionException;
+import org.teiid.client.security.LogonException;
+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;
+import org.teiid.dqp.service.SessionService;
+import org.teiid.dqp.service.SessionServiceException;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.net.CommunicationException;
+import org.teiid.net.TeiidURL;
+import org.teiid.security.Credentials;
+
+
+public class LogonImpl implements ILogon {
+
+ private SessionService service;
+ private String clusterName;
+
+ public LogonImpl(SessionService service, String clusterName) {
+ this.service = service;
+ this.clusterName = clusterName;
+ }
+
+ public LogonResult logon(Properties connProps) throws LogonException,
+ ComponentNotFoundException {
+ DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+ 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);
+ // password may be null if using trustedToken to log on
+ String password = connProps.getProperty(TeiidURL.CONNECTION.PASSWORD);
+ Credentials credential = null;
+ if (password != null) {
+ credential = new Credentials(password.toCharArray());
+ }
+
+ boolean adminConnection = Boolean.parseBoolean(connProps.getProperty(TeiidURL.CONNECTION.ADMIN));
+ try {
+ SessionMetadata sessionInfo = service.createSession(user,credential, applicationName, connProps, adminConnection, true);
+ updateDQPContext(sessionInfo);
+ if (DQPWorkContext.getWorkContext().getClientAddress() == null) {
+ sessionInfo.setEmbedded(true);
+ }
+ if (oldSessionId != null) {
+ try {
+ this.service.closeSession(oldSessionId);
+ } catch (InvalidSessionException e) {
+ }
+ }
+ return new LogonResult(sessionInfo.getSessionToken(), sessionInfo.getVDBName(), sessionInfo.getVDBVersion(), clusterName);
+ } catch (LoginException e) {
+ throw new LogonException(e.getMessage());
+ } catch (SessionServiceException e) {
+ throw new LogonException(e, e.getMessage());
+ }
+ }
+
+ private String updateDQPContext(SessionMetadata s) {
+ String sessionID = s.getSessionId();
+
+ DQPWorkContext workContext = DQPWorkContext.getWorkContext();
+ workContext.setSession(s);
+ return sessionID;
+ }
+
+ public ResultsFuture<?> logoff() throws InvalidSessionException {
+ this.service.closeSession(DQPWorkContext.getWorkContext().getSessionId());
+ DQPWorkContext.getWorkContext().getSession().setSessionId(null);
+ return ResultsFuture.NULL_FUTURE;
+ }
+
+ public ResultsFuture<?> ping() throws InvalidSessionException,TeiidComponentException {
+ // ping is double used to alert the aliveness of the client, as well as check the server instance is
+ // alive by socket server instance, so that they can be cached.
+ String id = DQPWorkContext.getWorkContext().getSessionId();
+ if (id != null) {
+ this.service.pingServer(id);
+ }
+ LogManager.logTrace(LogConstants.CTX_SECURITY, "Ping", id); //$NON-NLS-1$
+ return ResultsFuture.NULL_FUTURE;
+ }
+
+ @Override
+ public ResultsFuture<?> ping(Collection<String> sessions)
+ throws TeiidComponentException, CommunicationException {
+ for (String string : sessions) {
+ try {
+ this.service.pingServer(string);
+ } catch (InvalidSessionException e) {
+ }
+ }
+ return ResultsFuture.NULL_FUTURE;
+ }
+
+ @Override
+ public void assertIdentity(SessionToken checkSession) throws InvalidSessionException, TeiidComponentException {
+ SessionMetadata sessionInfo = null;
+ try {
+ sessionInfo = this.service.validateSession(checkSession.getSessionID());
+ } catch (SessionServiceException e) {
+ throw new TeiidComponentException(e);
+ }
+
+ if (sessionInfo == null) {
+ throw new InvalidSessionException();
+ }
+
+ SessionToken st = sessionInfo.getSessionToken();
+ if (!st.equals(checkSession)) {
+ throw new InvalidSessionException();
+ }
+ this.updateDQPContext(sessionInfo);
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,90 +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.transport;
-
-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.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.socket.ObjectChannel;
-import org.teiid.odbc.ODBCServerRemote;
-
-public class ODBCSocketListener extends SocketListener {
- private ODBCServerRemote.AuthenticationType authType = ODBCServerRemote.AuthenticationType.CLEARTEXT;
- private int maxLobSize;
- private TeiidDriver driver;
-
- public ODBCSocketListener(SocketConfiguration config, StorageManager storageManager, int portOffset, int maxLobSize) {
- //the clientserviceregistry isn't actually used by ODBC
- super(config, new ClientServiceRegistryImpl(ClientServiceRegistry.Type.ODBC), storageManager, portOffset);
- this.maxLobSize = maxLobSize;
- this.driver = new TeiidDriver();
- this.driver.setEmbeddedProfile(new EmbeddedProfile() {
- @Override
- protected ServerConnection createServerConnection(Properties info)
- throws TeiidException {
- //When using the non-blocking api, we don't want to use the calling thread
- return new LocalServerConnection(info, false);
- }
- });
- }
-
- public void setDriver(TeiidDriver driver) {
- this.driver = driver;
- }
-
- @Override
- protected SSLAwareChannelHandler createChannelPipelineFactory(final SSLConfiguration config, final StorageManager storageManager) {
- return new SSLAwareChannelHandler(this, config, Thread.currentThread().getContextClassLoader(), storageManager) {
- 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("handler", this); //$NON-NLS-1$
- return pipeline;
- }
- };
- }
-
- @Override
- public ChannelListener createChannelListener(ObjectChannel channel) {
- return new ODBCClientInstance(channel, this.authType, driver);
- }
-
- public void setAuthenticationType(String value) {
- this.authType = ODBCServerRemote.AuthenticationType.valueOf(value);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java (from rev 3218, trunk/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,83 @@
+/*
+ * 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.transport;
+
+import java.util.Properties;
+
+import org.jboss.netty.channel.ChannelPipeline;
+import org.jboss.netty.channel.DefaultChannelPipeline;
+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.socket.ObjectChannel;
+import org.teiid.odbc.ODBCServerRemote;
+
+public class ODBCSocketListener extends SocketListener {
+ private ODBCServerRemote.AuthenticationType authType = ODBCServerRemote.AuthenticationType.CLEARTEXT;
+ private int maxLobSize;
+ private TeiidDriver driver;
+
+ public ODBCSocketListener(SocketConfiguration config, StorageManager storageManager, int portOffset, int maxLobSize) {
+ //the clientserviceregistry isn't actually used by ODBC
+ super(config, new ClientServiceRegistryImpl(ClientServiceRegistry.Type.ODBC), storageManager, portOffset);
+ this.maxLobSize = maxLobSize;
+ this.driver = new TeiidDriver();
+ this.driver.setEmbeddedProfile(new EmbeddedProfile() {
+ @Override
+ protected ServerConnection createServerConnection(Properties info)
+ throws TeiidException {
+ //When using the non-blocking api, we don't want to use the calling thread
+ return new LocalServerConnection(info, false);
+ }
+ });
+ }
+
+ public void setDriver(TeiidDriver driver) {
+ this.driver = driver;
+ }
+
+ @Override
+ protected SSLAwareChannelHandler createChannelPipelineFactory(final SSLConfiguration config, final StorageManager storageManager) {
+ return new SSLAwareChannelHandler(this, config, Thread.currentThread().getContextClassLoader(), storageManager) {
+ public ChannelPipeline getPipeline() throws Exception {
+ ChannelPipeline pipeline = new DefaultChannelPipeline();
+
+ pipeline.addLast("odbcFrontendProtocol", new PgFrontendProtocol(1 << 20)); //$NON-NLS-1$
+ pipeline.addLast("odbcBackendProtocol", new PgBackendProtocol(maxLobSize, config)); //$NON-NLS-1$
+ pipeline.addLast("handler", this); //$NON-NLS-1$
+ return pipeline;
+ }
+ };
+ }
+
+ @Override
+ public ChannelListener createChannelListener(ObjectChannel channel) {
+ return new ODBCClientInstance(channel, this.authType, driver);
+ }
+
+ public void setAuthenticationType(String value) {
+ this.authType = ODBCServerRemote.AuthenticationType.valueOf(value);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/PgBackendProtocol.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/PgBackendProtocol.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/PgBackendProtocol.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,863 +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.transport;
-
-import java.io.ByteArrayOutputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.io.StreamCorruptedException;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.nio.charset.Charset;
-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 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.ChannelHandlerContext;
-import org.jboss.netty.channel.Channels;
-import org.jboss.netty.channel.MessageEvent;
-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.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
- */
- at SuppressWarnings("nls")
-public class PgBackendProtocol implements ChannelDownstreamHandler, ODBCClientRemote {
-
- 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 ResultsWorkItem(List<PgColInfo> cols, String sql,
- ResultSetImpl rs, ResultsFuture<Void> result) {
- this.cols = cols;
- this.sql = sql;
- this.rs = rs;
- this.result = result;
- }
-
- @Override
- public void run() {
- while (true) {
- try {
- nextFuture = rs.submitNext();
- if (!nextFuture.isDone()) {
- nextFuture.addCompletionListener(new ResultsFuture.CompletionListener<Boolean>() {
- @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();
- }
- }
- });
- return;
- }
- if (!processRow(nextFuture)) {
- break;
- }
- } catch (Throwable t) {
- result.getResultsReceiver().exceptionOccurred(t);
- }
- }
- }
-
- private boolean processRow(ResultsFuture<Boolean> future) {
- nextFuture = null;
- boolean processNext = true;
- try {
- if (future.get()) {
- sendDataRow(rs, cols);
- } else {
- sendCommandComplete(sql, 0);
- result.getResultsReceiver().receiveResults(null);
- processNext = false;
- }
- } catch (Throwable t) {
- result.getResultsReceiver().exceptionOccurred(t);
- return false;
- }
- return processNext;
- }
- }
-
- 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;
- private Properties props;
- private Charset encoding = Charset.forName("UTF-8");
- private ReflectionHelper clientProxy = new ReflectionHelper(ODBCClientRemote.class);
- private ChannelHandlerContext ctx;
- private MessageEvent message;
- private int maxLobSize = (2*1024*1024); // 2 MB
-
- private volatile ResultsFuture<Boolean> nextFuture;
-
- public PgBackendProtocol(int maxLobSize) {
- this.maxLobSize = maxLobSize;
- }
-
- @Override
- public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
- if (!(evt instanceof MessageEvent)) {
- ctx.sendDownstream(evt);
- return;
- }
-
- MessageEvent me = (MessageEvent) evt;
- if (!(me.getMessage() instanceof ServiceInvocationStruct)) {
- ctx.sendDownstream(evt);
- return;
- }
- this.ctx = ctx;
- this.message = me;
- ServiceInvocationStruct serviceStruct = (ServiceInvocationStruct)me.getMessage();
-
- try {
- Method m = this.clientProxy.findBestMethodOnTarget(serviceStruct.methodName, serviceStruct.args);
- try {
- m.invoke(this, serviceStruct.args);
- } catch (InvocationTargetException e) {
- throw e.getCause();
- }
- } catch (Throwable e) {
- terminate(e);
- }
- }
-
- @Override
- public void initialized(Properties props) {
- this.props = props;
- setEncoding(props.getProperty("client_encoding", "UTF-8"));
- }
-
- @Override
- public void useClearTextAuthentication() {
- try {
- sendAuthenticationCleartextPassword();
- } catch (IOException e) {
- terminate(e);
- }
- }
-
- @Override
- public void authenticationSucess(int processId, int screctKey) {
- try {
- sendAuthenticationOk();
- // server_version, server_encoding, client_encoding, application_name,
- // is_superuser, session_authorization, DateStyle, IntervalStyle, TimeZone,
- // integer_datetimes, and standard_conforming_strings.
- // (server_encoding, TimeZone, and integer_datetimes were not reported
- // by releases before 8.0; standard_conforming_strings was not reported by
- // releases before 8.1; IntervalStyle was not reported by releases before 8.4;
- // application_name was not reported by releases before 9.0.)
-
- sendParameterStatus("client_encoding", PGCharsetConverter.getEncoding(this.encoding));
- sendParameterStatus("DateStyle", this.props.getProperty("DateStyle", "ISO"));
- sendParameterStatus("integer_datetimes", "off");
- sendParameterStatus("is_superuser", "off");
- sendParameterStatus("server_encoding", "SQL_ASCII");
- sendParameterStatus("server_version", "8.1.4");
- sendParameterStatus("session_authorization", this.props.getProperty("user"));
- sendParameterStatus("standard_conforming_strings", "off");
- sendParameterStatus("application_name", this.props.getProperty("application_name", "ODBCClient"));
-
- // TODO PostgreSQL TimeZone
- sendParameterStatus("TimeZone", "CET");
-
- sendBackendKeyData(processId, screctKey);
- } catch (IOException e) {
- terminate(e);
- }
- }
-
- @Override
- public void prepareCompleted(String preparedName) {
- sendParseComplete();
- }
-
- @Override
- public void bindComplete() {
- sendBindComplete();
- }
-
- @Override
- public void errorOccurred(String msg) {
- try {
- sendErrorResponse(msg);
- } catch (IOException e) {
- terminate(e);
- }
- }
-
- @Override
- public void errorOccurred(Throwable t) {
- try {
- sendErrorResponse(t);
- } catch (IOException e) {
- terminate(e);
- }
- }
-
- @Override
- public void ready(boolean inTransaction, boolean failedTransaction) {
- try {
- sendReadyForQuery(inTransaction, failedTransaction);
- } catch (IOException e) {
- terminate(e);
- }
- }
-
- public void setEncoding(String value) {
- Charset cs = PGCharsetConverter.getCharset(value);
- if (cs != null) {
- this.encoding = cs;
- }
- }
-
- @Override
- public void sendParameterDescription(ParameterMetaData meta, int[] paramType) {
- try {
- try {
- int count = meta.getParameterCount();
- startMessage('t');
- writeShort(count);
- for (int i = 0; i < count; i++) {
- int type;
- if (paramType != null && paramType[i] != 0) {
- type = paramType[i];
- } else {
- type = convertType(meta.getParameterType(i+1));
- }
- writeInt(type);
- }
- sendMessage();
- } catch (SQLException e) {
- sendErrorResponse(e);
- }
- } catch (IOException e) {
- terminate(e);
- }
- }
-
- @Override
- public void sendResultSetDescription(ResultSetMetaData metaData, Statement stmt) {
- try {
- try {
- List<PgColInfo> cols = getPgColInfo(metaData, stmt);
- sendRowDescription(cols);
- } catch (SQLException e) {
- sendErrorResponse(e);
- }
- } catch (IOException e) {
- terminate(e);
- }
- }
-
- @Override
- public void sendResults(final String sql, final ResultSetImpl rs, ResultsFuture<Void> 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);
- r.run();
- } catch (SQLException e) {
- result.getResultsReceiver().exceptionOccurred(e);
- } catch (IOException e) {
- terminate(e);
- }
- }
-
- @Override
- public void sendUpdateCount(String sql, int updateCount) {
- try {
- sendCommandComplete(sql, updateCount);
- } catch (IOException e) {
- terminate(e);
- }
- }
-
- @Override
- public void statementClosed() {
- startMessage('3');
- sendMessage();
- }
-
- @Override
- public void terminated() {
- try {
- trace("channel being terminated");
- this.sendNoticeResponse("Connection closed");
- this.ctx.getChannel().close();
- } catch (IOException e) {
- trace(e.getMessage());
- }
- }
-
- @Override
- public void flush() {
- try {
- this.dataOut.flush();
- this.dataOut = null;
- Channels.write(this.ctx.getChannel(), null);
- } catch (IOException e) {
- terminate(e);
- }
- }
-
- @Override
- public void emptyQueryReceived() {
- sendEmptyQueryResponse();
- }
-
- private void terminate(Throwable t) {
- trace("channel being terminated - ", t.getMessage());
- this.ctx.getChannel().close();
- }
-
- private void sendEmptyQueryResponse() {
- startMessage('I');
- sendMessage();
- }
-
- private void sendCommandComplete(String sql, int updateCount) throws IOException {
- startMessage('C');
- sql = sql.trim().toUpperCase();
- // TODO remove remarks at the beginning
- String tag;
- if (sql.startsWith("INSERT")) {
- tag = "INSERT 0 " + updateCount;
- } else if (sql.startsWith("DELETE")) {
- tag = "DELETE " + updateCount;
- } else if (sql.startsWith("UPDATE")) {
- tag = "UPDATE " + updateCount;
- } else if (sql.startsWith("SELECT") || sql.startsWith("CALL")) {
- tag = "SELECT";
- } else if (sql.startsWith("BEGIN")) {
- tag = "BEGIN";
- } else if (sql.startsWith("COMMIT")) {
- tag = "COMMIT";
- } else if (sql.startsWith("ROLLBACK")) {
- tag = "ROLLBACK";
- } else if (sql.startsWith("SET ")) {
- tag = "SET";
- }else {
- trace("Check command tag:", sql);
- tag = "UPDATE " + updateCount;
- }
- writeString(tag);
- sendMessage();
- }
-
- private void sendDataRow(ResultSet rs, List<PgColInfo> cols) throws SQLException, IOException {
- startMessage('D');
- writeShort(cols.size());
- for (int i = 0; i < cols.size(); i++) {
- byte[] bytes = getContent(rs, cols.get(i), i+1);
- if (bytes == null) {
- writeInt(-1);
- } else {
- writeInt(bytes.length);
- write(bytes);
- }
- }
- sendMessage();
- }
-
- private byte[] getContent(ResultSet rs, PgColInfo col, int column) throws SQLException, TeiidSQLException, IOException {
- byte[] bytes = null;
- switch (col.type) {
- case PG_TYPE_BOOL:
- case PG_TYPE_BPCHAR:
- case PG_TYPE_DATE:
- case PG_TYPE_FLOAT4:
- case PG_TYPE_FLOAT8:
- case PG_TYPE_INT2:
- case PG_TYPE_INT4:
- case PG_TYPE_INT8:
- case PG_TYPE_NUMERIC:
- case PG_TYPE_TIME:
- case PG_TYPE_TIMESTAMP_NO_TMZONE:
- case PG_TYPE_VARCHAR:
- String value = rs.getString(column);
- if (value != null) {
- bytes = value.getBytes(this.encoding);
- }
- break;
-
- case PG_TYPE_TEXT:
- Clob clob = rs.getClob(column);
- if (clob != null) {
- bytes = ObjectConverterUtil.convertToByteArray(new ReaderInputStream(clob.getCharacterStream(), this.encoding), this.maxLobSize);
- }
- break;
-
- case PG_TYPE_BYTEA:
- Blob blob = rs.getBlob(column);
- if (blob != null) {
- try {
- bytes = PGbytea.toPGString(ObjectConverterUtil.convertToByteArray(blob.getBinaryStream(), this.maxLobSize)).getBytes(this.encoding);
- } catch(OutOfMemoryError e) {
- throw new StreamCorruptedException("data too big: " + e.getMessage()); //$NON-NLS-1$
- }
- }
- break;
-
- case PG_TYPE_CHARARRAY:
- case PG_TYPE_TEXTARRAY:
- case PG_TYPE_OIDARRAY:
- {
- Object[] obj = (Object[])rs.getObject(column);
- if (obj != null) {
- StringBuilder sb = new StringBuilder();
- sb.append("{");
- boolean first = true;
- for (Object o:obj) {
- if (!first) {
- sb.append(",");
- }
- else {
- first = false;
- }
- if (col.type == PG_TYPE_TEXTARRAY) {
- escapeQuote(sb, o.toString());
- }
- else {
- sb.append(o.toString());
- }
- }
- sb.append("}");
- bytes = sb.toString().getBytes(this.encoding);
- }
- }
- break;
-
- case PG_TYPE_OIDVECTOR:
- {
- Object[] obj = (Object[])rs.getObject(column);
- if (obj != null) {
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- for (Object o:obj) {
- if (!first) {
- sb.append(" ");
- }
- else {
- first = false;
- }
- sb.append(o);
- }
- bytes = sb.toString().getBytes(this.encoding);
- }
- }
- break;
-
- default:
- throw new TeiidSQLException("unknown datatype failed to convert");
- }
- return bytes;
- }
-
- public static void escapeQuote(StringBuilder sb, String s) {
- sb.append('"');
- for (int i = 0; i < s.length(); i++) {
- char c = s.charAt(i);
- if (c == '"' || c == '\\') {
- sb.append('\\');
- }
-
- sb.append(c);
- }
- sb.append('"');
- }
-
- @Override
- public void sslDenied() {
- ChannelBuffer buffer = ChannelBuffers.directBuffer(1);
- buffer.writeByte('N');
- Channels.write(this.ctx, this.message.getFuture(), buffer, this.message.getRemoteAddress());
- }
-
- private void sendErrorResponse(Throwable t) throws IOException {
- trace(t.getMessage());
- SQLException e = TeiidSQLException.create(t);
- startMessage('E');
- write('S');
- writeString("ERROR");
- write('C');
- writeString(e.getSQLState());
- write('M');
- writeString(e.getMessage());
- write('D');
- writeString(e.toString());
- 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());
- for (PgColInfo info : cols) {
- writeString(info.name);
- // rel ID
- writeInt(info.reloid);
- // attribute number of the column
- writeShort(info.attnum);
- // data type
- writeInt(info.type);
- // pg_type.typlen
- writeShort(getTypeSize(info.type, info.precision));
- // pg_attribute.atttypmod
- writeInt(-1);
- // text
- writeShort(0);
- }
- 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:
- return Math.max(255, precision + 10);
- default:
- return precision + 4;
- }
- }
-
- private void sendErrorResponse(String message) throws IOException {
- trace("Exception:", message);
- startMessage('E');
- write('S');
- writeString("ERROR");
- write('C');
- // PROTOCOL VIOLATION
- writeString("08P01");
- write('M');
- writeString(message);
- sendMessage();
- }
-
- private void sendNoticeResponse(String message) throws IOException {
- trace("notice:", message);
- startMessage('N');
- write('S');
- writeString("ERROR");
- write('M');
- writeString(message);
- sendMessage();
- }
-
- private void sendParseComplete() {
- startMessage('1');
- sendMessage();
- }
-
- private void sendBindComplete() {
- startMessage('2');
- sendMessage();
- }
-
- private void sendAuthenticationCleartextPassword() throws IOException {
- startMessage('R');
- writeInt(3);
- sendMessage();
- }
-
- private void sendAuthenticationOk() throws IOException {
- startMessage('R');
- writeInt(0);
- sendMessage();
- }
-
- private void sendReadyForQuery(boolean inTransaction, boolean failedTransaction) throws IOException {
- startMessage('Z');
- char c;
- if (failedTransaction) {
- // failed transaction block
- c = 'E';
- }
- else {
- if (inTransaction) {
- // in a transaction block
- c = 'T';
- } else {
- // idle
- c = 'I';
- }
- }
- write((byte) c);
- sendMessage();
- }
-
- private void sendBackendKeyData(int processId, int screctKey) throws IOException {
- startMessage('K');
- writeInt(processId);
- writeInt(screctKey);
- sendMessage();
- }
-
- private void sendParameterStatus(String param, String value) throws IOException {
- startMessage('S');
- writeString(param);
- writeString(value);
- sendMessage();
- }
-
- @Override
- public void functionCallResponse(byte[] data) {
- try {
- startMessage('V');
- if (data == null) {
- writeInt(-1);
- }
- else {
- writeInt(data.length);
- write(data);
- }
- sendMessage();
- } catch (IOException e) {
- terminate(e);
- }
- }
-
- @Override
- public void functionCallResponse(int data) {
- try {
- startMessage('V');
- writeInt(4);
- writeInt(data);
- sendMessage();
- } catch (IOException e) {
- terminate(e);
- }
- }
-
- private void writeString(String s) throws IOException {
- write(s.getBytes(this.encoding));
- write(0);
- }
-
- private void writeInt(int i) throws IOException {
- dataOut.writeInt(i);
- }
-
- private void writeShort(int i) throws IOException {
- dataOut.writeShort(i);
- }
-
- private void write(byte[] data) throws IOException {
- dataOut.write(data);
- }
-
- private void write(int b) throws IOException {
- dataOut.write(b);
- }
-
- private void startMessage(char newMessageType) {
- this.messageType = newMessageType;
- this.outBuffer = new ByteArrayOutputStream();
- this.dataOut = new DataOutputStream(this.outBuffer);
- }
-
- private void sendMessage() {
- byte[] buff = outBuffer.toByteArray();
- int len = buff.length;
- this.outBuffer = null;
- this.dataOut = null;
-
- // now build the wire contents.
- ChannelBuffer buffer = ChannelBuffers.directBuffer(len+5);
- buffer.writeByte((byte)this.messageType);
- buffer.writeInt(len+4);
- buffer.writeBytes(buff);
- Channels.write(this.ctx, this.message.getFuture(), buffer, this.message.getRemoteAddress());
- }
-
- private static void trace(String... msg) {
- LogManager.logTrace(LogConstants.CTX_ODBC, (Object[])msg);
- }
-
- /**
- * Types.ARRAY is not supported
- */
- private 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;
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/PgBackendProtocol.java (from rev 3218, trunk/runtime/src/main/java/org/teiid/transport/PgBackendProtocol.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/PgBackendProtocol.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/java/org/teiid/transport/PgBackendProtocol.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,904 @@
+
+/*
+ * 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.transport;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.StreamCorruptedException;
+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.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
+ */
+ at SuppressWarnings("nls")
+public class PgBackendProtocol implements ChannelDownstreamHandler, ODBCClientRemote {
+
+ 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();
+ }
+ }
+ }
+
+ 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 ResultsWorkItem(List<PgColInfo> cols, String sql,
+ ResultSetImpl rs, ResultsFuture<Void> result) {
+ this.cols = cols;
+ this.sql = sql;
+ this.rs = rs;
+ this.result = result;
+ }
+
+ @Override
+ public void run() {
+ while (true) {
+ try {
+ nextFuture = rs.submitNext();
+ if (!nextFuture.isDone()) {
+ nextFuture.addCompletionListener(new ResultsFuture.CompletionListener<Boolean>() {
+ @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();
+ }
+ }
+ });
+ return;
+ }
+ if (!processRow(nextFuture)) {
+ break;
+ }
+ } catch (Throwable t) {
+ result.getResultsReceiver().exceptionOccurred(t);
+ }
+ }
+ }
+
+ private boolean processRow(ResultsFuture<Boolean> future) {
+ nextFuture = null;
+ boolean processNext = true;
+ try {
+ if (future.get()) {
+ sendDataRow(rs, cols);
+ } else {
+ sendCommandComplete(sql, 0);
+ result.getResultsReceiver().receiveResults(null);
+ processNext = false;
+ }
+ } catch (Throwable t) {
+ result.getResultsReceiver().exceptionOccurred(t);
+ return false;
+ }
+ return processNext;
+ }
+ }
+
+ 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;
+ private Properties props;
+ private Charset encoding = Charset.forName("UTF-8");
+ private ReflectionHelper clientProxy = new ReflectionHelper(ODBCClientRemote.class);
+ private ChannelHandlerContext ctx;
+ private MessageEvent message;
+ private int maxLobSize = (2*1024*1024); // 2 MB
+
+ private volatile ResultsFuture<Boolean> nextFuture;
+
+ private SSLConfiguration config;
+
+ public PgBackendProtocol(int maxLobSize, SSLConfiguration config) {
+ this.maxLobSize = maxLobSize;
+ this.config = config;
+ }
+
+ @Override
+ public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
+ if (!(evt instanceof MessageEvent)) {
+ ctx.sendDownstream(evt);
+ return;
+ }
+
+ MessageEvent me = (MessageEvent) evt;
+ if (!(me.getMessage() instanceof ServiceInvocationStruct)) {
+ ctx.sendDownstream(evt);
+ return;
+ }
+ this.ctx = ctx;
+ this.message = me;
+ ServiceInvocationStruct serviceStruct = (ServiceInvocationStruct)me.getMessage();
+
+ try {
+ Method m = this.clientProxy.findBestMethodOnTarget(serviceStruct.methodName, serviceStruct.args);
+ try {
+ m.invoke(this, serviceStruct.args);
+ } catch (InvocationTargetException e) {
+ throw e.getCause();
+ }
+ } catch (Throwable e) {
+ terminate(e);
+ }
+ }
+
+ @Override
+ public void initialized(Properties props) {
+ this.props = props;
+ setEncoding(props.getProperty("client_encoding", "UTF-8"));
+ }
+
+ @Override
+ public void useClearTextAuthentication() {
+ try {
+ sendAuthenticationCleartextPassword();
+ } catch (IOException e) {
+ terminate(e);
+ }
+ }
+
+ @Override
+ public void authenticationSucess(int processId, int screctKey) {
+ try {
+ sendAuthenticationOk();
+ // server_version, server_encoding, client_encoding, application_name,
+ // is_superuser, session_authorization, DateStyle, IntervalStyle, TimeZone,
+ // integer_datetimes, and standard_conforming_strings.
+ // (server_encoding, TimeZone, and integer_datetimes were not reported
+ // by releases before 8.0; standard_conforming_strings was not reported by
+ // releases before 8.1; IntervalStyle was not reported by releases before 8.4;
+ // application_name was not reported by releases before 9.0.)
+
+ sendParameterStatus("client_encoding", PGCharsetConverter.getEncoding(this.encoding));
+ sendParameterStatus("DateStyle", this.props.getProperty("DateStyle", "ISO"));
+ sendParameterStatus("integer_datetimes", "off");
+ sendParameterStatus("is_superuser", "off");
+ sendParameterStatus("server_encoding", "SQL_ASCII");
+ sendParameterStatus("server_version", "8.1.4");
+ sendParameterStatus("session_authorization", this.props.getProperty("user"));
+ sendParameterStatus("standard_conforming_strings", "off");
+ sendParameterStatus("application_name", this.props.getProperty("application_name", "ODBCClient"));
+
+ // TODO PostgreSQL TimeZone
+ sendParameterStatus("TimeZone", "CET");
+
+ sendBackendKeyData(processId, screctKey);
+ } catch (IOException e) {
+ terminate(e);
+ }
+ }
+
+ @Override
+ public void prepareCompleted(String preparedName) {
+ sendParseComplete();
+ }
+
+ @Override
+ public void bindComplete() {
+ sendBindComplete();
+ }
+
+ @Override
+ public void errorOccurred(String msg) {
+ try {
+ sendErrorResponse(msg);
+ } catch (IOException e) {
+ terminate(e);
+ }
+ }
+
+ @Override
+ public void errorOccurred(Throwable t) {
+ try {
+ sendErrorResponse(t);
+ } catch (IOException e) {
+ terminate(e);
+ }
+ }
+
+ @Override
+ public void ready(boolean inTransaction, boolean failedTransaction) {
+ try {
+ sendReadyForQuery(inTransaction, failedTransaction);
+ } catch (IOException e) {
+ terminate(e);
+ }
+ }
+
+ public void setEncoding(String value) {
+ Charset cs = PGCharsetConverter.getCharset(value);
+ if (cs != null) {
+ this.encoding = cs;
+ }
+ }
+
+ @Override
+ public void sendParameterDescription(ParameterMetaData meta, int[] paramType) {
+ try {
+ try {
+ int count = meta.getParameterCount();
+ startMessage('t');
+ writeShort(count);
+ for (int i = 0; i < count; i++) {
+ int type;
+ if (paramType != null && paramType[i] != 0) {
+ type = paramType[i];
+ } else {
+ type = convertType(meta.getParameterType(i+1));
+ }
+ writeInt(type);
+ }
+ sendMessage();
+ } catch (SQLException e) {
+ sendErrorResponse(e);
+ }
+ } catch (IOException e) {
+ terminate(e);
+ }
+ }
+
+ @Override
+ public void sendResultSetDescription(ResultSetMetaData metaData, Statement stmt) {
+ try {
+ try {
+ List<PgColInfo> cols = getPgColInfo(metaData, stmt);
+ sendRowDescription(cols);
+ } catch (SQLException e) {
+ sendErrorResponse(e);
+ }
+ } catch (IOException e) {
+ terminate(e);
+ }
+ }
+
+ @Override
+ public void sendResults(final String sql, final ResultSetImpl rs, ResultsFuture<Void> 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);
+ r.run();
+ } catch (SQLException e) {
+ result.getResultsReceiver().exceptionOccurred(e);
+ } catch (IOException e) {
+ terminate(e);
+ }
+ }
+
+ @Override
+ public void sendUpdateCount(String sql, int updateCount) {
+ try {
+ sendCommandComplete(sql, updateCount);
+ } catch (IOException e) {
+ terminate(e);
+ }
+ }
+
+ @Override
+ public void statementClosed() {
+ startMessage('3');
+ sendMessage();
+ }
+
+ @Override
+ public void terminated() {
+ try {
+ trace("channel being terminated");
+ this.sendNoticeResponse("Connection closed");
+ this.ctx.getChannel().close();
+ } catch (IOException e) {
+ trace(e.getMessage());
+ }
+ }
+
+ @Override
+ public void flush() {
+ try {
+ this.dataOut.flush();
+ this.dataOut = null;
+ Channels.write(this.ctx.getChannel(), null);
+ } catch (IOException e) {
+ terminate(e);
+ }
+ }
+
+ @Override
+ public void emptyQueryReceived() {
+ sendEmptyQueryResponse();
+ }
+
+ private void terminate(Throwable t) {
+ trace("channel being terminated - ", t.getMessage());
+ this.ctx.getChannel().close();
+ }
+
+ private void sendEmptyQueryResponse() {
+ startMessage('I');
+ sendMessage();
+ }
+
+ private void sendCommandComplete(String sql, int updateCount) throws IOException {
+ startMessage('C');
+ sql = sql.trim().toUpperCase();
+ // TODO remove remarks at the beginning
+ String tag;
+ if (sql.startsWith("INSERT")) {
+ tag = "INSERT 0 " + updateCount;
+ } else if (sql.startsWith("DELETE")) {
+ tag = "DELETE " + updateCount;
+ } else if (sql.startsWith("UPDATE")) {
+ tag = "UPDATE " + updateCount;
+ } else if (sql.startsWith("SELECT") || sql.startsWith("CALL")) {
+ tag = "SELECT";
+ } else if (sql.startsWith("BEGIN")) {
+ tag = "BEGIN";
+ } else if (sql.startsWith("COMMIT")) {
+ tag = "COMMIT";
+ } else if (sql.startsWith("ROLLBACK")) {
+ tag = "ROLLBACK";
+ } else if (sql.startsWith("SET ")) {
+ tag = "SET";
+ }else {
+ trace("Check command tag:", sql);
+ tag = "UPDATE " + updateCount;
+ }
+ writeString(tag);
+ sendMessage();
+ }
+
+ private void sendDataRow(ResultSet rs, List<PgColInfo> cols) throws SQLException, IOException {
+ startMessage('D');
+ writeShort(cols.size());
+ for (int i = 0; i < cols.size(); i++) {
+ byte[] bytes = getContent(rs, cols.get(i), i+1);
+ if (bytes == null) {
+ writeInt(-1);
+ } else {
+ writeInt(bytes.length);
+ write(bytes);
+ }
+ }
+ sendMessage();
+ }
+
+ private byte[] getContent(ResultSet rs, PgColInfo col, int column) throws SQLException, TeiidSQLException, IOException {
+ byte[] bytes = null;
+ switch (col.type) {
+ case PG_TYPE_BOOL:
+ case PG_TYPE_BPCHAR:
+ case PG_TYPE_DATE:
+ case PG_TYPE_FLOAT4:
+ case PG_TYPE_FLOAT8:
+ case PG_TYPE_INT2:
+ case PG_TYPE_INT4:
+ case PG_TYPE_INT8:
+ case PG_TYPE_NUMERIC:
+ case PG_TYPE_TIME:
+ case PG_TYPE_TIMESTAMP_NO_TMZONE:
+ case PG_TYPE_VARCHAR:
+ String value = rs.getString(column);
+ if (value != null) {
+ bytes = value.getBytes(this.encoding);
+ }
+ break;
+
+ case PG_TYPE_TEXT:
+ Clob clob = rs.getClob(column);
+ if (clob != null) {
+ bytes = ObjectConverterUtil.convertToByteArray(new ReaderInputStream(clob.getCharacterStream(), this.encoding), this.maxLobSize);
+ }
+ break;
+
+ case PG_TYPE_BYTEA:
+ Blob blob = rs.getBlob(column);
+ if (blob != null) {
+ try {
+ bytes = PGbytea.toPGString(ObjectConverterUtil.convertToByteArray(blob.getBinaryStream(), this.maxLobSize)).getBytes(this.encoding);
+ } catch(OutOfMemoryError e) {
+ throw new StreamCorruptedException("data too big: " + e.getMessage()); //$NON-NLS-1$
+ }
+ }
+ break;
+
+ case PG_TYPE_CHARARRAY:
+ case PG_TYPE_TEXTARRAY:
+ case PG_TYPE_OIDARRAY:
+ {
+ Object[] obj = (Object[])rs.getObject(column);
+ if (obj != null) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("{");
+ boolean first = true;
+ for (Object o:obj) {
+ if (!first) {
+ sb.append(",");
+ }
+ else {
+ first = false;
+ }
+ if (col.type == PG_TYPE_TEXTARRAY) {
+ escapeQuote(sb, o.toString());
+ }
+ else {
+ sb.append(o.toString());
+ }
+ }
+ sb.append("}");
+ bytes = sb.toString().getBytes(this.encoding);
+ }
+ }
+ break;
+
+ case PG_TYPE_OIDVECTOR:
+ {
+ Object[] obj = (Object[])rs.getObject(column);
+ if (obj != null) {
+ StringBuilder sb = new StringBuilder();
+ boolean first = true;
+ for (Object o:obj) {
+ if (!first) {
+ sb.append(" ");
+ }
+ else {
+ first = false;
+ }
+ sb.append(o);
+ }
+ bytes = sb.toString().getBytes(this.encoding);
+ }
+ }
+ break;
+
+ default:
+ throw new TeiidSQLException("unknown datatype failed to convert");
+ }
+ return bytes;
+ }
+
+ public static void escapeQuote(StringBuilder sb, String s) {
+ sb.append('"');
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ if (c == '"' || c == '\\') {
+ sb.append('\\');
+ }
+
+ sb.append(c);
+ }
+ sb.append('"');
+ }
+
+ @Override
+ 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);
+ 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 {
+ trace(t.getMessage());
+ SQLException e = TeiidSQLException.create(t);
+ startMessage('E');
+ write('S');
+ writeString("ERROR");
+ write('C');
+ writeString(e.getSQLState());
+ write('M');
+ writeString(e.getMessage());
+ write('D');
+ writeString(e.toString());
+ 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());
+ for (PgColInfo info : cols) {
+ writeString(info.name);
+ // rel ID
+ writeInt(info.reloid);
+ // attribute number of the column
+ writeShort(info.attnum);
+ // data type
+ writeInt(info.type);
+ // pg_type.typlen
+ writeShort(getTypeSize(info.type, info.precision));
+ // pg_attribute.atttypmod
+ writeInt(-1);
+ // text
+ writeShort(0);
+ }
+ 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:
+ return Math.max(255, precision + 10);
+ default:
+ return precision + 4;
+ }
+ }
+
+ private void sendErrorResponse(String message) throws IOException {
+ trace("Exception:", message);
+ startMessage('E');
+ write('S');
+ writeString("ERROR");
+ write('C');
+ // PROTOCOL VIOLATION
+ writeString("08P01");
+ write('M');
+ writeString(message);
+ sendMessage();
+ }
+
+ private void sendNoticeResponse(String message) throws IOException {
+ trace("notice:", message);
+ startMessage('N');
+ write('S');
+ writeString("ERROR");
+ write('M');
+ writeString(message);
+ sendMessage();
+ }
+
+ private void sendParseComplete() {
+ startMessage('1');
+ sendMessage();
+ }
+
+ private void sendBindComplete() {
+ startMessage('2');
+ sendMessage();
+ }
+
+ private void sendAuthenticationCleartextPassword() throws IOException {
+ startMessage('R');
+ writeInt(3);
+ sendMessage();
+ }
+
+ private void sendAuthenticationOk() throws IOException {
+ startMessage('R');
+ writeInt(0);
+ sendMessage();
+ }
+
+ private void sendReadyForQuery(boolean inTransaction, boolean failedTransaction) throws IOException {
+ startMessage('Z');
+ char c;
+ if (failedTransaction) {
+ // failed transaction block
+ c = 'E';
+ }
+ else {
+ if (inTransaction) {
+ // in a transaction block
+ c = 'T';
+ } else {
+ // idle
+ c = 'I';
+ }
+ }
+ write((byte) c);
+ sendMessage();
+ }
+
+ private void sendBackendKeyData(int processId, int screctKey) throws IOException {
+ startMessage('K');
+ writeInt(processId);
+ writeInt(screctKey);
+ sendMessage();
+ }
+
+ private void sendParameterStatus(String param, String value) throws IOException {
+ startMessage('S');
+ writeString(param);
+ writeString(value);
+ sendMessage();
+ }
+
+ @Override
+ public void functionCallResponse(byte[] data) {
+ try {
+ startMessage('V');
+ if (data == null) {
+ writeInt(-1);
+ }
+ else {
+ writeInt(data.length);
+ write(data);
+ }
+ sendMessage();
+ } catch (IOException e) {
+ terminate(e);
+ }
+ }
+
+ @Override
+ public void functionCallResponse(int data) {
+ try {
+ startMessage('V');
+ writeInt(4);
+ writeInt(data);
+ sendMessage();
+ } catch (IOException e) {
+ terminate(e);
+ }
+ }
+
+ private void writeString(String s) throws IOException {
+ write(s.getBytes(this.encoding));
+ write(0);
+ }
+
+ private void writeInt(int i) throws IOException {
+ dataOut.writeInt(i);
+ }
+
+ private void writeShort(int i) throws IOException {
+ dataOut.writeShort(i);
+ }
+
+ private void write(byte[] data) throws IOException {
+ dataOut.write(data);
+ }
+
+ private void write(int b) throws IOException {
+ dataOut.write(b);
+ }
+
+ private void startMessage(char newMessageType) {
+ this.messageType = newMessageType;
+ this.outBuffer = new ByteArrayOutputStream();
+ this.dataOut = new DataOutputStream(this.outBuffer);
+ }
+
+ private void sendMessage() {
+ byte[] buff = outBuffer.toByteArray();
+ int len = buff.length;
+ this.outBuffer = null;
+ this.dataOut = null;
+
+ // now build the wire contents.
+ ChannelBuffer buffer = ChannelBuffers.directBuffer(len+5);
+ buffer.writeByte((byte)this.messageType);
+ buffer.writeInt(len+4);
+ buffer.writeBytes(buff);
+ Channels.write(this.ctx, this.message.getFuture(), buffer, this.message.getRemoteAddress());
+ }
+
+ private static void trace(String... msg) {
+ LogManager.logTrace(LogConstants.CTX_ODBC, (Object[])msg);
+ }
+
+ /**
+ * Types.ARRAY is not supported
+ */
+ private 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;
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/resources/org/teiid/runtime/i18n.properties
===================================================================
--- trunk/runtime/src/main/resources/org/teiid/runtime/i18n.properties 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/resources/org/teiid/runtime/i18n.properties 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,94 +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.
-#
-
-
-
-LocalBufferService.Failed_initializing_buffer_manager._8=Failed initializing buffer manager.
-
-VDBService.VDB_does_not_exist._1=VDB \"{0}\" version \"{1}\" does not exist.
-VDBService.VDB_does_not_exist._2=VDB \"{0}\" version \"{1}\" is not in the "active" status.
-VDBService.VDB_does_not_exist._4=VDB \"{0}\" version \"{1}\" is not accepting connections.
-VDBService.VDB_does_not_exist._3=Invalid VDB version \"{0}\" - must be a positive integer.
-
-# session service
-SessionServiceImpl.invalid_session=The specified session ID "{0}" is invalid. It cannot be found in the userbase.
-SessionServiceImpl.reached_max_sessions = The server has reached the maximum number of sessions of {0} as defined by the property "sessionMaxLimit". If more sessions are required, modify this property value in the "teiid-jboss-beans.xml" file.
-SessionServiceImpl.expireSession = Expiring session {0}
-SessionServiceImpl.keepaliveFailed = Keepalive failed for session {0}
-SessionServiceImpl.The_username_0_and/or_password_are_incorrect=The username "{0}" and/or password and/or payload token could not be authenticated by any membership domain.
-SessionServiceImpl.terminateSession = Admin [{0}] is terminating this session: {1}.
-
-no_passthrough_identity_found = Passthrough authentication failed. No authentication information found.
-
-
-ServerWorkItem.Received_exception_processing_request=Unexpected exception for session {0}
-ServerWorkItem.processing_error=Processing exception ''{0}'' for session {1}. Exception type {2} thrown from {3}. Enable more detailed logging to see the entire stacktrace.
-ServerWorkItem.Component_Not_Found=Only {0} connections are allowed on this port. Component not found: {1}
-
-SocketTransport.1=Bound to address {0} listening on port {1}
-LocalTransportHandler.Transport_shutdown=Transport has been shutdown.
-SocketClientInstance.invalid_sessionkey=Invalid session key used during handshake
-SSLAwareChannelHandler.channel_closed=Channel closed
-
-invlaid_vdb_file=Invalid VDB file deployment failed {0}
-redeploying_vdb=Re-deploying VDB {0}
-validity_errors_in_vdb=VDB has validity errors; failed to deploy - {0}
-vdb_save_failed=Failed to save metadata for VDB {0}
-vdb_delete_failed=Failed to delete the cached metadata files due to:
-vdb_deployed=VDB "{0}" deployed in {1} state.
-vdb_undeployed=VDB "{0}" undeployed.
-system_vdb_load_error=System.vdb needs to be loaded before any other VDBs.
-fail_to_deploy="{0}" Can not be active because model "{1}" is not fully configured.
-failed_to_retrive_metadata={0}.{1} is now "incomplete", because model "{2}" can not retrieve metadata. Please fix any errors and re-deploy relevant DataSources and/or the VDB.
-nosources_to_retrive_metadata={0}.{1} is now "incomplete", because model "{2}" can not retrieve metadata. Please deploy the necessary DataSources.
-invalid_metadata_file=Invalid metadata file found at {0}; delete this file and restart server.
-udf_model_not_found=User Defined Function (UDF) model "{0}" not found in the VDB
-duplicate_vdb=VDB with given name and version already exists! {0}.{1}
-system_vdb_not_found=System.vdb not found in classpath
-invalid_udf_file=No "path" information found to load the FUNCTION model {0}; FUNCTION model must have path information.
-failed_matadata_load=Failed to load metadata for VDB {0}.{1}
-vdb_not_found=VDB {0}.{1} not found deployed.
-translator_not_found=For {0}.{1} VDB, Translator "{2}" not found.
-recursive_delegation=For {0}.{1} VDB, recursive delegation {2} found.
-datasource_not_found=For {0}.{1} VDB, Data Source "{2}" not found.
-vdb_activated={0}.{1} status has been changed to active
-vdb_inactivated={0}.{1} status has been changed to inactive. Check the required translators and data sources!
-translator_added=Teiid translator "{0}" has been added.
-invalid_class={0} invalid type of class specified. Must be of type org.teiid.connector.api.Connector
-class_not_found=Class {0} not found.
-translator_removed=Teiid translator "{0}" removed.
-no_set_method=No {0} method found for translator property {1}
-required_property_not_exists=Required property "{0}" has no value. Deployment is incomplete.
-undefined_translator_props=The provided translator property values {0} were not used. Please check the properties that are expected by translator {1}.
-name_not_found=Translator property "name" not defined for the deployment "{0}"
-translator_type_not_found=The parent translator defined not found in configuration "{0}"
-failed_to_load_odbc_metadata=Failed to load the ODBC metadata repository.
-no_active_connection=No active connection found
-bad_binding=Binding on a statement, that has not been prepared:{0}
-not_bound=No bound statement found with name {0}
-no_stmt_found=No prepared statement found with name {0}
-error_closing_stmt=Error closing portal statement {0}
-model_metadata_loading=VDB {0}.{1} model {2} metadata is currently being loaded. Start Time: {3}
-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
Copied: tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/resources/org/teiid/runtime/i18n.properties (from rev 3218, trunk/runtime/src/main/resources/org/teiid/runtime/i18n.properties)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/resources/org/teiid/runtime/i18n.properties (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/main/resources/org/teiid/runtime/i18n.properties 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,96 @@
+#
+# 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.
+#
+
+
+
+LocalBufferService.Failed_initializing_buffer_manager._8=Failed initializing buffer manager.
+
+VDBService.VDB_does_not_exist._1=VDB \"{0}\" version \"{1}\" does not exist.
+VDBService.VDB_does_not_exist._2=VDB \"{0}\" version \"{1}\" is not in the "active" status.
+VDBService.VDB_does_not_exist._4=VDB \"{0}\" version \"{1}\" is not accepting connections.
+VDBService.VDB_does_not_exist._3=Invalid VDB version \"{0}\" - must be a positive integer.
+
+# session service
+SessionServiceImpl.invalid_session=The specified session ID "{0}" is invalid. It cannot be found in the userbase.
+SessionServiceImpl.reached_max_sessions = The server has reached the maximum number of sessions of {0} as defined by the property "sessionMaxLimit". If more sessions are required, modify this property value in the "teiid-jboss-beans.xml" file.
+SessionServiceImpl.expireSession = Expiring session {0}
+SessionServiceImpl.keepaliveFailed = Keepalive failed for session {0}
+SessionServiceImpl.The_username_0_and/or_password_are_incorrect=The username "{0}" and/or password and/or payload token could not be authenticated by any membership domain.
+SessionServiceImpl.terminateSession = Admin [{0}] is terminating this session: {1}.
+
+no_passthrough_identity_found = Passthrough authentication failed. No authentication information found.
+
+
+ServerWorkItem.Received_exception_processing_request=Unexpected exception for session {0}
+ServerWorkItem.processing_error=Processing exception ''{0}'' for session {1}. Exception type {2} thrown from {3}. Enable more detailed logging to see the entire stacktrace.
+ServerWorkItem.Component_Not_Found=Only {0} connections are allowed on this port. Component not found: {1}
+
+SocketTransport.1=Bound to address {0} listening on port {1}
+LocalTransportHandler.Transport_shutdown=Transport has been shutdown.
+SocketClientInstance.invalid_sessionkey=Invalid session key used during handshake
+SSLAwareChannelHandler.channel_closed=Channel closed
+
+invlaid_vdb_file=Invalid VDB file deployment failed {0}
+redeploying_vdb=Re-deploying VDB {0}
+validity_errors_in_vdb=VDB has validity errors; failed to deploy - {0}
+vdb_save_failed=Failed to save metadata for VDB {0}
+vdb_delete_failed=Failed to delete the cached metadata files due to:
+vdb_deployed=VDB "{0}" deployed in {1} state.
+vdb_undeployed=VDB "{0}" undeployed.
+system_vdb_load_error=System.vdb needs to be loaded before any other VDBs.
+fail_to_deploy="{0}" Can not be active because model "{1}" is not fully configured.
+failed_to_retrive_metadata={0}.{1} is now "incomplete", because model "{2}" can not retrieve metadata. Please fix any errors and re-deploy relevant DataSources and/or the VDB.
+nosources_to_retrive_metadata={0}.{1} is now "incomplete", because model "{2}" can not retrieve metadata. Please deploy the necessary DataSources.
+invalid_metadata_file=Invalid metadata file found at {0}; delete this file and restart server.
+udf_model_not_found=User Defined Function (UDF) model "{0}" not found in the VDB
+duplicate_vdb=VDB with given name and version already exists! {0}.{1}
+system_vdb_not_found=System.vdb not found in classpath
+invalid_udf_file=No "path" information found to load the FUNCTION model {0}; FUNCTION model must have path information.
+failed_matadata_load=Failed to load metadata for VDB {0}.{1}
+vdb_not_found=VDB {0}.{1} not found deployed.
+translator_not_found=For {0}.{1} VDB, Translator "{2}" not found.
+recursive_delegation=For {0}.{1} VDB, recursive delegation {2} found.
+datasource_not_found=For {0}.{1} VDB, Data Source "{2}" not found.
+vdb_activated={0}.{1} status has been changed to active
+vdb_inactivated={0}.{1} status has been changed to inactive. Check the required translators and data sources!
+translator_added=Teiid translator "{0}" has been added.
+invalid_class={0} invalid type of class specified. Must be of type org.teiid.connector.api.Connector
+class_not_found=Class {0} not found.
+translator_removed=Teiid translator "{0}" removed.
+no_set_method=No {0} method found for translator property {1}
+required_property_not_exists=Required property "{0}" has no value. Deployment is incomplete.
+undefined_translator_props=The provided translator property values {0} were not used. Please check the properties that are expected by translator {1}.
+name_not_found=Translator property "name" not defined for the deployment "{0}"
+translator_type_not_found=The parent translator defined not found in configuration "{0}"
+failed_to_load_odbc_metadata=Failed to load the ODBC metadata repository.
+no_active_connection=No active connection found
+bad_binding=Binding on a statement, that has not been prepared:{0}
+not_bound=No bound statement found with name {0}
+no_stmt_found=No prepared statement found with name {0}
+error_closing_stmt=Error closing portal statement {0}
+model_metadata_loading=VDB {0}.{1} model {2} metadata is currently being loaded. Start Time: {3}
+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.
+
+PgBackendProtocol.ssl_error=Could not initialize ODBC SSL. non-SSL connections will still be allowed.
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/runtime/src/test/java/org/teiid/deployers/TestCompositeVDB.java
===================================================================
--- trunk/runtime/src/test/java/org/teiid/deployers/TestCompositeVDB.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/test/java/org/teiid/deployers/TestCompositeVDB.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,142 +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.deployers;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.core.types.DataTypeManager;
-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.metadata.MetadataStore;
-import org.teiid.metadata.Schema;
-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;
-import org.teiid.translator.ExecutionFactory;
-
- at SuppressWarnings("nls")
-public class TestCompositeVDB {
-
- public static TransformationMetadata createTransformationMetadata(MetadataStore metadataStore, String vdbName) throws Exception {
- 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()));
- }
- MetadataStoreGroup metaGroup = new MetadataStoreGroup();
- metaGroup.addStore(metadataStore);
-
- ConnectorManagerRepository cmr = new ConnectorManagerRepository();
- 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);
- }
-
- private static ConnectorManager getConnectorManager(String modelName, String translatorName, String connectionName, List<FunctionMethod> funcs) {
- final ExecutionFactory<Object, Object> ef = Mockito.mock(ExecutionFactory.class);
-
- Mockito.stub(ef.getPushDownFunctions()).toReturn(funcs);
-
- ConnectorManager cm = new ConnectorManager(translatorName,connectionName) {
- protected ExecutionFactory getExecutionFactory() {
- return ef;
- }
- };
- cm.setModelName(modelName);
- cm.start();
- return cm;
- }
-
- private static List<FunctionMethod> getFuncsOne() {
- List<FunctionMethod> funcs = new ArrayList<FunctionMethod>();
- funcs.add(new FunctionMethod("echo", "echo", "misc", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- new FunctionParameter[] {new FunctionParameter("columnName", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
- new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
- funcs.add(new FunctionMethod("duplicate_func", "duplicate", "misc", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- new FunctionParameter[] {new FunctionParameter("columnName", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
- new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
- return funcs;
- }
-
- private static List<FunctionMethod> getFuncsTwo() {
- List<FunctionMethod> funcs = new ArrayList<FunctionMethod>();
- funcs.add(new FunctionMethod("duplicate_func", "duplicate", "misc", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- new FunctionParameter[] {new FunctionParameter("columnName", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
- new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
- funcs.add(new FunctionMethod("duplicate_func", "duplicate", "misc", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- new FunctionParameter[] {new FunctionParameter("c1", DataTypeManager.DefaultDataTypes.INTEGER, ""),
- new FunctionParameter("c2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
- new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
- return funcs;
- }
-
-
- private void helpResolve(String sql) throws Exception {
- TransformationMetadata metadata = createTransformationMetadata(RealMetadataFactory.exampleBQTStore(), "bqt");
- Command command = QueryParser.getQueryParser().parseCommand(sql);
- QueryResolver.resolveCommand(command, metadata);
- }
-
- @Test
- public void testSourceMetadataStoreFunction() throws Exception {
- helpResolve("SELECT bqt1.reverse(BQT1.SmallA.INTKEY) FROM BQT1.SmallA");
- }
-
- @Test
- public void testTranslatorDefinedFunction() throws Exception {
- helpResolve("SELECT SYS.echo(BQT1.SmallA.INTKEY) FROM BQT1.SmallA");
- }
-
- @Test
- public void testPartialUDFName() throws Exception {
- helpResolve("SELECT echo(BQT1.SmallA.STRINGKEY) FROM BQT1.SmallA");
- }
-
- @Test
- public void testFullyQualifiedDuplicate() throws Exception {
- helpResolve("SELECT SYS.duplicate_func(BQT1.SmallA.STRINGKEY) FROM BQT1.SmallA");
- }
-
- @Test
- public void testNonQualifiedDuplicateWithDifferentSignature() throws Exception {
- helpResolve("SELECT duplicate_func(BQT1.SmallA.INTKEY, BQT1.SmallA.STRINGKEY) FROM BQT1.SmallA");
- }
-
- @Test
- public void testNonQualifiedDuplicate() throws Exception {
- helpResolve("SELECT duplicate_func(BQT1.SmallA.INTKEY) FROM BQT1.SmallA");
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/runtime/src/test/java/org/teiid/deployers/TestCompositeVDB.java (from rev 3218, trunk/runtime/src/test/java/org/teiid/deployers/TestCompositeVDB.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/runtime/src/test/java/org/teiid/deployers/TestCompositeVDB.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/runtime/src/test/java/org/teiid/deployers/TestCompositeVDB.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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.deployers;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.core.types.DataTypeManager;
+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.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+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.RealMetadataFactory;
+import org.teiid.translator.ExecutionFactory;
+
+ at SuppressWarnings("nls")
+public class TestCompositeVDB {
+
+ public static TransformationMetadata createTransformationMetadata(MetadataStore metadataStore, String vdbName) throws Exception {
+ VDBMetaData vdbMetaData = new VDBMetaData();
+ vdbMetaData.setName(vdbName); //$NON-NLS-1$
+ vdbMetaData.setVersion(1);
+ for (Schema schema : metadataStore.getSchemas().values()) {
+ vdbMetaData.addModel(RealMetadataFactory.createModel(schema.getName(), schema.isPhysical()));
+ }
+ MetadataStoreGroup metaGroup = new MetadataStoreGroup();
+ metaGroup.addStore(metadataStore);
+
+ ConnectorManagerRepository cmr = new ConnectorManagerRepository();
+ cmr.addConnectorManager("source", getConnectorManager("bqt1", "FakeTranslator", "FakeConnection", getFuncsOne()));
+ cmr.addConnectorManager("source2", getConnectorManager("bqt2", "FakeTranslator2", "FakeConnection2", getFuncsTwo()));
+
+ CompositeVDB cvdb = new CompositeVDB(vdbMetaData, metaGroup, null, null, RealMetadataFactory.SFM.getSystemFunctions(),cmr);
+ VDBMetaData vdb = cvdb.getVDB();
+ return vdb.getAttachment(TransformationMetadata.class);
+ }
+
+ private static ConnectorManager getConnectorManager(String modelName, String translatorName, String connectionName, List<FunctionMethod> funcs) {
+ final ExecutionFactory<Object, Object> ef = Mockito.mock(ExecutionFactory.class);
+
+ Mockito.stub(ef.getPushDownFunctions()).toReturn(funcs);
+
+ ConnectorManager cm = new ConnectorManager(translatorName,connectionName) {
+ protected ExecutionFactory getExecutionFactory() {
+ return ef;
+ }
+ };
+ cm.setModelName(modelName);
+ cm.start();
+ return cm;
+ }
+
+ private static List<FunctionMethod> getFuncsOne() {
+ List<FunctionMethod> funcs = new ArrayList<FunctionMethod>();
+ funcs.add(new FunctionMethod("echo", "echo", "misc", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ new FunctionParameter[] {new FunctionParameter("columnName", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
+ new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
+ funcs.add(new FunctionMethod("duplicate_func", "duplicate", "misc", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ new FunctionParameter[] {new FunctionParameter("columnName", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
+ new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
+ return funcs;
+ }
+
+ private static List<FunctionMethod> getFuncsTwo() {
+ List<FunctionMethod> funcs = new ArrayList<FunctionMethod>();
+ funcs.add(new FunctionMethod("duplicate_func", "duplicate", "misc", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ new FunctionParameter[] {new FunctionParameter("columnName", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
+ new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
+ funcs.add(new FunctionMethod("duplicate_func", "duplicate", "misc", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ new FunctionParameter[] {new FunctionParameter("c1", DataTypeManager.DefaultDataTypes.INTEGER, ""),
+ new FunctionParameter("c2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
+ new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
+ return funcs;
+ }
+
+
+ private void helpResolve(String sql) throws Exception {
+ TransformationMetadata metadata = createTransformationMetadata(RealMetadataFactory.exampleBQTStore(), "bqt");
+ Command command = QueryParser.getQueryParser().parseCommand(sql);
+ QueryResolver.resolveCommand(command, metadata);
+ }
+
+ @Test
+ public void testSourceMetadataStoreFunction() throws Exception {
+ helpResolve("SELECT bqt1.reverse(BQT1.SmallA.INTKEY) FROM BQT1.SmallA");
+ }
+
+ @Test
+ public void testTranslatorDefinedFunction() throws Exception {
+ helpResolve("SELECT SYS.echo(BQT1.SmallA.INTKEY) FROM BQT1.SmallA");
+ }
+
+ @Test
+ public void testPartialUDFName() throws Exception {
+ helpResolve("SELECT echo(BQT1.SmallA.STRINGKEY) FROM BQT1.SmallA");
+ }
+
+ @Test
+ public void testFullyQualifiedDuplicate() throws Exception {
+ helpResolve("SELECT SYS.duplicate_func(BQT1.SmallA.STRINGKEY) FROM BQT1.SmallA");
+ }
+
+ @Test
+ public void testNonQualifiedDuplicateWithDifferentSignature() throws Exception {
+ helpResolve("SELECT duplicate_func(BQT1.SmallA.INTKEY, BQT1.SmallA.STRINGKEY) FROM BQT1.SmallA");
+ }
+
+ @Test
+ public void testNonQualifiedDuplicate() throws Exception {
+ helpResolve("SELECT duplicate_func(BQT1.SmallA.INTKEY) FROM BQT1.SmallA");
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/test-integration/common/pom.xml
===================================================================
--- trunk/test-integration/common/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/common/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,20 +0,0 @@
-<?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-test-integration</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>test-integration-common</artifactId>
- <name>Common Integration Tests</name>
- <description>Common Integration tests that do not require external dependencies</description>
- <dependencies>
- <dependency>
- <groupId>postgresql</groupId>
- <artifactId>postgresql</artifactId>
- <version>8.3-606.jdbc3</version>
- </dependency>
- </dependencies>
-
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/test-integration/common/pom.xml (from rev 3220, trunk/test-integration/common/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/test-integration/common/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/common/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,25 @@
+<?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-test-integration</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>test-integration-common</artifactId>
+ <name>Common Integration Tests</name>
+ <description>Common Integration tests that do not require external dependencies</description>
+ <dependencies>
+ <dependency>
+ <groupId>postgresql</groupId>
+ <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
Deleted: tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestCrossSourceStarJoin.java
===================================================================
--- trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestCrossSourceStarJoin.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestCrossSourceStarJoin.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,122 +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 static org.teiid.query.unittest.RealMetadataFactory.*;
-
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.dqp.internal.datamgr.CapabilitiesConverter;
-import org.teiid.metadata.Column;
-import org.teiid.metadata.KeyRecord;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.metadata.Schema;
-import org.teiid.metadata.Table;
-import org.teiid.query.metadata.TransformationMetadata;
-import org.teiid.query.optimizer.TestOptimizer;
-import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
-import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
-import org.teiid.query.unittest.RealMetadataFactory;
-import org.teiid.translator.jdbc.oracle.OracleExecutionFactory;
-import org.teiid.translator.jdbc.sybase.SybaseExecutionFactory;
-
- at SuppressWarnings("nls")
-public class TestCrossSourceStarJoin {
-
- @Test public void testCrossSourceStartJoin() 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";
-
- MetadataStore metadataStore = new MetadataStore();
-
- Schema oracle = createPhysicalModel("oracle", metadataStore); //$NON-NLS-1$
- Schema sybase = createPhysicalModel("sybase", metadataStore); //$NON-NLS-1$
-
- // Create physical groups
- Table f = createPhysicalGroup("o1", oracle); //$NON-NLS-1$
- f.setCardinality(5276965);
- Table b = createPhysicalGroup("s1", sybase); //$NON-NLS-1$
- b.setCardinality(141496);
- Table c = createPhysicalGroup("s2", sybase); //$NON-NLS-1$
- c.setCardinality(228);
- Table p = createPhysicalGroup("s3", sybase); //$NON-NLS-1$
- p.setCardinality(200);
-
- List<Column> f_cols = createElements(f,
- new String[] { "PRODUCT", "CURRENCY", "BOOK", "AMOUNT"}, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_DECIMAL});
-
- f_cols.get(0).setDistinctValues(400);
- f_cols.get(1).setDistinctValues(228);
- f_cols.get(2).setDistinctValues(141496);
- createKey(KeyRecord.Type.Index, "idx_p", f, f_cols.subList(0, 1));
- createKey(KeyRecord.Type.Index, "idx_c", f, f_cols.subList(1, 2));
- createKey(KeyRecord.Type.Index, "idx_b", f, f_cols.subList(2, 3));
-
- List<Column> b_cols = createElements(b,
- new String[] { "BOOKID", "Name"}, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
- createKey(KeyRecord.Type.Primary, "pk", b, b_cols.subList(0, 1));
- b_cols.get(1).setDistinctValues(70000);
-
- //createKey(KeyRecord.Type.Unique, "uk", b, b_cols.subList(1, 2));
-
- List<Column> c_cols = createElements(c,
- new String[] { "Name", "CurrencyCode"}, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
-
- createKey(KeyRecord.Type.Primary, "pk", c, c_cols.subList(1, 2));
- //createKey(KeyRecord.Type.Unique, "uk", c, c_cols.subList(0, 1));
-
- List<Column> p_cols = createElements(p,
- new String[] { "PRODUCTID", "Description"}, //$NON-NLS-1$
- new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
- createKey(KeyRecord.Type.Primary, "pk", p, p_cols.subList(0, 1));
-
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- finder.addCapabilities("oracle", CapabilitiesConverter.convertCapabilities(new OracleExecutionFactory())); //$NON-NLS-1$
- finder.addCapabilities("sybase", CapabilitiesConverter.convertCapabilities(new SybaseExecutionFactory())); //$NON-NLS-1$
-
- TransformationMetadata metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "star");
-
- TestOptimizer.helpPlan(sql, metadata, new String[] {
- "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"
- }, finder, ComparisonMode.EXACT_COMMAND_STRING);
-
- //test that aggregate will not be staged
- f.setCardinality(527696);
- TestOptimizer.helpPlan(sql, metadata, new String[] {
- "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"
- }, finder, ComparisonMode.EXACT_COMMAND_STRING);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestCrossSourceStarJoin.java (from rev 3218, trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestCrossSourceStarJoin.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestCrossSourceStarJoin.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestCrossSourceStarJoin.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,122 @@
+/*
+ * 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.teiid.query.unittest.RealMetadataFactory.*;
+
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.dqp.internal.datamgr.CapabilitiesConverter;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.KeyRecord;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.optimizer.TestOptimizer;
+import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
+import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.translator.jdbc.oracle.OracleExecutionFactory;
+import org.teiid.translator.jdbc.sybase.SybaseExecutionFactory;
+
+ at SuppressWarnings("nls")
+public class TestCrossSourceStarJoin {
+
+ @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";
+
+ MetadataStore metadataStore = new MetadataStore();
+
+ Schema oracle = createPhysicalModel("oracle", metadataStore); //$NON-NLS-1$
+ Schema sybase = createPhysicalModel("sybase", metadataStore); //$NON-NLS-1$
+
+ // Create physical groups
+ Table f = createPhysicalGroup("o1", oracle); //$NON-NLS-1$
+ f.setCardinality(5276965);
+ Table b = createPhysicalGroup("s1", sybase); //$NON-NLS-1$
+ b.setCardinality(141496);
+ Table c = createPhysicalGroup("s2", sybase); //$NON-NLS-1$
+ c.setCardinality(228);
+ Table p = createPhysicalGroup("s3", sybase); //$NON-NLS-1$
+ p.setCardinality(200);
+
+ List<Column> f_cols = createElements(f,
+ new String[] { "PRODUCT", "CURRENCY", "BOOK", "AMOUNT"}, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.BIG_DECIMAL});
+
+ f_cols.get(0).setDistinctValues(400);
+ f_cols.get(1).setDistinctValues(228);
+ f_cols.get(2).setDistinctValues(141496);
+ createKey(KeyRecord.Type.Index, "idx_p", f, f_cols.subList(0, 1));
+ createKey(KeyRecord.Type.Index, "idx_c", f, f_cols.subList(1, 2));
+ createKey(KeyRecord.Type.Index, "idx_b", f, f_cols.subList(2, 3));
+
+ List<Column> b_cols = createElements(b,
+ new String[] { "BOOKID", "Name"}, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+ createKey(KeyRecord.Type.Primary, "pk", b, b_cols.subList(0, 1));
+ b_cols.get(1).setDistinctValues(70000);
+
+ //createKey(KeyRecord.Type.Unique, "uk", b, b_cols.subList(1, 2));
+
+ List<Column> c_cols = createElements(c,
+ new String[] { "Name", "CurrencyCode"}, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
+
+ createKey(KeyRecord.Type.Primary, "pk", c, c_cols.subList(1, 2));
+ //createKey(KeyRecord.Type.Unique, "uk", c, c_cols.subList(0, 1));
+
+ List<Column> p_cols = createElements(p,
+ new String[] { "PRODUCTID", "Description"}, //$NON-NLS-1$
+ new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+ createKey(KeyRecord.Type.Primary, "pk", p, p_cols.subList(0, 1));
+
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ finder.addCapabilities("oracle", CapabilitiesConverter.convertCapabilities(new OracleExecutionFactory())); //$NON-NLS-1$
+ finder.addCapabilities("sybase", CapabilitiesConverter.convertCapabilities(new SybaseExecutionFactory())); //$NON-NLS-1$
+
+ TransformationMetadata metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "star");
+
+ TestOptimizer.helpPlan(sql, metadata, new String[] {
+ "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, 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
+ f.setCardinality(527696);
+ TestOptimizer.helpPlan(sql, metadata, new String[] {
+ "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, 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: tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestRelate.java (from rev 3218, trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestRelate.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestRelate.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestRelate.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -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;
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java
===================================================================
--- trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,123 +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 java.io.FileInputStream;
-import java.math.BigInteger;
-import java.sql.Timestamp;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.mockito.Mockito;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.core.util.ObjectConverterUtil;
-import org.teiid.core.util.UnitTestUtil;
-import org.teiid.dqp.message.RequestID;
-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.FakeCapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.processor.HardcodedDataManager;
-import org.teiid.translator.SourceSystemFunctions;
-
-
-public class TestXMLTypeTranslations extends BaseQueryTest {
-
- private static final boolean DEBUG = false;
-
- public TestXMLTypeTranslations(String name) {
- super(name);
- }
-
- //NOTE that the gMonth and gDay values are invalid (but properly formatted)
- public void testXSDTranslations() throws Exception {
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- BasicSourceCapabilities bsc = new BasicSourceCapabilities();
- bsc.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
- bsc.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
- bsc.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
- finder.addCapabilities("sample", bsc); //$NON-NLS-1$
-
- QueryMetadataInterface metadata = createMetadata(UnitTestUtil.getTestDataPath()+"/test.vdb"); //$NON-NLS-1$
-
- String sql = "select * from testdocument.testDocument"; //$NON-NLS-1$
-
- HardcodedDataManager dataMgr = new HardcodedDataManager();
-
- Set<String> models = new HashSet<String>();
- models.add("sample"); //$NON-NLS-1$
- dataMgr.setValidModels(models);
-
- 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$
-
- 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$
- })});
-
-
- List[] expected = new List[] { Arrays.asList(new Object[] {"<?xml version=\"1.0\" encoding=\"UTF-8\"?><XSDTypesNS:test xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:XSDTypesNS=\"http://www.metamatrix.com/XMLSchema/DataSets/XSDTypes\"><book><datetime>1903-04-04T11:06:10.006Z</datetime><double>-INF</double><float>INF</float><gday>---100</gday><gmonth>--100</gmonth><gmonthday>--04-04</gmonthday><gyear>0100</gyear><gyearmonth>1903-04Z</gyearmonth><string>1</string></book></XSDTypesNS:test>" })}; //$NON-NLS-1$
- doProcess(metadata,
- sql,
- finder, dataMgr , expected, DEBUG);
-
- }
-
- public void testGetXmlSchemas() throws Exception {
- FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
- finder.addCapabilities("sample", new BasicSourceCapabilities()); //$NON-NLS-1$
-
- TransformationMetadata metadata = createMetadata(UnitTestUtil.getTestDataPath()+"/test.vdb"); //$NON-NLS-1$
-
- String sql = "call getXMLSchemas('testdocument.testDocument')"; //$NON-NLS-1$
-
- DQPCore core = Mockito.mock(DQPCore.class);
- RequestWorkItem rwi = Mockito.mock(RequestWorkItem.class);
- DQPWorkContext workContext = new DQPWorkContext();
- VDBMetaData vdb = new VDBMetaData();
- vdb.addAttchment(TransformationMetadata.class, metadata);
- workContext.getSession().setVdb(vdb);
- Mockito.stub(rwi.getDqpWorkContext()).toReturn(workContext);
-
- Mockito.stub(core.getRequestWorkItem((RequestID)Mockito.anyObject())).toReturn(rwi);
- DataTierManagerImpl dataMgr = new DataTierManagerImpl(core, null, true);
- doProcess(metadata,
- sql,
- finder, dataMgr , new List[] {Arrays.asList(new String(ObjectConverterUtil.convertToByteArray(new FileInputStream(UnitTestUtil.getTestDataFile("test-schema.xsd")))))}, DEBUG); //$NON-NLS-1$
-
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java (from rev 3218, trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,119 @@
+/*
+ * 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 java.io.FileInputStream;
+import java.math.BigInteger;
+import java.sql.Timestamp;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.mockito.Mockito;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.core.util.ObjectConverterUtil;
+import org.teiid.core.util.UnitTestUtil;
+import org.teiid.dqp.message.RequestID;
+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.FakeCapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.processor.HardcodedDataManager;
+import org.teiid.translator.SourceSystemFunctions;
+
+
+public class TestXMLTypeTranslations extends BaseQueryTest {
+
+ private static final boolean DEBUG = false;
+
+ public TestXMLTypeTranslations(String name) {
+ super(name);
+ }
+
+ //NOTE that the gMonth and gDay values are invalid (but properly formatted)
+ public void testXSDTranslations() throws Exception {
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ BasicSourceCapabilities bsc = new BasicSourceCapabilities();
+ bsc.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
+ bsc.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+ bsc.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+ finder.addCapabilities("sample", bsc); //$NON-NLS-1$
+
+ QueryMetadataInterface metadata = createMetadata(UnitTestUtil.getTestDataPath()+"/test.vdb"); //$NON-NLS-1$
+
+ String sql = "select * from testdocument.testDocument"; //$NON-NLS-1$
+
+ HardcodedDataManager dataMgr = new HardcodedDataManager();
+
+ Set<String> models = new HashSet<String>();
+ models.add("sample"); //$NON-NLS-1$
+ dataMgr.setValidModels(models);
+
+ 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.\"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$
+ ts,
+ })});
+
+
+ List[] expected = new List[] { Arrays.asList(new Object[] {"<?xml version=\"1.0\" encoding=\"UTF-8\"?><XSDTypesNS:test xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:XSDTypesNS=\"http://www.metamatrix.com/XMLSchema/DataSets/XSDTypes\"><book><datetime>1903-04-04T11:06:10.006Z</datetime><double>-INF</double><float>INF</float><gday>---100</gday><gmonth>--100</gmonth><gmonthday>--04-04</gmonthday><gyear>0100</gyear><gyearmonth>1903-04Z</gyearmonth><string>1</string></book></XSDTypesNS:test>" })}; //$NON-NLS-1$
+ doProcess(metadata,
+ sql,
+ finder, dataMgr , expected, DEBUG);
+
+ }
+
+ public void testGetXmlSchemas() throws Exception {
+ FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
+ finder.addCapabilities("sample", new BasicSourceCapabilities()); //$NON-NLS-1$
+
+ TransformationMetadata metadata = createMetadata(UnitTestUtil.getTestDataPath()+"/test.vdb"); //$NON-NLS-1$
+
+ String sql = "call getXMLSchemas('testdocument.testDocument')"; //$NON-NLS-1$
+
+ DQPCore core = Mockito.mock(DQPCore.class);
+ RequestWorkItem rwi = Mockito.mock(RequestWorkItem.class);
+ DQPWorkContext workContext = new DQPWorkContext();
+ VDBMetaData vdb = new VDBMetaData();
+ vdb.addAttchment(TransformationMetadata.class, metadata);
+ workContext.getSession().setVdb(vdb);
+ Mockito.stub(rwi.getDqpWorkContext()).toReturn(workContext);
+
+ Mockito.stub(core.getRequestWorkItem((RequestID)Mockito.anyObject())).toReturn(rwi);
+ DataTierManagerImpl dataMgr = new DataTierManagerImpl(core, null, true);
+ doProcess(metadata,
+ sql,
+ finder, dataMgr , new List[] {Arrays.asList(new String(ObjectConverterUtil.convertToByteArray(new FileInputStream(UnitTestUtil.getTestDataFile("test-schema.xsd")))))}, DEBUG); //$NON-NLS-1$
+
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java
===================================================================
--- trunk/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,204 +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.jdbc;
-
-import java.io.File;
-import java.util.LinkedHashMap;
-import java.util.Properties;
-
-import org.jboss.deployers.spi.DeploymentException;
-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.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.VDBRepository;
-import org.teiid.dqp.internal.datamgr.ConnectorManager;
-import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
-import org.teiid.dqp.internal.datamgr.FakeTransactionService;
-import org.teiid.dqp.internal.process.DQPConfiguration;
-import org.teiid.dqp.internal.process.DQPCore;
-import org.teiid.dqp.service.FakeBufferService;
-import org.teiid.metadata.MetadataRepository;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.metadata.Schema;
-import org.teiid.metadata.index.IndexMetadataFactory;
-import org.teiid.metadata.index.VDBMetadataFactory;
-import org.teiid.net.CommunicationException;
-import org.teiid.net.ConnectionException;
-import org.teiid.query.function.SystemFunctionManager;
-import org.teiid.query.metadata.TransformationMetadata.Resource;
-import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities;
-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")
-public class FakeServer extends ClientServiceRegistryImpl implements ConnectionProfile {
-
- SessionServiceImpl sessionService = new SessionServiceImpl();
- LogonImpl logon;
- DQPCore dqp = new DQPCore();
- VDBRepository repo = new VDBRepository();
- private ConnectorManagerRepository cmr;
- private boolean useCallingThread = true;
-
- public FakeServer() {
- this.logon = new LogonImpl(sessionService, null);
-
- this.repo.setSystemStore(VDBMetadataFactory.getSystem());
- this.repo.setSystemFunctionManager(new SystemFunctionManager());
- this.repo.odbcEnabled();
- this.repo.start();
-
- this.sessionService.setVDBRepository(repo);
- this.dqp.setBufferService(new FakeBufferService());
- this.dqp.setCacheFactory(new DefaultCacheFactory());
- this.dqp.setTransactionService(new FakeTransactionService());
-
- cmr = Mockito.mock(ConnectorManagerRepository.class);
- Mockito.stub(cmr.getConnectorManager("source")).toReturn(new ConnectorManager("x", "x") {
- @Override
- public SourceCapabilities getCapabilities() {
- return new BasicSourceCapabilities();
- }
- });
-
- DQPConfiguration config = new DQPConfiguration();
- config.setResultsetCacheConfig(new CacheConfiguration(Policy.LRU, 60, 250, "resultsetcache")); //$NON-NLS-1$
- this.dqp.setCacheFactory(new DefaultCacheFactory());
- this.dqp.start(config);
- this.sessionService.setDqp(this.dqp);
-
- registerClientService(ILogon.class, logon, null);
- registerClientService(DQP.class, dqp, null);
- }
-
- public void stop() {
- this.dqp.stop();
- }
-
- public void setMetadataRepository(MetadataRepository metadataRepository) {
- this.repo.setMetadataRepository(metadataRepository);
- this.dqp.setMetadataRepository(metadataRepository);
- }
-
- public void setUseCallingThread(boolean useCallingThread) {
- this.useCallingThread = useCallingThread;
- }
-
- public void deployVDB(String vdbName, String vdbPath) throws Exception {
-
- IndexMetadataFactory imf = VDBMetadataFactory.loadMetadata(new File(vdbPath).toURI().toURL());
- MetadataStore metadata = imf.getMetadataStore(repo.getSystemStore().getDatatypes());
- LinkedHashMap<String, Resource> entries = imf.getEntriesPlusVisibilities();
-
- deployVDB(vdbName, metadata, entries);
- }
-
- public void deployVDB(String vdbName, MetadataStore metadata,
- LinkedHashMap<String, Resource> entries) {
- VDBMetaData vdbMetaData = new VDBMetaData();
- vdbMetaData.setName(vdbName);
- vdbMetaData.setStatus(VDB.Status.ACTIVE);
-
- for (Schema schema : repo.getSystemStore().getSchemas().values()) {
- addModel(vdbMetaData, schema);
- }
-
- for (Schema schema : repo.getODBCStore().getSchemas().values()) {
- addModel(vdbMetaData, schema);
- }
-
- for (Schema schema : metadata.getSchemas().values()) {
- addModel(vdbMetaData, schema);
- }
-
- try {
- MetadataStoreGroup stores = new MetadataStoreGroup();
- stores.addStore(metadata);
- this.repo.addVDB(vdbMetaData, stores, entries, null, cmr);
- this.repo.finishDeployment(vdbName, 1);
- } catch (DeploymentException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void removeVDB(String vdbName) {
- this.repo.removeVDB(vdbName, 1);
- }
-
- private void addModel(VDBMetaData vdbMetaData, Schema schema) {
- ModelMetaData model = new ModelMetaData();
- model.setName(schema.getName());
- vdbMetaData.addModel(model);
- model.addSourceMapping("source", "translator", "jndi:source");
- }
-
- public VDBMetaData getVDB(String vdbName) {
- return this.repo.getVDB(vdbName, 1);
- }
-
- public void undeployVDB(String vdbName) {
- this.repo.removeVDB(vdbName, 1);
- }
-
- public void mergeVDBS(String sourceVDB, String targetVDB) throws AdminException {
- this.repo.mergeVDBs(sourceVDB, 1, targetVDB, 1);
- }
-
- public ConnectionImpl createConnection(String embeddedURL) throws Exception {
- final Properties p = new Properties();
- TeiidDriver.parseURL(embeddedURL, p);
-
- return connect(embeddedURL, p);
- }
-
- @Override
- public ConnectionImpl connect(String url, Properties info)
- throws TeiidSQLException {
- LocalServerConnection conn;
- try {
- conn = new LocalServerConnection(info, useCallingThread) {
- @Override
- protected ClientServiceRegistry getClientServiceRegistry() {
- return FakeServer.this;
- }
- };
- } catch (CommunicationException e) {
- throw TeiidSQLException.create(e);
- } catch (ConnectionException e) {
- throw TeiidSQLException.create(e);
- }
- return new ConnectionImpl(conn, info, url);
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java (from rev 3218, trunk/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,211 @@
+/*
+ * 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.jdbc;
+
+import java.io.File;
+import java.util.LinkedHashMap;
+import java.util.Properties;
+
+import org.jboss.deployers.spi.DeploymentException;
+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.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.VDBRepository;
+import org.teiid.dqp.internal.datamgr.ConnectorManager;
+import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
+import org.teiid.dqp.internal.datamgr.FakeTransactionService;
+import org.teiid.dqp.internal.process.DQPConfiguration;
+import org.teiid.dqp.internal.process.DQPCore;
+import org.teiid.dqp.service.FakeBufferService;
+import org.teiid.metadata.MetadataRepository;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.index.IndexMetadataFactory;
+import org.teiid.metadata.index.VDBMetadataFactory;
+import org.teiid.net.CommunicationException;
+import org.teiid.net.ConnectionException;
+import org.teiid.query.function.SystemFunctionManager;
+import org.teiid.query.metadata.TransformationMetadata.Resource;
+import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities;
+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")
+public class FakeServer extends ClientServiceRegistryImpl implements ConnectionProfile {
+
+ SessionServiceImpl sessionService = new SessionServiceImpl();
+ LogonImpl logon;
+ DQPCore dqp = new DQPCore();
+ VDBRepository repo = new VDBRepository();
+ private ConnectorManagerRepository cmr;
+ private boolean useCallingThread = true;
+
+ public FakeServer() {
+ this(new DQPConfiguration());
+ }
+
+ public FakeServer(DQPConfiguration config) {
+ this.logon = new LogonImpl(sessionService, null);
+
+ this.repo.setSystemStore(VDBMetadataFactory.getSystem());
+ this.repo.setSystemFunctionManager(new SystemFunctionManager());
+ this.repo.odbcEnabled();
+ this.repo.start();
+
+ this.sessionService.setVDBRepository(repo);
+ this.dqp.setBufferService(new FakeBufferService());
+ this.dqp.setCacheFactory(new DefaultCacheFactory());
+ this.dqp.setTransactionService(new FakeTransactionService());
+
+ cmr = Mockito.mock(ConnectorManagerRepository.class);
+ Mockito.stub(cmr.getConnectorManager("source")).toReturn(new ConnectorManager("x", "x") {
+ @Override
+ public SourceCapabilities getCapabilities() {
+ return new BasicSourceCapabilities();
+ }
+ });
+
+ config.setResultsetCacheConfig(new CacheConfiguration(Policy.LRU, 60, 250, "resultsetcache")); //$NON-NLS-1$
+ this.dqp.setCacheFactory(new DefaultCacheFactory());
+ this.dqp.start(config);
+ this.sessionService.setDqp(this.dqp);
+
+ registerClientService(ILogon.class, logon, null);
+ registerClientService(DQP.class, dqp, null);
+ }
+
+ public void setConnectorManagerRepository(ConnectorManagerRepository cmr) {
+ this.cmr = cmr;
+ }
+
+ public void stop() {
+ this.dqp.stop();
+ }
+
+ public void setMetadataRepository(MetadataRepository metadataRepository) {
+ this.repo.setMetadataRepository(metadataRepository);
+ this.dqp.setMetadataRepository(metadataRepository);
+ }
+
+ public void setUseCallingThread(boolean useCallingThread) {
+ this.useCallingThread = useCallingThread;
+ }
+
+ public void deployVDB(String vdbName, String vdbPath) throws Exception {
+
+ IndexMetadataFactory imf = VDBMetadataFactory.loadMetadata(new File(vdbPath).toURI().toURL());
+ MetadataStore metadata = imf.getMetadataStore(repo.getSystemStore().getDatatypes());
+ LinkedHashMap<String, Resource> entries = imf.getEntriesPlusVisibilities();
+
+ deployVDB(vdbName, metadata, entries);
+ }
+
+ public void deployVDB(String vdbName, MetadataStore metadata,
+ LinkedHashMap<String, Resource> entries) {
+ VDBMetaData vdbMetaData = new VDBMetaData();
+ vdbMetaData.setName(vdbName);
+ vdbMetaData.setStatus(VDB.Status.ACTIVE);
+
+ for (Schema schema : repo.getSystemStore().getSchemas().values()) {
+ addModel(vdbMetaData, schema);
+ }
+
+ for (Schema schema : repo.getODBCStore().getSchemas().values()) {
+ addModel(vdbMetaData, schema);
+ }
+
+ for (Schema schema : metadata.getSchemas().values()) {
+ addModel(vdbMetaData, schema);
+ }
+
+ try {
+ MetadataStoreGroup stores = new MetadataStoreGroup();
+ stores.addStore(metadata);
+ this.repo.addVDB(vdbMetaData, stores, entries, null, cmr);
+ this.repo.finishDeployment(vdbName, 1);
+ } catch (DeploymentException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void removeVDB(String vdbName) {
+ this.repo.removeVDB(vdbName, 1);
+ }
+
+ private void addModel(VDBMetaData vdbMetaData, Schema schema) {
+ ModelMetaData model = new ModelMetaData();
+ model.setName(schema.getName());
+ vdbMetaData.addModel(model);
+ model.addSourceMapping("source", "translator", "jndi:source");
+ }
+
+ public VDBMetaData getVDB(String vdbName) {
+ return this.repo.getVDB(vdbName, 1);
+ }
+
+ public void undeployVDB(String vdbName) {
+ this.repo.removeVDB(vdbName, 1);
+ }
+
+ public void mergeVDBS(String sourceVDB, String targetVDB) throws AdminException {
+ this.repo.mergeVDBs(sourceVDB, 1, targetVDB, 1);
+ }
+
+ public ConnectionImpl createConnection(String embeddedURL) throws Exception {
+ final Properties p = new Properties();
+ TeiidDriver.parseURL(embeddedURL, p);
+
+ return connect(embeddedURL, p);
+ }
+
+ @Override
+ public ConnectionImpl connect(String url, Properties info)
+ throws TeiidSQLException {
+ LocalServerConnection conn;
+ try {
+ conn = new LocalServerConnection(info, useCallingThread) {
+ @Override
+ protected ClientServiceRegistry getClientServiceRegistry() {
+ return FakeServer.this;
+ }
+ };
+ } catch (CommunicationException e) {
+ throw TeiidSQLException.create(e);
+ } catch (ConnectionException e) {
+ throw TeiidSQLException.create(e);
+ }
+ return new ConnectionImpl(conn, info, url);
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/TestLocalConnections.java
===================================================================
--- trunk/test-integration/common/src/test/java/org/teiid/jdbc/TestLocalConnections.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/TestLocalConnections.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,139 +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.jdbc;
-
-import static org.junit.Assert.*;
-
-import java.lang.Thread.UncaughtExceptionHandler;
-import java.sql.Connection;
-import java.sql.Statement;
-import java.util.LinkedHashMap;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.ReentrantLock;
-
-import org.jboss.netty.handler.timeout.TimeoutException;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.FunctionParameter;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.metadata.Schema;
-import org.teiid.metadata.FunctionMethod.PushDown;
-import org.teiid.query.function.metadata.FunctionCategoryConstants;
-import org.teiid.query.metadata.TransformationMetadata.Resource;
-
- at SuppressWarnings("nls")
-public class TestLocalConnections {
-
- private final class SimpleUncaughtExceptionHandler implements
- UncaughtExceptionHandler {
- Throwable t;
-
- @Override
- public void uncaughtException(Thread arg0, Throwable arg1) {
- t = arg1;
- }
- }
-
- static ReentrantLock lock = new ReentrantLock();
- static Condition waiting = lock.newCondition();
- static Condition wait = lock.newCondition();
-
- public static int blocking() throws InterruptedException {
- lock.lock();
- try {
- waiting.signal();
- if (!wait.await(2, TimeUnit.SECONDS)) {
- throw new TimeoutException();
- }
- } finally {
- lock.unlock();
- }
- return 1;
- }
-
- static FakeServer server = new FakeServer();
-
- @BeforeClass public static void oneTimeSetup() {
- server.setUseCallingThread(true);
- MetadataStore ms = new MetadataStore();
- Schema s = new Schema();
- s.setName("test");
- 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>());
- }
-
- @AfterClass public static void oneTimeTearDown() {
- server.stop();
- }
-
- @Test public void testConcurrentExection() throws Throwable {
-
- Thread t = new Thread() {
-
- public void run() {
- try {
- Connection c = server.createConnection("jdbc:teiid:test");
-
- Statement s = c.createStatement();
- s.execute("select foo()");
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- };
- SimpleUncaughtExceptionHandler handler = new SimpleUncaughtExceptionHandler();
- t.setUncaughtExceptionHandler(handler);
- t.start();
-
- lock.lock();
- try {
- waiting.await();
- } finally {
- lock.unlock();
- }
- Connection c = server.createConnection("jdbc:teiid:test");
- Statement s = c.createStatement();
- s.execute("select * from tables");
-
- lock.lock();
- try {
- wait.signal();
- } finally {
- lock.unlock();
- }
- t.join(2000);
- if (t.isAlive()) {
- fail();
- }
- if (handler.t != null) {
- throw handler.t;
- }
- }
-
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/TestLocalConnections.java (from rev 3218, trunk/test-integration/common/src/test/java/org/teiid/jdbc/TestLocalConnections.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/TestLocalConnections.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/jdbc/TestLocalConnections.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,139 @@
+/*
+ * 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.jdbc;
+
+import static org.junit.Assert.*;
+
+import java.lang.Thread.UncaughtExceptionHandler;
+import java.sql.Connection;
+import java.sql.Statement;
+import java.util.LinkedHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.jboss.netty.handler.timeout.TimeoutException;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.FunctionMethod;
+import org.teiid.metadata.FunctionParameter;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.FunctionMethod.PushDown;
+import org.teiid.query.function.metadata.FunctionCategoryConstants;
+import org.teiid.query.metadata.TransformationMetadata.Resource;
+
+ at SuppressWarnings("nls")
+public class TestLocalConnections {
+
+ private final class SimpleUncaughtExceptionHandler implements
+ UncaughtExceptionHandler {
+ Throwable t;
+
+ @Override
+ public void uncaughtException(Thread arg0, Throwable arg1) {
+ t = arg1;
+ }
+ }
+
+ static ReentrantLock lock = new ReentrantLock();
+ static Condition waiting = lock.newCondition();
+ static Condition wait = lock.newCondition();
+
+ public static int blocking() throws InterruptedException {
+ lock.lock();
+ try {
+ waiting.signal();
+ if (!wait.await(2, TimeUnit.SECONDS)) {
+ throw new TimeoutException();
+ }
+ } finally {
+ lock.unlock();
+ }
+ return 1;
+ }
+
+ static FakeServer server = new FakeServer();
+
+ @BeforeClass public static void oneTimeSetup() {
+ server.setUseCallingThread(true);
+ MetadataStore ms = new MetadataStore();
+ Schema s = new Schema();
+ s.setName("test");
+ 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>());
+ }
+
+ @AfterClass public static void oneTimeTearDown() {
+ server.stop();
+ }
+
+ @Test public void testConcurrentExection() throws Throwable {
+
+ Thread t = new Thread() {
+
+ public void run() {
+ try {
+ Connection c = server.createConnection("jdbc:teiid:test");
+
+ Statement s = c.createStatement();
+ s.execute("select foo()");
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+ SimpleUncaughtExceptionHandler handler = new SimpleUncaughtExceptionHandler();
+ t.setUncaughtExceptionHandler(handler);
+ t.start();
+
+ lock.lock();
+ try {
+ waiting.await();
+ } finally {
+ lock.unlock();
+ }
+ Connection c = server.createConnection("jdbc:teiid:test");
+ Statement s = c.createStatement();
+ s.execute("select * from tables");
+
+ lock.lock();
+ try {
+ wait.signal();
+ } finally {
+ lock.unlock();
+ }
+ t.join(2000);
+ if (t.isAlive()) {
+ fail();
+ }
+ if (handler.t != null) {
+ throw handler.t;
+ }
+ }
+
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java
===================================================================
--- trunk/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,184 +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.transport;
-
-import static org.junit.Assert.*;
-
-import java.net.InetSocketAddress;
-import java.nio.charset.Charset;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.Properties;
-
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.postgresql.Driver;
-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;
-
- at 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);
-
- FakeServer server = new FakeServer();
- server.setUseCallingThread(false);
- server.deployVDB("parts", UnitTestUtil.getTestDataPath() + "/PartsSupplier.vdb");
-
- TeiidDriver driver = new TeiidDriver();
- driver.setEmbeddedProfile(server);
- odbcTransport.setDriver(driver);
-
- }
-
- @AfterClass public static void oneTimeTearDown() throws Exception {
- if (odbcTransport != null) {
- odbcTransport.stop();
- }
- }
-
- Connection conn;
-
- @Before public void setUp() throws Exception {
- Driver d = new Driver();
- Properties p = new Properties();
- p.setProperty("user", "testuser");
- p.setProperty("password", "testpassword");
- conn = d.connect("jdbc:postgresql://"+addr.getHostName()+":" +odbcTransport.getPort()+"/parts", p);
- }
-
- @After public void tearDown() throws Exception {
- if (conn != null) {
- conn.close();
- }
- }
-
- /**
- * Under the covers this still executes a prepared statement due to the driver handling
- */
- @Test public void testSelect() throws Exception {
- Statement s = conn.createStatement();
- assertTrue(s.execute("select * from tables order by name"));
- TestMMDatabaseMetaData.compareResultSet(s.getResultSet());
- }
-
- @Test public void testBlob() throws Exception {
- Statement s = conn.createStatement();
- assertTrue(s.execute("select to_bytes('abc', 'UTF-16')"));
- ResultSet rs = s.getResultSet();
- assertTrue(rs.next());
- byte[] bytes = rs.getBytes(1);
- assertEquals("abc", new String(bytes, Charset.forName("UTF-16")));
- }
-
- @Test public void testClob() throws Exception {
- Statement s = conn.createStatement();
- assertTrue(s.execute("select cast('abc' as clob)"));
- ResultSet rs = s.getResultSet();
- assertTrue(rs.next());
- //getting as a clob is unsupported, since it uses the lo logic
- String clob = rs.getString(1);
- assertEquals("abc", clob);
- }
-
- @Test public void testTransactionCycle() throws Exception {
- //TODO: drill in to ensure that the underlying statement has been set to autocommit false
- conn.setAutoCommit(false);
- Statement s = conn.createStatement();
- assertTrue(s.execute("select * from tables order by name"));
- conn.setAutoCommit(true);
- }
-
- @Test public void testPk() throws Exception {
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery("select ta.attname, ia.attnum, ic.relname, n.nspname, tc.relname " +//$NON-NLS-1$
- "from pg_catalog.pg_attribute ta, pg_catalog.pg_attribute ia, pg_catalog.pg_class tc, pg_catalog.pg_index i, " +//$NON-NLS-1$
- "pg_catalog.pg_namespace n, pg_catalog.pg_class ic where tc.relname = E'pg_attribute' AND n.nspname = E'pg_catalog'");
- TestMMDatabaseMetaData.compareResultSet(rs);
- }
-
- @Test public void testPkPrepared() throws Exception {
- PreparedStatement stmt = conn.prepareStatement("select ta.attname, ia.attnum, ic.relname, n.nspname, tc.relname " +//$NON-NLS-1$
- "from pg_catalog.pg_attribute ta, pg_catalog.pg_attribute ia, pg_catalog.pg_class tc, pg_catalog.pg_index i, " +//$NON-NLS-1$
- "pg_catalog.pg_namespace n, pg_catalog.pg_class ic where tc.relname = E'pg_attribute' AND n.nspname = E'pg_catalog'");
- 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");
- try {
- stmt.executeQuery();
- } catch (SQLException e) {
- assertTrue(e.getMessage().contains("Error converting"));
- }
- }
-
- @Test public void testPreparedError1() throws Exception {
- PreparedStatement stmt = conn.prepareStatement("select");
- try {
- stmt.executeQuery();
- } catch (SQLException e) {
- assertTrue(e.getMessage().contains("Parsing error"));
- }
- }
-
- @Test public void testEscapedLiteral() throws Exception {
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery("select E'\\n\\thello pg'");
- assertTrue(rs.next());
- assertEquals("\n\thello pg", rs.getString(1));
- }
-
- @Test public void testPgProc() throws Exception {
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery("select * from pg_proc");
- rs.next();
- assertEquals("oid", rs.getArray("proargtypes").getBaseTypeName());
- }
-
- @Test public void testPgProcedure() throws Exception {
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery("select has_function_privilege(100, 'foo')");
- rs.next();
- }
-}
Copied: tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java (from rev 3218, trunk/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,277 @@
+/*
+ * 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.transport;
+
+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;
+import java.sql.SQLException;
+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.postgresql.Driver;
+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;
+
+ at SuppressWarnings("nls")
+public class TestODBCSocketTransport {
+
+public static class AnonSSLSocketFactory extends SSLSocketFactory {
+
+ private SSLSocketFactory sslSocketFactory;
+
+ 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();
+ }
+
+ }
+
+ 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);
+
+ 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 {
+ Driver d = new Driver();
+ Properties p = new Properties();
+ p.setProperty("user", "testuser");
+ p.setProperty("password", "testpassword");
+ conn = d.connect("jdbc:postgresql://"+odbcServer.addr.getHostName()+":" +odbcServer.odbcTransport.getPort()+"/parts", p);
+ }
+
+ @After public void tearDown() throws Exception {
+ if (conn != null) {
+ conn.close();
+ }
+ }
+
+ /**
+ * Under the covers this still executes a prepared statement due to the driver handling
+ */
+ @Test public void testSelect() throws Exception {
+ Statement s = conn.createStatement();
+ assertTrue(s.execute("select * from tables order by name"));
+ TestMMDatabaseMetaData.compareResultSet(s.getResultSet());
+ }
+
+ @Test public void testBlob() throws Exception {
+ Statement s = conn.createStatement();
+ assertTrue(s.execute("select to_bytes('abc', 'UTF-16')"));
+ ResultSet rs = s.getResultSet();
+ assertTrue(rs.next());
+ byte[] bytes = rs.getBytes(1);
+ assertEquals("abc", new String(bytes, Charset.forName("UTF-16")));
+ }
+
+ @Test public void testClob() throws Exception {
+ Statement s = conn.createStatement();
+ assertTrue(s.execute("select cast('abc' as clob)"));
+ ResultSet rs = s.getResultSet();
+ assertTrue(rs.next());
+ //getting as a clob is unsupported, since it uses the lo logic
+ String clob = rs.getString(1);
+ assertEquals("abc", clob);
+ }
+
+ @Test public void testTransactionCycle() throws Exception {
+ //TODO: drill in to ensure that the underlying statement has been set to autocommit false
+ conn.setAutoCommit(false);
+ Statement s = conn.createStatement();
+ assertTrue(s.execute("select * from tables order by name"));
+ conn.setAutoCommit(true);
+ }
+
+ @Test public void testPk() throws Exception {
+ Statement stmt = conn.createStatement();
+ ResultSet rs = stmt.executeQuery("select ta.attname, ia.attnum, ic.relname, n.nspname, tc.relname " +//$NON-NLS-1$
+ "from pg_catalog.pg_attribute ta, pg_catalog.pg_attribute ia, pg_catalog.pg_class tc, pg_catalog.pg_index i, " +//$NON-NLS-1$
+ "pg_catalog.pg_namespace n, pg_catalog.pg_class ic where tc.relname = E'pg_attribute' AND n.nspname = E'pg_catalog'");
+ TestMMDatabaseMetaData.compareResultSet(rs);
+ }
+
+ @Test public void testPkPrepared() throws Exception {
+ PreparedStatement stmt = conn.prepareStatement("select ta.attname, ia.attnum, ic.relname, n.nspname, tc.relname " +//$NON-NLS-1$
+ "from pg_catalog.pg_attribute ta, pg_catalog.pg_attribute ia, pg_catalog.pg_class tc, pg_catalog.pg_index i, " +//$NON-NLS-1$
+ "pg_catalog.pg_namespace n, pg_catalog.pg_class ic where tc.relname = E'pg_attribute' AND n.nspname = E'pg_catalog'");
+ 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");
+ try {
+ stmt.executeQuery();
+ } catch (SQLException e) {
+ assertTrue(e.getMessage().contains("Error converting"));
+ }
+ }
+
+ @Test public void testPreparedError1() throws Exception {
+ PreparedStatement stmt = conn.prepareStatement("select");
+ try {
+ stmt.executeQuery();
+ } catch (SQLException e) {
+ assertTrue(e.getMessage().contains("Parsing error"));
+ }
+ }
+
+ @Test public void testEscapedLiteral() throws Exception {
+ Statement stmt = conn.createStatement();
+ ResultSet rs = stmt.executeQuery("select E'\\n\\thello pg'");
+ assertTrue(rs.next());
+ assertEquals("\n\thello pg", rs.getString(1));
+ }
+
+ @Test public void testPgProc() throws Exception {
+ Statement stmt = conn.createStatement();
+ ResultSet rs = stmt.executeQuery("select * from pg_proc");
+ rs.next();
+ assertEquals("oid", rs.getArray("proargtypes").getBaseTypeName());
+ }
+
+ @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());
+ }
+}
Deleted: tags/teiid-parent-7.5.0.Alpha1/test-integration/db/pom.xml
===================================================================
--- trunk/test-integration/db/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/db/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,537 +0,0 @@
-<?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">
-
-<!--
- The database dependent tests are meant to be run on their own, not as part of the continous or nightly
- build for Teiid.
--->
-
- <parent>
- <artifactId>teiid-test-integration</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.5.0.Alpha1-SNAPSHOT</version>
- </parent>
-
- <modelVersion>4.0.0</modelVersion>
- <artifactId>test-integration-db</artifactId>
-
- <name>DB Dependent Integration Tests</name>
- <groupId>org.jboss.teiid.teiid-test-integration</groupId>
- <description>Integration tests that require external database dependencies </description>
- <dependencies>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.4</version>
- </dependency>
-
- <dependency>
- <groupId>javax.transaction</groupId>
- <artifactId>jta</artifactId>
- <version>1.1</version>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- <type>test-jar</type>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <type>test-jar</type>
- <scope>compile</scope>
- </dependency>
-
-
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-engine</artifactId>
- <type>test-jar</type>
- <scope>compile</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>test-integration-common</artifactId>
- <type>test-jar</type>
- <scope>compile</scope>
- <version>${project.version}</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.ant</groupId>
- <artifactId>ant</artifactId>
- <version>1.7.0</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.ant</groupId>
- <artifactId>ant-launcher</artifactId>
- <version>1.7.0</version>
- </dependency>
- <dependency>
- <groupId>ant-contrib</groupId>
- <artifactId>ant-contrib</artifactId>
- <version>1.0b3</version>
- <exclusions>
- <exclusion>
- <groupId>ant</groupId>
- <artifactId>ant</artifactId>
- </exclusion>
- </exclusions>
-
- </dependency>
-
- <dependency>
- <groupId>ant-contrib</groupId>
- <artifactId>cpptasks</artifactId>
- <version>1.0b3</version>
- <exclusions>
- <exclusion>
- <groupId>ant</groupId>
- <artifactId>ant</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
-
-
- <!-- DBUnit dependencies -->
-
- <dependency>
- <groupId>org.dbunit</groupId>
- <artifactId>dbunit</artifactId>
- <version>2.2</version>
- </dependency>
-
- <dependency>
- <groupId>commons-collections</groupId>
- <artifactId>commons-collections</artifactId>
- <version>3.2.1</version>
- </dependency>
-
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>1.5.6</version>
- </dependency>
-
-
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi</artifactId>
- <version>3.2-FINAL</version>
- </dependency>
-
- <dependency>
- <groupId>jdom</groupId>
- <artifactId>jdom</artifactId>
- <version>1.0</version>
- </dependency>
-
- <dependency>
- <groupId>postgresql</groupId>
- <artifactId>postgresql</artifactId>
- <version>${postgresql.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.derby</groupId>
- <artifactId>derby</artifactId>
- <version>${derby.version}</version>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>${mysql.connector.version}</version>
- </dependency>
-
- </dependencies>
-
- <profiles>
- <profile>
- <id>default</id>
- <activation>
- <activeByDefault>true</activeByDefault>
- </activation>
-
- <build>
- <plugins>
- <!-- Specify the compiler options and settings -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <source>1.6</source>
- <target>1.6</target>
- <showDeprecation>false</showDeprecation>
- <showWarnings>false</showWarnings>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
-
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <configuration>
- <descriptors>
- <descriptor>src/assembly/binaries.xml</descriptor>
- </descriptors>
- <outputDirectory>target/distribution</outputDirectory>
- <workDirectory>target/assembly/work</workDirectory>
- </configuration>
- <executions>
- <execution>
- <id>make-assembly</id>
- <phase>package</phase>
- <goals>
- <goal>attached</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
-
-
- <profile>
- <id>runalltests</id>
- <build>
- <plugins>
-
- <plugin>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <additionalClasspathElements>
- <additionalClasspathElement>${basedir}/lib/ojdbc6.jar</additionalClasspathElement>
- <additionalClasspathElement>${basedir}/lib/sqljdbc4.jar</additionalClasspathElement>
- <additionalClasspathElement>${basedir}/lib/db2jcc4.jar</additionalClasspathElement>
-
- </additionalClasspathElements>
- <systemProperties>
- <property>
- <name>usedatasources</name>
- <value>${usedatasources}</value>
- </property>
- <property>
- <name>datasourceloc</name>
- <value>${datasourceloc}</value>
- </property>
- </systemProperties>
-
-<!--
-<forkMode>always</forkMode>
- <forkedProcessTimeoutInSeconds>600</forkedProcessTimeoutInSeconds>
- -->
- <includes>
- <!-- <include>**/*TestCase.java</include> -->
- <include>**/*Test.java</include>
- <include>**/*Tests.java</include>
- <include>**/Test*.java</include>
- </includes>
- <excludes>
- <exclude>**/*Abstract*TestCase.java</exclude>
- <exclude>**/*Abstract*Test.java</exclude>
- <!-- hack to prevent anonymous inner classes in Tests from being run as tests -->
- <exclude>**/Test*$*.java</exclude>
- </excludes>
-
- </configuration>
- </plugin>
-
- </plugins>
-
- </build>
-
-<!-- <version>2.4.2</version> -->
-
- <reporting>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-report-plugin</artifactId>
-
- <configuration>
- <outputDirectory>${basedir}/target/newsite</outputDirectory>
- </configuration>
- </plugin>
- </plugins>
- </reporting>
- </profile>
-
- <profile>
- <id>runsingletest</id>
- <activation>
- <property>
- <name>classname</name>
- </property>
- </activation>
- <build>
- <plugins>
-
- <plugin>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <additionalClasspathElements>
- <additionalClasspathElement>${basedir}/lib/ojdbc6.jar</additionalClasspathElement>
- <additionalClasspathElement>${basedir}/lib/sqljdbc4.jar</additionalClasspathElement>
- <additionalClasspathElement>${basedir}/lib/db2jcc4.jar</additionalClasspathElement>
- </additionalClasspathElements>
- <systemProperties>
- <property>
- <name>usedatasources</name>
- <value>${usedatasources}</value>
- </property>
- <property>
- <name>datasourceloc</name>
- <value>${datasourceloc}</value>
- </property>
- </systemProperties>
-
-<!--
- <forkMode>always</forkMode>
-
- <forkedProcessTimeoutInSeconds>600</forkedProcessTimeoutInSeconds>
- -->
- <includes>
- <include>**/${classname}.java</include>
- </includes>
-
- </configuration>
- </plugin>
-
- </plugins>
- </build>
- </profile>
-
-
- <profile>
- <id>setupdatasources</id>
- <build>
- <plugins>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-antrun-plugin</artifactId>
- <dependencies>
- <dependency>
- <groupId>org.apache.ant</groupId>
- <artifactId>ant</artifactId>
- <version>${apache.ant.version}</version>
- </dependency>
- </dependencies>
- <configuration>
- </configuration>
- <executions>
- <execution>
- <id>setupalldatasources</id>
- <phase>pre-integration-test</phase>
- <configuration>
- <tasks>
- <property name="maven.runtime.classpath" refid="maven.runtime.classpath" />
- <property name="relative.resources.dir" value="src/main/resources" />
- <property name="datasourceloc" value="${datasourceloc}" />
- <ant antfile="src/main/resources/ddl/manage_schemas.xml" />
- </tasks>
- </configuration>
- <goals>
- <goal>run</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
-
- </plugins>
- </build>
- </profile>
- <profile>
- <id>singledatasource</id>
- <activation>
- <property>
- <name>datasource</name>
- </property>
- </activation>
- <build>
- <plugins>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-antrun-plugin</artifactId>
- <dependencies>
- <dependency>
- <groupId>org.apache.ant</groupId>
- <artifactId>ant</artifactId>
- <version>${apache.ant.version}</version>
- </dependency>
- </dependencies>
- <configuration>
-
- </configuration>
- <executions>
- <execution>
- <id>setupsingledatasource</id>
- <phase>pre-integration-test</phase>
- <configuration>
- <tasks>
-
- <property name="single" value="${datasource}" />
- <property name="maven.runtime.classpath" refid="maven.runtime.classpath" />
- <property name="datasourceloc" value="${datasourceloc}" />
-
- <property name="relative.resources.dir" value="src/main/resources" />
- <ant antfile="src/main/resources/ddl/manage_schemas.xml" />
- </tasks>
- </configuration>
- <goals>
- <goal>run</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
-
- </plugins>
- </build>
- </profile>
-
-
- <profile>
- <id>runclienttests</id>
- <activation>
- <property>
- <name>scenario.dir</name>
- </property>
- </activation>
- <build>
- <plugins>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-antrun-plugin</artifactId>
- <dependencies>
- <dependency>
- <groupId>org.apache.ant</groupId>
- <artifactId>ant</artifactId>
- <version>${apache.ant.version}</version>
- </dependency>
- </dependencies>
- <executions>
- <execution>
- <id>run-client-test</id>
- <phase>integration-test</phase>
- <configuration>
- <tasks>
-
- <property name="maven.runtime.classpath" refid="maven.runtime.classpath" />
- <property name="scenario.dir" value="${scenario.dir}" />
- <property name="queryset.artifacts.dir" value="${queryset.artifacts.dir}" />
- <property name="vdb.artifacts.dir" value="${vdb.artifacts.dir}" />
- <!-- optional properties -->
- <property name="config.file" value="${config.file}" />
- <property name="query.scenario.classname" value="${query.scenario.classname}" />
- <property name="proj.dir" value="${project.basedir}/target/" />
- <property name="usedatasources" value="${usedatasources}" />
- <property name="datasourceloc" value="${datasourceloc}" />
-
- <ant antfile="src/main/resources/ctc_tests/ctc.xml" />
-
- </tasks>
- </configuration>
- <goals>
- <goal>run</goal>
- </goals>
- </execution>
-
- </executions>
- </plugin>
- </plugins>
- </build>
-
- </profile>
-
- <profile>
- <id>assemble</id>
-<!-- assemble will compile, but not run the tests prior to assemblying the kit -->
-
- <build>
- <plugins>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <skip>true</skip>
- </configuration>
- </plugin>
-
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <configuration>
- <descriptors>
- <descriptor>src/assembly/binaries.xml</descriptor>
- </descriptors>
- <outputDirectory>target/distribution</outputDirectory>
- <workDirectory>target/work/assembly</workDirectory>
-
- </configuration>
- <executions>
-
- <execution>
- <id>make-assembly</id>
- <phase>package</phase>
- <goals>
- <goal>attached</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
- </plugins>
- </build>
- </profile>
-
- </profiles>
-
-
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/test-integration/db/pom.xml (from rev 3220, trunk/test-integration/db/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/test-integration/db/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/db/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,537 @@
+<?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">
+
+<!--
+ The database dependent tests are meant to be run on their own, not as part of the continous or nightly
+ build for Teiid.
+-->
+
+ <parent>
+ <artifactId>teiid-test-integration</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.5.0.Alpha1</version>
+ </parent>
+
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>test-integration-db</artifactId>
+
+ <name>DB Dependent Integration Tests</name>
+ <groupId>org.jboss.teiid.teiid-test-integration</groupId>
+ <description>Integration tests that require external database dependencies </description>
+ <dependencies>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.4</version>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.transaction</groupId>
+ <artifactId>jta</artifactId>
+ <version>1.1</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ <type>test-jar</type>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <type>test-jar</type>
+ <scope>compile</scope>
+ </dependency>
+
+
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-engine</artifactId>
+ <type>test-jar</type>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>test-integration-common</artifactId>
+ <type>test-jar</type>
+ <scope>compile</scope>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.ant</groupId>
+ <artifactId>ant</artifactId>
+ <version>1.7.0</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.ant</groupId>
+ <artifactId>ant-launcher</artifactId>
+ <version>1.7.0</version>
+ </dependency>
+ <dependency>
+ <groupId>ant-contrib</groupId>
+ <artifactId>ant-contrib</artifactId>
+ <version>1.0b3</version>
+ <exclusions>
+ <exclusion>
+ <groupId>ant</groupId>
+ <artifactId>ant</artifactId>
+ </exclusion>
+ </exclusions>
+
+ </dependency>
+
+ <dependency>
+ <groupId>ant-contrib</groupId>
+ <artifactId>cpptasks</artifactId>
+ <version>1.0b3</version>
+ <exclusions>
+ <exclusion>
+ <groupId>ant</groupId>
+ <artifactId>ant</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+
+ <!-- DBUnit dependencies -->
+
+ <dependency>
+ <groupId>org.dbunit</groupId>
+ <artifactId>dbunit</artifactId>
+ <version>2.2</version>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-collections</groupId>
+ <artifactId>commons-collections</artifactId>
+ <version>3.2.1</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>1.5.6</version>
+ </dependency>
+
+
+ <dependency>
+ <groupId>org.apache.poi</groupId>
+ <artifactId>poi</artifactId>
+ <version>3.2-FINAL</version>
+ </dependency>
+
+ <dependency>
+ <groupId>jdom</groupId>
+ <artifactId>jdom</artifactId>
+ <version>1.0</version>
+ </dependency>
+
+ <dependency>
+ <groupId>postgresql</groupId>
+ <artifactId>postgresql</artifactId>
+ <version>${postgresql.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.derby</groupId>
+ <artifactId>derby</artifactId>
+ <version>${derby.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>mysql</groupId>
+ <artifactId>mysql-connector-java</artifactId>
+ <version>${mysql.connector.version}</version>
+ </dependency>
+
+ </dependencies>
+
+ <profiles>
+ <profile>
+ <id>default</id>
+ <activation>
+ <activeByDefault>true</activeByDefault>
+ </activation>
+
+ <build>
+ <plugins>
+ <!-- Specify the compiler options and settings -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ <showDeprecation>false</showDeprecation>
+ <showWarnings>false</showWarnings>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <configuration>
+ <descriptors>
+ <descriptor>src/assembly/binaries.xml</descriptor>
+ </descriptors>
+ <outputDirectory>target/distribution</outputDirectory>
+ <workDirectory>target/assembly/work</workDirectory>
+ </configuration>
+ <executions>
+ <execution>
+ <id>make-assembly</id>
+ <phase>package</phase>
+ <goals>
+ <goal>attached</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+
+
+ <profile>
+ <id>runalltests</id>
+ <build>
+ <plugins>
+
+ <plugin>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <additionalClasspathElements>
+ <additionalClasspathElement>${basedir}/lib/ojdbc6.jar</additionalClasspathElement>
+ <additionalClasspathElement>${basedir}/lib/sqljdbc4.jar</additionalClasspathElement>
+ <additionalClasspathElement>${basedir}/lib/db2jcc4.jar</additionalClasspathElement>
+
+ </additionalClasspathElements>
+ <systemProperties>
+ <property>
+ <name>usedatasources</name>
+ <value>${usedatasources}</value>
+ </property>
+ <property>
+ <name>datasourceloc</name>
+ <value>${datasourceloc}</value>
+ </property>
+ </systemProperties>
+
+<!--
+<forkMode>always</forkMode>
+ <forkedProcessTimeoutInSeconds>600</forkedProcessTimeoutInSeconds>
+ -->
+ <includes>
+ <!-- <include>**/*TestCase.java</include> -->
+ <include>**/*Test.java</include>
+ <include>**/*Tests.java</include>
+ <include>**/Test*.java</include>
+ </includes>
+ <excludes>
+ <exclude>**/*Abstract*TestCase.java</exclude>
+ <exclude>**/*Abstract*Test.java</exclude>
+ <!-- hack to prevent anonymous inner classes in Tests from being run as tests -->
+ <exclude>**/Test*$*.java</exclude>
+ </excludes>
+
+ </configuration>
+ </plugin>
+
+ </plugins>
+
+ </build>
+
+<!-- <version>2.4.2</version> -->
+
+ <reporting>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-report-plugin</artifactId>
+
+ <configuration>
+ <outputDirectory>${basedir}/target/newsite</outputDirectory>
+ </configuration>
+ </plugin>
+ </plugins>
+ </reporting>
+ </profile>
+
+ <profile>
+ <id>runsingletest</id>
+ <activation>
+ <property>
+ <name>classname</name>
+ </property>
+ </activation>
+ <build>
+ <plugins>
+
+ <plugin>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <additionalClasspathElements>
+ <additionalClasspathElement>${basedir}/lib/ojdbc6.jar</additionalClasspathElement>
+ <additionalClasspathElement>${basedir}/lib/sqljdbc4.jar</additionalClasspathElement>
+ <additionalClasspathElement>${basedir}/lib/db2jcc4.jar</additionalClasspathElement>
+ </additionalClasspathElements>
+ <systemProperties>
+ <property>
+ <name>usedatasources</name>
+ <value>${usedatasources}</value>
+ </property>
+ <property>
+ <name>datasourceloc</name>
+ <value>${datasourceloc}</value>
+ </property>
+ </systemProperties>
+
+<!--
+ <forkMode>always</forkMode>
+
+ <forkedProcessTimeoutInSeconds>600</forkedProcessTimeoutInSeconds>
+ -->
+ <includes>
+ <include>**/${classname}.java</include>
+ </includes>
+
+ </configuration>
+ </plugin>
+
+ </plugins>
+ </build>
+ </profile>
+
+
+ <profile>
+ <id>setupdatasources</id>
+ <build>
+ <plugins>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.ant</groupId>
+ <artifactId>ant</artifactId>
+ <version>${apache.ant.version}</version>
+ </dependency>
+ </dependencies>
+ <configuration>
+ </configuration>
+ <executions>
+ <execution>
+ <id>setupalldatasources</id>
+ <phase>pre-integration-test</phase>
+ <configuration>
+ <tasks>
+ <property name="maven.runtime.classpath" refid="maven.runtime.classpath" />
+ <property name="relative.resources.dir" value="src/main/resources" />
+ <property name="datasourceloc" value="${datasourceloc}" />
+ <ant antfile="src/main/resources/ddl/manage_schemas.xml" />
+ </tasks>
+ </configuration>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+
+ </plugins>
+ </build>
+ </profile>
+ <profile>
+ <id>singledatasource</id>
+ <activation>
+ <property>
+ <name>datasource</name>
+ </property>
+ </activation>
+ <build>
+ <plugins>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.ant</groupId>
+ <artifactId>ant</artifactId>
+ <version>${apache.ant.version}</version>
+ </dependency>
+ </dependencies>
+ <configuration>
+
+ </configuration>
+ <executions>
+ <execution>
+ <id>setupsingledatasource</id>
+ <phase>pre-integration-test</phase>
+ <configuration>
+ <tasks>
+
+ <property name="single" value="${datasource}" />
+ <property name="maven.runtime.classpath" refid="maven.runtime.classpath" />
+ <property name="datasourceloc" value="${datasourceloc}" />
+
+ <property name="relative.resources.dir" value="src/main/resources" />
+ <ant antfile="src/main/resources/ddl/manage_schemas.xml" />
+ </tasks>
+ </configuration>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+
+ </plugins>
+ </build>
+ </profile>
+
+
+ <profile>
+ <id>runclienttests</id>
+ <activation>
+ <property>
+ <name>scenario.dir</name>
+ </property>
+ </activation>
+ <build>
+ <plugins>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.ant</groupId>
+ <artifactId>ant</artifactId>
+ <version>${apache.ant.version}</version>
+ </dependency>
+ </dependencies>
+ <executions>
+ <execution>
+ <id>run-client-test</id>
+ <phase>integration-test</phase>
+ <configuration>
+ <tasks>
+
+ <property name="maven.runtime.classpath" refid="maven.runtime.classpath" />
+ <property name="scenario.dir" value="${scenario.dir}" />
+ <property name="queryset.artifacts.dir" value="${queryset.artifacts.dir}" />
+ <property name="vdb.artifacts.dir" value="${vdb.artifacts.dir}" />
+ <!-- optional properties -->
+ <property name="config.file" value="${config.file}" />
+ <property name="query.scenario.classname" value="${query.scenario.classname}" />
+ <property name="proj.dir" value="${project.basedir}/target/" />
+ <property name="usedatasources" value="${usedatasources}" />
+ <property name="datasourceloc" value="${datasourceloc}" />
+
+ <ant antfile="src/main/resources/ctc_tests/ctc.xml" />
+
+ </tasks>
+ </configuration>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ </execution>
+
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+ </profile>
+
+ <profile>
+ <id>assemble</id>
+<!-- assemble will compile, but not run the tests prior to assemblying the kit -->
+
+ <build>
+ <plugins>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <configuration>
+ <descriptors>
+ <descriptor>src/assembly/binaries.xml</descriptor>
+ </descriptors>
+ <outputDirectory>target/distribution</outputDirectory>
+ <workDirectory>target/work/assembly</workDirectory>
+
+ </configuration>
+ <executions>
+
+ <execution>
+ <id>make-assembly</id>
+ <phase>package</phase>
+ <goals>
+ <goal>attached</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ </plugins>
+ </build>
+ </profile>
+
+ </profiles>
+
+
+</project>
\ No newline at end of file
Deleted: tags/teiid-parent-7.5.0.Alpha1/test-integration/pom.xml
===================================================================
--- trunk/test-integration/pom.xml 2011-06-02 18:23:22 UTC (rev 3213)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -1,107 +0,0 @@
-<?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-test-integration</artifactId>
- <packaging>pom</packaging>
- <name>Integration Tests</name>
- <description>Integration tests spanning server/embedded/connectors.</description>
-
- <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>
-
- <apache.ant.version>1.7.0</apache.ant.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <type>test-jar</type>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-metadata</artifactId>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-metadata</artifactId>
- <type>test-jar</type>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid.connectors</groupId>
- <artifactId>translator-jdbc</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-client</artifactId>
- <type>test-jar</type>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-engine</artifactId>
- <type>test-jar</type>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-adminshell</artifactId>
- <version>${project.version}</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-runtime</artifactId>
- </dependency>
-
- <!-- external dependencies -->
- <dependency>
- <groupId>org.apache.derby</groupId>
- <artifactId>derby</artifactId>
- <version>${derby.version}</version>
-
- </dependency>
-
- <dependency>
- <groupId>javax.resource</groupId>
- <artifactId>connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>javax.transaction</groupId>
- <artifactId>jta</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.deployers</groupId>
- <artifactId>jboss-deployers-vfs-spi</artifactId>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.jboss.deployers</groupId>
- <artifactId>jboss-deployers-vfs</artifactId>
- <scope>provided</scope>
- </dependency>
-
- </dependencies>
-
- <modules>
- <module>common</module>
- <module>db</module>
- </modules>
-</project>
\ No newline at end of file
Copied: tags/teiid-parent-7.5.0.Alpha1/test-integration/pom.xml (from rev 3220, trunk/test-integration/pom.xml)
===================================================================
--- tags/teiid-parent-7.5.0.Alpha1/test-integration/pom.xml (rev 0)
+++ tags/teiid-parent-7.5.0.Alpha1/test-integration/pom.xml 2011-06-05 18:45:10 UTC (rev 3221)
@@ -0,0 +1,107 @@
+<?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</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>teiid-test-integration</artifactId>
+ <packaging>pom</packaging>
+ <name>Integration Tests</name>
+ <description>Integration tests spanning server/embedded/connectors.</description>
+
+ <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>
+
+ <apache.ant.version>1.7.0</apache.ant.version>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-metadata</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-metadata</artifactId>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <artifactId>translator-jdbc</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-client</artifactId>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-engine</artifactId>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-adminshell</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-runtime</artifactId>
+ </dependency>
+
+ <!-- external dependencies -->
+ <dependency>
+ <groupId>org.apache.derby</groupId>
+ <artifactId>derby</artifactId>
+ <version>${derby.version}</version>
+
+ </dependency>
+
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.transaction</groupId>
+ <artifactId>jta</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.deployers</groupId>
+ <artifactId>jboss-deployers-vfs-spi</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.deployers</groupId>
+ <artifactId>jboss-deployers-vfs</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ </dependencies>
+
+ <modules>
+ <module>common</module>
+ <module>db</module>
+ </modules>
+</project>
\ No newline at end of file
More information about the teiid-commits
mailing list